<?php
namespace app\admin\controller;

use think\App;

class ArticlePaper extends Auth
{

    public function __construct(App $app = null) {
        parent::__construct($app);
        $this->model= new \app\common\model\ArticlePaper();
        $this->table= $this->model->table;
        $this->table1= 'article_record';

    }
    public function index(){
        if(request()->isAjax()){
            //分页参数
            $length = input('rows',10,'intval');   //每页条数
            $page = input('page',1,'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx','id','trim');      //排序列
            $sort = input('sord','desc','trim');        //排序方式
            $order = $sortRow.' '.$sort;

            $title = input('title','','trim');
            if($title){
                $map[] = ['title','like','%'.$title.'%'];
            }
            $enable = input('enable','','trim');
            if($enable != ''){
                $map[] = ['enable','=',$enable];
            }
            $map[] = ['del','=',0];
            $map[] = ['org_id','=',$this->orgId];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = db($this->table)->where($map)->limit($start,$length)->order($order)->select();
            foreach ($lists as $k=>$v){
                $lists[$k]['article_title'] = db('article')
                    ->where('id',$v['article_id'])
                    ->value('title');
            }
            //数据返回
            $totalCount = db($this->table)->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            $this->assign('m_name','试卷列表');
            return $this->fetch();
        }
    }
    public function record($id){
        if(request()->isAjax()){
            //分页参数
            $length = input('rows',10,'intval');   //每页条数
            $page = input('page',1,'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx','id','trim');      //排序列
            $sort = input('sord','desc','trim');        //排序方式
            $order = $sortRow.' '.$sort;

            $title = input('title','','trim');
            if($title){
                $map[] = ['title','like','%'.$title.'%'];
            }
            $enable = input('enable','','trim');
            if($enable != ''){
                $map[] = ['enable','=',$enable];
            }
            $map[] = ['questionnaire_id','=',$id];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = db($this->table1)->where($map)->limit($start,$length)->order($order)->select();
            //数据返回
            $totalCount = db($this->table1)->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            $info = db($this->table)
                ->where('id',$id)
                ->find();
            $this->assign('m_name','['.$info['title'].']'.'回收记录');
            $this->assign('id',$id);
            return $this->fetch();
        }
    }

