<?php
namespace app\adminVue\controller;
use think\facade\Db;

class V2Question extends V2Base
{
    private function run($action) {
        try { return json(['code'=>0,'data'=>$action()]); }
        catch (\InvalidArgumentException $e) { $this->fail($e->getMessage()); }
    }
    private function paper() {
        $id=filter_var($this->request->get('item_type'),FILTER_VALIDATE_INT,['options'=>['min_range'=>1]]);
        if (!$id || !Db::name('quality_base')->where(['id'=>$id,'mid'=>4,'status'=>1])->count()) $this->fail('请选择有效试卷');
        return $id;
    }
    public function options() {
        return $this->run(function(){return Db::name('quality_base')->where(['mid'=>4,'status'=>1])->field('id as value,content as label')->order('id')->select()->toArray();});
    }
    public function index() {
        return $this->run(function(){
            $id=$this->paper();$page=max(1,min(100000,(int)$this->request->get('page',1)));$limit=max(1,min(100,(int)$this->request->get('limit',15)));
            $type=$this->request->get('exam_type','');$keyword=$this->request->get('keyword','');
            if (!is_scalar($keyword) || mb_strlen((string)$keyword)>100 || !is_scalar($type) || !in_array((string)$type,['','1','2','3'],true)) $this->fail('筛选参数无效');
            $all=Db::name('quality_ppi_exam')->where(['item_type'=>$id,'status'=>1]);$counts=[];
            foreach([1,2,3] as $t) $counts[$t]=(clone $all)->where('exam_type',$t)->count();
            $query=clone $all;if($type!=='')$query->where('exam_type',(int)$type);
            if(trim((string)$keyword)!=='')$query->whereLike('content','%'.addcslashes(trim((string)$keyword),'%_\\').'%');
            $total=(clone $query)->count();$rows=$query->order('exam_type,id')->limit(($page-1)*$limit,$limit)->select()->toArray();
            foreach($rows as &$row)$row['version']=V2QuestionBank::version($row);unset($row);
            $set=Db::name('quality_exam_set')->where('item_type',$id)->field('num1,num2,num3')->find();
            return ['list'=>$rows,'total'=>$total,'counts'=>$counts,'required'=>$set ?: null];
        });
    }
    public function preview() { return $this->run(function(){return V2QuestionBank::preview($this->request->post('rows'));}); }
    public function import() { return $this->run(function(){ $d=$this->request->post();return V2QuestionBank::import($d['rows']??null,$d['stamp']??null,$d['overwrite']??false);}); }
    public function update() { return $this->run(function(){ $d=$this->request->post();V2QuestionBank::change($d['id']??0,$d['version']??null,$d);return ['saved'=>true];}); }
    public function remove() { return $this->run(function(){ $d=$this->request->post();V2QuestionBank::change($d['id']??0,$d['version']??null);return ['removed'=>true];}); }
}
