<?php
namespace app\api\controller;
use app\common\controller\Authentication;
use app\common\model\QuestionModel;
use \think\Db;

class Question extends Authentication{
    
    private static $M_question;
    public function __construct(){
        parent::__construct();
        $this->init();
    }

    private function init(){
        self::$M_question = new QuestionModel();
    }

    public function index(){
        echo 'index';
        die;
    }
    // 检测用户是否是首次登陆并存储用户
    public function get_rand(){
        $where['grade'] = input('grade');
        $where['lv'] = 'LV' . input('lv');
        $query = "(SELECT * FROM jr_question WHERE  grade = ".$where['grade']."  AND lv = '".$where["lv"]."' and level = 0 ORDER BY rand() LIMIT 4) union all (SELECT * FROM jr_question WHERE  grade = ".$where['grade']."  AND lv = '".$where['lv']."' and level = 10 ORDER BY rand() LIMIT 1)";
        $result = Db::query($query);
        return json($result);
    }
    // 根据条件返回题库数据
    public function get_list(){
        $where = [];
        if(input('grade')){
            $where['grade'] = input('grade');
        }
        if(input('subject')){
            $where['subject'] = input('subject');
        }
        if(input('keyword')){
            // $where['id'] = ['LIKE' , '%'.input('keyword').'%'];
            $where['title'] = ['LIKE' , '%'.input('keyword').'%'];
        }
        $list = self::$M_question->get_by_where($where);
        return json($list);
    }
    // 返回某个题库详细
    public function info($id){
        if( $id ){
            $where['id'] = $id;
            $info = self::$M_question->get_by_where($where);
            return json($info['list'][0]);
        }
    }
    // 单个题库保存
    public function do_save(){
        $result['status'] = self::$M_question->save(input(),['id' => input('id')]);
        return json($result);
    }
    //  批量上传题目
    public function do_import_paset(){
        $list = json_decode(input('data'));
        $length = 0;
        foreach ($list as $value) {
            $length ++;
            $question = new QuestionModel;
            $question->data($value);
            $question->save();
        }
        $result['length'] = $length;
        return json($result);
    }
}
