<?php
namespace app\workerapi\logic;
use app\adminapi\logic\master_worker_register\MasterWorkerRegisterLogic;
use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\bank_account\BankAccount;
use app\common\model\goods_category\GoodsCategory;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerAccountLog;
use app\common\model\master_worker\MasterWorkerAgree;
use app\common\model\master_worker\MasterWorkerInfo;
use app\common\model\master_worker\MasterWorkerTeam;
use app\common\model\shops\ShopOrderGoods;
use app\common\model\shops\ShopOrders;
use app\common\model\tenant\TenantAgree;
use app\common\model\tenant\TenantRegister;
use app\common\model\training\TrainingCategory;
use app\common\model\training\TrainingCourse;
use app\common\model\training\TrainingQuestions;
use app\common\model\training\TrainingTask;
use app\common\model\training\TrainingWorkerCourse;
use app\common\model\training\TrainingWorkerQuestion;
use app\common\model\training\TrainingWorkerTask;
use app\common\model\works\ServiceWork;
use app\common\service\FileService;
use app\workerapi\lists\MasterWorkerLists;
use app\workerapi\lists\ServiceWorkLists;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;


class TrainingLogic extends  BaseLogic
{
    public static function getDetail(int $masterWorkerId)
    {
        try {
            TrainingWorkerTaskLogic::upTaskOrder($masterWorkerId);

            $task_info = ['id'=>0];
            $task = TrainingWorkerTask::where('master_worker_id',$masterWorkerId)->findOrEmpty();
            if (!$task->isEmpty()) {
                $task_info = $task->toArray();
                // 0 不展示按钮 1 去学习 2 已学完
                $task_info['learning_status'] = $task_info['shop_orders_id']>0?1:0;
                $task_info['operate_status'] = empty($task_info['lead_master_worker_id'])?0:($task_info['operate_status']?1:2);
                $task_info['bank_status'] = BankAccount::where('worker_id',$masterWorkerId)->where('audit_state',1)->value('id')?1:0;
                $masterWorker = MasterWorker::where('id',$masterWorkerId)->find();
                //服务类目
                $task_info['category_status'] = empty($masterWorker['category_ids'])?0:1;
                $task_info['category_ids'] = $masterWorker['category_ids']??[];
                $task_info['service_status'] = (empty($masterWorker['lon']) || empty($masterWorker['lat']))?0:1;
                // 团队入驻状态 审核状态 0待审核 1审核通过 2审核拒绝
                $task_info['tenant_register_status'] = TenantRegister::where('mobile',$masterWorker['mobile'])->value('status')??0;
                // 团队协议状态 审核状态 0待审核 1审核通过 2审核拒绝 3待提交
                $tenant_agree_status = TenantAgree::where('worker_id',$masterWorker['id'])->value('pdf_url');
                $task_info['tenant_agree_status'] = (empty($tenant_agree_status))?3:(TenantAgree::where('worker_id',$masterWorker['id'])->value('audit_state'));
                $task_info['tenant_agree_info'] = TenantAgreeLogic::getAgreeByType('tenant_cooperate',$masterWorker['id']);

                // 工程师免责协议状态 审核状态 0待审核 1审核通过 2审核拒绝 3待提交
                $harmless_agree_status = MasterWorkerAgree::where(['agree_type'=>'harmless_content','worker_id'=>$masterWorker['id']])->value('pdf_url');
                $task_info['harmless_agree_status'] = MasterWorkerAgree::where(['agree_type'=>'harmless_content','worker_id'=>$masterWorker['id']])->value('audit_state')==1?1:0;
                $task_info['harmless_agree_info'] = MasterWorkerAgreeLogic::getAgreeByType('harmless',$masterWorker['id']);
                // 工程师无犯罪协议状态 审核状态 0待审核 1审核通过 2审核拒绝 3待提交
                $crime_agree_status = MasterWorkerAgree::where(['agree_type'=>'crime_content','worker_id'=>$masterWorker['id']])->value('pdf_url');
                $task_info['crime_agree_status'] = MasterWorkerAgree::where(['agree_type'=>'crime_content','worker_id'=>$masterWorker['id']])->value('audit_state')==1?1:0;
                $task_info['crime_agree_info'] = MasterWorkerAgreeLogic::getAgreeByType('crime',$masterWorker['id']);

                // 该工程师所有必须任务是否完成
                $task_info['task_required'] = MasterWorkerLogic::taskRequired($masterWorker['id'],$masterWorker['identity_source'])?1:0;
            }
            //$task_info['free_videos'] = TrainingCourse::where('course_lock',1)->select()->toArray();
            return $task_info;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return [];
        }
    }


