Question.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. <?php
  2. namespace app\admin\controller\train;
  3. use app\admin\model\train\ClassDictModel;
  4. use app\admin\model\train\TrainExam;
  5. use app\admin\model\train\TrainExamReQuestion;
  6. use app\admin\service\train\TrainService;
  7. use app\common\controller\Backend;
  8. use think\Db;
  9. use think\Exception;
  10. use think\exception\PDOException;
  11. use think\exception\ValidateException;
  12. use think\facade\Request;
  13. /**
  14. * 培训-题目
  15. *
  16. * @icon fa fa-circle-o
  17. */
  18. class Question extends Backend
  19. {
  20. protected $searchFields = 'title';
  21. /**
  22. * QuestionModel模型对象
  23. * @var \app\admin\model\train\QuestionModel
  24. */
  25. protected $model = null;
  26. public function _initialize()
  27. {
  28. parent::_initialize();
  29. $this->model = new \app\admin\model\train\QuestionModel;
  30. $this->view->assign([
  31. 'question_type' => [
  32. 1 => '单选',
  33. 2 => '多选',
  34. 3 => '判断'
  35. ]
  36. ]);
  37. }
  38. /**
  39. * 查看
  40. */
  41. public function index()
  42. {
  43. //设置过滤方法
  44. $this->request->filter(['strip_tags']);
  45. if ($this->request->isAjax()) {
  46. //如果发送的来源是Selectpage,则转发到Selectpage
  47. if ($this->request->request('keyField')) {
  48. return $this->selectpage();
  49. }
  50. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  51. $del_where = ['is_del' => 0];
  52. $exam_where = false;
  53. if($this->request->has('show_exam_id')){
  54. $question_ids = model(TrainExamReQuestion::class)
  55. ->whereIn('exam_id', $this->request->param('show_exam_id'))
  56. ->column('question_id');
  57. $exam_where = [
  58. 'id' => ['in', $question_ids]
  59. ];
  60. $del_where = false;
  61. }
  62. $total = $this->model
  63. ->where($where)
  64. ->where($del_where)
  65. ->where($exam_where)
  66. ->order($sort, $order)
  67. ->count();
  68. $list = $this->model
  69. ->where($where)
  70. ->where($del_where)
  71. ->where($exam_where)
  72. ->order($sort, $order)
  73. ->limit($offset, $limit)
  74. ->field('is_del, answer1, answer2, answer3, answer4, answer5, answer6',true)
  75. ->select();
  76. $list = collection($list)->toArray();
  77. $total_score = 0;
  78. $qualified = 0;
  79. if ($list) {
  80. $class_dict = Db::table(ClassDictModel::getTable())
  81. ->column('id, title');
  82. foreach ($list as &$val) {
  83. $val['class_id'] = $class_dict[$val['class_id']] ?? '';
  84. $val['result'] = TrainService::instance()->formatResult($val['result'], $val['type']);
  85. }
  86. unset($val);
  87. if($this->request->has('exam_id')){
  88. $question_ids = model(TrainExamReQuestion::class)
  89. ->whereIn('exam_id', $this->request->param('exam_id'))
  90. ->column('question_id');
  91. foreach ($list as &$val){
  92. $val['checkbox'] = in_array($val['id'], $question_ids) ? 1 : 0;
  93. }
  94. unset($val);
  95. }
  96. if($this->request->has('show_exam_id')){
  97. $scores = model(TrainExamReQuestion::class)
  98. ->where('exam_id', $this->request->param('show_exam_id'))
  99. ->column('question_id, score');
  100. foreach ($list as &$val){
  101. $val['score'] = $scores[$val['id']] ?? '';
  102. }
  103. unset($val);
  104. $exam = model(TrainExam::class)->get($this->request->param('show_exam_id'));
  105. $total_score = $exam['total'];
  106. $qualified = $exam['qualified'];
  107. }
  108. }
  109. $result = array("total" => $total, "rows" => $list, 'total_score' => $total_score, 'qualified' => $qualified);
  110. return json($result);
  111. }
  112. return $this->view->fetch();
  113. }
  114. /**
  115. * 添加
  116. */
  117. public function add()
  118. {
  119. if ($this->request->isPost()) {
  120. $params = $this->request->post("row/a");
  121. $type = $params['type'];
  122. $correct = $params['result'];
  123. if(!$correct){
  124. $this->error('缺少正确答案');
  125. }
  126. switch ($type){
  127. case 2:
  128. $correct = implode('', $correct);
  129. break;
  130. case 3:
  131. $params['answer1'] = '对';
  132. $params['answer2'] = '错';
  133. unset($params['answer3'], $params['answer4'], $params['answer5'], $params['answer6']);
  134. break;
  135. default;
  136. }
  137. $params['result'] = $correct;
  138. if ($params) {
  139. $params = $this->preExcludeFields($params);
  140. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  141. $params[$this->dataLimitField] = $this->auth->id;
  142. }
  143. $result = false;
  144. Db::startTrans();
  145. try {
  146. //是否采用模型验证
  147. if ($this->modelValidate) {
  148. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  149. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  150. $this->model->validateFailException(true)->validate($validate);
  151. }
  152. $result = $this->model->allowField(true)->save($params);
  153. Db::commit();
  154. } catch (ValidateException $e) {
  155. Db::rollback();
  156. $this->error($e->getMessage());
  157. } catch (PDOException $e) {
  158. Db::rollback();
  159. $this->error($e->getMessage());
  160. } catch (Exception $e) {
  161. Db::rollback();
  162. $this->error($e->getMessage());
  163. }
  164. if ($result !== false) {
  165. $this->success();
  166. } else {
  167. $this->error(__('No rows were inserted'));
  168. }
  169. }
  170. $this->error(__('Parameter %s can not be empty', ''));
  171. }
  172. return $this->view->fetch();
  173. }
  174. public function del($ids = "")
  175. {
  176. if ($ids) {
  177. $pk = $this->model->getPk();
  178. $adminIds = $this->getDataLimitAdminIds();
  179. if (is_array($adminIds)) {
  180. $this->model->where($this->dataLimitField, 'in', $adminIds);
  181. }
  182. try {
  183. $count = $this->model->where($pk, 'in', explode(',', $ids))
  184. ->update([
  185. 'is_del' => 1
  186. ]);
  187. } catch (PDOException $e) {
  188. Db::rollback();
  189. $this->error($e->getMessage());
  190. } catch (Exception $e) {
  191. Db::rollback();
  192. $this->error($e->getMessage());
  193. }
  194. if ($count) {
  195. $this->success();
  196. } else {
  197. $this->error(__('No rows were deleted'));
  198. }
  199. }
  200. $this->error(__('Parameter %s can not be empty', 'ids'));
  201. }
  202. public function import()
  203. {
  204. // 获取文件
  205. $file = $this->request->file('file');
  206. if(!$file){
  207. return $this->setError('获取文件失败');
  208. }
  209. $info = $file->validate(['ext'=>'xls,xlsx'])->move( './uploads');
  210. if ($info) {
  211. $realPath = ROOT_PATH . 'public/uploads/' . $info->getSaveName();
  212. $data = read_excel($realPath);
  213. if (!$data) {
  214. return $this->setError('请写入内容');
  215. }
  216. $save = [];
  217. $type_arr = [
  218. '单选' => 1,
  219. '多选' => 2,
  220. '判断' => 3
  221. ];
  222. $result_arr = [
  223. 'A' => 1,
  224. 'B' => 2,
  225. 'C' => 3,
  226. 'D' => 4,
  227. 'E' => 5,
  228. 'F' => 6,
  229. '对' => 1,
  230. '错' => 2,
  231. ];
  232. $class_dict = Db::table(ClassDictModel::getTable())->column('title, id');
  233. foreach ($data as $key => $val){
  234. // 验证格式
  235. if(!$val[0]){
  236. $this->error($key + 2 . '行,缺少题目类型');
  237. }
  238. if(!$val[2]){
  239. $this->error($key + 2 . '行,缺少题目标题');
  240. }
  241. if(!$val[3]){
  242. $this->error($key + 2 . '行,缺少正确答案');
  243. }
  244. $type = trim($val[0]);
  245. if(!isset($type_arr[$type])){
  246. $this->error($key + 2 . '行,错误的题目类型格式');
  247. }
  248. $class = trim($val[1]);
  249. if(!isset($class_dict[$class])){
  250. $this->error($key + 2 . '行,不存在的分类');
  251. }
  252. // 格式化正确答案
  253. $answer = (string) trim($val[3]);
  254. $answer_arr = ch2arr($answer);
  255. $answer_temp = [];
  256. foreach ($answer_arr as $word){
  257. if(!$word){
  258. continue;
  259. }
  260. if(!isset($result_arr[$word])){
  261. $this->error($key + 2 . '行,错误的正确答案格式');
  262. }
  263. $answer_temp[] = $result_arr[$word];
  264. }
  265. $answer_temp = array_unique($answer_temp);
  266. sort($answer_temp);
  267. $answer = implode('', $answer_temp);
  268. // 组装数据
  269. if($type_arr[$type] === 3){
  270. $val[4] = '对';
  271. $val[5] = '错';
  272. $val[6] = '';
  273. $val[7] = '';
  274. $val[8] = '';
  275. $val[9] = '';
  276. }
  277. $save[] = [
  278. 'title' => trim($val[2]),
  279. 'class_id' => $class_dict[$class],
  280. 'type' => $type_arr[$type],
  281. 'result' => $answer,
  282. 'answer1' => trim($val[4]),
  283. 'answer2' => trim($val[5]),
  284. 'answer3' => trim($val[6]),
  285. 'answer4' => trim($val[7]),
  286. 'answer5' => trim($val[8]),
  287. 'answer6' => trim($val[9])
  288. ];
  289. }
  290. $res = $this->model->insertAll($save);
  291. if(!$res){
  292. $this->error();
  293. }
  294. return json(['code'=>1]);
  295. }
  296. $this->error();
  297. }
  298. public function detail($ids)
  299. {
  300. $data = $this->model->get($ids);
  301. $this->view->detail = $data;
  302. $this->view->result = TrainService::instance()->formatResult($data['result'], $data['type']);
  303. $this->view->type = TrainService::instance()->formatType($data['type']);
  304. return $this->view->fetch();
  305. }
  306. }