    /**
     * 新增/编辑
     */
    public function add($id=0){
        if(request()->isPost()){
            $res = $this->model->updates();
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error($this->model->getError());
            }
        }else{
            if($id){
                $info =db($this->table)->where('id',$id)->find();
                $this->assign('info',$info);
            }
            $article = (new \app\common\model\Article())->getList();
            $this->assign('cate',$article);
            return $this->fetch();
        }
    }

    public function share($id){
        $info =db($this->table)
            ->where('id',$id)
            ->find();
        $strs = aes_encrypt('wj',config('app.encryption_key'));
        $code = getSite().'/h5/Wj/index?id='.$id.'&code='.$strs.'&orgId='.$info['org_id'];
        $this->assign('url',$code);
        return $this->fetch();
    }

    /**
     * 删除记录
     * @param int $id
     */
    public function del_question($id=0){
        if(!$id){
            $this->error('参数错误');
        }
        $info = db('article_question')
            ->where('id',$id)
            ->find();
        $page = db('article_paper')
            ->where('id',$info['article_paper_id'])
            ->find();
        if($page['status'] ==2){
            $this->error("已发布的试卷不能删除题目");
        }
        $res = db('article_question')->where('id',$id)->setField('del',1);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }


    public function fb($id=0,$status=0){
        $enable = $status==1 || $status==0 ?2:1;
        $res = db($this->table)->where('id',$id)->setField('status',$enable);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 改变字段值
     * @param int $fv
     * @param string $fn
     * @param int $fv
     */
    public function changeField($id=0,$fn='',$fv=0){
        if(!$fn||!$id){
            $this->error('参数错误');
        }
        $res = db($this->table)->where('id',$id)->setField($fn,$fv);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    //回收记录详情
    public function info($id){
        $info = $this->model->record_info($id);
        if (!$info) {
            exit('数据不存在');
        }
        $this->assign('info',$info);
        return $this->fetch();
    }


    //试题管理
    public function article($id=0){
        if(request()->isAjax()){
            //分页参数
            $length = input('rows',10,'intval');   //每页条数
            $page = input('page',1,'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx','id','trim');      //排序列
            $sort = input('sord','desc','trim');        //排序方式
            $order = $sortRow.' '.$sort;

            $title = input('title','','trim');
            if($title){
                $map[] = ['title','like','%'.$title.'%'];
            }
            $enable = input('enable','','trim');
            if($enable != ''){
                $map[] = ['enable','=',$enable];
            }
            $map[] = ['del','=',0];
            $map[] = ['article_paper_id','=',$id];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = db('article_question')->where($map)->limit($start,$length)->order($order)->select();

            //数据返回
            $totalCount = db('article_question')->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            $info = db('article_paper')
                ->where('id',$id)
                ->find();
            $this->assign('m_name','['.$info['title'].']试题列表');
            $this->assign('id',$id);
            return $this->fetch();
        }
    }
    //添加试题
    public function article_add($id=0){
        if(request()->isPost()){
            $data = request()->post();
            $info =db('article_paper')
                ->where('id',$data['article_paper_id'])
                ->find();
            if(!$info || $info['org_id'] != $this->orgId){
                $this->error("试卷不存在");
            }
            if(!in_array($info['status'],[0,1])){
                $this->error('已发布过的试卷无法添加新题目');
            }
            $title = trim($data['title']);
            $score = (int) $data['score'];
            $sort = (int) $data['sort'];
            $type = (int) $data['type'];
            $options = trim($data['options']);
            if(!$title){
                $this->error('未填写题干');
            }
            if(mb_strlen($title) > 500){
                $this->error('题干过长,请控制在500字以内');
            }
            if($score <= 0){
                $this->error('分值错误');
            }
            if(!in_array($type,array(0,1))){
                $this->error('类型错误');
            }
            if(!$options){
                $this->error('未填写题目选项');
            }
            $options = json_decode($options,true);
            if(!$options){
                $this->error('选项参数错误');
            }

            $correct = 0; // 正确答案个数
            foreach ($options as $k=>$v){
                $text = trim($v['text']);
                if(!$text){
                    $this->error('选项不能为空');
                }
                $options[$k]['text'] = $text;
                if($v['answer'] == '1'){
                    $correct++;
                }
            }
            if($correct == 0){
                $this->error('未设置正确答案');
            }
            if($correct > 1&&$type == 0){
                $this->error('单选题只能设置一个正确答案');
            }

            $data = array(
                'article_paper_id' => $data['article_paper_id'],
                'title' => $title,
                'type' => $type,
                'score' => $score,
                'sort' => $sort>0?$sort:0,
                'options' => json_encode($options,JSON_UNESCAPED_UNICODE),
                'create_time' => date('Y-m-d h:i:s'),
                'update_time' => date('Y-m-d h:i:s')
            );
            $res = db('article_question')
                ->insertGetId($data);
            if($res){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
        }else{
            $this->assign('id',$id);
            return $this->fetch();
        }
    }

    public function edit_question($id){
        if ($id <= 0) {
            $this->error("参数错误");
        }

        $question = db('article_question')
            ->where('id',$id)
            ->find();
        if(!$question){
            $this->error("题目不存在");
        }

        $info = db('article_paper')
            ->where('id',$question['article_paper_id'])
            ->find();
        if(!$info || $info['org_id'] != $this->orgId){
            $this->error("试卷不存在");
        }
        if(request()->isPost()){
            $data = request()->post();
            $title = trim($data['title']);
            $options = trim($data['options']);
            if(!$title){
                $this->error('未填写题干');
            }
            if(mb_strlen($title) > 500){
                $this->error('题干过长,请控制在500字以内');
            }
            if(in_array($info['status'],[0,1])){
                $score = (int) $data['score'];
                $sort = (int) $data['sort'];
                $type = (int) $data['type'];
                if($score <= 0){
                    $this->error('分值错误');
                }
                if(!in_array($type,array(0,1))){
                    $this->error('类型错误');
                }
            }
            if(!$options){
                $this->error('未填写题目选项');
            }
            $options = json_decode($options,true);
            if(!$options){
                $this->error('选项参数错误');
            }

            $correct = 0; // 正确答案个数
            foreach ($options as $k=>$v){
                $text = trim($v['text']);
                if(!$text){
                    $this->error('选项不能为空');
                }
                $options[$k]['text'] = $text;
                if($v['answer'] == '1'){
                    $correct++;
                }
            }
            if($correct == 0){
                $this->error('未设置正确答案');
            }
            if($correct > 1&& in_array($info['status'],[0,1]) &&$type == 0){
                $this->error('单选题只能设置一个正确答案');
            }

            $oldoptions = json_decode($question['options'],true);
            if(count($oldoptions) != count($options)){
                $this->error('选项参数错误');
            }

            $data = array(
                'title' => $title,
                'options' => json_encode($options,JSON_UNESCAPED_UNICODE),
                'update_time' => date('Y-m-d h:i:s')
            );

            if($info['status'] == 0){
                $data['score'] = $score;
                $data['type'] = $type;
                $data['sort'] = $sort>0?$sort:0;
            }

            $res = db('article_question')->where('id',$id)->update($data);
            if($res){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
        }else{
            $this->assign('info',$info);
            $question['options'] = json_decode($question['options'],true);
            $this->assign('question',$question);
            return $this->fetch();
        }
    }

    public function article_rank($id){

        $ret = db('article_record')
            ->where('article_paper_id', $id)
            ->field('article_record.*,max(SCORE) as SCORE')
            ->group('user_id')
            ->order(['score'=>'desc','create_time'=>'asc'])
            ->select();
        foreach ($ret as $key => $value) {
            $ret[$key]['article_paper_name'] = db('article_paper')
              ->where('id',$value['article_paper_id'])
              ->value('title');
            $ret[$key]['user_name'] = db('user')
            ->where('id',$value['user_id'])
            ->value('real_name');
        }

        $this->assign('list',$ret);
        return $this->fetch();
    }
    public function article_log($id){
        if(request()->isAjax()){
            //分页参数
            $length = input('rows',10,'intval');   //每页条数
            $page = input('page',1,'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx','id','trim');      //排序列
            $sort = input('sord','desc','trim');        //排序方式
            $order = $sortRow.' '.$sort;

            $title = input('title','','trim');
            if($title){
                $map[] = ['title','like','%'.$title.'%'];
            }
            $enable = input('enable','','trim');
            if($enable != ''){
                $map[] = ['enable','=',$enable];
            }
            $map[] = ['article_paper_id','=',$id];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = db('article_record')->where($map)->limit($start,$length)->order($order)->select();
            foreach ($lists as $key => $value) {
                $lists[$key]['article_paper_name'] = db('article_paper')
                    ->where('id',$value['article_paper_id'])
                    ->value('title');
                $lists[$key]['user_name'] = db('user')
                    ->where('id',$value['user_id'])
                    ->value('real_name');
            }
            //数据返回
            $totalCount = db('article_record')->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            $info = db('article_paper')
                ->where('id',$id)
                ->find();
            $this->assign('m_name','['.$info['title'].']考试记录');
            $this->assign('id',$id);
            return $this->fetch();
        }
    }
    public function log_info($id){

        $list = $this->show_detail_info($id);
        $info = $this->show_info($id);
        $this->assign('list',$list);
        $this->assign('info',$info);
        return $this->fetch();
    }

    public function show_detail_info($id)
    {
        $ret = db('article_record_answer')
            ->alias('a')
            ->field('c.*,a.answer,b.user_id,b.article_paper_id')
            ->join('article_record b','b.id = a.article_record_id')
            ->join('article_question c','c.id = a.article_question_id')
            ->where('a.article_record_id', $id)
            ->order('c.sort', 'asc')
            ->select();
        foreach ($ret as $key => $value) {
            $ret[$key]['article_paper_name'] = db('article_paper')
                ->where('id',$value['article_paper_id'])
                ->value('title');
            $ret[$key]['user_name'] = db('user')
                ->where('id',$value['user_id'])
                ->value('real_name');
            $ret[$key]['options'] = json_decode($value['options'],true);
         }
        return $ret;
    }

    public function show_info($id)
    {
        $ret = db('article_record')
            ->where('id',$id)
             ->find();
        if ($ret) {
            $ret['article_paper_name'] =
                db('article_paper')
                    ->where('id',$ret['article_paper_id'])
                    ->value('title');
            $ret['user_name'] =
                db('user')
                    ->where('id',$ret['user_id'])
                    ->value('real_name');
        }
        return $ret;
    }
}