fuliqi
2024-07-05 3179257af77acbc229fe873de7495e2d3f8dfb6e
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
package com.ycl.jxkg.service.impl;
 
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ycl.jxkg.base.Result;
import com.ycl.jxkg.base.SystemCode;
import com.ycl.jxkg.context.WebContext;
import com.ycl.jxkg.domain.entity.ExamPaper;
import com.ycl.jxkg.domain.entity.Question;
import com.ycl.jxkg.domain.entity.Subject;
import com.ycl.jxkg.domain.exam.PaperFixQuestionDTO;
import com.ycl.jxkg.domain.exam.PaperQuestion;
import com.ycl.jxkg.domain.exam.PaperQuestionSettingDTO;
import com.ycl.jxkg.domain.exam.PaperSettingItem;
import com.ycl.jxkg.domain.form.ExamPaperForm;
import com.ycl.jxkg.domain.other.KeyValue;
import com.ycl.jxkg.domain.question.QuestionItemObject;
import com.ycl.jxkg.domain.question.QuestionObject;
import com.ycl.jxkg.domain.question.RandomQuestionDTO;
import com.ycl.jxkg.domain.vo.admin.exam.*;
import com.ycl.jxkg.domain.vo.student.dashboard.PaperFilter;
import com.ycl.jxkg.domain.vo.student.dashboard.PaperInfo;
import com.ycl.jxkg.domain.vo.student.exam.ExamPaperPageVO;
import com.ycl.jxkg.enums.ExamPaperTypeEnum;
import com.ycl.jxkg.enums.QuestionTypeEnum;
import com.ycl.jxkg.enums.VisibilityEnum;
import com.ycl.jxkg.enums.general.StatusEnum;
import com.ycl.jxkg.excel.*;
import com.ycl.jxkg.mapper.ExamPaperMapper;
import com.ycl.jxkg.mapper.QuestionMapper;
import com.ycl.jxkg.service.ExamPaperService;
import com.ycl.jxkg.service.QuestionService;
import com.ycl.jxkg.service.SubjectService;
import com.ycl.jxkg.service.TextContentService;
import com.ycl.jxkg.utils.DateTimeUtil;
import com.ycl.jxkg.utils.PageInfoHelper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
 
@Service
@RequiredArgsConstructor
public class ExamPaperServiceImpl extends ServiceImpl<ExamPaperMapper, ExamPaper> implements ExamPaperService {
 