    /**
     * 获取工程师的课程列表
     * @param int $masterWorkerId
     * @param array $params
     * @return array training_task_id => 工程师的任务id
     */
    public static function getCourseList(int $masterWorkerId,$params = [])
    {
        try {
            if(!isset($params['training_task_id']) || empty($params['training_task_id'])) {
                return [];
            }
        
            $trainingTask = TrainingTask::where('id',$params['training_task_id'])->findOrEmpty()->toArray();
            if(empty($trainingTask)){
                return [];
            }
            $trainingWorkerCourse = $trainingWorkerCourseList =  TrainingWorkerCourse::with(['trainingCourse'])
                        ->where('master_worker_id',$masterWorkerId)
                        ->where('training_task_id',$params['training_task_id'])
                        ->where('subclass',$trainingTask['subclass']);

            // 为空则初始化课程记录列表
            if(empty($trainingWorkerCourse->count())){
                \app\adminapi\logic\training\TrainingWorkerTaskLogic::trainingCourseRecordInitial($masterWorkerId,$trainingTask);
            }
            
            $list = $trainingWorkerCourseList->select()->toArray();
            foreach ($list as &$item) {
                $item['course_name'] = $item['trainingCourse']['course_name']??'';
                $item['course_picture'] = FileService::getFileUrl($item['trainingCourse']['course_picture']??'');
                $item['course_url'] = FileService::getFileUrl($item['trainingCourse']['course_url']??'');
            }
            return $list;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return [];
        }
    }

