<?php

namespace app\admin\controller\teacher;

use app\admin\model\Fault;
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;
use app\admin\model\teacher\Exams;
use app\admin\model\teacher\ExamsScore;
/**
 * sim-练习集合管理
 *
 * @icon fa fa-circle-o
 */
class Practice extends Backend
{

    protected $noNeedRight = ['score'];
    /**
     * 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->assign('sim_sim_type', ConfigModel::getSimTypeList());
        $this->assign('sim_question_setting_method', ConfigModel::getSimQuestionList());

        $this->whereExtend['exam_collection_type'] = 1;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if(empty($params['depart_ids'])){
            $this->error('请选择区队名称');
        }
        if(!empty($params['question_setting_method'])){
            if($params['question_setting_method']==2 && empty($params['question_ids'])){
                $this->error('出题方式为考题自选，请选择考题');
            }
            if($params['question_setting_method']==3 && empty($params['task_id'])){
                $this->error('出题方式为任务自选，请选择任务');
            }
        }

        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            $depart_ids = $params['depart_ids'];
            if($params['question_setting_method']==3 && !empty($params['fault_name'])){
                $params['question_name'] = $params['fault_name'];
                unset($params['fault_name']);
            }
            $result = $this->model->allowField(true)->save($params);
            foreach(explode(',',$depart_ids) as $item){
                if(!empty($item)){
                    $arr = [
                        'exam_collection_id' => $this->model->exam_collection_id,
                        'dept_id' => $item,
                        'update_time' => date('Y-m-d H:i:s'),
                    ];
                    Db::name('real_exam_collection_dept')->insert($arr);
                }
            }

            //匹配的学员自动加入  mx_real_exam 考试表  总分
            $admin_list = Db::name('admin')->where('depart_id','in',$depart_ids)->select();
            foreach ($admin_list as $it){
                $arr1 = [
                    'exam_collection_id' => $this->model->exam_collection_id,
                    'exam_collection_name' => $params['exam_collection_name'],
                    'exam_collection_type' => $params['exam_collection_type'],
                    'sim_type' => $params['sim_type'],
                    'user_username' => $it['username'],
                    'user_nickname' => $it['nickname'],
                    'user_id' => $it['id'],
                    'user_depart_id' => $it['depart_id'],
                    'create_time'=>date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                ];
                $examid = Db::name('real_exam')->insertGetId($arr1);
                //匹配的学员自动加入  mx_real_exam_fault 考试故障关联表
                $fault_list = Fault::where(['sim_type' => $params['sim_type'], 'fault_state' => 0,'fault_type'=>3])->select();
                if($params['question_setting_method']==1){ //系统随机
                    $fault_key1 = rand(0, 1);
                    $fault_key2 = rand(2, 3);
                    $fault_key3 = rand(4, 5);
                    $fault_key = [$fault_key1,$fault_key2,$fault_key3];
                    // $fault_key = array_rand($fault_list, 3);
                    // $fault_key = $this->rand_fault($fault_list);
                }else if($params['question_setting_method']==2){//教师自选
                    $question_ids = $params['question_ids'];
                }else if($params['question_setting_method']==3){ //任务自选
                    $task_ids = Db::name('task_fault')->where(['task_id'=>['in',$params['task_id']]])->column('fault_id');
                }
                foreach ($fault_list as $key=> $item1){
                    $flag = 0;
                    if(!empty($fault_key) && in_array($key,$fault_key)){
                        $flag = 1;
                    }
                    if(!empty($question_ids) && in_array($item1['fault_id'],explode(',',$question_ids))){
                        $flag = 1;
                    }
                    if(!empty($task_ids) && in_array($item1['fault_id'],$task_ids)){
                        $flag = 1;
                    }
                    $add= [
                        'exam_id'=>$examid,
                        'fault_id'=>$item1['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($item1);

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

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->assignConfig('row_info', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if(!empty($params['question_setting_method'])){
            if($params['question_setting_method']==2 && empty($params['question_ids'])){
                $this->error('出题方式为考题自选，请选择考题');
            }
            if($params['question_setting_method']==3 && empty($params['task_id'])){
                $this->error('出题方式为任务自选，请选择任务');
            }
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $depart_ids = $params['depart_ids'];
            if($params['question_setting_method']==3 && !empty($params['fault_name'])){
                $params['question_name'] = $params['fault_name'];
                unset($params['fault_name']);
            }
            $result = $row->allowField(true)->save($params);

            Db::name('real_exam_collection_dept')->where(['exam_collection_id'=>$row->exam_collection_id])->delete();
            foreach(explode(',',$depart_ids) as $item){
                if(!empty($item)){
                    $arr = [
                        'exam_collection_id' => $row->exam_collection_id,
                        'dept_id' => $item,
                        'update_time' => date('Y-m-d H:i:s'),
                    ];
                    Db::name('real_exam_collection_dept')->insert($arr);
                }
            }

            Db::name('real_exam')->where(['exam_collection_id'=>$row->exam_collection_id,'starttime'=>0])->delete();
            //匹配的学员自动加入  mx_real_exam 考试表  总分
            $admin_list = Db::name('admin')->where('depart_id','in',$depart_ids)->select();
            foreach ($admin_list as $it){
                $real_exam = Db::name('real_exam')->where(['exam_collection_id'=>$row->exam_collection_id,'user_id'=>$it['id']])->find();
                if(empty($real_exam)){
                    $arr1 = [
                        'exam_collection_id' => $row->exam_collection_id,
                        'exam_collection_name' => $params['exam_collection_name'],
                        'exam_collection_type' => $row['exam_collection_type'],
                        'sim_type' => $params['sim_type'],
                        'user_username' => $it['username'],
                        'user_nickname' => $it['nickname'],
                        'user_id' => $it['id'],
                        'user_depart_id' => $it['depart_id'],
                        'create_time'=>date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s'),
                    ];
                    $examid = Db::name('real_exam')->insertGetId($arr1);
                    //匹配的学员自动加入  mx_real_exam_fault 考试故障关联表
                    $fault_list = Fault::where(['sim_type' => $params['sim_type'], 'fault_state' => 0,'fault_type'=>3])->select();
                    if($params['question_setting_method']==1){ //系统随机
                        $fault_key1 = rand(0, 1);
                        $fault_key2 = rand(2, 3);
                        $fault_key3 = rand(4, 5);
                        $fault_key = [$fault_key1,$fault_key2,$fault_key3];
                        // $fault_key = array_rand($fault_list, 3);
                        // $fault_key = $this->rand_fault($fault_list);
                    }else if($params['question_setting_method']==2){//教师自选
                        $question_ids = $params['question_ids'];
                    }else if($params['question_setting_method']==3){ //任务自选
                        $task_ids = Db::name('task_fault')->where(['task_id'=>['in',$params['task_id']]])->column('fault_id');
                    }
                    Db::name('real_exam_fault')->where(['exam_id'=>$examid])->delete();

                    foreach ($fault_list as $key=> $item1){
                        $flag = 0;
                        if(!empty($fault_key) && in_array($key,$fault_key)){
                            $flag = 1;
                        }
                        if(!empty($question_ids) && in_array($item1['fault_id'],explode(',',$question_ids))){
                            $flag = 1;
                        }
                        if(!empty($task_ids) && in_array($item1['fault_id'],$task_ids)){
                            $flag = 1;
                        }
                        $add= [
                            'exam_id'=>$examid,
                            'fault_id'=>$item1['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($item1);
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            //删除考试集合  mx_real_exam_collection
            foreach ($list as $item) {
                if($item['yikao_count']>0){
                    $this->error('已有学生参加考试，无法删除');
                }
                $count += $item->delete();
            }
            //删除学员考试 mx_real_exam
            $exam_list = $this->exam_model->where('exam_collection_id',$ids)->select();
            if(!empty($exam_list)){
                foreach ($exam_list as $k=>$it)
                {
                    //删除学员考试故障表 mx_real_exam_fault
                    Db::name('real_exam_fault')->where('exam_id',$it['exam_id'])->delete();
                    $it->delete();
                }

            }
            //删除考试关联区队表 mx_real_exam_collection_dept
            Db::name('real_exam_collection_dept')->where('exam_collection_id',$ids)->delete();


            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }




    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = true ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
//        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        if(!empty($values['exam_collection_state'])){
            //开始考试集合
            if($values['exam_collection_state']==2){
                //触发Java端后台的接口数据，
                //dev-api/sim/real-exam-collection/teacher/exam/open/{examcollectionId}  $ids  put
                if(Env::get('app.is_fault')){
                    $url = config('site.url_type').'/sim/real-exam-collection/teacher/exam/open/'.$ids;
                    $ret = json_decode(send_post($url),true);
                    if($ret['code']!=200){
                        $this->error($ret['msg']);
                    }
                }else{
//                    $state_count = $this->model->where(['exam_collection_state'=>$values['exam_collection_state'],'exam_collection_type'=>1])->count();
//                    if($state_count>0){
//                        $this->error('已有启用的考试，请先关闭原来的考试');
//                    }
                }
                $count = 1;
            }
            //关闭
            if($values['exam_collection_state']==3){
                //触发Java端后台的接口数据，
                //dev-api/sim/real-exam-collection/teacher/exam/open/{examcollectionId}  $ids  put
                if(Env::get('app.is_fault')){
                    $url = config('site.url_type').'/sim/real-exam-collection/teacher/exam/close/'.$ids;
                    $ret = json_decode(send_post($url),true);
                    if($ret['code']!=200){
                        $this->error($ret['msg']);
                    }
                }
                $count = 1;
            }
        }

        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }
    public function persent($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->assignConfig('ids', $ids);
            return $this->view->fetch();
        }
        $exam_ids = $this->exam_model->where('exam_collection_id',$ids)->column('exam_id');
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = Db::name('real_exam_comp_request')
            ->where($where)->where('exam_id','in',$exam_ids)
            ->order($sort, $order)
            ->paginate($limit);
        unset($v);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function examing($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->assignConfig('ids', $ids);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $sim_type = Db::name('real_exam_collection')->where('exam_collection_id',$ids)->value('sim_type');
        $list = Db::name('seat')->select();
        foreach ($list as $key => $value) {
            $sim = Db::name('sim')->where('seat_id',$value['seat_id'])->where('sim_type',$sim_type)->find();
            if(!empty($sim['sim_state'])){
                switch ($sim['sim_state']) {
                    case '1':
                        $sim_state = '在线';
                        break;
                    case '2':
                        $sim_state = '离线';
                        break;
                    default:
                        $sim_state = '';
                        break;
                }
            }else{
                $sim_state = '';
            }
            $exam = $this->exam_model->where('exam_collection_id',$ids)->order('exam_id desc')->where('seat_id',$value['seat_id'])->find();
            $user_username = '';
            $user_nickname = '';
            $exam_status = '未登录';
            $total_score = 0;
            $fault_names = '';
            $exam_id = 0;
            if(!empty($exam)){
                $user_username = $exam['user_username']??'';
                $user_nickname = $exam['user_nickname']??'';
                if($exam['exam_status']==1){
                    $exam_status= '已登录未开始考试';
                }else if($exam['exam_status']==4){
                    $exam_status= '已开始考试';
                }else if($exam['exam_status']==5){
                    $exam_status= '已交卷';
                }
                $total_score = $exam['total_score']??'';
                $fault_names = $exam['fault_names']??'';
                $exam_id = $exam['exam_id']??0;
            }
            $list[$key]['user_username'] = $user_username;
            $list[$key]['user_nickname'] = $user_nickname;
            $list[$key]['exam_status'] = $exam_status;
            $list[$key]['total_score'] = $total_score;
            $list[$key]['fault_names'] = $fault_names;
            $list[$key]['exam_id'] = $exam_id;
            $list[$key]['sim_state'] = $sim_state;
        }
        $result = ['total' => count($list), 'rows' => $list];
        return json($result);
    }

    public function score($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->assignConfig('ids', $ids);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $exam_ids = $this->exam_model->where('exam_collection_id',$ids)->column('exam_id');
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = ExamsScore::where($where)->where('exam_id','in',$exam_ids)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as $k => $v){
            $exam =  $this->exam_model->where(['exam_id'=>$v['exam_id']])->find();
            if($exam){
                $v->seat_id = $exam['seat_id'];
                $v->user_username = $exam['user_username'];
                $v->user_nickname = $exam['user_nickname'];
            }
        }
        unset($v);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    public function rand_fault($fault_list = null){

        // $fault_key = array_rand($fault_list,3);
        // $fault_key1 = array_rand($fault_list);
        // $fault_key2 = array_rand($fault_list);
        // $fault_key3 = array_rand($fault_list);
        // if($fault_list[$fault_key1]['parent_fault_id']==$fault_list[$fault_key2]['parent_fault_id']){
        //     $fault_key2 = array_rand($fault_list);
        // }
        // if($fault_list[$fault_key2]['parent_fault_id']==$fault_list[$fault_key3]['parent_fault_id']){
        //     $fault_key3 = array_rand($fault_list);
        // }
        // $arr = [$fault_key1,$fault_key2,$fault_key3];
        $arr = [1,5,7];
        return $arr;
    }

//    public function start($ids = null){
////        $row = $this->model->get($ids);
////        if (!$row) {
////            $this->error(__('No Results were found'));
////        }
////        $params['starttime'] = time();
////        $result = $row->allowField(true)->save($params);
//        $this->success('开始成功');
//    }
}