    private final ExamPaperMapper examPaperMapper;
    private final QuestionMapper questionMapper;
    private final TextContentService textContentService;
    private final QuestionService questionService;
    private final SubjectService subjectService;
    private final WebContext webContext;
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addPaper(ExamPaperForm form) {
        ExamPaper examPaper = ExamPaperForm.getEntityByForm(form, null);
        examPaper.setScore(new BigDecimal(form.getScore()));
        //随机试卷
        if (ExamPaperTypeEnum.Random.getCode().equals(form.getPaperType())) {
            //校验题目数量
            List<PaperQuestionSettingDTO> questionSetting = form.getQuestionSetting();
            for (PaperQuestionSettingDTO settingDTO : questionSetting) {
                Integer questionType = settingDTO.getQuestionType();
                for (PaperSettingItem item : settingDTO.getSettingList()) {
                    Integer num = item.getNum();
                    Integer difficult = item.getDifficult();
                    //需要配置的题目数量为0则跳过
                    if(num ==null || num ==0 )continue;
                    //前端默认数据为0,转换为null
                    if (0 == item.getDifficult()){
                        difficult= null;
                    }
                    RandomQuestionDTO randomQuestionDTO = new RandomQuestionDTO();
                    randomQuestionDTO.setQuestionType(questionType);
                    randomQuestionDTO.setSubjectId(item.getSubjectId());
                    randomQuestionDTO.setDifficult(difficult);
                    Integer numInData = questionMapper.selectByDifAndSub(randomQuestionDTO);
                    if(num > numInData)return Result.fail(SystemCode.InnerError.getCode(), QuestionTypeEnum.fromCode(questionType).getName()+"难度为"+item.getDifficult()+"的题目数量不足");
                }
            }
            examPaper.setContent(JSON.toJSONString(form.getQuestionSetting()));
            baseMapper.insert(examPaper);
            return Result.ok();
        } else if (ExamPaperTypeEnum.Fixed.getCode().equals(form.getPaperType())) {
            //固定试卷
            examPaper.setContent(JSON.toJSONString(form.getQuestionTitleList()));
            baseMapper.insert(examPaper);
            return Result.ok();
        } else {
            //随序试卷
            List<PaperQuestionSettingDTO> questionSetting = form.getQuestionSetting();
            //题目配置里配的试卷类型
            List<Integer> types = questionSetting.stream().map(PaperQuestionSettingDTO::getQuestionType).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(types)) {
                return Result.fail(SystemCode.InnerError.getCode(), "试卷题目类型不能为空");
            }
            List<PaperFixQuestionDTO> questionTitleList = new ArrayList<>();
            for (PaperQuestionSettingDTO settingDTO : questionSetting) {
                List<PaperSettingItem> settingList = settingDTO.getSettingList();
                List<PaperQuestion> questionList = new ArrayList<>();
                for (PaperSettingItem item : settingList) {
                    Integer num = item.getNum();
                    Integer difficult = item.getDifficult();
                    //需要配置的题目数量为0则跳过
                    if(num ==null || num ==0 )continue;
                    //前端默认数据为0,转换为null
                    if (0 == difficult){
                        difficult = null;
                    }
                    List<Question> questions = questionMapper.getRandomQuestion(item.getSubjectId(), settingDTO.getQuestionType(), difficult, item.getNum());
                    if (CollectionUtils.isEmpty(questions) || item.getNum() > questions.size()) {
                        return Result.fail(SystemCode.InnerError.getCode(), QuestionTypeEnum.fromCode(settingDTO.getQuestionType()).getName()+"难度为:"+item.getDifficult()+"的题目数量不足");
                    }
                    //转换数据
                    convert(questionList, item, questions);
                }
                    PaperFixQuestionDTO dto = new PaperFixQuestionDTO();
                    dto.setTitle(settingDTO.getTitle());
                    dto.setQuestionType(settingDTO.getQuestionType());
                    dto.setQuestionList(questionList);
                    questionTitleList.add(dto);
            }
            examPaper.setContent(JSON.toJSONString(questionTitleList));
            baseMapper.insert(examPaper);
            return Result.ok();
        }
    }
    //转换数据
    private void convert(List<PaperQuestion> questionList, PaperSettingItem item, List<Question> questions) {
        for (Question question : questions) {
            PaperQuestion paperQuestion = new PaperQuestion();
            BeanUtils.copyProperties(question,paperQuestion);
            paperQuestion.setScore(item.getScore());
            //转换
            QuestionObject questionObject = JSONObject.parseObject(question.getContent(), QuestionObject.class);
            if(questionObject != null){
                paperQuestion.setItems(questionObject.getQuestionItemObjects());
                paperQuestion.setAnalyze(questionObject.getAnalyze());
                paperQuestion.setTitle(questionObject.getTitleContent());
            }
            questionList.add(paperQuestion);
        }
    }
 
 
    @Override
    public Result updateExamPaper(ExamPaperForm form) {
        //TODO:验证是否是试卷创建人
        ExamPaper examPaper = ExamPaperForm.getEntityByForm(form, null);
        examPaper.setScore(new BigDecimal(form.getScore()));
        //随机试卷
        if (ExamPaperTypeEnum.Random.getCode().equals(form.getPaperType())) {
            examPaper.setContent(JSON.toJSONString(form.getQuestionSetting()));
            baseMapper.updateById(examPaper);
            return Result.ok();
        } else if (ExamPaperTypeEnum.Fixed.getCode().equals(form.getPaperType())) {
            //固定试卷
            examPaper.setContent(JSON.toJSONString(form.getQuestionTitleList()));
            baseMapper.updateById(examPaper);
            return Result.ok();
        } else {
            //随序试卷
            examPaper.setContent(JSON.toJSONString(form.getQuestionTitleList()));
            baseMapper.updateById(examPaper);
            return Result.ok();
        }
    }
 
    @Override
    public PageInfo<ExamResponseVO> page(ExamPaperPageRequestVO requestVM) {
        //TODO: 数据权限
        PageInfo<ExamPaper> page = PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                examPaperMapper.page(requestVM));
        PageInfo<ExamResponseVO> pageVO = PageInfoHelper.copyMap(page, e -> {
            ExamResponseVO vo = new ExamResponseVO();
            BeanUtils.copyProperties(e, vo);
            vo.setVisibility(VisibilityEnum.valueOf(vo.getVisibility()).getCode() + "");
            vo.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            return vo;
        });
        return pageVO;
    }
 
 