    /**
     * 获取工程师的课程详情
     * @param int $masterWorkerId
     * @param array $params
     * @return array id => 工程师的课程id  free_course_id => 免费课程ID
     */
    public static function getCourseDetail(int $masterWorkerId,$params = [])
    {
        try {
            if(isset($params['free_course_id']) && $params['free_course_id'] > 0) $params['id'] = self::freeWorkerCourseId($masterWorkerId,$params['free_course_id']);
            $info =  TrainingWorkerCourse::with(['trainingCourse'])->where('master_worker_id',$masterWorkerId)->where('id',$params['id'])->findOrEmpty()->toArray();
            $info['course_name'] = $info['trainingCourse']['course_name']??'';
            $info['course_picture'] = FileService::getFileUrl($info['trainingCourse']['course_picture']??'');
            $info['course_url'] = FileService::getFileUrl($info['trainingCourse']['course_url']??'');
            return $info;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return [];
        }
    }
    /**
     * 修改学习记录状态 播放开始 播放暂停 播放结束 考试开始 考试结束
     * @param array $params
     * @param int $masterWorkerId
     * @return bool
     */
    public static function upWorkerCourse(array $params)
    {
        try {
            $logCourse = TrainingWorkerCourse::where('id',$params['id'])->findOrEmpty();
            if ($logCourse->isEmpty()) {
                throw new \Exception('课程不存在');
            }
            // 播放开始 播放暂停 播放结束
            switch ($params['status']) {
                case 1:
                    $logCourse->play_time = $params['play_time']??($params['play_time']>0?$params['play_time']:1);
                    if($logCourse->study_status < 5){
                        $logCourse->study_status = 1;
                        TrainingWorkerTask::where('training_task_id',$logCourse->training_task_id)
                            ->where('master_worker_id',$logCourse->master_worker_id)
                            ->where('training_status',0)
                            ->update(['training_status'=>1]);
                    }
                    break;
                case 2:
                    $logCourse->play_time = $params['play_time']??10;
                    break;
                case 3:
                    $logCourse->study_status = 2;
                    break;
                case 4:
                    $logCourse->exam_start_time = time();
                    $logCourse->exam_end_time = 0;
                    $logCourse->study_status = 3;
                    break;
                case 5:
                    $logCourse->exam_end_time = time();
                    $logCourse->study_status = 4;
                    break;
                case 6:
                    $logCourse->exam_end_time = time();
                    $logCourse->study_status = 5;
                    break;
            }
            $logCourse->save();
            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 获取工程师的考试试题列表（即开始考试）
     * @param array $params  worker_course_id 工程师的课程id
     * @return array      id 工程师的试题id
     */
    public static function getQuestionList(array $params)
    {
        try {
            $workerCourse = TrainingWorkerCourse::where('id',$params['worker_course_id'])->findOrEmpty()->toArray();
            if($workerCourse['study_status'] == 5) {
                throw new \Exception('考试已通过，无需再考！');
            }
            $study_status = 0;
            if(isset($params['is_resit']) && $params['is_resit'] == 1 && $workerCourse['study_status'] == 4){
                // 重置
                TrainingWorkerCourse::update(['exam_start_time'=>0,'exam_end_time'=>0,'study_status'=>2,'exam_score'=>0],['id'=>$params['worker_course_id']]);
                TrainingWorkerQuestion::update(['worker_answer'=>'','exam_score'=>0],['worker_course_id'=>$params['worker_course_id']]);
                $study_status = 2;
            }
            if($workerCourse['study_status'] == 2 || $study_status == 2) {
                // 开始考试
                self::upWorkerCourse(['id'=>$params['worker_course_id'],'status'=> 4]);
            }

            // 检查是否随机课程 即初始化试题
            \app\adminapi\logic\training\TrainingWorkerTaskLogic::trainingQuestionRecordInitial($workerCourse);

            $list = TrainingWorkerQuestion::with(['trainingQuestions'])->where('worker_course_id',$params['worker_course_id'])->select()->toArray();
            foreach ($list as &$item) {
                $item['title'] = $item['trainingQuestions']['title'];
                $item['question_type'] = $item['trainingQuestions']['question_type'];
                $item['question_selects'] = $item['trainingQuestions']['question_selects'];
                $item['question_answer'] = $item['trainingQuestions']['question_answer'];
                $item['question_analysis'] = $item['trainingQuestions']['question_analysis'];
            }
            return $list;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }


    /**
     * 提交考试  该工程师的课程id + 所有的工程师的试题id、答案
     * @param array
     * @param int $masterWorkerId
     * @return
     */
    public static function submitExam($params){
        Db::startTrans();
        try {

            // 课程试卷详情
            $exam_paper_details = self::getExamPaperDetails(['worker_course_id'=>$params['worker_course_id']]);

            // 提交的答案 [['id'=> ,'answer'=>],['id'=> ,'answer'=>]]
            !is_array($params['worker_answer']) && $params['worker_answer'] = json_decode($params['worker_answer'],true);
            $worker_answer = array_column($params['worker_answer'],'answer','id');

            //对比答案 更新答题记录实际每题得分，总得分
            $all_exam_score = 0;
            $course_question_setting = $exam_paper_details['course']['course_question_setting'];
            foreach ($course_question_setting as &$item) {
                $exam_score = 0;
                $worker_answer_value = '';
                ($worker_answer_value = explode(',',$worker_answer[$item['select_value']])) && sort($worker_answer_value) && ($worker_answer_value = implode(',',$worker_answer_value));
                if($worker_answer_value == $item['question_answer']){
                    $exam_score = $item['score'];
                }
                $all_exam_score += $exam_score;
                TrainingWorkerQuestion::update(
                    ['worker_answer' => $worker_answer_value,'exam_score' => $exam_score],
                    ['worker_course_id' => $params['worker_course_id'],'questions_id' => $item['select_value']]
                );
            }

            // 更新课程得分、状态
            if((float)$all_exam_score < (float)$exam_paper_details['course']['course_question_score']){
                $study_status = 4;
            }else{
                $study_status = 5;
            }
            TrainingWorkerCourse::update(
                ['exam_score' => $all_exam_score,'study_status'=>$study_status,'exam_end_time'=>time()],
                ['id' => $params['worker_course_id']]
            );

            Log::info(
                '提交考试结果：'.$params['worker_course_id'].' 得分: '.$all_exam_score.' 状态: '.$study_status.
                ' 合格分: '.$exam_paper_details['course']['course_question_score'].
                ' 工程师id: '. $exam_paper_details['master_worker_id'].
                ' 试题详情: '.json_encode($exam_paper_details)
            );
            // 判断是否为服务类目考试
            if($exam_paper_details['subclass'] > 0){
                if($study_status == 5){
                    // 该工程师的服务类目课程全部完成，更新任务状态
                    $workerCourseCount = TrainingWorkerCourse::where('master_worker_id',$exam_paper_details['master_worker_id'])
                        ->where('training_task_id',$exam_paper_details['training_task_id'])
                        ->where('subclass',$exam_paper_details['subclass'])
                        ->where('study_status','<',5)
                        ->count();
                    if($workerCourseCount == 0){
                        TrainingCategory::where('master_worker_id',$exam_paper_details['master_worker_id'])
                            ->where('training_task_id',$exam_paper_details['training_task_id'])
                            ->where('category_id',$exam_paper_details['subclass'])
                            ->update(['is_must' => 1]);

                        $masterWorker = MasterWorker::where('id',$exam_paper_details['master_worker_id'])->findOrEmpty();
                        $category_ids = explode(',',$masterWorker->category_ids);
                        $category_ids[] = $exam_paper_details['subclass'];
                        $category_ids = array_unique($category_ids);
                        // 更新工程师服务类目
                        MasterWorker::update(['category_ids' => implode(',',$category_ids)],['id'=>$exam_paper_details['master_worker_id']]);
                    }
                }
            }else{
                // 该工程师的课程全部完成，更新任务状态
                $workerCourseCount = TrainingWorkerCourse::where('master_worker_id',$exam_paper_details['master_worker_id'])
                    ->where('training_task_id',$exam_paper_details['training_task_id'])
                    ->where('study_status','<',5)
                    ->count();
                if($workerCourseCount == 0){
                    TrainingWorkerTask::where('master_worker_id',$exam_paper_details['master_worker_id'])
                        ->where('training_task_id',$exam_paper_details['training_task_id'])
                        ->where('training_status',1)
                        ->update(['training_status'=>2]);
                }
            }

            Db::commit();
            return true;
        }catch(\Exception $e){
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function getExamPaperDetails($params){
        // 试卷详情
        $workerCourse = [];
        if(isset($params['worker_course_id'])){
            $workerCourse = TrainingWorkerCourse::where('id',$params['worker_course_id'])->findOrEmpty()->toArray();
            // 课程详情
            $course = TrainingCourse::where('id',$workerCourse['training_course_id'])->findOrEmpty()->toArray();

            // 若$workerCourse['course_question_setting']存在说明随机题 则 替换最新试题配置
            if($workerCourse['course_question_setting']){
                $course['course_question_setting'] = json_decode($workerCourse['course_question_setting'],true);
            }

            // 该课程所有试题 答案、分数
            $question_ids = array_column($course['course_question_setting'],'select_value')??[];
            $question_column = TrainingQuestions::whereIn('id',$question_ids)->column('question_answer','id');
            foreach ($course['course_question_setting'] as &$item) {
                $item['question_answer'] = $question_column[$item['select_value']];
            }
            $workerCourse['course'] = $course;
        }
        Log::info('exam_paper_details:'.json_encode($workerCourse));
        return $workerCourse;
    }


    /**
     * 考试结果统计
     * @param int $teamId
     * @param int $masterWorkerId
     * @return array
     */
    public static function examStatistics($params){
        // 计算考试结果： 总题数 正确率(>0的题数) 总得分(每题得分累计) | 总用时   是否合格
        // training_worker_question  training_worker_course
        /*total_questions 总题数 correct_questions 正确题数 correct_rate_percentage 正确率  total_score 总得分

        exam_time 总用时秒*/

        $res = [];
        $res['statistics'] = TrainingWorkerQuestion::where('worker_course_id',$params['worker_course_id'])
            ->field(['worker_course_id',Db::raw('COUNT(id) AS total_questions,SUM(CASE WHEN exam_score > 0 THEN 1 ELSE 0 END) AS correct_questions,ROUND((SUM(CASE WHEN exam_score > 0 THEN 1 ELSE 0 END) / COUNT(id)) * 100, 0) AS correct_rate_percentage,SUM(exam_score) AS total_score')])
            ->group('worker_course_id')
            ->find();
        $workerCourse = TrainingWorkerCourse::where('id',$params['worker_course_id'])->findOrEmpty()->toArray();
        $res['statistics']['exam_time'] = $workerCourse['exam_end_time'] - $workerCourse['exam_start_time'];
        $res['statistics']['study_status'] = $workerCourse['study_status'];
        $res['statistics_list'] = TrainingWorkerQuestion::where('worker_course_id',$params['worker_course_id'])->select();
        return $res;
    }

    /**
     * 免费课程进入（不存在则创建返回ID）
     * @param  array
     * @return array
     */
    public static function freeWorkerCourseId($masterWorkerId,$free_course_id){
        $free_course = TrainingWorkerCourse::where('master_worker_id',$masterWorkerId)
            ->where('training_task_id',0)
            ->where('subclass',0)
            ->where('training_course_id',$free_course_id)->findOrEmpty();
        if($free_course->isEmpty()){
            $free_course = TrainingWorkerCourse::create([
                'master_worker_id' => $masterWorkerId,
                'training_task_id' => 0,
                'training_course_id' => $free_course_id,
                'play_time' => 0,
                'exam_start_time' => 0,
                'exam_end_time' => 0,
                'study_status' => 0,
                'exam_score' => 0,
            ]);

            // 添加该工程师该课程的所有试题初始化记录
            //[{"block_key":1,"select_value":1,"score":"20"},{"block_key":2,"select_value":2,"score":"10"},{"block_key":3,"select_value":3,"score":"70"}]
            $course_question = json_decode(TrainingCourse::where('id',$free_course_id)->value('course_question_setting'),true);
            $course_question_ids = array_column($course_question,'select_value');
            foreach ($course_question_ids as $question_id) {
                $workerQuestion = TrainingWorkerQuestion::create([
                    'worker_course_id' => $free_course->id,
                    'questions_id' => $question_id,
                    'worker_answer' => '',
                    'exam_score' => 0
                ]);
            }
        }
        return $free_course->id;
    }


    /**
     * 提交分类
     * @param  array
     * @return bool
     */
    public static function submitCategory($params){

        try {
            if(!isset($params['category_ids']) || empty($params['category_ids'])){
                throw new \Exception('分类不能为空');
            }
            $category_ids = explode(',',$params['category_ids']);
            foreach ($category_ids as $category_id) {
                // 检查该分类下是否存在该分类的培训任务以及课程?

                $trainingCategory = TrainingCategory::where('master_worker_id',$params['user_id'])->where('category_id',$category_id)->findOrEmpty();
                if($trainingCategory->isEmpty()){
                    TrainingCategory::create([
                        'master_worker_id' => $params['user_id'],
                        'category_id' => $category_id
                    ]);
                }
            }
            return true;
        }catch(\Exception $e){
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * 获取所有类目信息
     * @param  array
     * @return array
     */
    public static function getTrainingCategory($params){
        try {
            $lists = TrainingCategory::with(['goodsCategory'])->where('master_worker_id',$params['user_id'])->select()->toArray();
            foreach ($lists as &$item) {
                $item['category_id_text'] = $item['goodsCategory']['name']??'';
                $item['category_two_text'] = GoodsCategory::where('id',$item['goodsCategory']['pid']??0)->value('name')??'';
                $item['category_three_text'] = GoodsCategory::where('id',GoodsCategory::where('id',$item['goodsCategory']['pid']??0)->value('pid')??0)->value('name')??'';
            }
            return $lists;
        }catch(\Exception $e){
            self::setError($e->getMessage());
            return [];
        }
    }

    /**
     * 获取某类目所有课程任务ID
     * @param  array
     * @return int
     */
    public static function getCategoryCourse($params){
        try {
            $trainingCategory = TrainingCategory::where('id',$params['id'])->findOrEmpty();
            if($trainingCategory->isEmpty()){
                throw new \Exception('该类目不存在');
            }
            $params['category_id'] = $trainingCategory->category_id;
            if($trainingCategory->training_task_id){
                    $trainingTask = TrainingTask::where('id',$trainingCategory->training_task_id)->findOrEmpty();
            }else{
                $trainingCourse = TrainingCourse::where('subclass',$params['category_id'])->order(Db::raw('rand()'))->limit(1)->select()->toArray();
                if(empty($trainingCourse)){
                    return 0;
                }
                $fixed_course_ids = array_column($trainingCourse,'id');
                $trainingTask = TrainingTask::create([
                    'task_name' => '分类ID-'.$params['category_id'],
                    'training_course_id' => array_map('intval', $fixed_course_ids),
                    'subclass' => $params['category_id'],
                    'master_worker_id' => $params['user_id'],
                ]);
                $trainingCategory->training_task_id = $trainingTask->id;
                $trainingCategory->save();
            }
            return $trainingTask->id;
        }catch(\Exception $e){
            self::setError($e->getMessage());
            return false;
        }
    }




}
