<?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 Practice 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->assignConfig('sim_sim_type', ConfigModel::getSimTypeList());
        $this->assignConfig('sim_question_setting_method', ConfigModel::getSimQuestionList());

        $this->whereExtend['exam_collection_type'] = 1;//练习
        $this->whereExtend['exam_collection_state'] = 2;
    }



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

    public function index()
    {
        $isset = $this->model->alias('z')
            ->join('real_exam r','z.exam_collection_id=r.exam_collection_id','left')
            ->where('z.exam_collection_type=1 and z.exam_collection_state=2  and r.endtime=0 and r.user_id='.$this->auth->id)->find();

        if(empty($isset)){
            //提示页面，没有开始的考试
            return $this->view->fetch('tishi');
        }else{
////             $this->redirect('/ZQOtIMLKud.php/student/collection/examing/ids/'.$isset['exam_id'].'?ref=addtabs');
//            echo "<script>location.href='/ZQOtIMLKud.php/student/collection/examing/ids/".$isset['exam_id']."';</script>";
//            //$this->redirect('/hotelmanage/room/displayindex/ids/1');
//            exit();
            echo "<script>location.href='/ZQOtIMLKud.php/student/practice/into/ids/".$isset['exam_collection_id']."'</script>";
        }
        die();

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)->where($this->whereExtend)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as $k => $v){
            $exam_isset =  $this->exam_model->where(['user_id'=>$this->auth->id,'exam_collection_id'=>$v['exam_collection_id'],'exam_collection_type'=>1])->find();
            if(isset($exam_isset)){
                $v->is_user_examed = 1;
            }else{
                $v->is_user_examed = 0;
            }
        }
        unset($v);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    //进入考试
    public function  into($ids = null)
    {
        $row = $this->model->get($ids);
        if(!$row){
            $this->error('未找到记录');
        }
        $info = $this->exam_model->where(['user_id'=>$this->auth->id,'exam_collection_id'=>$ids])->find();
        if(empty($info)){
            $arr = [
                'exam_collection_id' => $ids,
                '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' => $row->exam_collection_name,
                'exam_collection_type' =>1,
                'sim_type' => $row->sim_type,
                'seat_id' => 1,
                'sim_id' => 12,
            ];
            $this->exam_model->save($arr);
        }
        if(!empty($info['starttime']))
        {
            echo "<script>location.href='/ZQOtIMLKud.php/student/practice/examing/ids/".$info['exam_id']."'</script>";
            die();
        }
//        if ($this->request->isPost()) {
//            $exam_collection_id = $this->request->post('exam_collection_id');
//            if(empty($info->starttime)){
//                $info->start_time = date('Y-m-d H:i:s');
//                $info->starttime = time();
//            }
//            $info->exam_status = 4;
//            $info->save();
//            $this->success('开始成功','/ZQOtIMLKud.php/student/practice/examing/ids/'.$info['exam_id']);
//        }
        $this->assignConfig('exam_id', $info['exam_id']);
        $this->assignConfig('url_type', config('site.url_type'));
        $this->assignConfig('is_fault', Env::get('app.is_fault'));
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    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/exam/submit/'.$ids;
                // /dev-api/sim/real-exam/student/exam/submit/{examId}
                $ret = json_decode(send_get($url),true);
                // halt($ret);
                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 = [];


            Db::startTrans();
            try {

                //更新考试结束时间
                $row->end_time = date('Y-m-d H:i:s');
                $row->endtime = time();
                $row->exam_status = 5;
                $row->other_report = $params['other_report'];
                $result = $row->save();

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

                //更新故障是否正确
                $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 = 0;
                        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;
                            }else{
                                $answer_right=2;
                            }
                        }
                        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]])->column('pc_id');
                //根据故障部位查找，匹配可能原因
                $yy_arr = Report::where(['bw_id'=>['in',$fault_arr]])->column('yy_id');

                $partent_fault_id = Fault::where(['fault_id'=>['in',$fault_arr]])->column('parent_fault_id');

                //获取数组
                $other_report = json_decode($params['other_report'],true);
                if(!empty($other_report)){
                    foreach ($other_report as $key => $em){
                        //故障现象
                        $xianxian_arr[] = $em['xx_id'];
                        //故障部位
                        $buwei_arr[] = $em['bw_id'];
                        //可能原因
                        $yuanyin_arr[] = $em['yy_id'];
                        //排除方法
                        $fangfa_arr[] = $em['pc_id'];
                    }
                }
                
                //故障现象 分数 start
                foreach ($partent_fault_id as $k1 =>$t){
                    if(!in_array($t,$xianxian_arr)){
                        $xianxian_score = 1+$xianxian_score;
                        $xianxian_content[] = [
                            'cx_id'=>$t,
                            'cx_type'=>'少写',
                            'cx_name'=>Fault::where(['fault_id'=>$t])->value('name'),
                        ];
                    }
                }
                foreach ($xianxian_arr as $k2 =>$t2){
                    if(!in_array($t2,$partent_fault_id)){
                        $xianxian_score = 1+$xianxian_score;
                        $xianxian_content[] = [
                            'cx_id'=>$t2,
                            'cx_type'=>'错写',
                            'cx_name'=>Fault::where(['fault_id'=>$t2])->value('name'),
                        ];
                    }
                }
                //故障现象 end
              
                
                //故障部位 start
                foreach ($fault_arr as $k11 =>$t11){
                    if(!in_array($t11,$buwei_arr)){
                        $buwei_score = 1+$buwei_score;
                        $buwei_content[] = [
                            'cx_id'=>$t11,
                            'cx_type'=>'少写',
                            'cx_name'=>Fault::where(['fault_id'=>$t11])->value('name'),
                        ];
                    }
                }
                foreach ($buwei_arr as $k12 =>$t12){
                    if(!empty($t12) && !in_array($t12,$fault_arr)){
                        //错写
                        $buwei_score = 1+$buwei_score;
                        $buwei_content[] = [
                            'cx_id'=>$t12,
                            'cx_type'=>'错写',
                            'cx_name'=>Fault::where(['fault_id'=>$t12])->value('name'),
                        ];
                    }
                }
                //故障部位 end
                
                //排除方法 start
                //循环固定的排除方法，匹配作答的排除方法
                foreach ($paichu_arr as $k21 =>$t21){
                    if(!in_array($t21,$fangfa_arr)){
                        $fangfa_score = 1+$fangfa_score;
                        $fangfa_content[] = [
                            'cx_id'=>$t21,
                            'cx_type'=>'少写',
                            'cx_name'=>Fault::where(['fault_id'=>$t21])->value('name'),
                        ];
                    }
                }
                //循环作答的排除方法，，匹配固定的排除方法
                foreach ($fangfa_arr as $k22 =>$t22){
                    if(!empty($t22) && !in_array($t22,$paichu_arr)){
                        $fangfa_score = 1+$fangfa_score;
                        $fangfa_content[] = [
                            'cx_id'=>$t22,
                            'cx_type'=>'错写',
                            'cx_name'=>Fault::where(['fault_id'=>$t22])->value('name'),
                        ];
                    }
                }
                //排除方法 end

                //可能原因 start
                //循环固定的可能原因，匹配作答的可能原因
                foreach ($yy_arr as $k31 =>$t31){
                    if(!in_array($t31,$yuanyin_arr)){
                        $yuanyin_socre = 1+$yuanyin_socre;
                        $yuanyin_content[] = [
                            'cx_id'=>$t31,
                            'cx_type'=>'少写',
                            'cx_name'=>Fault::where(['fault_id'=>$t31])->value('name'),
                        ];
                    }
                }
                //循环作答的排除方法，，匹配固定的排除方法
                foreach ($yuanyin_arr as $k32 =>$t32){
                    if(!empty($t32) && !in_array($t32,$yy_arr)){
                        $yuanyin_socre = 1+$yuanyin_socre;
                        $yuanyin_content[] = [
                            'cx_id'=>$t32,
                            'cx_type'=>'错写',
                            'cx_name'=>Fault::where(['fault_id'=>$t32])->value('name'),
                        ];
                    }
                }
                //可能原因 end

                $weixiu_score = $xianxian_score+$yuanyin_socre+$buwei_score+$fangfa_score;
                if($weixiu_score>15){
                    $weixiu_score = 15;
                }

                //是否超时
                $overtime_fen = intval((time()-$info['endtime']) / 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['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('交卷成功','/ZQOtIMLKud.php/student/practice/analysis/ids/'.$row['exam_id']);
        }


        if(empty($row->starttime)){
            $row->start_time = date('Y-m-d H:i:s');
            $row->starttime = time();
            $row->exam_status = 4;
            $row->save();
        }
        $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);
        }

        $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('操作成功','/ZQOtIMLKud.php/student/practice/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['xianxian_content_name'] = '';
        if(!empty($row['xianxian_content']))
        {
            $row['xianxian_content_name'] = json_decode($row['xianxian_content'],true);
        }
        $row['yuanyin_content_name'] = '';
        if(!empty($row['yuanyin_content']))
        {
            $row['yuanyin_content_name'] = json_decode($row['yuanyin_content'],true);
        }
        $row['buwei_content_name'] = '';
        if(!empty($row['buwei_content']))
        {
            $row['buwei_content_name'] = json_decode($row['buwei_content'],true);
        }
        $row['fangfa_content_name'] = '';
        if(!empty($row['fangfa_content']))
        {
            $row['fangfa_content_name'] = json_decode($row['fangfa_content'],true);
        }


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

}
