刘光辉
6 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
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
package jnpf.tmsService.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.audit.sdk.annotation.AuditLog;
import jnpf.exception.DataException;
import jnpf.tmsEntity.TmsPaperEntity;
import jnpf.tmsEntity.TmsPaperQuestionEntity;
import jnpf.tmsEntity.TmsPaperSectionEntity;
import jnpf.tmsEntity.TmsQuestionBankEntity;
import jnpf.tmsEntity.TmsQuestionEntity;
import jnpf.tmsEntity.paper.TmsPaperExportForm;
import jnpf.tmsEntity.paper.TmsPaperForm;
import jnpf.tmsEntity.paper.TmsPaperQuestionForm;
import jnpf.tmsEntity.paper.TmsPaperQuery;
import jnpf.tmsEntity.paper.TmsPaperSectionForm;
import jnpf.tmsEntity.enums.TmsOpenClosedInvalid;
import jnpf.tmsEntity.enums.TmsPaperSortMode;
import jnpf.tmsEntity.enums.TmsQuestionType;
import jnpf.tmsMapper.TmsPaperMapper;
import jnpf.tmsMapper.TmsPaperQuestionMapper;
import jnpf.tmsMapper.TmsPaperSectionMapper;
import jnpf.tmsMapper.TmsQuestionBankMapper;
import jnpf.tmsMapper.TmsQuestionMapper;
import jnpf.tmsService.TmsPaperService;
import jnpf.tmsUtil.TmsExcelExportHelper;
import jnpf.util.DateUtil;
import jnpf.util.RandomUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
@Service
@RequiredArgsConstructor
public class TmsPaperServiceImpl implements TmsPaperService {
    private static final Set<String> SUBJECTIVE_TYPES = Collections.singleton(TmsQuestionType.ESSAY.getCode());
 
