<?php

namespace app\admin\controller\teacher;

use app\admin\model\department\Department;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\teacher\ExamsScore;
use app\admin\model\Fault;
use app\admin\model\Report;
/**
 * sim-考试表/成绩总分
 *
 * @icon fa fa-circle-o
 */
class Exams extends Backend
{

    /**
     * Exams模型对象
     * @var \app\admin\model\teacher\Exams
     */
    protected $model = null;
    protected $whereExtend = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\teacher\Exams;
        $this->whereExtend['exam_collection_type'] = 3;
        $this->whereExtend['starttime'] = ['>',0];
        $this->whereExtend['endtime'] = ['>',0];

        $this->relationtTable = 'collection';
    }



    /**
     * 默认生成的控制器所继承的父类中有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();
        }
        //如果发送的来源是 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);
        //最高分 最低分 平均分
        $select = $this->model->where($where)->where($this->whereExtend)->field('count(*) as count,sum(total_score) as totalscore,min(total_score) as min,max(total_score) as max')->select();
        $pingfen  = '';
        if(!empty($select[0]['totalscore']) && !empty($select[0]['count'])){
            $pingfen  = bcdiv($select[0]['totalscore'],$select[0]['count']);
        }
        $defen = ['max'=>$select[0]['max'],'min'=>$select[0]['min'],'pingfen'=>$pingfen];
        $one_static = [];
        $two_static = [];
        $three_static = [];
        $where_falut = ['fault_type' => 3,'fault_state'=>0];
        $exam_ids = $this->model->where($where)->where($this->whereExtend)->column('exam_id');
        foreach ($list as $k => $val){
            $one = Fault::where(['sim_type'=>'0001'])->where($where_falut)->field('fault_id,name')->select();
            if($val['sim_type']=='0001'){
                foreach ($one as $k1 => $val1){
                    //先查分配次数,在查错误率
                    $one_total = Db::name('real_exam_fault')->where(['flag'=>1,'exam_id'=>['in',$exam_ids],'fault_id'=>$val1['fault_id']])->count();
                    $error_total = Db::name('real_exam_fault')->where(['flag'=>1,'exam_id'=>['in',$exam_ids],'fault_id'=>$val1['fault_id'],'answer_right'=>2])->count();
                    $one[$k1]['epercent'] = '';
                    if($one_total>0){
                        $bili = bcmul(bcdiv($error_total,$one_total,2),100);
                        $one[$k1]['epercent'] = $bili>0 ? $bili.'%' : '';
                    }
                }
                $one_static = $one;
            }
            $two = Fault::where(['sim_type'=>'0002'])->where($where_falut)->field('fault_id,name')->select();
            if($val['sim_type']=='0002'){
                foreach ($two as $k2 => $val2){
                    $two_total = Db::name('real_exam_fault')->where(['flag'=>1,'exam_id'=>['in',$exam_ids],'fault_id'=>$val2['fault_id']])->count();
                    $error_total = Db::name('real_exam_fault')->where(['flag'=>1,'exam_id'=>['in',$exam_ids],'fault_id'=>$val2['fault_id'],'answer_right'=>2])->count();
                    $two[$k2]['epercent'] = '';
                    if($two_total>0){
                        $bili = bcmul(bcdiv($error_total,$two_total,2),100);
                        $two[$k2]['epercent'] = $bili>0 ? $bili.'%' : '';
                    }
                }
            }
            $two_static = $two;
            $three = Fault::where(['sim_type'=>'0003'])->where($where_falut)->field('fault_id,name')->select();
            if($val['sim_type']=='0003'){
                foreach ($three as $k3 => $val3){
                    $three_total = Db::name('real_exam_fault')->where(['flag'=>1,'exam_id'=>['in',$exam_ids],'fault_id'=>$val3['fault_id']])->count();
                    $error_total = Db::name('real_exam_fault')->where(['flag'=>1,'exam_id'=>['in',$exam_ids],'fault_id'=>$val3['fault_id'],'answer_right'=>2])->count();
                    $three[$k3]['epercent'] = '';
                    if($three_total>0){
                        $bili = bcmul(bcdiv($error_total,$three_total,2),100);
                        $three[$k3]['epercent'] = $bili>0 ? $bili.'%' : '';
                    }
                }
            }
            $three_static = $three;
        }
        //统计错误率
        $statistics = [
            'one_static' => $one_static,
            'two_static' => $two_static,
            'three_static' => $three_static,
        ];
        $result = ['total' => $list->total(), 'rows' => $list->items(),'defen'=>$defen,'tongji'=>$statistics];
        return json($result);
    }



    public function edit($ids = null)
    {
        $row = Db::name('real_exam_score')->where('exam_id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $rows = $this->model->get($ids);
        $row['seat_id'] = $rows->seat_id;
        $row['user_nickname'] = $rows->user_nickname;
        $row['user_username'] = $rows->user_username;
        $row['is_sure'] = $rows->is_sure;


        $fault_list = Db::name('real_exam_fault')->where(['exam_id'=>$ids,'flag'=>1])->select();
        $row['fault_name_one'] = Fault::where('fault_id',$fault_list[0]['fault_id'])->value('name');
        $row['fault_name_two'] = Fault::where('fault_id',$fault_list[1]['fault_id'])->value('name');
        $row['fault_name_three'] = 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);
        }

        $other_report = !empty($row['other_report']) ? json_decode($row['other_report'],true):[];
        if (false === $this->request->isPost()) {
            $this->view->assign('other_report', $other_report);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $params['total'] = 100-$params['fault_one_score']-$params['fault_two_score']-$params['fault_three_score']-$params['xianxian_score']-$params['yuanyin_socre']-$params['buwei_score']-$params['fangfa_score']-$params['overtime_score'];
            $result = Db::name('real_exam_score')->where('id', $row['id'])->update($params);

            $rows->total_score = $params['total'];
            $rows->is_sure = 1;
            $rows->save();
            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 view($ids = null)
    {
        $row = Db::name('real_exam_score')->where('exam_id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $rows = $this->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'] = Fault::where('fault_id',$fault_list[0]['fault_id'])->value('name');
        $row['fault_name_two'] = Fault::where('fault_id',$fault_list[1]['fault_id'])->value('name');
        $row['fault_name_three'] = 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);
        }
        $other_report = !empty($row['other_report']) ? json_decode($row['other_report'],true):[];
        $this->view->assign('other_report', $other_report);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //正在考试
    public function persent($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->model->where('exam_collection_id',$ids)->column('exam_id');
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = Db::name('real_exam_comp_request')
//            ->where('exam_collection_type',3)
            ->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();
        // $list = $this->model
        //     ->where($where)->where('exam_collection_id',$ids)
        //     ->where($this->whereExtend)->with($this->relationtTable)
        //     ->order($sort, $order)
        //     ->paginate($limit);
        $list = Db::name('seat')->select();
        foreach ($list as $key => $value) {
            $sim = Db::name('sim')->where('seat_id',$value['seat_id'])->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->model->where('exam_collection_id',$ids)->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']==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->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->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 handle($type = null,$ids = null)
    {
        $row = Db::name('real_exam_comp_request')->where('rel_id',$ids)->find($ids);
        if(!$row){
            $this->error('未找到记录');
        }
        if($type ==1){
            $request_status = 2;
        }
        if($type==2)
        {
            $request_status= 3;
        }
        Db::name('real_exam_comp_request')->where('rel_id',$ids)->update(['request_status'=>$request_status]);

        //同步更新考试表json串
        $exam_info  = $this->model->get($row['exam_id']);
        if(!empty($exam_info)){
            $other_replace = json_decode($exam_info['other_replace'],true)??[];
            foreach ($other_replace as $k=>$v){
                if($v['fault_id'] == $row['fault_id']){
                    $other_replace[$k]['request_status'] = $request_status;
                }
            }
            $exam_info->other_replace = json_encode($other_replace);
            $exam_info->save();
            unset($v);
        }
        $this->success();
    }


    //啦
    public function editscore($ids = "")
    {
        $row = Db::name('real_exam_score')->where('exam_id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $rows = $this->model->get($ids);
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $result = Db::name('real_exam_score')->where('id', $row['id'])->update($params);

            $info = Db::name('real_exam_score')->where('exam_id', $ids)->find();
            $total =100-$info['fault_one_score']-$info['fault_two_score']-$info['fault_three_score']-$info['xianxian_score']-$info['yuanyin_socre']-$info['buwei_score']-$info['fangfa_score']-$info['overtime_score']-$info['jielun_score'];;


            $rows->total_score = $total;
            $rows->is_sure = 1;
            $rows->save();
            $result = Db::name('real_exam_score')->where('id', $row['id'])->update(['total'=>$total]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
