Question.php 30.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
<?php

namespace app\admin\controller\exam;

use addons\exam\enum\CommonStatus;
use addons\exam\library\FrontService;
use app\admin\model\exam\MaterialQuestionModel;
use app\admin\model\exam\QuestionModel;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 试题
 * @icon fa fa-circle-o
 */
class Question extends Backend
{

    /**
     * QuestionModel模型对象
     * @var \app\admin\model\exam\QuestionModel
     */
    protected $model = null;
    protected $noNeedRight = ['*'];
    protected $multiFields = 'status';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\exam\QuestionModel;
        $this->view->assign("kindList", $this->model->getKindList());
        $this->view->assign("difficultyList", $this->model->getDifficultyList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['cate'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('cate')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // if ($params['options_extend']) {
            //     $params['options_extend'] = json_decode(urldecode($params['options_extend']), true);
            // }
            // dd($params);
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 检查题目输入
                $this->checkTitle($params);
                // 检查答案输入
                $this->checkAnswer($params);
                // 处理选项图片链接域名
                $this->optionsImage($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);

                    // 保存材料题父题目
                    $this->saveMaterialParentQuestion($this->model);
                    // 保存材料题子题目
                    $this->saveMaterialQuestions($this->model, $params['material_questions'] ?? []);

                    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 edit($ids = null)
    {
        $row = $this->model->get($ids, [
            'material_questions' => function ($query) {
                return $query->with([
                    'question' => function ($query) {
                        return $query->with('cates');
                    }
                ])->order('weigh');
            }
        ]);

        // dd($row->toArray());
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 检查题目输入
                $this->checkTitle($params);
                // 检查答案输入
                $this->checkAnswer($params);
                // 处理选项图片链接域名
                $this->optionsImage($params);

                $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 . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    // 保存材料题父题目
                    $this->saveMaterialParentQuestion($row);
                    // 保存材料题子题目
                    $this->saveMaterialQuestions($row, $params['material_questions'] ?? []);

                    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 updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 选项图片页面
     * @return string
     */
    public function image()
    {
        if ($this->request->isPost()) {
            $this->success($this->request->post());
        }
        return $this->view->fetch();
    }

    /**
     * 试题导入
     */
    public function importExcel()
    {
        if ($this->request->isPost()) {
            // parent::import();
            $cate = $this->request->param('cate');
            // $exam_type = $this->request->param('exam_type');
            if (!$cate) { //  || !$exam_type
                $this->error('请先选择所属类型及考试分类再进行上传');
            }

            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }

            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }

            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }

            if ($ext === 'csv') {
                $file     = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp       = fopen($filePath, "w");
                $n        = 0;
                while ($line = fgets($file)) {
                    $line     = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    throw new \Exception(__('Unknown data format'));
                }
                $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
                $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields          = [
                    'kind',
                    'title',
                    'explain',
                    'difficulty',
                    'answer',
                    'A',
                    'B',
                    'C',
                    'D',
                    'E',
                    'F',
                    'G',
                    'H',
                ];

                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;

                    }
                    // $temp    = array_combine($fields, $values);
                    $row     = [];
                    $options = [];

                    // 选项及字段组合
                    for ($i = 0; $i < min($maxColumnNumber, count($fields)); $i++) {
                        $field = $fields[$i];
                        $value = $values[$i];

                        if ($i > 4) {
                            if (!empty($value) || $value == '0') {
                                $options[$field] = $value;
                            }
                        } else {
                            $row[$field] = $value;
                        }
                    }

                    // 过滤空行
                    if (!$row['title']) {
                        continue;
                    }

                    // 特殊字段处理
                    foreach ($row as $key => $item) {
                        if ($key == 'kind') {
                            switch ($item) {
                                case '判断':
                                case '判断题':
                                    $item = 'JUDGE';
                                    break;
                                case '单选':
                                case '单选题':
                                    $item = 'SINGLE';
                                    break;
                                case '多选':
                                case '多选题':
                                    $item = 'MULTI';
                                    break;
                                case '填空':
                                case '填空题':
                                    $item = 'FILL';
                                    break;
                                case '简答':
                                case '简答题':
                                    $item = 'SHORT';
                                    break;
                            }
                        } else if ($key == 'difficulty') {
                            switch ($item) {
                                case '低':
                                case '简单':
                                    $item = 'EASY';
                                    break;
                                case '高':
                                case '困难':
                                    $item = 'HARD';
                                    break;
                                default:
                                    $item = 'GENERAL';
                                    break;
                            }
                        }

                        $row[$key] = $item;
                    }

                    // 判断题特殊情况处理
                    if ($row['kind'] == 'JUDGE') {
                        switch ($row['answer']) {
                            case '正确':
                            case '对':
                                $row['answer'] = 'A';
                                break;
                            case '错误':
                            case '错':
                                $row['answer'] = 'B';
                                break;
                        }

                        $options = $options ? $options : ['A' => '正确', 'B' => '错误'];
                    }

                    // 答案特殊处理
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace(',', ',', $row['answer']);

                    if (!$row['answer'] || ($row['kind'] == 'MULTI' && !strpos($row['answer'], ','))) {
                        throw new \Exception('题目【' . $row['title'] . '】答案格式有误');
                    }
                    // 填空题
                    if ($row['kind'] == 'FILL') {
                        $row['answer'] = explode('|||', $row['answer']);
                        $fill_count    = count(explode('______', $row['title'])) - 1;
                        $answer_count  = count($row['answer']);

                        if ($fill_count != $answer_count) {
                            throw new \Exception('题目【' . $row['title'] . '】填空位与答案数量不匹配');
                        }

                        $fill_answers = [];
                        foreach ($row['answer'] as $item) {
                            $fill_answers[] = ['answers' => explode(',', $item)];
                        }

                        $row['answer'] = json_encode($fill_answers, JSON_UNESCAPED_UNICODE);
                    }
                    // 简答题
                    if ($row['kind'] == 'SHORT') {
                        $row['answer'] = explode('|||', $row['answer']);
                        if ($row['answer']) {
                            $short_answers = [
                                'answer' => $row['answer'][0],
                                'config' => [],
                            ];

                            if (isset($row['answer'][1]) && $row['answer'][1]) {
                                $keywords = explode(',', str_replace(',', ',', $row['answer'][1]));
                                foreach ($keywords as $keyword) {
                                    $short_answers['config'][] = [
                                        'answer' => $keyword,
                                        'score'  => 1,
                                    ];
                                }
                            }

                            $row['answer'] = json_encode($short_answers, JSON_UNESCAPED_UNICODE);
                        }
                    }

                    $row['options_json'] = json_encode($options, JSON_UNESCAPED_UNICODE);
                    $row['cate_id']      = $cate;
                    // $row['exam_type_id'] = $exam_type;
                    $insert[] = $row;
                }

                Session::set('import_question', $insert);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }

            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            $this->success('识别成功', '', ['count' => count($insert)]);
        }
        $this->error('错误的提交方式');
    }

    /**
     * 试题导入提交
     * @return string|void
     */
    public function import()
    {
        if ($this->request->isPost()) {
            // 加载数据
            $insert = Session::pull('import_question');
            if (!$insert) {
                $this->error(__('没有可以导入的数据,请重新上传Excel文件'));
            }

            try {
                $this->model->saveAll($insert);
            } catch (PDOException $exception) {
                $msg = $exception->getMessage();
                if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                    $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
                };
                $this->error($msg);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }

            $this->success();
        }

        return $this->view->fetch();
    }

    /**
     * 获取题库数量
     */
    public function getCount()
    {
        $cate_ids = $this->request->param('cate_ids');

        if (!$cate_ids) {
            $this->error('请先选择题库');
        }

        $this->success('', '', $this->model->getCount($cate_ids));
    }

    /**
     * 选择题目页面
     */
    public function select()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['cate'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('cate')->visible(['name']);
            }
            $rows = $list->items();
            foreach ($rows as &$row) {
                $row['title'] = strip_tags($row['title']);
            }

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function test()
    {
        $this->success('', '', Session::get('import_question'));
    }

    /**
     * 检查答案输入
     * @param $params
     */
    protected function checkAnswer(&$params)
    {
        $answer  = $params['answer'] ?? '';
        $options = $params['options_json'] ?? [];

        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!$answer) {
                $this->error('请设置题目答案');
            }
            if (!$options) {
                $this->error('请设置题目选项');
            }

            $options     = json_decode($options, true);
            $option_keys = array_keys($options);

            // 多选题
            if (strpos($answer, ',') !== false) {
                $answer_arr = explode(',', trim($answer));
                foreach ($answer_arr as $item) {
                    if (!in_array($item, $option_keys)) {
                        $this->error('答案设置有误,答案选项不存在');
                    }
                }
            } else {
                if (!in_array($answer, $option_keys)) {
                    $this->error('答案设置有误,答案选项不存在');
                }
            }
        }

        // 后期拓展题型
        switch ($params['kind']) {
            // 填空题
            case 'FILL':
                if (!is_array($answer) || !count($answer)) {
                    $this->error('未设置填空题答案,至少设置一个');
                }

                // 转json
                $params['answer'] = json_encode($params['answer'], JSON_UNESCAPED_UNICODE);
                break;

            // 简答题
            case 'SHORT':
                $answer = $params['short_answer'] ?? '';
                if (!$answer) {
                    $this->error('请设置简答题标准答案');
                }
                $answer_config = $params['answer_config'] ?? [];
                if (!$answer_config) {
                    $this->error('请设置简答题答案关键词');
                }

                foreach ($answer_config as &$item) {
                    if (!$item['answer']) {
                        $this->error('简答题答案关键词不能为空');
                    }
                    if (!is_numeric($item['score']) || $item['score'] < 0) {
                        $this->error('简答题分数设置有误,必须为数字且不能小于0');
                    }

                    // $item['score'] = 0;
                }

                // 转json
                $params['answer'] = json_encode([
                    'answer' => $answer,
                    'config' => $answer_config
                ], JSON_UNESCAPED_UNICODE);
                break;

            // 材料题
            case 'MATERIAL':
                // dd([$params, $answer, $options]);

                if ($params['is_material_child']) {
                    $this->error('题型设置有误,材料题不能再设置为材料题的子题');
                }

                $params['is_material_child']    = 0;
                $params['material_question_id'] = 0;
                $params['material_questions']   = $params['material_questions'] ? json_decode($params['material_questions'], true) : [];
                if (!$params['material_questions']) {
                    if ($params['status'] == CommonStatus::NORMAL) {
                        $this->error('请设置材料题的子题(或者状态先设置隐藏)');
                    }
                }

                // foreach ($params['material_questions'] as $material_question) {
                //     if ($material_question['kind'] == 'MATERIAL') {
                //         $this->error('材料题的子题不能为材料题');
                //     }
                // }

                // 转json
                $params['answer'] = json_encode([
                    'questions' => $params['material_questions']
                ], JSON_UNESCAPED_UNICODE);
                break;
        }

        if ($params['is_material_child']) {
            $params['material_question_id'] = $params['material_question_id'] ?? 0;
            if (!$params['material_question_id']) {
                $this->error('请设置材料题的父题');
            }
            if ($params['material_score'] <= 0) {
                $this->error('请设置材料题子题的分数');
            }
        }
    }

    /**
     * 保存材料题父题
     * @param $question
     * @return void
     */
    protected function saveMaterialParentQuestion($question)
    {
        if (!$question || !$question['is_material_child'] || $question['kind'] == 'MATERIAL') {
            return;
        }
        if ($parentQuestion = QuestionModel::where('id', $question['material_question_id'])
            ->where('kind', 'MATERIAL')
            ->find()) {
            $answer = json_decode($parentQuestion->answer, true);
            if (!$answer) {
                $answer = [
                    'questions' => [
                        [
                            'id'            => $question['id'],
                            'score'         => $question['material_score'],
                            'answer'        => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
                            'answer_config' => null,
                        ]
                    ],
                ];
            } else {
                $has_child = false;
                foreach ($answer['questions'] as &$child_question) {
                    if ($child_question['id'] == $question['id']) {
                        $has_child                = true;
                        $child_question['score']  = $question['material_score'];
                        $child_question['answer'] = is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'];
                        break;
                    }
                }

                if (!$has_child) {
                    $answer['questions'][] = [
                        'id'            => $question['id'],
                        'score'         => $question['material_score'],
                        'answer'        => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
                        'answer_config' => null,
                    ];
                }
            }

            // 材料题父题答案追加子题设置
            $parentQuestion->answer = json_encode($answer, JSON_UNESCAPED_UNICODE);
            $parentQuestion->save();

            if ($materialQuestion = MaterialQuestionModel::where('parent_question_id', $question['material_question_id'])
                ->where('question_id', $question['id'])
                ->find()) {
                $materialQuestion->score  = $question['material_score'];
                $materialQuestion->answer = is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'];
                $materialQuestion->save();
            } else {
                // 保存材料题子题关联
                MaterialQuestionModel::create([
                    'parent_question_id' => $question['material_question_id'],
                    'question_id'        => $question['id'],
                    'score'              => $question['material_score'],
                    'answer'             => $question['answer'],
                    'weigh'              => 0,
                ]);
            }

        } else {
            $this->error('未找到所属材料题');
        }
    }

    /**
     * 保存材料题子题
     * @param $parentQuestion
     * @param $questions
     * @return void
     */
    protected function saveMaterialQuestions($parentQuestion, $questions)
    {
        if (!$parentQuestion || $parentQuestion['kind'] != 'MATERIAL' || !$questions) {
            return;
        }
        // 删除旧的子题
        MaterialQuestionModel::where('parent_question_id', $parentQuestion->id)->delete();

        // 保存新的子题
        $inserts = [];
        foreach ($questions as $key => $question) {
            $inserts[] = [
                'parent_question_id' => $parentQuestion->id,
                'question_id'        => $question['id'],
                'score'              => $question['score'],
                'answer'             => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
                'weigh'              => $key,
                'createtime'         => time(),
            ];
        }
        (new MaterialQuestionModel())->saveAll($inserts);
    }

    /**
     * 处理选项图片链接域名
     * @param $data
     */
    protected function optionsImage(&$data)
    {
        $options_img = $data['options_img'] ?? [];
        $options_img = json_decode($options_img, true);
        if ($options_img) {
            foreach ($options_img as &$item) {
                if (strpos($item['value'], '://') === false) {
                    $item['value'] = cdnurl($item['value'], true);
                }
            }
        }
        $data['options_img'] = json_encode($options_img);
        $data['options_img'] = $data['options_img'] == 'null' ? [] : $data['options_img'];
    }

    /**
     * 检查题目内容输入
     * @param $params
     */
    protected function checkTitle(&$params)
    {
        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!($params['title'] ?? '')) {
                $this->error('请输入题目内容');
            }
        } else if ($params['kind'] == 'FILL') {
            if (!($params['title_fill'] ?? '')) {
                $this->error('请输入填空题题目内容');
            }
            $params['title'] = $params['title_fill'];
        }

        // 替换题目图片CDN链接
        $params['title'] = FrontService::replaceImgUrl($params['title']);
    }
}