//    @Override
//    public PageInfo<ExamPaper> taskExamPage(ExamPaperPageRequestVO requestVM) {
//        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
//                examPaperMapper.taskExamPage(requestVM));
//    }
 
    @Override
    public PageInfo<ExamPaper> studentPage(ExamPaperPageVO requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                examPaperMapper.studentPage(requestVM));
    }
 
 
//    @Override
//    @Transactional
//    public ExamPaper savePaperFromVM(ExamPaperEditRequestVO examPaperEditRequestVO, User user) {
//        ActionEnum actionEnum = (examPaperEditRequestVO.getId() == null) ? ActionEnum.ADD : ActionEnum.UPDATE;
//        Date now = new Date();
//        List<ExamPaperTitleItemVO> titleItemsVM = examPaperEditRequestVO.getTitleItems();
//        List<ExamPaperTitleItemObject> frameTextContentList = frameTextContentFromVM(titleItemsVM);
//        String frameTextContentStr = JsonUtil.toJsonStr(frameTextContentList);
//
//        ExamPaper examPaper = new ExamPaper();
//        BeanUtils.copyProperties(examPaperEditRequestVO, examPaper);
//        if (actionEnum == ActionEnum.ADD) {
//            TextContent frameTextContent = new TextContent();
//            frameTextContent.setContent(frameTextContentStr);
//            frameTextContent.setCreateTime(now);
//            textContentService.save(frameTextContent);
//            examPaper.setCreateTime(now);
//            examPaper.setCreateUser(user.getId());
//            examPaperFromVM(examPaperEditRequestVO, examPaper, titleItemsVM);
//            examPaperMapper.insert(examPaper);
//        } else {
//            examPaper = examPaperMapper.selectById(examPaperEditRequestVO.getId());
//          //TODO:
//            TextContent frameTextContent = textContentService.getById(examPaper.getFrameTextContentId());
//            frameTextContent.setContent(frameTextContentStr);
//            textContentService.updateById(frameTextContent);
//            examPaperFromVM(examPaperEditRequestVO, examPaper, titleItemsVM);
//            examPaperMapper.updateById(examPaper);
//        }
//        return examPaper;
//    }
 
    @Override
    public ExamPaperEditRequestVO examPaperToVM(Integer id) {
        ExamPaper examPaper = examPaperMapper.selectById(id);
        ExamPaperEditRequestVO vo = new ExamPaperEditRequestVO();
        BeanUtils.copyProperties(examPaper, vo);
        vo.setVisibility(VisibilityEnum.valueOf(vo.getVisibility()).getCode());
        //随机试卷
        if (ExamPaperTypeEnum.Random.getCode().equals(examPaper.getPaperType())) {
            vo.setQuestionSetting(JSONArray.parseArray(examPaper.getContent(), PaperQuestionSettingDTO.class));
        } else if (ExamPaperTypeEnum.Fixed.getCode().equals(examPaper.getPaperType())) {
            //固定试卷
            vo.setQuestionTitleList(JSONArray.parseArray(examPaper.getContent(), PaperFixQuestionDTO.class));
        } else {
            //随序试卷
            vo.setQuestionTitleList(JSONArray.parseArray(examPaper.getContent(), PaperFixQuestionDTO.class));
        }
        return vo;
    }
 
    @Override
    public List<PaperInfo> indexPaper(PaperFilter paperFilter) {
        return examPaperMapper.indexPaper(paperFilter);
    }
 
 
    @Override
    public Integer selectAllCount() {
        return examPaperMapper.selectAllCount();
    }
 
    @Override
    public List<Integer> selectMothCount() {
        Date startTime = DateTimeUtil.getMonthStartDay();
        Date endTime = DateTimeUtil.getMonthEndDay();
        List<KeyValue> mouthCount = examPaperMapper.selectCountByDate(startTime, endTime);
        List<String> mothStartToNowFormat = DateTimeUtil.MothStartToNowFormat();
        return mothStartToNowFormat.stream().map(md -> {
            KeyValue keyValue = mouthCount.stream().filter(kv -> kv.getName().equals(md)).findAny().orElse(null);
            return null == keyValue ? 0 : keyValue.getValue();
        }).collect(Collectors.toList());
    }
 
 
    private void examPaperFromVM(ExamPaperEditRequestVO examPaperEditRequestVO, ExamPaper examPaper, List<ExamPaperTitleItemVO> titleItemsVM) {
        //TODO:
//        Integer gradeLevel = subjectService.levelBySubjectId(examPaperEditRequestVO.getSubjectId());
//        Integer questionCount = titleItemsVM.stream()
//                .mapToInt(t -> t.getQuestionItems().size()).sum();
//        Integer score = titleItemsVM.stream().
//                flatMapToInt(t -> t.getQuestionItems().stream()
//                        .mapToInt(q -> ExamUtil.scoreFromVM(q.getScore()))
//                ).sum();
//        examPaper.setQuestionCount(questionCount);
//        examPaper.setScore(score);
//        examPaper.setGradeLevel(gradeLevel);
//        List<String> dateTimes = examPaperEditRequestVO.getLimitDateTime();
//        if (ExamPaperTypeEnum.Random == ExamPaperTypeEnum.fromCode(examPaper.getPaperType())) {
//            examPaper.setLimitStartTime(DateTimeUtil.parse(dateTimes.get(0), DateTimeUtil.STANDER_FORMAT));
//            examPaper.setLimitEndTime(DateTimeUtil.parse(dateTimes.get(1), DateTimeUtil.STANDER_FORMAT));
//        }
    }
 
