<?php

namespace app\admin\controller\student;

use app\common\controller\Backend;
use app\common\model\Config as ConfigModel;
use app\admin\model\Report;
use app\admin\model\Fault;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use think\Db;
/**
 * sim-考试集合管理
 *
 * @icon fa fa-circle-o
 */
class Collection 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'] = 3;
        $this->whereExtend['exam_collection_state'] = 2;
        $this->assignConfig('sim_sim_type', ConfigModel::getSimTypeList());

        $groupIds = $this->auth->getGroupIds();
        //学员查看自己区队的考试集合
        if(in_array(8, $groupIds)){
            $departid = $this->auth->depart_id;
            $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($departid,depart_ids)")];
        }
    }



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

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    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=3 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();
       }
        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'=>3,'endtime'=>['>',0]])->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' => 3,
                'sim_type' => $row->sim_type,
                'seat_id' => 1,
                'sim_id' => intval($row->sim_type),
            ];
            $this->exam_model->save($arr);

            //考试和故障关联表
            $fault_list = Fault::where(['sim_type' => $row->sim_type, 'fault_state' => 0,'fault_type'=>3])->select();
            $fault_key = array_rand($fault_list, 3);
            foreach ($fault_list as $key=> $item){
                $flag = 0;
                if(in_array($key,$fault_key)){
                    $flag = 1;
                }
                $add= [
                    'exam_id'=>$this->exam_model->exam_id,
                    'fault_id'=>$item->fault_id,
                    'ref_type'=>2,
                    'flag'=>$flag,
                    'ref_state'=>3,
                    'sim_fault_question_value'=>'0000000'.rand(1,2),
                    '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);
            }
            unset($item);
        }
        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/collection/examing/ids/'.$info['exam_id']);
        }
        $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()) {
            //计算分数，保存记录
            $params = $this->request->post('row/a');

            $result = false;
            $score = 100;
            $fault_one_score = 0;
            $fault_two_score = 0;
            $fault_three_score = 0;
            $xianxian_score = 0;
            $yuanyin_socre= 0;
            $buwei_score= 0;
            $fangfa_score= 0;
            $jielun_score = 0;
            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();

                //更新考试关联表，计算得分 mx_real_exam_fault
                $fault_list = Db::name('real_exam_fault')->where(['exam_id'=>$ids,'flag'=>1])->select();
                foreach ($fault_list as $it)
                {
                    $update['sim_fault_answer_value'] ='0000000'.rand(1,2);
                    if($update['sim_fault_answer_value']==$it['sim_fault_question_value']){
                        $update['answer_right'] = 1;
                    }else{
                        $update['answer_right'] = 2;
                    }
                    Db::name('real_exam_fault')->where('ref_id',$it['ref_id'])->update($update);
                }
                unset($it);

                //计算得分，故障是否有扣分  扣分制
                $fault_right_list = Db::name('real_exam_fault')->where(['exam_id'=>$ids,'flag'=>1,'answer_right'=>['>',0]])->select();
                if($fault_right_list[0]['answer_right']==2){
                    $fault_one_score = 25;
                }
                if($fault_right_list[1]['answer_right']==2){
                    $fault_two_score = 25;
                }
                if($fault_right_list[2]['answer_right']==2){
                    $fault_three_score = 25;
                }
                $xianxian_score = rand(1,3);
                $yuanyin_socre= rand(1,3);
                $buwei_score= rand(1,3);
                $fangfa_score= rand(1,3);
                if(empty($params['other_jielun'])){
                    $jielun_score = rand(1,3);
                }
                //是否超时
                $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-$xianxian_score-$yuanyin_socre-$buwei_score-$fangfa_score-$jielun_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['yuanyin_socre'] = $yuanyin_socre;//得分;
                $params['buwei_score'] = $buwei_score;//得分;
                $params['fangfa_score'] = $fangfa_score;//得分;
                $params['jielun_score'] = $jielun_score;//得分;
                $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/exam/index');
        }


        //还未开始考试
        $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{
            $fen =  $row->limit_duration - intval((time()-$row->starttime) / 60);
            $timer = 60*$fen;
        }

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

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

        //更换件数据
        $this->view->assign('departmentdata', $departmentdata);

        //故障现象
        $xianxiang = Fault::where(['fault_type'=>1,'sim_type'=>$row->sim_type])->select();
        $this->view->assign('xianxiang', $xianxiang);
        //可能原因
        $yuanyin = Fault::where(['fault_type'=>2,'sim_type'=>$row->sim_type])->select();
        $this->view->assign('yuanyin', $yuanyin);
        //故障部位
        $buwei = Fault::where(['fault_type'=>3,'sim_type'=>$row->sim_type])->select();
        $this->view->assign('buwei', $buwei);
        //排除方法
        $paichu = Fault::where(['fault_type'=>4,'sim_type'=>$row->sim_type])->select();
        $this->view->assign('paichu', $paichu);

        return $this->view->fetch();
    }


    public function replace($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('other_replace','');
            $param = json_decode($params,true);
            if(!empty($param)){
                foreach ($param as $key=>$item){
                    $isreplace = Db::name('real_exam_comp_request')->where(['exam_id'=>$ids,'fault_id'=>$item['fault_id']])->find();
                    if(empty($isreplace)){
                        $add = [
                            'exam_id'=>$ids,
                            'fault_id'=>$item['fault_id'],
                            'request_status'=>1,
                            'fault_name'=>Db::name('fault')->where('fault_id',$item['fault_id'])->value('replace_name'),
                            'create_by_user_id'=>$this->auth->id,
                            'create_by'=>$this->auth->nickname,
                            '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_comp_request')->insert($add);
                        $status = 1;
                    }else{
                        $status = $isreplace['request_status'];
                    }
                    $faultid_arr[] = [
                        'fault_id'=>$item['fault_id'],
                        'request_status'=>$status,
                    ];
                }
                unset($item);
                $row = $this->exam_model->get($ids);
                $row-> other_replace = json_encode($faultid_arr);
                $result = $row->save();
            }
            $this->success('申请成功,待老师审批');
        }
    }


    public function analysis($ids = null)
    {
        $row = $this->exam_model->get($ids);
        if(!$row){
            $this->error('未找到记录');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            //计算总分到学员考试表
            $this->success('操作成功','/ZQOtIMLKud.php/student/collection/index');
        }
        return $this->view->fetch();
    }
}
