<?php
namespace app\api\controller;

use app\model\WorkRecord as WorkRecordModel;
use app\model\Questionnaire as QuestionnaireModel;
use app\model\Product as ProductModel;
use app\model\ProductOrder as ProductOrderModel;
use app\model\BalanceLog;
use support\think\Db;
use taoser\facade\Validate;
use hg\apidoc\annotation as Apidoc;

/**
 * 问卷
 */
class QuestionnaireController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];
    public $noNeedLogin = [];
    /**
     * 简介
     * @Apidoc\Method("GET")
     */
    public function info(){
        $user = \support\Jwt::getUser();
        return $this->success(__('successful'),[
            'success_count'   =>  WorkRecordModel::where('status',\app\enum\ServerStatus::COMPLETE->value)
                        ->where('user_id',$user->id)
                        ->count('id'),
            'audit_count'   =>  WorkRecordModel::where('status',\app\enum\ServerStatus::AUDITING->value)
                        ->where('user_id',$user->id)
                        ->count('id'),
        ]);

    }
    /**
     * 列表
     * @Apidoc\Query("kw", type="string", require=false, desc="搜索关键字")
     * @Apidoc\Query("country", type="string", require=false, desc="国家,i18n编码")
     * @Apidoc\Query("category_id", type="int", require=false, desc="分类")
     * @Apidoc\Query("page", type="int", require=true, desc="页码",default=1)
     * @Apidoc\Query("limit", type="int", require=true, desc="分页大小",default=10)
     */
    public function list(){
        $limit = (int)input('limit',10);
        $model = QuestionnaireModel::with(['category'])->where('status',1);
        if($category_id = input('category_id')){
            $model = $model->where('category_id', $category_id);
        }
        if($country = input('country')){
            $model = $model->where('country',  $country);
        }
        $list = $model->order('id desc')->paginate($limit);
        $list = $list->toArray();
        foreach($list['data'] as $k=>$item){
        	$list['data'][$k]['id'] = idEncode($item['id']);
        }
        return $this->success(__('successful'),$list);

    }
    /**
     * 问卷详情
     * @Apidoc\Query("id", type="int", require=true, desc="ID")
     */
    public function detail(){
        try{
            $user = \support\Jwt::getUser();
        }catch(\Exception $e){
            $user = ['id'=>0,'role_id'=>0];
        }
        $appid = input('id');
        if(!$appid){
            return $this->error(__("Product does not exist"));
        }
        /** @var ProductModel $product */
        $product = ProductModel::where('id',$appid)->find();
        //->cache(true,86400,'product_detail')
        if(!$product) {
            return $this->error(__("Product does not exist"));
        }
        if($user['id']){
            $total_quantity_user = ProductOrderModel::where('product_id',$product->id)->where('user_id',$user['id'])->sum('quantity');
            
            $total_quantity_system = $product->user_quantity ?: 99999999;
            $max_quantity = $total_quantity_system-$total_quantity_user;
            $max_quantity= $max_quantity < 0 ? 0: $max_quantity;
            $product->max_quantity = $max_quantity;
            $product->total_quantity_user = $total_quantity_user;
        }else{
            $product->total_quantity_user = 0;
            $product->max_quantity = 0;
        }
        return $this->success(__('successful'),$product->toArray());
    }
    /**
     * 领取问卷
     * @Apidoc\Method("GET")
     */
    function claim(){
        $user = \support\Jwt::getUser();
        //判断是否有问卷可领取
        if($user->currency6<=0){
            return $this->success(__('successful'));
        }
        //产生工作记录
        $datas = [];
        $questionnaire_ids = QuestionnaireModel::where('status',1)
            ->whereTime('start_time','<',time())
            ->whereTime('end_time','>',time())
            ->column('id');
        $time = time();
        for ($i=0; $i < $user->currency6; $i++) { 
            //随机选取一份问卷
            $questionnaire_id = $questionnaire_ids[array_rand($questionnaire_ids)];
            /** @var QuestionnaireModel $questionnaire */
            $questionnaire = QuestionnaireModel::field('id,score')->find($questionnaire_id);
            array_push($datas,[
                "user_id"           =>  $user->id,
                "product_id"        =>  null,
                "questionnaire_id"  =>  $questionnaire->id,
                "order_id"          =>  null,
                "income"            =>  $questionnaire->score,
                "start_time"        =>  0, 
                "end_time"          =>  0, 
                "status"            =>  0,  //自动开始
                "created_at"        =>  $time,
            ]);
        }
        Db::startTrans();
        try {
            (new WorkRecordModel)->saveAll($datas);
            //领取完成,待领取清0;
            $logData = [
                'user_id'               => $user->id.'',
                'currency'              => 'currency6',
                'amount'                => (0-$user->currency6).'',
                'before'                => $user->currency6.'',
                'after'                 => '0',
                'type'                  => \app\enum\BalanceType::CLAIM->value,
                'created_at'            => $time.'',
                'memo'                  =>  ''
            ];
            
            // 写入日志
            BalanceLog::create($logData);
            $user->currency6 = 0;
            $user->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success(__('successful'));
    }
    /**
     * 用户参与的问卷列表
     * @Apidoc\Query("order_id", type="string", require=false, desc="订单号")
     * @Apidoc\Query("step", type="string", require=false, desc="类型,progress,done")
     * @Apidoc\Query("page", type="int", require=true, desc="页码",default=1)
     * @Apidoc\Query("limit", type="int", require=true, desc="分页大小",default=10)
     */
    public function record(){
        $limit = (int)input('limit',10);
        $type = input('type','all');
        $user_id = \support\Jwt\JwtToken::getCurrentId();
        $step = input('step');
        $order_id = input('order_id');
        $model = WorkRecordModel::withJoin([
            'questionnaire'	=>	function($query) {
                $query->field('title,category_id,country');
            },
            // 'product'	=>	function($query) {
            //     $query->field('title');
            // }
        ])->where('work_record.user_id',$user_id);

        if($type && $type !='all'){
            $model = $model->where('work_record.status',  $type);
        }
        if($order_id){
            $model = $model->where('work_record.order_id',$order_id);
        }

        if($step){
            if($step=='done'){
                $model = $model->where('work_record.status',\app\enum\ServerStatus::COMPLETE->value);
            }
            if($step=='progress'){
                $model = $model->whereBetween('work_record.status',[1,\app\enum\ServerStatus::AUDITING->value,\app\enum\ServerStatus::SETTLEMENT->value]);
            }
        }
        $list = $model->order('work_record.id desc')
            ->paginate($limit);
        $list->each(function($item){
            $item->questionnaire->country = Config('site.questionnaire_country')[$item->questionnaire->country];
            $item->category = Db::name('category')->where('id',$item->questionnaire->category_id)->value('name');
            return $item;
        });
        return $this->success(__('successful'),$list->toArray());
    }
    /**
     * 开始任务
     * @Apidoc\Method("POST")
     * @Apidoc\Param("server_id", type="string", require=true, desc="产品ID")
     */
    public function start()
    {
        $server_id = input('server_id');
        $user = \support\Jwt::getUser();
        if(!$server_id){
            return $this->error(__('Incorrect parameter'));
        }
        if($server_id === 'all'){
            $work_records = WorkRecordModel::where('user_id',$user->id)
                ->where('status',\app\enum\ServerStatus::WAITING->value)
                ->select();
        }else{
            $work_records = WorkRecordModel::where('user_id',$user->id)
                ->where('status',\app\enum\ServerStatus::WAITING->value)
                ->where('id',$server_id)->select();
            if(count($work_records) === 0){
                return $this->error(__('Server is not exist'));
            }
        }
        /** @var WorkRecordModel $server */
        foreach($work_records as $server){
            $server->start();
        }
        return $this->success(__('successful'));
    }
    /**
     * 用户参与的问卷详情
     * @Apidoc\Method("POST")
     * @Apidoc\Param("server_id", type="string", require=true, desc="产品ID")
     */
    function progress(){
        $server_id = (int)input('server_id',1);
        $user = \support\Jwt::getUser();
        /** @var WorkRecordModel $work_record */
        $work_record = WorkRecordModel::with(['questionnaire'])->where('id',$server_id)->find();
        if(!$work_record){
            return $this->error(__('Server is not exist %sadds_f%',["%sadds_f%"=>'']));
        }
        $work_record->step_text = $work_record->getStep();
        
        return $this->success(__('successful'),$work_record->toArray());
    }
}