//    private List<ExamPaperTitleItemObject> frameTextContentFromVM(List<ExamPaperTitleItemVO> titleItems) {
//        AtomicInteger index = new AtomicInteger(1);
//        return titleItems.stream().map(t -> {
//            ExamPaperTitleItemObject titleItem = new ExamPaperTitleItemObject();
//            BeanUtils.copyProperties(t, titleItem);
//            List<ExamPaperQuestionItemObject> questionItems = t.getQuestionItems().stream()
//                    .map(q -> {
//                        ExamPaperQuestionItemObject examPaperQuestionItemObject = new ExamPaperQuestionItemObject();
//                        BeanUtils.copyProperties(q, examPaperQuestionItemObject);
//                        examPaperQuestionItemObject.setItemOrder(index.getAndIncrement());
//                        return examPaperQuestionItemObject;
//                    })
//                    .collect(Collectors.toList());
//            titleItem.setQuestionItems(questionItems);
//            return titleItem;
//        }).collect(Collectors.toList());
//    }
 
    @Override
    public List<ExamPaper> myExamPaper(Integer paperType) {
        Integer userId = webContext.getCurrentUser().getId();
        List<ExamPaper> list = new LambdaQueryChainWrapper<>(baseMapper)
                .select(ExamPaper::getId, ExamPaper::getName, ExamPaper::getVisibility)
                .eq(ExamPaper::getCreateUser, userId)
                .eq(Objects.nonNull(paperType), ExamPaper::getPaperType, paperType)
                .or()
                .eq(ExamPaper::getVisibility, VisibilityEnum.Public.getName())
                .eq(Objects.nonNull(paperType), ExamPaper::getPaperType, paperType)
                .list();
        list.stream().forEach(item -> {
            if (VisibilityEnum.Public.getName().equals(item.getVisibility())) {
                item.setName(item.getName() + " (公开)");
            }
        });
        return list;
    }
 
    @Override
    @SneakyThrows
    public void importTemplate(HttpServletResponse response) {
        String fileName = URLEncoder.encode("试卷导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
 
        // 构建模板样例数据
        List<QuestionImportVO> data = new ArrayList<>(8);
        QuestionImportVO questionImportVO = new QuestionImportVO();
        questionImportVO.setLabel("标题1");
        questionImportVO.setQuestionType("单选题");
        questionImportVO.setDifficult(2);
        questionImportVO.setCorrect("A");
        questionImportVO.setScore(2);
        questionImportVO.setAnalyze("A是对的");
        questionImportVO.setTitle("这是一道测试题目,使用该模板请删除或替换这道题");
        questionImportVO.setOptionName("A");
        questionImportVO.setOptionValue("选我");
        data.add(questionImportVO);
 
        QuestionImportVO questionImport1 = new QuestionImportVO();
        questionImport1.setOptionName("B");
        questionImport1.setOptionValue("选B");
        data.add(questionImport1);
 
        QuestionImportVO questionImport2 = new QuestionImportVO();
        questionImport2.setOptionName("C");
        questionImport2.setOptionValue("选C");
        data.add(questionImport2);
 
        QuestionImportVO questionImport3 = new QuestionImportVO();
        questionImport3.setOptionName("D");
        questionImport3.setOptionValue("选D");
        data.add(questionImport3);
 
        EasyExcel.write(response.getOutputStream(), QuestionImportVO.class)
                .sheet("模板")
                .registerWriteHandler(new FixedMergeCellStrategy(2, 4, Arrays.asList(2, 3, 6, 7, 8, 9)))
                .registerWriteHandler(new FixedMergeCellStrategy(2, 20, Arrays.asList(0, 1)))
                .doWrite(data);
    }
 
    @Override
    @SneakyThrows
    public void export(QuestionExportVO query, HttpServletResponse response) {
        // 查询导出数据
        List<QuestionImportVO> exportData = questionService.export(query);
        // 构建数据
        List<QuestionImportVO> exportList = new ArrayList<>(exportData.size() * 4);
        // 行合并规则
        List<RowItem> mergeRowList = new ArrayList<>(exportData.size());
        int j = 2;
        for (QuestionImportVO data : exportData) {
            QuestionObject questionContent = JSON.parseObject(data.getQuestionContent(), QuestionObject.class);
 
            RowItem rowItem = new RowItem();
            rowItem.setStart(j);
            int end = j + questionContent.getQuestionItemObjects().size() - 1;
            rowItem.setEnd(end);
            mergeRowList.add(rowItem);
            j = end + 1;
            int i = 0;
            for (QuestionItemObject option : questionContent.getQuestionItemObjects()) {
                if (i == 0) {
                    QuestionImportVO master = new QuestionImportVO();
                    BeanUtils.copyProperties(data, master);
                    if (org.springframework.util.StringUtils.hasText(data.getQuestionType())) {
                        master.setQuestionType(QuestionTypeEnum.fromCode(Integer.valueOf(data.getQuestionType())).getName());
                    }
                    master.setOptionName(option.getPrefix());
                    master.setOptionValue(option.getContent());
                    master.setTitle(questionContent.getTitleContent());
                    master.setAnalyze(questionContent.getAnalyze());
                    master.setCorrect(data.getCorrect().replaceAll(",", "、"));
                    BigDecimal score = BigDecimal.valueOf(master.getScore());
                    master.setScore(score.divide(BigDecimal.TEN).intValue());
                    exportList.add(master);
                } else {
                    QuestionImportVO optionItem = new QuestionImportVO();
                    optionItem.setOptionName(option.getPrefix());
                    optionItem.setOptionValue(option.getContent());
                    exportList.add(optionItem);
                }
                i++;
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("题目导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
 
        // 查出所有的课目(excel下拉数据)
        List<Subject> subjects = subjectService.list();
        List<String> subjectNameList = subjects.stream().map(Subject::getName).collect(Collectors.toList());
        EasyExcel.write(response.getOutputStream(), QuestionImportVO.class)
                .sheet("题目导出数据")
                .registerWriteHandler(new SelectExcel(subjectNameList))
                .registerWriteHandler(new DynamicMergeCellStrategy(mergeRowList, Arrays.asList(0, 1, 2, 5, 6, 7, 8)))
                .doWrite(exportList);
    }
 
    @Override
    @Transactional
    @SneakyThrows
    public Result importPaper(MultipartFile file, ExamPaperForm form) {
        List<Subject> subjects = subjectService.list();
        List<Integer> questionNum = new ArrayList<>();
        List<Integer> totalScore = new ArrayList<>();
        // 拿到试卷
        ExamPaper examPaper = ExamPaperForm.getEntityByForm(form, null);
        // 题目集合用于批量保存
        ArrayList<Question> questions = new ArrayList<>();
        // 一张试卷多个标题
        ArrayList<PaperFixQuestionDTO> list = new ArrayList<>();
 
        Consumer<List<QuestionImportVO>> consumer = (data) -> {
            // 循环每一行
            for (int i = 0; i < data.size(); i++) {
                // 读取的题目
                QuestionImportVO excelQuestion = data.get(i);
                String questionType = excelQuestion.getQuestionType();
                String label = excelQuestion.getLabel();
                // 判断是否标题
                if (excelQuestion.master()) {
                    // 一个标题多个题目
                    ArrayList<PaperQuestion> paperQuestions = new ArrayList<>();
                    // 循环题目
                    while (Boolean.TRUE) {
                        // 更新读取的题目
                        excelQuestion = data.get(i);
                        // 判断是否题目
                        if (excelQuestion.intact()) {
                            Question question = new Question();
                            totalScore.add(excelQuestion.getScore());
                            // 该题的选项
                            List<QuestionItemObject> options = new ArrayList<>(8);
                            // 选项内容
                            QuestionItemObject option = new QuestionItemObject();
                            option.setPrefix(excelQuestion.getOptionName());
                            option.setContent(excelQuestion.getOptionValue());
                            options.add(option);
                            // 循环选项
                            while (Boolean.TRUE) {
                                // 判断是否是最后一条
                                if (i + 1 == data.size()) {
                                    break;
                                }
                                QuestionImportVO nextQuestion = data.get(1 + i);
                                if (nextQuestion.intact()) {
                                    break;
                                }
                                QuestionItemObject nextOption = new QuestionItemObject();
                                nextOption.setPrefix(nextQuestion.getOptionName());
                                nextOption.setContent(nextQuestion.getOptionValue());
                                options.add(nextOption);
                                i++;
                            }
                            // 保存题目内容
                            QuestionObject questionObject = new QuestionObject();
                            questionObject.setQuestionItemObjects(options);
                            questionObject.setAnalyze(excelQuestion.getAnalyze());
                            questionObject.setTitleContent(excelQuestion.getTitle());
                            questionObject.setCorrect(excelQuestion.getCorrect());
                            question.setTitle(excelQuestion.getTitle());
                            question.setContent(JSON.toJSONString(questionObject));
                            question.setQuestionType(QuestionTypeEnum.get(excelQuestion.getQuestionType()));
                            // 答案(多选需要用、分割保存字符串到数据库)
                            String[] corrects = excelQuestion.getCorrect().split("、");
                            if (corrects.length > 1) {
                                question.setCorrect(String.join(",", corrects));
                            } else {
                                question.setCorrect(excelQuestion.getCorrect());
                            }
                            // 难度
                            question.setDifficult(excelQuestion.getDifficult());
                            // 创建人
                            question.setCreateUser(2);
                            question.setStatus(StatusEnum.ENABLE);
                            question.setCreateTime(new Date());
                            question.setDeleted(0);
                            question.setQuestionType(QuestionTypeEnum.get(questionType));
                            // 根据科目名称获取id
                            QuestionImportVO finalExcelQuestion = excelQuestion;
                            question.setSubjectId(subjects.stream().filter(subject -> subject.getName().equals(finalExcelQuestion.getSubject())).findFirst().get().getId());
                            questions.add(question);
 
                            PaperQuestion paperQuestion = new PaperQuestion();
                            BeanUtils.copyProperties(question, paperQuestion);
                            paperQuestion.setItems(options);
                            paperQuestion.setAnalyze(excelQuestion.getAnalyze());
                            paperQuestion.setScore(BigDecimal.valueOf(excelQuestion.getScore()));
                            paperQuestions.add(paperQuestion);
                        }
                        if (i + 1 == data.size() || data.get(i + 1).master()) {
                            break;
                        }
                        i++;
                    }
                    // 组装试卷内容
                    PaperFixQuestionDTO paperFixQuestionDTO = new PaperFixQuestionDTO();
                    paperFixQuestionDTO.setTitle(label);
                    paperFixQuestionDTO.setQuestionType(QuestionTypeEnum.get(questionType));
                    paperFixQuestionDTO.setQuestionList(paperQuestions);
                    questionNum.add(paperQuestions.size());
                    list.add(paperFixQuestionDTO);
                }
            }
        };
        EasyExcel.read(file.getInputStream(), QuestionImportVO.class, new CurrencyDataListener(consumer)).sheet("模板").doRead();
        // 保存题目
        questionService.saveBatch(questions);
        // 保存试卷
        examPaper.setContent(JSON.toJSONString(list));
        examPaper.setVisibility(VisibilityEnum.fromCode(form.getVisibility()).getName());
        examPaper.setCreateUser(2);
        examPaper.setCreateTime(new Date());
        Integer score = totalScore.stream().reduce(Integer::sum).orElse(0);
        Integer num = questionNum.stream().reduce(Integer::sum).orElse(0);
        examPaper.setScore(new BigDecimal(score));
        examPaper.setNum(num);
        examPaperMapper.insert(examPaper);
        return Result.ok();
    }
}