<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\training;


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\logic\BaseLogic;
use think\facade\Db;


/**
 * TrainingWorkerTask逻辑
 * Class TrainingWorkerTaskLogic
 * @package app\adminapi\logic
 */
class TrainingWorkerTaskLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/16 13:49
     */
    public static function add(array $params): bool
    {

        Db::startTrans();
        try {

            // training_task_id 课程组id，配置为 0 或 1,2,3
            if($params['training_task_id']){
                $trainingTask = TrainingTask::create([
                    'task_name' => '工程师个人-'.$params['master_worker_id'],
                    'training_course_id' => array_map('intval', explode(',',$params['training_task_id'])),
                    'subclass' => 0,
                    'master_worker_id' => $params['master_worker_id'],
                ]);
                $params['training_task_id'] = $trainingTask->id;
            }

            TrainingWorkerTask::create([
                'master_worker_id' => $params['master_worker_id'],
                'shop_goods_id' => $params['shop_goods_id']??0,
                'training_task_id' => $params['training_task_id']??0,
                'lead_master_worker_id' => $params['lead_master_worker_id']??0,
                'operate_status' => $params['operate_status']??0,
                'task_list' => $params['task_list']??'',
            ]);

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


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/16 13:49
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            TrainingWorkerTask::where('id', $params['id'])->update([
                'master_worker_id' => $params['master_worker_id'],
                //'shop_goods_id' => $params['shop_goods_id']??0,
                //'training_task_id' => $params['training_task_id']??0,
                'lead_master_worker_id' => $params['lead_master_worker_id']??0,
                'operate_status' => $params['operate_status']??0,
                'task_list' => $params['task_list']?json_encode($params['task_list']):'',
            ]);

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


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/16 13:49
     */
    public static function delete(array $params): bool
    {
        return TrainingWorkerTask::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2025/02/16 13:49
     */
    public static function detail($params): array
    {
        return TrainingWorkerTask::findOrEmpty($params['id'])->toArray();
    }

    /** 培训课程试题记录初始化
     */
    public static function trainingCourseRecord($masterWorkerId,$training_task_id): array
    {
        /*
        $ids = TrainingWorkerCourse::where('master_worker_id',$masterWorkerId)->where('training_task_id',$training_task_id)->column('id');
        if(count($ids)>0){
            return $ids;
        }
        $training_course_ids  = json_decode(TrainingTask::where('id',$training_task_id)->value('training_course_id')??'[]',true);
        // 添加该工程师的所有培训课程初始化记录
        foreach ($training_course_ids as $course_id) {
            $workerCourse = TrainingWorkerCourse::create([
                'master_worker_id' => $masterWorkerId,
                'training_task_id' => $training_task_id,
                'training_course_id' => $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',$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' => $workerCourse->id,
                    'questions_id' => $question_id,
                    'worker_answer' => '',
                    'exam_score' => 0
                ]);
            }
        }
        $training_course_ids??*/
        return [];
    }

    /** 培训课程初始化记录 
     */
    public static function trainingCourseRecordInitial($masterWorkerId,$trainingTask): bool
    {
        $training_course_ids  = $trainingTask['training_course_id'];
        // 添加该工程师的所有培训课程初始化记录
        foreach ($training_course_ids as $course_id) {
            $trainingCourse = TrainingCourse::where(['id' => $course_id])->findOrEmpty();
            if($trainingCourse->isEmpty()){
                continue;
            }
            TrainingWorkerCourse::create([
                'master_worker_id' => $masterWorkerId,
                'training_task_id' => $trainingTask['id'],
                'training_course_id' => $course_id,
                'subclass' => $trainingTask['subclass'],
                'play_time' => 0,
                'exam_start_time' => 0,
                'exam_end_time' => 0,
                'study_status' => 0,
                'exam_score' => 0,
            ]);
        }
        return true;
    }

    /** 培训试题初始化记录 
     */
    public static function trainingQuestionRecordInitial($workerCourse): bool
    {

        $trainingCourse = TrainingCourse::where('id',$workerCourse['training_course_id'])->findOrEmpty();
        // 配置是否随机出题？ 0 1
        if($trainingCourse->randomly_question){
            // 将之前题全删除 重新选题
            TrainingWorkerQuestion::where([
                'master_worker_id' => $workerCourse['master_worker_id'],
                'subclass' => $workerCourse['subclass'],
                'worker_course_id' => $workerCourse['id']
            ])->delete();
            $trainingQuestions = TrainingQuestions::where('subclass',$trainingCourse->subclass)->order(Db::raw('rand()'))->limit($trainingCourse->randomly_num)->select()->toArray();
            if(empty($trainingQuestions)){
                return false;
            }
            
            //每题多少分(按总分100分计算)
            $score = bcdiv(100, count($trainingQuestions), 2);
            $course_question = [];
            foreach ($trainingQuestions as $block_key => $trainingQuestion) {
                //[{"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[] = [
                    'block_key' => $block_key+1,
                    'select_value' => $trainingQuestion['id'],
                    'score' => $score
                ];
            }
            TrainingWorkerCourse::where('id',$workerCourse['id'])->update(['course_question_setting'=>json_encode($course_question)]);
        }else{
            if(empty($trainingCourse['course_question_setting'])){
                return false;
            }
            $course_question = $trainingCourse['course_question_setting'];
        }

        // 添加该工程师该课程的所有试题初始化记录
        $course_question_ids = array_column($course_question,'select_value');
        foreach ($course_question_ids as $question_id) {
            $trainingQuestions = TrainingQuestions::where(['id' => $question_id])->findOrEmpty();
            if($trainingQuestions->isEmpty()){
                continue;
            }

            $trainingWorkerQuestion = TrainingWorkerQuestion::where([
                'master_worker_id' => $workerCourse['master_worker_id'],
                'subclass' => $workerCourse['subclass'],
                'worker_course_id' => $workerCourse['id'],
                'questions_id' => $question_id
            ])->findOrEmpty();
            if($trainingWorkerQuestion->isEmpty()){
                TrainingWorkerQuestion::create([
                    'master_worker_id' => $workerCourse['master_worker_id'],
                    'subclass' => $workerCourse['subclass'],
                    'worker_course_id' => $workerCourse['id'],
                    'questions_id' => $question_id,
                    'worker_answer' => '',
                    'exam_score' => 0
                ]);
            }
        }

        return true;
    }

}