    private final TmsPaperMapper paperMapper;
    private final TmsPaperSectionMapper sectionMapper;
    private final TmsPaperQuestionMapper paperQuestionMapper;
    private final TmsQuestionMapper questionMapper;
    private final TmsQuestionBankMapper bankMapper;
    /**
     * 试卷:条件分页查询列表
     */
    @Override
    public List<TmsPaperForm> getList(TmsPaperQuery query) {
        LambdaQueryWrapper<TmsPaperEntity> qw = new LambdaQueryWrapper<>();
        if (StringUtil.isNotEmpty(query.getBizStatus())) {
            qw.eq(TmsPaperEntity::getBizStatus, query.getBizStatus());
        } else {
            qw.ne(TmsPaperEntity::getBizStatus, TmsOpenClosedInvalid.INVALID.getCode());
        }
        if (StringUtil.isNotEmpty(query.getKeyword()) && !"null".equalsIgnoreCase(query.getKeyword())) {
            String kw = query.getKeyword().trim();
            qw.and(w -> w.like(TmsPaperEntity::getPaperName, kw).or().like(TmsPaperEntity::getPaperNo, kw));
        }
        qw.orderByDesc(TmsPaperEntity::getCreatorTime);
 
        long current = query.getCurrentPage() > 0 ? query.getCurrentPage() : 1;
        long size = query.getPageSize() > 0 ? query.getPageSize() : 20;
        Page<TmsPaperEntity> page = paperMapper.selectPage(new Page<>(current, size), qw);
 
        Map<String, Integer> countMap = loadQuestionCounts(page.getRecords());
        List<TmsPaperForm> list = new ArrayList<>(page.getRecords().size());
        for (TmsPaperEntity row : page.getRecords()) {
            TmsPaperForm form = toHeaderForm(row);
            form.setQuestionCount(countMap.getOrDefault(row.getId(), 0));
            list.add(form);
        }
        query.setData(list, page.getTotal());
        return list;
    }
    /**
     * 试卷:按主键查询详情
     */
    @Override
    public TmsPaperForm getInfo(String id) {
        TmsPaperEntity entity = requireOne(id);
        TmsPaperForm form = toHeaderForm(entity);
        form.setSections(loadSections(id));
        int count = 0;
        if (form.getSections() != null) {
            for (TmsPaperSectionForm sec : form.getSections()) {
                if (sec.getQuestions() != null) {
                    count += sec.getQuestions().size();
                }
            }
        }
        form.setQuestionCount(count);
        return form;
    }
    /**
     * 试卷:新增
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(TmsPaperForm form) {
        validateForm(form);
        String id = RandomUtil.uuId();
        Date now = new Date();
        String userId = UserProvider.getLoginUserId();
 
        TmsPaperEntity entity = new TmsPaperEntity();
        entity.setId(id);
        entity.setPaperNo(nextPaperNo());
        applyHeader(entity, form);
        entity.setCreatorUserId(userId);
        entity.setCreatorTime(now);
        paperMapper.insert(entity);
 
        saveComposition(id, form.getSections(), userId, now);
        refreshComputed(id);
        return id;
    }
    /**
     * 试卷:更新
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(String id, TmsPaperForm form) {
        TmsPaperEntity entity = requireOne(id);
        if (TmsOpenClosedInvalid.INVALID.equalsCode(entity.getBizStatus())) {
            throw new DataException("已废弃试卷不可编辑");
        }
        if (TmsOpenClosedInvalid.OPEN.equalsCode(entity.getBizStatus())) {
            throw new DataException("请先停用后再编辑");
        }
        validateForm(form);
        Date now = new Date();
        String userId = UserProvider.getLoginUserId();
 
        applyHeader(entity, form);
        entity.setLastModifyUserId(userId);
        entity.setLastModifyTime(now);
        paperMapper.updateById(entity);
 
        // 章节/试题全量替换(已考快照在 tms_exam_item,改卷不影响历史)
        clearComposition(id);
        saveComposition(id, form.getSections(), userId, now);
        refreshComputed(id);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    @AuditLog(action = "PAPER_INVALIDATE", label = "废弃试卷", bizType = "TMS_PAPER",
            bizCodeExpr = "#id", targetTable = "tms_paper", targetIdExpr = "#id")
    /**
     * 试卷:作废
     */
    public void invalidate(String id) {
        TmsPaperEntity entity = requireOne(id);
        if (TmsOpenClosedInvalid.INVALID.equalsCode(entity.getBizStatus())) {
            return;
        }
        if (TmsOpenClosedInvalid.OPEN.equalsCode(entity.getBizStatus())) {
            throw new DataException("请先停用后再废弃");
        }
        entity.setBizStatus(TmsOpenClosedInvalid.INVALID.getCode());
        entity.setLastModifyUserId(UserProvider.getLoginUserId());
        entity.setLastModifyTime(new Date());
        paperMapper.updateById(entity);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    @AuditLog(action = "PAPER_STATUS", label = "试卷开放状态变更", bizType = "TMS_PAPER",
            bizCodeExpr = "#id", targetTable = "tms_paper", targetIdExpr = "#id",
            extraExpr = "{'bizStatus': #bizStatus}")
    /**
     * 设置业务状态
     */
    public void setBizStatus(String id, String bizStatus) {
        if (!TmsOpenClosedInvalid.OPEN.equalsCode(bizStatus) && !TmsOpenClosedInvalid.CLOSED.equalsCode(bizStatus)) {
            throw new DataException("状态无效,仅支持开放/不开放");
        }
        TmsPaperEntity entity = requireOne(id);
        if (TmsOpenClosedInvalid.INVALID.equalsCode(entity.getBizStatus())) {
            throw new DataException("已废弃试卷不可启用或停用");
        }
        entity.setBizStatus(bizStatus);
        entity.setLastModifyUserId(UserProvider.getLoginUserId());
        entity.setLastModifyTime(new Date());
        paperMapper.updateById(entity);
    }
 
    /**
     * 校验表单
     */
    private void validateForm(TmsPaperForm form) {
        if (form == null || StringUtil.isEmpty(form.getPaperName())) {
            throw new DataException("请填写试卷名称");
        }
        if (form.getDurationMin() != null && form.getDurationMin() < 0) {
            throw new DataException("考试时长不能为负数");
        }
        Date start = parseDate(form.getExamStart());
        Date end = parseDate(form.getExamEnd());
        Date publish = parseDate(form.getScorePublishTime());
        if ((start == null) != (end == null)) {
            throw new DataException("开考时间与结束时间需同时填写或同时留空");
        }
        if (start != null && end != null) {
            if (!end.after(start)) {
                throw new DataException("结束时间必须晚于开考时间");
            }
            if (form.getDurationMin() != null && form.getDurationMin() > 0) {
                long spanMin = (end.getTime() - start.getTime()) / 60_000L;
                if (form.getDurationMin() > spanMin) {
                    throw new DataException("考试时长不能超过开考至结束的间隔(" + spanMin + " 分钟)");
                }
            }
        }
        if (publish != null) {
            if (end != null && publish.before(end)) {
                throw new DataException("成绩公布时间不能早于结束时间");
            }
            if (end == null && start != null && publish.before(start)) {
                throw new DataException("成绩公布时间不能早于开考时间");
            }
        }
        BigDecimal totalFromForm = sumSectionScores(form);
        if (form.getPassScore() != null && totalFromForm != null
                && form.getPassScore().compareTo(totalFromForm) > 0) {
            throw new DataException("合格分数不能大于试卷总分(当前总分 " + totalFromForm.stripTrailingZeros().toPlainString() + ")");
        }
        if (form.getSections() != null) {
            Set<String> usedQuestionIds = new HashSet<>();
            for (TmsPaperSectionForm sec : form.getSections()) {
                if (sec.getQuestions() == null) {
                    continue;
                }
                for (TmsPaperQuestionForm q : sec.getQuestions()) {
                    if (StringUtil.isEmpty(q.getQuestionId())) {
                        throw new DataException("试卷试题缺少试题ID");
                    }
                    if (q.getScore() == null || q.getScore().compareTo(BigDecimal.ZERO) <= 0) {
                        throw new DataException("组卷试题分值必须大于 0");
                    }
                    if (!usedQuestionIds.add(q.getQuestionId())) {
                        throw new DataException("同一试卷不能重复添加同一试题");
                    }
                    TmsQuestionEntity question = questionMapper.selectById(q.getQuestionId());
                    if (question == null) {
                        throw new DataException("试题不存在或已废弃,无法组卷");
                    }
                    if (TmsOpenClosedInvalid.INVALID.equalsCode(question.getBizStatus())) {
                        throw new DataException("废弃试题不可用于组卷:" + question.getQuestionNo());
                    }
                    if (StringUtil.isNotEmpty(sec.getQuestionType())
                            && StringUtil.isNotEmpty(question.getQuestionType())
                            && !sec.getQuestionType().equals(question.getQuestionType())) {
                        throw new DataException("试题「" + question.getQuestionNo() + "」与章节题型不一致");
                    }
                }
            }
        }
    }
 
    /**
     * 汇总各大题分值
     */
    private static BigDecimal sumSectionScores(TmsPaperForm form) {
        if (form == null || form.getSections() == null) {
            return BigDecimal.ZERO;
        }
        BigDecimal total = BigDecimal.ZERO;
        for (TmsPaperSectionForm sec : form.getSections()) {
            if (sec.getQuestions() == null) {
                continue;
            }
            for (TmsPaperQuestionForm q : sec.getQuestions()) {
                if (q.getScore() != null) {
                    total = total.add(q.getScore());
                }
            }
        }
        return total;
    }
 
    /**
     * 写入试卷头信息
     */
    private void applyHeader(TmsPaperEntity entity, TmsPaperForm form) {
        entity.setPaperName(form.getPaperName().trim());
        // 保存仅允许开放/不开放;废弃走 invalidate
        String status = StringUtil.isNotEmpty(form.getBizStatus()) ? form.getBizStatus() : TmsOpenClosedInvalid.OPEN.getCode();
        if (!TmsOpenClosedInvalid.OPEN.equalsCode(status) && !TmsOpenClosedInvalid.CLOSED.equalsCode(status)) {
            status = TmsOpenClosedInvalid.OPEN.getCode();
        }
        entity.setBizStatus(status);
        entity.setDurationMin(form.getDurationMin() == null ? 60 : form.getDurationMin());
        entity.setExamStart(parseDate(form.getExamStart()));
        entity.setExamEnd(parseDate(form.getExamEnd()));
        entity.setScorePublishTime(parseDate(form.getScorePublishTime()));
        entity.setPassScore(form.getPassScore());
        entity.setTotalScore(form.getTotalScore());
        entity.setSortMode(StringUtil.isNotEmpty(form.getSortMode()) ? form.getSortMode() : TmsPaperSortMode.PAPER.getCode());
        entity.setRemark(form.getRemark());
    }
 
    /**
     * 清空试卷组卷结构
     */
    private void clearComposition(String paperId) {
        LambdaQueryWrapper<TmsPaperQuestionEntity> qQw = new LambdaQueryWrapper<>();
        qQw.eq(TmsPaperQuestionEntity::getForeignId, paperId);
        paperQuestionMapper.delete(qQw);
 
        LambdaQueryWrapper<TmsPaperSectionEntity> sQw = new LambdaQueryWrapper<>();
        sQw.eq(TmsPaperSectionEntity::getForeignId, paperId);
        sectionMapper.delete(sQw);
    }
 
    /**
     * 保存试卷大题与题目
     */
    private void saveComposition(String paperId, List<TmsPaperSectionForm> sections, String userId, Date now) {
        if (sections == null || sections.isEmpty()) {
            return;
        }
        int secIdx = 0;
        for (TmsPaperSectionForm secForm : sections) {
            String sectionId = RandomUtil.uuId();
            TmsPaperSectionEntity sec = new TmsPaperSectionEntity();
            sec.setId(sectionId);
            sec.setForeignId(paperId);
            sec.setSectionName(StringUtil.isEmpty(secForm.getSectionName())
                    ? defaultSectionName(secForm.getQuestionType(), ++secIdx)
                    : secForm.getSectionName().trim());
            sec.setQuestionType(secForm.getQuestionType());
            sec.setSortNo(secForm.getSortNo() != null ? secForm.getSortNo() : secIdx);
            sec.setCreatorUserId(userId);
            sec.setCreatorTime(now);
            sectionMapper.insert(sec);
 
            if (secForm.getQuestions() == null || secForm.getQuestions().isEmpty()) {
                continue;
            }
            int qIdx = 0;
            for (TmsPaperQuestionForm qForm : secForm.getQuestions()) {
                TmsPaperQuestionEntity pq = new TmsPaperQuestionEntity();
                pq.setId(RandomUtil.uuId());
                pq.setForeignId(paperId);
                pq.setSectionId(sectionId);
                pq.setQuestionId(qForm.getQuestionId());
                pq.setScore(qForm.getScore() == null ? BigDecimal.ZERO : qForm.getScore());
                pq.setSortNo(qForm.getSortNo() != null ? qForm.getSortNo() : ++qIdx);
                pq.setCreatorUserId(userId);
                pq.setCreatorTime(now);
                paperQuestionMapper.insert(pq);
            }
        }
    }
 
    /** 按卷内试题重算总分、是否含主观题 */
    private void refreshComputed(String paperId) {
        TmsPaperEntity entity = paperMapper.selectById(paperId);
        if (entity == null) {
            return;
        }
        LambdaQueryWrapper<TmsPaperQuestionEntity> qw = new LambdaQueryWrapper<>();
        qw.eq(TmsPaperQuestionEntity::getForeignId, paperId);
        List<TmsPaperQuestionEntity> rows = paperQuestionMapper.selectList(qw);
 
        BigDecimal total = BigDecimal.ZERO;
        boolean subjective = false;
        for (TmsPaperQuestionEntity row : rows) {
            if (row.getScore() != null) {
                total = total.add(row.getScore());
            }
            if (!subjective) {
                TmsQuestionEntity q = questionMapper.selectById(row.getQuestionId());
                if (q != null && SUBJECTIVE_TYPES.contains(q.getQuestionType())) {
                    subjective = true;
                }
            }
        }
        entity.setTotalScore(total);
        entity.setHasSubjective(subjective ? "1" : "0");
        entity.setLastModifyUserId(UserProvider.getLoginUserId());
        entity.setLastModifyTime(new Date());
        paperMapper.updateById(entity);
    }
 
    /**
     * 加载试卷大题结构
     */
    private List<TmsPaperSectionForm> loadSections(String paperId) {
        LambdaQueryWrapper<TmsPaperSectionEntity> sQw = new LambdaQueryWrapper<>();
        sQw.eq(TmsPaperSectionEntity::getForeignId, paperId);
        sQw.orderByAsc(TmsPaperSectionEntity::getSortNo);
        List<TmsPaperSectionEntity> sections = sectionMapper.selectList(sQw);
 
        LambdaQueryWrapper<TmsPaperQuestionEntity> qQw = new LambdaQueryWrapper<>();
        qQw.eq(TmsPaperQuestionEntity::getForeignId, paperId);
        qQw.orderByAsc(TmsPaperQuestionEntity::getSortNo);
        List<TmsPaperQuestionEntity> questions = paperQuestionMapper.selectList(qQw);
 
        Map<String, TmsQuestionEntity> questionMap = loadQuestions(questions);
        Map<String, String> bankNames = loadBankNames(questionMap.values());
 
        Map<String, List<TmsPaperQuestionForm>> bySection = new HashMap<>();
        for (TmsPaperQuestionEntity pq : questions) {
            TmsPaperQuestionForm qf = new TmsPaperQuestionForm();
            qf.setId(pq.getId());
            qf.setSectionId(pq.getSectionId());
            qf.setQuestionId(pq.getQuestionId());
            qf.setScore(pq.getScore());
            qf.setSortNo(pq.getSortNo());
            TmsQuestionEntity q = questionMap.get(pq.getQuestionId());
            if (q != null) {
                qf.setQuestionNo(q.getQuestionNo());
                qf.setStem(q.getStem());
                qf.setQuestionType(q.getQuestionType());
                qf.setBankName(bankNames.get(q.getBankId()));
            }
            bySection.computeIfAbsent(pq.getSectionId(), k -> new ArrayList<>()).add(qf);
        }
 
        List<TmsPaperSectionForm> result = new ArrayList<>(sections.size());
        for (TmsPaperSectionEntity sec : sections) {
            TmsPaperSectionForm sf = new TmsPaperSectionForm();
            sf.setId(sec.getId());
            sf.setSectionName(sec.getSectionName());
            sf.setQuestionType(sec.getQuestionType());
            sf.setSortNo(sec.getSortNo());
            sf.setQuestions(bySection.getOrDefault(sec.getId(), Collections.emptyList()));
            result.add(sf);
        }
        return result;
    }
 
    /**
     * 批量加载试题
     */
    private Map<String, TmsQuestionEntity> loadQuestions(List<TmsPaperQuestionEntity> rows) {
        Set<String> ids = new HashSet<>();
        for (TmsPaperQuestionEntity row : rows) {
            if (StringUtil.isNotEmpty(row.getQuestionId())) {
                ids.add(row.getQuestionId());
            }
        }
        if (ids.isEmpty()) {
            return Collections.emptyMap();
        }
        List<TmsQuestionEntity> list = questionMapper.selectBatchIds(ids);
        Map<String, TmsQuestionEntity> map = new HashMap<>(list.size());
        for (TmsQuestionEntity q : list) {
            map.put(q.getId(), q);
        }
        return map;
    }
 
    /**
     * 加载题库名称
     */
    private Map<String, String> loadBankNames(Iterable<TmsQuestionEntity> questions) {
        Set<String> bankIds = new HashSet<>();
        for (TmsQuestionEntity q : questions) {
            if (q != null && StringUtil.isNotEmpty(q.getBankId())) {
                bankIds.add(q.getBankId());
            }
        }
        if (bankIds.isEmpty()) {
            return Collections.emptyMap();
        }
        List<TmsQuestionBankEntity> banks = bankMapper.selectBatchIds(bankIds);
        Map<String, String> map = new HashMap<>(banks.size());
        for (TmsQuestionBankEntity bank : banks) {
            map.put(bank.getId(), bank.getBankName());
        }
        return map;
    }
 
    /**
     * 统计各试卷题目数
     */
    private Map<String, Integer> loadQuestionCounts(List<TmsPaperEntity> papers) {
        if (papers == null || papers.isEmpty()) {
            return Collections.emptyMap();
        }
        Set<String> ids = new HashSet<>();
        for (TmsPaperEntity p : papers) {
            ids.add(p.getId());
        }
        LambdaQueryWrapper<TmsPaperQuestionEntity> qw = new LambdaQueryWrapper<>();
        qw.in(TmsPaperQuestionEntity::getForeignId, ids);
        List<TmsPaperQuestionEntity> rows = paperQuestionMapper.selectList(qw);
        Map<String, Integer> map = new HashMap<>();
        for (TmsPaperQuestionEntity row : rows) {
            map.merge(row.getForeignId(), 1, Integer::sum);
        }
        return map;
    }
 
    /**
     * 按 ID 查询,不存在则抛错
     */
    private TmsPaperEntity requireOne(String id) {
        if (StringUtil.isEmpty(id)) {
            throw new DataException("试卷不存在");
        }
        TmsPaperEntity entity = paperMapper.selectById(id);
        if (entity == null) {
            throw new DataException("试卷不存在");
        }
        return entity;
    }
 
    /**
     * 转为试卷头表单
     */
    private TmsPaperForm toHeaderForm(TmsPaperEntity entity) {
        TmsPaperForm form = new TmsPaperForm();
        form.setId(entity.getId());
        form.setPaperNo(entity.getPaperNo());
        form.setPaperName(entity.getPaperName());
        form.setBizStatus(entity.getBizStatus());
        form.setDurationMin(entity.getDurationMin());
        form.setExamStart(formatDate(entity.getExamStart()));
        form.setExamEnd(formatDate(entity.getExamEnd()));
        form.setScorePublishTime(formatDate(entity.getScorePublishTime()));
        form.setPassScore(entity.getPassScore());
        form.setTotalScore(entity.getTotalScore());
        form.setSortMode(entity.getSortMode());
        form.setHasSubjective(entity.getHasSubjective());
        form.setRemark(entity.getRemark());
        form.setCreatorTime(formatDate(entity.getCreatorTime()));
        return form;
    }
 
    /**
     * 试卷编号:年份后两位 + 4 位流水,如 260001。
     * 按当年最大号 +1,含已删记录,避免流水回退。
     */
    private synchronized String nextPaperNo() {
        String prefix = String.format("%02d", LocalDate.now().getYear() % 100);
        String maxNo = paperMapper.selectMaxPaperNo(prefix);
        int next = 1;
        if (StringUtil.isNotEmpty(maxNo) && maxNo.length() >= 6 && maxNo.startsWith(prefix)) {
            try {
                next = Integer.parseInt(maxNo.substring(prefix.length())) + 1;
            } catch (NumberFormatException ignored) {
                next = 1;
            }
        }
        if (next > 9999) {
            throw new DataException("当年试卷编号已用尽(" + prefix + "9999)");
        }
        return prefix + String.format("%04d", next);
    }
 
    /**
     * 默认大题名称
     */
    private static String defaultSectionName(String questionType, int idx) {
        if (StringUtil.isEmpty(questionType)) {
            return "第" + idx + "章";
        }
        TmsQuestionType type = TmsQuestionType.of(questionType);
        if (type == null) {
            return "第" + idx + "章";
        }
        switch (type) {
            case SINGLE:
                return "单选题";
            case MULTI:
                return "多选题";
            case JUDGE:
                return "判断题";
            case BLANK:
                return "填空题";
            case ESSAY:
                return "问答题";
            default:
                return "第" + idx + "章";
        }
    }
 
    /**
     * 解析日期时间
     */
    private static Date parseDate(String text) {
        if (StringUtil.isEmpty(text)) {
            return null;
        }
        String raw = text.trim();
        try {
            if (raw.matches("^\\d{10,13}$")) {
                long ts = Long.parseLong(raw);
                if (raw.length() == 10) {
                    ts = ts * 1000L;
                }
                return new Date(ts);
            }
            return DateUtil.stringToDate(raw);
        } catch (Exception ex) {
            throw new DataException("时间格式无效:" + text);
        }
    }
 
    /**
     * 格式化日期时间
     */
    private static String formatDate(Date date) {
        if (date == null) {
            return null;
        }
        return DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss");
    }
    /**
     * 导出试卷试题
     */
    @Override
    public void exportQuestions(TmsPaperExportForm form, HttpServletResponse response) {
        if (form == null || form.getIds() == null || form.getIds().isEmpty()) {
            throw new DataException("请先勾选要导出的试卷");
        }
        List<String> ids = form.getIds().stream()
                .filter(StringUtil::isNotEmpty)
                .distinct()
                .collect(java.util.stream.Collectors.toList());
        if (ids.isEmpty()) {
            throw new DataException("请先勾选要导出的试卷");
        }
        List<String> headers = Arrays.asList(
                "试卷编号", "试卷名称", "章节", "题序", "试题编号", "题型", "题干", "分值", "题库");
        List<Integer> widths = Arrays.asList(100, 160, 120, 50, 80, 70, 280, 50, 120);
        List<List<String>> rows = new ArrayList<>();
        for (String id : ids) {
            TmsPaperForm paper = getInfo(id);
            if (paper.getSections() == null) {
                continue;
            }
            for (TmsPaperSectionForm sec : paper.getSections()) {
                String sectionName = sec.getSectionName() == null ? "" : sec.getSectionName();
                if (sec.getQuestions() == null) {
                    continue;
                }
                int seq = 0;
                for (TmsPaperQuestionForm q : sec.getQuestions()) {
                    seq++;
                    TmsQuestionType type = TmsQuestionType.of(q.getQuestionType());
                    rows.add(Arrays.asList(
                            nvl(paper.getPaperNo()),
                            nvl(paper.getPaperName()),
                            sectionName,
                            String.valueOf(seq),
                            nvl(q.getQuestionNo()),
                            type == null ? nvl(q.getQuestionType()) : type.getLabel(),
                            stripHtml(q.getStem()),
                            q.getScore() == null ? "" : q.getScore().stripTrailingZeros().toPlainString(),
                            nvl(q.getBankName())));
                }
            }
        }
        if (rows.isEmpty()) {
            throw new DataException("所选试卷没有可导出的试题");
        }
        try {
            TmsExcelExportHelper.writeSpreadsheet(response, "试卷试题清单", "试卷试题", headers, widths, rows);
        } catch (IOException e) {
            throw new DataException("导出试卷试题失败");
        }
    }
 
    /**
     * 空值兜底
     */
    private static String nvl(String v) {
        return v == null ? "" : v;
    }
 
    /**
     * 去除 HTML 标签
     */
    private static String stripHtml(String html) {
        if (StringUtil.isEmpty(html)) {
            return "";
        }
        return html.replaceAll("<[^>]+>", " ")
                .replace("&nbsp;", " ")
                .replaceAll("\\s+", " ")
                .trim();
    }
}