123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325 |
- <?php
- namespace app\admin\controller\train;
- use app\admin\model\train\ClassDictModel;
- use app\admin\model\train\TrainExam;
- use app\admin\model\train\TrainExamReQuestion;
- use app\admin\service\train\TrainService;
- use app\common\controller\Backend;
- use think\Db;
- use think\Exception;
- use think\exception\PDOException;
- use think\exception\ValidateException;
- use think\facade\Request;
- /**
- * 培训-题目
- *
- * @icon fa fa-circle-o
- */
- class Question extends Backend
- {
- protected $searchFields = 'title';
- /**
- * QuestionModel模型对象
- * @var \app\admin\model\train\QuestionModel
- */
- protected $model = null;
- public function _initialize()
- {
- parent::_initialize();
- $this->model = new \app\admin\model\train\QuestionModel;
- $this->view->assign([
- 'question_type' => [
- 1 => '单选',
- 2 => '多选',
- 3 => '判断'
- ]
- ]);
- }
- /**
- * 查看
- */
- public function index()
- {
- //设置过滤方法
- $this->request->filter(['strip_tags']);
- if ($this->request->isAjax()) {
- //如果发送的来源是Selectpage,则转发到Selectpage
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $del_where = ['is_del' => 0];
- $exam_where = false;
- if($this->request->has('show_exam_id')){
- $question_ids = model(TrainExamReQuestion::class)
- ->whereIn('exam_id', $this->request->param('show_exam_id'))
- ->column('question_id');
- $exam_where = [
- 'id' => ['in', $question_ids]
- ];
- $del_where = false;
- }
- $total = $this->model
- ->where($where)
- ->where($del_where)
- ->where($exam_where)
- ->order($sort, $order)
- ->count();
- $list = $this->model
- ->where($where)
- ->where($del_where)
- ->where($exam_where)
- ->order($sort, $order)
- ->limit($offset, $limit)
- ->field('is_del, answer1, answer2, answer3, answer4, answer5, answer6',true)
- ->select();
- $list = collection($list)->toArray();
- $total_score = 0;
- $qualified = 0;
- if ($list) {
- $class_dict = Db::table(ClassDictModel::getTable())
- ->column('id, title');
- foreach ($list as &$val) {
- $val['class_id'] = $class_dict[$val['class_id']] ?? '';
- $val['result'] = TrainService::instance()->formatResult($val['result'], $val['type']);
- }
- unset($val);
- if($this->request->has('exam_id')){
- $question_ids = model(TrainExamReQuestion::class)
- ->whereIn('exam_id', $this->request->param('exam_id'))
- ->column('question_id');
- foreach ($list as &$val){
- $val['checkbox'] = in_array($val['id'], $question_ids) ? 1 : 0;
- }
- unset($val);
- }
- if($this->request->has('show_exam_id')){
- $scores = model(TrainExamReQuestion::class)
- ->where('exam_id', $this->request->param('show_exam_id'))
- ->column('question_id, score');
- foreach ($list as &$val){
- $val['score'] = $scores[$val['id']] ?? '';
- }
- unset($val);
- $exam = model(TrainExam::class)->get($this->request->param('show_exam_id'));
- $total_score = $exam['total'];
- $qualified = $exam['qualified'];
- }
- }
- $result = array("total" => $total, "rows" => $list, 'total_score' => $total_score, 'qualified' => $qualified);
- return json($result);
- }
- return $this->view->fetch();
- }
- /**
- * 添加
- */
- public function add()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- $type = $params['type'];
- $correct = $params['result'];
- if(!$correct){
- $this->error('缺少正确答案');
- }
- switch ($type){
- case 2:
- $correct = implode('', $correct);
- break;
- case 3:
- $params['answer1'] = '对';
- $params['answer2'] = '错';
- unset($params['answer3'], $params['answer4'], $params['answer5'], $params['answer6']);
- break;
- default;
- }
- $params['result'] = $correct;
- if ($params) {
- $params = $this->preExcludeFields($params);
- if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
- $params[$this->dataLimitField] = $this->auth->id;
- }
- $result = false;
- Db::startTrans();
- try {
- //是否采用模型验证
- if ($this->modelValidate) {
- $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
- $this->model->validateFailException(true)->validate($validate);
- }
- $result = $this->model->allowField(true)->save($params);
- Db::commit();
- } catch (ValidateException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (PDOException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were inserted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- return $this->view->fetch();
- }
- public function del($ids = "")
- {
- if ($ids) {
- $pk = $this->model->getPk();
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds)) {
- $this->model->where($this->dataLimitField, 'in', $adminIds);
- }
- try {
- $count = $this->model->where($pk, 'in', explode(',', $ids))
- ->update([
- 'is_del' => 1
- ]);
- } catch (PDOException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($count) {
- $this->success();
- } else {
- $this->error(__('No rows were deleted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', 'ids'));
- }
- public function import()
- {
- // 获取文件
- $file = $this->request->file('file');
- if(!$file){
- return $this->setError('获取文件失败');
- }
- $info = $file->validate(['ext'=>'xls,xlsx'])->move( './uploads');
- if ($info) {
- $realPath = ROOT_PATH . 'public/uploads/' . $info->getSaveName();
- $data = read_excel($realPath);
- if (!$data) {
- return $this->setError('请写入内容');
- }
- $save = [];
- $type_arr = [
- '单选' => 1,
- '多选' => 2,
- '判断' => 3
- ];
- $result_arr = [
- 'A' => 1,
- 'B' => 2,
- 'C' => 3,
- 'D' => 4,
- 'E' => 5,
- 'F' => 6,
- '对' => 1,
- '错' => 2,
- ];
- $class_dict = Db::table(ClassDictModel::getTable())->column('title, id');
- foreach ($data as $key => $val){
- // 验证格式
- if(!$val[0]){
- $this->error($key + 2 . '行,缺少题目类型');
- }
- if(!$val[2]){
- $this->error($key + 2 . '行,缺少题目标题');
- }
- if(!$val[3]){
- $this->error($key + 2 . '行,缺少正确答案');
- }
- $type = trim($val[0]);
- if(!isset($type_arr[$type])){
- $this->error($key + 2 . '行,错误的题目类型格式');
- }
- $class = trim($val[1]);
- if(!isset($class_dict[$class])){
- $this->error($key + 2 . '行,不存在的分类');
- }
- // 格式化正确答案
- $answer = (string) trim($val[3]);
- $answer_arr = ch2arr($answer);
- $answer_temp = [];
- foreach ($answer_arr as $word){
- if(!$word){
- continue;
- }
- if(!isset($result_arr[$word])){
- $this->error($key + 2 . '行,错误的正确答案格式');
- }
- $answer_temp[] = $result_arr[$word];
- }
- $answer_temp = array_unique($answer_temp);
- sort($answer_temp);
- $answer = implode('', $answer_temp);
- // 组装数据
- if($type_arr[$type] === 3){
- $val[4] = '对';
- $val[5] = '错';
- $val[6] = '';
- $val[7] = '';
- $val[8] = '';
- $val[9] = '';
- }
- $save[] = [
- 'title' => trim($val[2]),
- 'class_id' => $class_dict[$class],
- 'type' => $type_arr[$type],
- 'result' => $answer,
- 'answer1' => trim($val[4]),
- 'answer2' => trim($val[5]),
- 'answer3' => trim($val[6]),
- 'answer4' => trim($val[7]),
- 'answer5' => trim($val[8]),
- 'answer6' => trim($val[9])
- ];
- }
- $res = $this->model->insertAll($save);
- if(!$res){
- $this->error();
- }
- return json(['code'=>1]);
- }
- $this->error();
- }
- public function detail($ids)
- {
- $data = $this->model->get($ids);
- $this->view->detail = $data;
- $this->view->result = TrainService::instance()->formatResult($data['result'], $data['type']);
- $this->view->type = TrainService::instance()->formatType($data['type']);
- return $this->view->fetch();
- }
- }
|