<?php

namespace app\admin\controller\student;

use app\admin\model\department\Department;
use app\admin\model\Fault;
use app\admin\model\Report;
use app\common\controller\Backend;
use app\common\model\Config as ConfigModel;
use think\Db;
use think\Env;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * sim-练习集合管理
 *
 * @icon fa fa-circle-o
 */
class Exercise extends Backend
{

    /**
     * Collection模型对象
     * @var \app\admin\model\teacher\Collection
     */
    protected $model = null;
    protected $exam_model = null;

    protected $whereExtend = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\teacher\Collection;
        $this->exam_model = new \app\admin\model\teacher\Exams;
        $this->assign('sim_sim_type', ConfigModel::getSimTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $count = 0;
            Db::startTrans();
            try {
                $params['exam_collection_type'] = 2;
                $params['exam_collection_state'] = 2;
                $params['question_setting_method'] = 1;
                $params['exam_collection_name'] = $this->auth->nickname.'练习';
                $params['limit_duration'] = 30;
                $params['start_time'] = date('Y-m-d');
                $params['end_time'] = date('Y-m-d');

                $exam_id = $this->model->insertGetId($params);
                
                $sim = Db::name('sim')->where('sim_type',$params['sim_type'])->where('seat_id',$this->auth->seat_id)->find();
                if(empty($sim)){
                    $this->error('未找到模拟器,不可练习');
                }

                $data = [
                    'exam_collection_id' => $exam_id,
                    'user_id' => $this->auth->id,
                    'user_username' => $this->auth->username,
                    'user_nickname' => $this->auth->nickname,
                    'user_depart_id' => $this->auth->depart_id,
                    'exam_collection_name' => $params['exam_collection_name'],
                    'exam_collection_type' =>$params['exam_collection_type'],
                    'sim_type' => $params['sim_type'],
                    'seat_id' =>0,
                    'sim_id' =>0,
                    'exam_status'=>4,
                    'start_time'=>date('Y-m-d H:i:s'),
                    'starttime'=>time(),
                    'create_time'=>date('Y-m-d H:i:s'),
                    'createtime'=>time(),
                    'update_time'=>date('Y-m-d H:i:s'),
                    'updatetime'=>time(),
                ];
                $examid = $this->exam_model->insertGetId($data);


                //匹配的学员自动加入  mx_real_exam_fault 考试故障关联表
                $fault_list = Fault::where(['sim_type' => $params['sim_type'], 'fault_state' => 0,'fault_type'=>3])->select();
                foreach ($fault_list as $key=> $item1){
                    $fault_key = [1,5,10];
                    if($params['sim_type']=='0002'){
                        $fault_key1 = 1;
                        $fault_key2 = 5;
                        $fault_key3 = rand(10,11);
                    }else{
                        $fault_key1 = rand(0, 1);
                        $fault_key2 = rand(2, 3);
                        $fault_key3 = 9;
                    }
                    $fault_key = [$fault_key1,$fault_key2,$fault_key3];

                    $flag = 0;
                    if(!empty($fault_key) && in_array($key,$fault_key)){
                        $flag = 1;
                    }
                    $add= [
                        'exam_id'=>$examid,
                        'fault_id'=>$item1['fault_id'],
                        'ref_type'=>2,
                        'flag'=>$flag,
                        'ref_state'=>0,
                        'createtime'=>time(),
                        'updatetime'=>time(),
                        'create_time'=>date('Y-m-d H:i:s'),
                        'update_time'=>date('Y-m-d H:i:s'),
                    ];
                    Db::name('real_exam_fault')->insert($add);
                }

                $count = $examid;

                
                Db::commit();
            } catch (PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                //先请求接口判断，再进行处理
                if(Env::get('app.is_fault')){
                    $url = config('site.url_type').'/sim/real-exam/student/self-exercise/start/'.$count.'?ip='.$this->auth->server_ip;
                    $ret = json_decode(send_get($url),true);
                    if($ret['code']!=200){
                        $this->error($ret['msg']);
                    }
                }
                $this->success('开始成功','/admin/student/exercise/examing/ids/'.$count);
            }
            $this->error(__('No rows were updated'));
        }
    }

    public  function  examing($ids = null)
    {
        $row = $this->exam_model->get($ids);
        if(!$row){
            $this->error('未找到记录');
        }
                
        if ($this->request->isPost()) {

            //先请求接口判断，再进行处理
            if(Env::get('app.is_fault')){
                $url = config('site.url_type').'/sim/real-exam/student/self-exercise/submit/'.$ids;
                $ret = json_decode(send_get($url),true);
                if($ret['code']!=200){
                    $this->error($ret['msg']);
                }
            }

            //计算分数，保存记录
            $params = $this->request->post('row/a');

            $result = false;
            $score = 100;
            $fault_one_score = 25;
            $fault_two_score = 25;
            $fault_three_score = 25;

            //故障现象
            $xianxian_score = 0;
            $xianxian_arr = [];
            $xianxian_content = [];

            //故障部位
            $buwei_score= 0;
            $buwei_arr = [];
            $buwei_content = [];

            //可能原因
            $yuanyin_socre= 0;
            $yuanyin_arr = [];
            $yuanyin_content = [];

            //排除方法
            $fangfa_score= 0;
            $fangfa_arr = [];
            $fangfa_content = [];

            $other_content = [];
            $content = [];

            Db::startTrans();
            try {

                if(!empty($params['other_report'])){
                    //获取数组
                    $other_report = json_decode($params['other_report'],true);
                    if(count($other_report)==1){
                        $other_report[1] = [
                           'xh_id' => 1,
                           'xx_id' => '',
                           'xx_name' => '',
                           'yy_id' => '',
                           'yy_name' => '',
                           'bw_id' => '',
                           'bw_name' => '',
                           'pc_id' => '',
                           'pc_name' => ''
                        ];
                        $other_report[2] = [
                           'xh_id' => 2,
                           'xx_id' => '',
                           'xx_name' => '',
                           'yy_id' => '',
                           'yy_name' => '',
                           'bw_id' => '',
                           'bw_name' => '',
                           'pc_id' => '',
                           'pc_name' => ''
                        ];
                    }else if(count($other_report)==2){
                        $other_report[2] = [
                           'xh_id' => 2,
                           'xx_id' => '',
                           'xx_name' => '',
                           'yy_id' => '',
                           'yy_name' => '',
                           'bw_id' => '',
                           'bw_name' => '',
                           'pc_id' => '',
                           'pc_name' => ''
                        ];
                    }
                    $params['other_report'] = json_encode($other_report);
                }
                //计算用时
                $endtime = time();
                $timediff = $endtime-$row->starttime;
                $remain = $timediff%86400;
                //计算分钟数
                $remain = $remain%3600;
                $mins = intval($remain/60);
                //计算秒数
                $secs = $remain%60;

                //更新考试结束时间
                $row->end_time = date('Y-m-d H:i:s',$endtime);
                $row->endtime = $endtime;
                $row->exam_status = 5;
                $row->exam_duration = $mins*60+$secs;
                $row->exam_duration_text = $mins.'分'.$secs.'秒';
                $row->other_report = $params['other_report'];
                $result = $row->save();

                $info = $this->exam_model->where(['exam_id'=>$ids])->find();


                //特殊判断结果 故障部位
                // 002型  薄膜开关FPC排线 蜂鸣器出声口 检测剂 干燥管 维护管
                // 003型  检测剂  干燥管 维护管
                $question_arr = ['0002GZBW0001','0002GZBW0003','0002GZBW0005','0002GZBW0009','0002GZBW0010','0003GZBW0006','0003GZBW0007','0003GZBW0008'];
                //更新故障是否正确
                $fault_list = Db::name('real_exam_fault')->where(['exam_id'=>$ids,'flag'=>1])->select();
                if(!empty($fault_list)){
                    foreach ($fault_list as $k =>$t){
                        $answer_right = 2;
                        //真实故障id 故障部位在  特殊故障部位里面
                        if(in_array($t['fault_id'],$question_arr)){
                            if(!empty($t['sim_fault_answer_value']) &&  substr($t['sim_fault_answer_value'], -1,1)==0){
                                $answer_right=1;
                            }
                        }else{
                            if(!empty($t['sim_fault_question_value']) && !empty($t['sim_fault_answer_value'])){  
                                if($t['sim_fault_question_value']!=$t['sim_fault_answer_value'] ){
                                    $answer_right=1;
                                }
                            }
                        }
                        Db::name('real_exam_fault')->where(['ref_id'=>$t['ref_id']])->update(['answer_right'=>$answer_right]);
                    }
                }


                //计算得分，故障是否有扣分  扣分制
                $fault_right_list = Db::name('real_exam_fault')->where(['exam_id'=>$ids,'flag'=>1,'answer_right'=>['>',0]])->select();
                if(!empty($fault_right_list)){
                    if($fault_right_list[0]['answer_right']==1){
                        $fault_one_score = 0;
                    }
                    if($fault_right_list[1]['answer_right']==1){
                        $fault_two_score = 0;
                    }
                    if($fault_right_list[2]['answer_right']==1){
                        $fault_three_score = 0;
                    }
                }
                    
                $fault_right_list = Db::name('real_exam_fault')->where(['exam_id'=>$ids,'flag'=>1])->select();

                //根据故障部位,查找故障现象
                $fault_arr = [$fault_right_list[0]['fault_id'],$fault_right_list[1]['fault_id'],$fault_right_list[2]['fault_id']];
                
                //根据故障部位查找，匹配的排除方法
                $paichu_arr = Report::where(['bw_id'=>['in',$fault_arr],'sim_type'=>$info['sim_type']])->column('pc_id');
                // //根据故障部位查找，匹配可能原因
                // $yy_arr = Report::where(['bw_id'=>['in',$fault_arr],'sim_type'=>$info['sim_type']])->column('yy_id');

                //查找故障现象 数组
                $partent_fault_id = Fault::where(['fault_id'=>['in',$fault_arr],'sim_type'=>$info['sim_type']])->column('parent_fault_id');

                //根据故障部位查找，匹配可能原因
                $yy_arr = Fault::where(['parent_fault_id'=>['in',$partent_fault_id],'sim_type'=>$info['sim_type'],'fault_type'=>2])->column('fault_id');

                if(!empty($other_report)){
                    foreach ($other_report as $k => $v) {
                        if(!empty($v['xx_id'])){
                            if(in_array($v['xx_id'],$partent_fault_id)){
                                //故障现象正确
                                
                                $kscore = 0;
                                //故障部位 故障部位错误
                                $buwei_id= '';
                                $paichu_id= '';
                                $yy_id = [];
                                foreach($fault_arr as $kk1 =>$va1){
                                    $fault_find = Fault::where(['fault_id'=>$va1])->find();
                                    if($fault_find['parent_fault_id']==$v['xx_id']){
                                        $buwei_id = $fault_find['fault_id'];
                                        $paichu_id = $fault_find['ref_type4_fault_id'];
                                        $yy_id = Fault::where(['parent_fault_id'=>$fault_find['parent_fault_id'],'sim_type'=>$info['sim_type'],'fault_type'=>2])->column('fault_id');
                                    }
                                }


                                if($v['bw_id']!=$buwei_id){
                                    $buwei_score = 1+$buwei_score;
                                    $kscore = 1+$kscore;
                                    $content[] = [
                                        'gzxz_id'=>$v['xx_id'],
                                        'cx_id'=>$v['bw_id'],
                                        'cx_type'=>'故障部位错写',
                                        'cx_name'=>Fault::where(['fault_id'=>$v['bw_id']])->value('name'),
                                    ];
                                }
                                //故障部位少写
                                //获取当前的故障部位
                                if($buwei_id!=$v['bw_id']){
                                    $buwei_score = 1+$buwei_score;
                                    $kscore = 1+$kscore;
                                    $content[] = [
                                        'gzxz_id'=>$v['xx_id'],
                                        'cx_id'=>$buwei_id,
                                        'cx_type'=>'故障部位少写',
                                        'cx_name'=>Fault::where(['fault_id'=>$buwei_id])->value('name'),
                                    ];
                                }
                            
                                //排除方法  错写
                                if($v['pc_id']!=$paichu_id){
                                    $buwei_score = 1+$buwei_score;
                                    $kscore = 1+$kscore;
                                    $content[] = [
                                        'gzxz_id'=>$v['xx_id'],
                                        'cx_id'=>$v['pc_id'],
                                        'cx_type'=>'排除方法错写',
                                        'cx_name'=>Fault::where(['fault_id'=>$v['pc_id']])->value('name'),
                                    ];
                                }
                                //排放方法  少写
                                if($paichu_id!=$v['pc_id']){
                                    $fangfa_score = 1+$fangfa_score;
                                    $kscore = 1+$kscore;
                                    $content[] = [
                                        'gzxz_id'=>$v['xx_id'],
                                        'cx_id'=>$v['pc_id'],
                                        'cx_type'=>'排除方法少写',
                                        'cx_name'=>Fault::where(['fault_id'=>$buwei_id])->value('name'),
                                    ];
                                }


                                //可能原因 错写
                                foreach (explode(',',$v['yy_id']) as $key => $value) {
                                    if(!in_array($value,$yy_id)){
                                        $yuanyin_socre = 1+$yuanyin_socre;
                                        $kscore = 1+$kscore;
                                        $content[] = [
                                            'gzxz_id'=>$v['xx_id'],
                                            'cx_id'=>$value,
                                            'cx_type'=>'可能原因错写',
                                            'cx_name'=>Fault::where(['fault_id'=>$value])->value('name'),
                                        ];
                                        // echo $v['xx_id']."@@@".$value."@@@".$kscore."<br/>";
                                    }
                                }
                                //可能原因 少写
                                foreach ($yy_id as $key1 => $value1) {
                                    $yy_id_arr = explode(',',$v['yy_id']);
                                    if(!in_array($value1,$yy_id_arr)){
                                        $yuanyin_socre = 1+$yuanyin_socre;
                                        $kscore = 1+$kscore;
                                        $content[] = [
                                            'gzxz_id'=>$v['xx_id'],
                                            'cx_id'=>$value1,
                                            'cx_type'=>'可能原因少写',
                                            'cx_name'=>Fault::where(['fault_id'=>$value1])->value('name'),
                                        ];
                                    }
                                }
                                
                                if($kscore>5){
                                   $kscore = '-5';
                                }else if($kscore>0){
                                    $kscore = '-'.$kscore;
                                }else{
                                   $kscore=0; 
                                }
                                $other_content[$k] = [
                                    'gzxz_id'=>$v['xx_id'],
                                    'xh_id' => $k,
                                    'xx_id' => $v['xx_id'],
                                    'xx_name' => $v['xx_name'],
                                    'yy_id' =>$v['yy_id'],
                                    'yy_name' => $v['yy_name'],
                                    'bw_id' => $v['bw_id'],
                                    'bw_name' => $v['bw_name'],
                                    'pc_id' => $v['pc_id'],
                                    'pc_name' => $v['pc_name'],
                                    'cx_type'=>'',
                                    'cx_name'=>$content,
                                    'cx_score'=>$kscore,
                                ];
                            }else{
                                $xianxian_score = 5+$xianxian_score;
                                $other_content[$k] = [
                                    'gzxz_id'=>$v['xx_id'],
                                    'xh_id' => $k,
                                    'xx_id' => $v['xx_id'],
                                    'xx_name' => $v['xx_name'],
                                    'yy_id' =>$v['yy_id'],
                                    'yy_name' => $v['yy_name'],
                                    'bw_id' => $v['bw_id'],
                                    'bw_name' => $v['bw_name'],
                                    'pc_id' => $v['pc_id'],
                                    'pc_name' => $v['pc_name'],
                                    'cx_type'=>'故障现象错写',
                                    'cx_name'=>Fault::where(['fault_id'=>$v['xx_id']])->value('name'),
                                    'cx_score'=>-5,
                                ];
                            }
                        }else{
                            $xianxian_score = 5+$xianxian_score;
                            $other_content[$k] = [
                                'gzxz_id'=>'',
                                'xh_id' => $k,
                                'xx_id' => '',
                                'xx_name' => '',
                                'yy_id' => '',
                                'yy_name' => '',
                                'bw_id' => '',
                                'bw_name' => '',
                                'pc_id' => '',
                                'pc_name' => '',
                                'cx_type'=>'未作答',
                                'cx_name'=>'',
                                'cx_score'=>-5,
                            ];
                        }
                    }
                }else{
                    foreach ($partent_fault_id as $key => $em){
                        $xianxian_score = 5+$xianxian_score;
                        $other_content[] = [
                            'gzxz_id'=>$em,
                            'xh_id' => $key,
                            'xx_id' => '',
                            'xx_name' => '',
                            'yy_id' => '',
                            'yy_name' => '',
                            'bw_id' => '',
                            'bw_name' => '',
                            'pc_id' => '',
                            'pc_name' => '',
                            'cx_type'=>'未作答',
                            'cx_name'=>'',
                            'cx_score'=>-5,
                        ];
                    }
                    unset($em);
                }
                
                
                $weixiu_score = $xianxian_score+$yuanyin_socre+$buwei_score+$fangfa_score;
                if($weixiu_score>15){
                    $weixiu_score = 15;
                }

                //是否超时
                //$info['countdown_time'] 开始时间+考试时长+10分倒计时
                $countdown_time= strtotime(date('Y-m-d H:i:s', strtotime('-10 minute',$info['countdown_time'])));
                $overtime_fen = ceil((time()-$countdown_time) / 60);
                if($overtime_fen>=10){
                    $overtime_score = 10;
                }else if($overtime_fen>0 && $overtime_fen<10){
                    $overtime_score = $overtime_fen ;
                }else{
                    $overtime_score =0;
                }
                $fault_score = $score-$fault_one_score-$fault_two_score-$fault_three_score-$weixiu_score-$overtime_score;

                //更新考试结果表
                $params['exam_id'] = $ids;
                $params['total'] = $fault_score;//得分;
                $params['fault_one_score'] = $fault_one_score;//得分;
                $params['fault_two_score'] = $fault_two_score;//得分;
                $params['fault_three_score'] = $fault_three_score;//得分;

                $params['xianxian_score'] = $xianxian_score;//得分;
                $params['xianxian_content'] = json_encode($xianxian_content);//错题;

                $params['yuanyin_socre'] = $yuanyin_socre;//得分;
                $params['yuanyin_content'] = json_encode($yuanyin_content);//错题;

                $params['buwei_score'] = $buwei_score;//得分;
                $params['buwei_content'] = json_encode($buwei_content);//错题;

                $params['fangfa_score'] = $fangfa_score;//得分;
                $params['fangfa_content'] = json_encode($fangfa_content);//错题;

                $params['other_jielun'] = json_encode($other_content);//每个答题的得分
//                
                $params['overtime_score'] = $overtime_score;//得分;
                Db::name('real_exam_score')->insert($params);

                $this->exam_model->where(['exam_id'=>$ids])->update(['total_score'=>$fault_score]);

                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error(__('No rows were inserted'));
            }

            $this->success('交卷成功','/admin/student/exercise/analysis/ids/'.$row['exam_id']);
        }
        $isloading =1;
        if(empty($row->other_replace)){
            $isloading = 0;
            $row->other_replace = '[{"fault_id":"","request_status":"0"}]';
        }
        $row->other_report_text = !empty($row->other_report) ? json_decode($row->other_report,true) : [];

        $row->limit_duration = $this->model->where(['exam_collection_id'=>$row['exam_collection_id']])->value('limit_duration');
        if(empty($row->starttime)){
            $timer = 60*$row->limit_duration;
        }else{
            $timer = $row->limit_duration*60 - abs(time() - $row->starttime);
        }
        if(empty($row->countdown_time)){
            $duration = 10+$row->limit_duration;
            $this->exam_model->where('exam_id',$ids)->update(['countdown_time'=>strtotime(date('Y-m-d H:i:s', strtotime('+'.$duration.' minute',$row->starttime)))]);
        }

        $departmentdata = [];
        $departmentdata = Fault::where(['replace_part'=>1,'sim_type'=>$row->sim_type])->order('fault_id asc')->select();


        $this->view->assign('departmentdata', $departmentdata);
        //故障现象
        $xianxiang = Fault::where(['fault_type'=>1,'sim_type'=>$row->sim_type])->select();
        $this->view->assign('xianxiang', $xianxiang);

        $row->replace_list =Db::name('real_exam_comp_request')->where(['exam_id'=>$ids])->select();
        $this->assignConfig('ids',$ids);
        $this->assignConfig('timer',$timer);
        $this->assignConfig('isloading',$isloading);

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    public function analysis($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            //计算总分到学员考试表
            $this->success('操作成功','/admin/student/exercise/index');
        }
        $row = Db::name('real_exam_score')->where('exam_id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $rows = $this->exam_model->get($ids);
        $row['seat_id'] = $rows->seat_id;
        $row['user_nickname'] = $rows->user_nickname;
        $row['user_username'] = $rows->user_username;
        $row['user_depart_id'] = $rows->user_depart_id;
        $row['user_depart_name'] = Department::where('id',$rows->user_depart_id)->value('name');
        $row['start_time'] = $rows->start_time;
        $row['end_time'] = $rows->end_time;


        $fault_list = Db::name('real_exam_fault')->where(['exam_id'=>$ids,'flag'=>1])->select();
        $row['fault_name_one'] = !empty($fault_list[0]['fault_id']) ? Fault::where('fault_id',$fault_list[0]['fault_id'])->value('name'):'';
        $row['fault_name_two'] = !empty($fault_list[1]['fault_id']) ? Fault::where('fault_id',$fault_list[1]['fault_id'])->value('name'):'';
        $row['fault_name_three'] = !empty($fault_list[2]['fault_id']) ? Fault::where('fault_id',$fault_list[2]['fault_id'])->value('name'):'';

        $row['fault_score'] = 75-$row['fault_one_score']-$row['fault_two_score']-$row['fault_three_score'];


        $row['weixiu_score'] = 10-$row['overtime_score']??0; 

        $diffInSeconds = $rows['endtime'] - $rows['starttime']; // 两个时间戳之间的差异（秒）
        $minutes = floor($diffInSeconds / 60); // 计算分钟数
        $seconds = $diffInSeconds % 60; // 计算剩余的秒数
        $row['shijian'] = $minutes.'分'.$seconds.'秒';
        
        $other_jielun = !empty($row['other_jielun']) ? json_decode($row['other_jielun'],true):[];


        $koufen = 0;
        foreach ($other_jielun as $key => $value) {
            if(!empty($value['cx_score'])){
                $koufen = $koufen+abs($value['cx_score']);
            }
        }
        $report_score = 15-$koufen;
        $row['report_score'] = $report_score>0?$report_score:0; 


        $total = $row['fault_score']+$row['report_score']+$row['weixiu_score'];
        Db::name('real_exam_score')->where('exam_id', $ids)->update(['total'=>$total]);
        Db::name('real_exam')->where('exam_id', $ids)->update(['total_score'=>$total]);

        $row['total'] = $total;

        
        $this->view->assign('other_jielun', $other_jielun);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

}
