qirong
2023-06-26 77be36cc9077b09186e69440f3204f9e623c335a
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
package com.mindskip.xzs.service.impl;
 
import com.mindskip.xzs.configuration.spring.exception.QuestionException;
import com.mindskip.xzs.domain.*;
import com.mindskip.xzs.domain.TextContent;
import com.mindskip.xzs.domain.enums.ExamPaperTypeEnum;
import com.mindskip.xzs.domain.enums.QuestionTypeEnum;
import com.mindskip.xzs.domain.exam.ExamPaperQuestionItemObject;
import com.mindskip.xzs.domain.exam.ExamPaperTitleItemObject;
import com.mindskip.xzs.domain.other.KeyValue;
import com.mindskip.xzs.repository.ExamPaperMapper;
import com.mindskip.xzs.repository.QuestionMapper;
import com.mindskip.xzs.service.*;
import com.mindskip.xzs.service.enums.ActionEnum;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.JsonUtil;
import com.mindskip.xzs.utility.ModelMapperSingle;
import com.mindskip.xzs.utility.ExamUtil;
import com.mindskip.xzs.viewmodel.admin.exam.ExamPaperEditRequestVM;
import com.mindskip.xzs.viewmodel.admin.exam.ExamPaperPageRequestVM;
import com.mindskip.xzs.viewmodel.admin.exam.ExamPaperTitleItemVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionEditRequestVM;
import com.mindskip.xzs.viewmodel.student.dashboard.PaperFilter;
import com.mindskip.xzs.viewmodel.student.dashboard.PaperInfo;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperPageVM;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mindskip.xzs.domain.ExamPaper;
import com.mindskip.xzs.domain.Question;
import com.mindskip.xzs.domain.User;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
 
@Service
public class ExamPaperServiceImpl extends BaseServiceImpl<ExamPaper> implements ExamPaperService {
 
    protected final static ModelMapper modelMapper = ModelMapperSingle.Instance();
    private final ExamPaperMapper examPaperMapper;
    private final QuestionMapper questionMapper;
    private final TextContentService textContentService;
    private final QuestionService questionService;
    private final SubjectService subjectService;
    private final ExamPaperDepartmentService examPaperDepartmentService;
    private final ExamPaperSubjectService examPaperSubjectService;
    private final QuestionSubjectService questionSubjectService;
 
    @Autowired
    public ExamPaperServiceImpl(ExamPaperMapper examPaperMapper, QuestionMapper questionMapper, TextContentService textContentService, QuestionService questionService, SubjectService subjectService, ExamPaperDepartmentService examPaperDepartmentService, ExamPaperSubjectService examPaperSubjectService, QuestionSubjectService questionSubjectService) {
        super(examPaperMapper);
        this.examPaperMapper = examPaperMapper;
        this.questionMapper = questionMapper;
        this.textContentService = textContentService;
        this.questionService = questionService;
        this.subjectService = subjectService;
        this.examPaperDepartmentService = examPaperDepartmentService;
        this.examPaperSubjectService = examPaperSubjectService;
        this.questionSubjectService = questionSubjectService;
    }
 
 
    @Override
    public PageInfo<ExamPaper> page(ExamPaperPageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                examPaperMapper.page(requestVM));
    }
 
    @Override
    public PageInfo<ExamPaper> taskExamPage(ExamPaperPageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                examPaperMapper.taskExamPage(requestVM));
    }
 
    @Override
    public PageInfo<ExamPaper> studentPage(ExamPaperPageVM requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                examPaperMapper.studentPage(requestVM));
    }
 
 
    @Override
    @Transactional
    public ExamPaper savePaperFromVM(ExamPaperEditRequestVM examPaperEditRequestVM, User user) throws QuestionException {
        ActionEnum actionEnum = (examPaperEditRequestVM.getId() == null) ? ActionEnum.ADD : ActionEnum.UPDATE;
        Date now = new Date();
 
        List<ExamPaperTitleItemObject> frameTextContentList = new ArrayList<>();
        List<ExamPaperTitleItemVM> titleItemsVM = new ArrayList<>();
        //随机试卷
        if (examPaperEditRequestVM.getSubjectSource().size() != 0) {
//            Map<Integer, Integer> questionList = questionService.getAll().stream().collect(Collectors.toMap(Question::getId, Question::getScore));
            randomQuestion(examPaperEditRequestVM, frameTextContentList, titleItemsVM);
        }
        if (titleItemsVM.size() == 0) {
            titleItemsVM = examPaperEditRequestVM.getTitleItems();
        }
        if (frameTextContentList.size() == 0) {
            frameTextContentList = frameTextContentFromVM(titleItemsVM);
        }
 
        String frameTextContentStr = JsonUtil.toJsonStr(frameTextContentList);
 
        ExamPaper examPaper;
        if (actionEnum == ActionEnum.ADD) {
            examPaper = modelMapper.map(examPaperEditRequestVM, ExamPaper.class);
            TextContent frameTextContent = new TextContent(frameTextContentStr, now);
            textContentService.insertByFilter(frameTextContent);
            examPaper.setFrameTextContentId(frameTextContent.getId());
            examPaper.setCreateTime(now);
            examPaper.setCreateUser(user.getId());
            examPaper.setDeleted(false);
            examPaperFromVM(examPaperEditRequestVM, examPaper, titleItemsVM);
            examPaperMapper.insertSelective(examPaper);
 
        } else {
            examPaper = examPaperMapper.selectByPrimaryKey(examPaperEditRequestVM.getId());
            TextContent frameTextContent = textContentService.selectById(examPaper.getFrameTextContentId());
            frameTextContent.setContent(frameTextContentStr);
            textContentService.updateByIdFilter(frameTextContent);
            modelMapper.map(examPaperEditRequestVM, examPaper);
            examPaperFromVM(examPaperEditRequestVM, examPaper, titleItemsVM);
            examPaperMapper.updateByPrimaryKeySelective(examPaper);
            //批量修改
            examPaperDepartmentService.removeByExamPaperId(examPaper.getId());
            examPaperSubjectService.removeByExamPaperId(examPaper.getId());
        }
        addExamPaperDepartment(examPaperEditRequestVM, examPaper);
        addExamPaperSubject(examPaperEditRequestVM, examPaper);
        return examPaper;
    }
 
    @Override
    public ExamPaperEditRequestVM examPaperToVM(Integer id) {
        ExamPaper examPaper = examPaperMapper.selectByPrimaryKey(id);
        ExamPaperEditRequestVM vm = modelMapper.map(examPaper, ExamPaperEditRequestVM.class);
        vm.setLevel(examPaper.getGradeLevel());
        TextContent frameTextContent = textContentService.selectById(examPaper.getFrameTextContentId());
        List<ExamPaperTitleItemObject> examPaperTitleItemObjects = JsonUtil.toJsonListObject(frameTextContent.getContent(), ExamPaperTitleItemObject.class);
        List<Integer> questionIds = examPaperTitleItemObjects.stream()
                .flatMap(t -> t.getQuestionItems().stream()
                        .map(q -> q.getId()))
                .collect(Collectors.toList());
        List<Question> questions = questionMapper.selectByIds(questionIds);
        Integer order = 0;
        Set<Integer> generatedNumbers = new HashSet<>();
        Random random = new Random();
        List<ExamPaperTitleItemVM> examPaperTitleItemVMS = examPaperTitleItemObjects.stream().map(t -> {
            ExamPaperTitleItemVM tTitleVM = modelMapper.map(t, ExamPaperTitleItemVM.class);
            List<QuestionEditRequestVM> questionItemsVM = t.getQuestionItems().stream().map(i -> {
                        Question question = questions.stream().filter(q -> q.getId().equals(i.getId())).findFirst().get();
                        QuestionEditRequestVM questionEditRequestVM = questionService.getQuestionEditRequestVM(question);
                        questionEditRequestVM.setItemOrder(getRandomNumber(t.getQuestionItems().size() - 1, generatedNumbers, random));
                        return questionEditRequestVM;
                    }).sorted(Comparator.comparing(QuestionEditRequestVM::getItemOrder))
                    .collect(Collectors.toList());
            tTitleVM.setQuestionItems(questionItemsVM);
            return tTitleVM;
        }).collect(Collectors.toList());
        vm.setTitleItems(examPaperTitleItemVMS);
        vm.setScore(ExamUtil.scoreToVM(examPaper.getScore()));
        if (ExamPaperTypeEnum.TimeLimit == ExamPaperTypeEnum.fromCode(examPaper.getPaperType())) {
            List<String> limitDateTime = Arrays.asList(DateTimeUtil.dateFormat(examPaper.getLimitStartTime()), DateTimeUtil.dateFormat(examPaper.getLimitEndTime()));
            vm.setLimitDateTime(limitDateTime);
        }
 
        //查询部门和课目
        vm.setSubjectId(examPaperSubjectService.getByExamPaperId(examPaper.getId())
                .stream().map(ExamPaperSubject::getSubjectId).toArray(Integer[]::new));
        vm.setDepartmentIds(examPaperDepartmentService.getByExamPaperId(examPaper.getId())
                .stream().map(ExamPaperDepartment::getDepartmentId).toArray(Integer[]::new));
        return vm;
    }
 
    @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());
    }
 
    @Override
    public Integer removeByIds(Integer[] ids) {
        return examPaperMapper.removeByIds(ids);
    }
 
    @Override
    public List<ExamPaper> gets(Integer[] ids) {
        return examPaperMapper.gets(ids);
    }
 
    private void examPaperFromVM(ExamPaperEditRequestVM examPaperEditRequestVM, ExamPaper examPaper, List<ExamPaperTitleItemVM> titleItemsVM) {
//        Integer gradeLevel = subjectService.levelBySubjectId(examPaperEditRequestVM.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(null);
        List<String> dateTimes = examPaperEditRequestVM.getLimitDateTime();
        if (ExamPaperTypeEnum.TimeLimit == 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<ExamPaperTitleItemVM> titleItems) {
        AtomicInteger index = new AtomicInteger(1);
        return titleItems.stream().map(t -> {
            ExamPaperTitleItemObject titleItem = modelMapper.map(t, ExamPaperTitleItemObject.class);
            List<ExamPaperQuestionItemObject> questionItems = t.getQuestionItems().stream()
                    .map(q -> {
                        ExamPaperQuestionItemObject examPaperQuestionItemObject = modelMapper.map(q, ExamPaperQuestionItemObject.class);
                        examPaperQuestionItemObject.setItemOrder(index.getAndIncrement());
                        return examPaperQuestionItemObject;
                    })
                    .collect(Collectors.toList());
            titleItem.setQuestionItems(questionItems);
            return titleItem;
        }).collect(Collectors.toList());
    }
 
    private void addExamPaperDepartment(ExamPaperEditRequestVM examPaperEditRequestVM, ExamPaper examPaper) {
        if(examPaperEditRequestVM.getDepartmentIds().length==0){
            return;
        }
        List<ExamPaperDepartment> list = Arrays.asList(examPaperEditRequestVM.getDepartmentIds()).stream().map(e -> {
            ExamPaperDepartment examPaperDepartment = new ExamPaperDepartment();
            examPaperDepartment.setExamPaperId(examPaper.getId());
            examPaperDepartment.setDepartmentId(e);
            examPaperDepartment.setDeleted("0");
            return examPaperDepartment;
        }).collect(Collectors.toList());
        examPaperDepartmentService.saves(list);
    }
 
    private void addExamPaperSubject(ExamPaperEditRequestVM examPaperEditRequestVM, ExamPaper examPaper) {
        List<ExamPaperSubject> subjectList = Arrays.asList(examPaperEditRequestVM.getSubjectId()).stream().map(e -> {
            ExamPaperSubject examPaperSubject = new ExamPaperSubject();
            examPaperSubject.setSubjectId(e);
            examPaperSubject.setExamPaperId(examPaper.getId());
            examPaperSubject.setDeleted("0");
            return examPaperSubject;
        }).collect(Collectors.toList());
        examPaperSubjectService.saves(subjectList);
    }
 
    /**
     * @param result
     * @param scoresMap
     * @param quantity
     * @param totalScore
     */
    public static void selectRandomScores(Map<Integer, Integer> result, Map<Integer, Integer> scoresMap, int quantity, int totalScore) throws QuestionException {
//        Map<String, Integer> selectedScoresMap = new HashMap<>();
 
        if (quantity <= 0 || totalScore <= 0 || scoresMap.isEmpty()) {
            return; // 返回空Map
        }
 
        List<Integer> keys = new ArrayList<>(scoresMap.keySet());
        List<Integer> values = scoresMap.values().stream().map(e -> e = e / 10).collect(Collectors.toList());
 
        Random random = new Random();
        int remainingQuantity = quantity;
        int remainingScore = totalScore;
 
        for (int i = 0; i < quantity - 1; i++) {
            if (i >= scoresMap.size()) {
                throw new QuestionException();
            }
            int index = random.nextInt(values.size());
            int score = values.get(index);
 
            if (score <= remainingScore) {
                result.put(keys.get(index), score);
                remainingQuantity--;
                remainingScore -= score;
                values.remove(index);
                keys.remove(index);
            }
        }
 
        if (!values.isEmpty()) {
            int index = random.nextInt(values.size());
            int score = values.get(index);
            result.put(keys.get(index), score); // 最后一个分数为剩余的分数
        }
 
    }
 
    /**
     * 随机试卷
     *
     * @param examPaperEditRequestVM 传参
     * @param frameTextContentList
     * @param titleItemsVM           title
     */
    private void randomQuestion(ExamPaperEditRequestVM examPaperEditRequestVM, List<ExamPaperTitleItemObject> frameTextContentList, List<ExamPaperTitleItemVM> titleItemsVM) throws QuestionException {
        Map<Integer, Integer> subjectSource = examPaperEditRequestVM.getSubjectSource();
        //总数量
        Integer sum = subjectSource.values().stream().mapToInt(Integer::intValue).sum();
        Integer count = 0;
        Integer mark = 0;
 
        ExamPaperTitleItemObject examPaperTitleItemObject = new ExamPaperTitleItemObject();
        examPaperTitleItemObject.setName(examPaperEditRequestVM.getTitleItems().get(0).getName());
 
        ExamPaperTitleItemVM examPaperTitleItemVM = new ExamPaperTitleItemVM();
        //titleItemsVM
        examPaperTitleItemVM.setName(examPaperEditRequestVM.getTitleItems().get(0).getName());
 
        List<ExamPaperQuestionItemObject> examPaperQuestionItemObjectList = new ArrayList<>();
 
        List<QuestionEditRequestVM> questionItems = new ArrayList<>();
        Integer order = 0;
        for (Integer key : subjectSource.keySet()) {    // key:数量
            //该标签对应的分数   多选:3 判断:3 单选:4
            Integer source = 80 * subjectSource.get(key) / sum - mark;
            // 多选和判断数量
            Integer multipleNumber = (subjectSource.get(key) + count) * 3 / 10;
            //多选和判断分数
            Integer multipleSource = source * 3 / 10;
            List<Integer> questions = questionSubjectService.getSubject(key)
                    .stream().map(QuestionSubject::getQuestionId).collect(Collectors.toList());
            List<Question> list = questionService.selectByIds(questions);
 
            Map<Integer, Integer> multiple = new HashMap<>();
            //多选
            Map<Integer, Integer> multipleMap = list.stream()
                    .filter(e -> e.getQuestionType().equals(QuestionTypeEnum.MultipleChoice.getCode()))
                    .collect(Collectors.toMap(Question::getId, Question::getScore));
 
            selectRandomScores(multiple, multipleMap, multipleNumber < multipleMap.size() ? multipleNumber : multipleMap.size(), multipleSource);
 
 
            //判断
            Map<Integer, Integer> judgmentMap = list.stream()
                    .filter(e -> e.getQuestionType().equals(QuestionTypeEnum.TrueFalse.getCode()))
                    .collect(Collectors.toMap(Question::getId, Question::getScore));
            selectRandomScores(multiple, judgmentMap, multipleNumber < judgmentMap.size() ? multipleNumber : judgmentMap.size(), multipleSource);
 
            //单选数量
            Integer radioNumber = subjectSource.get(key) - multiple.size();
            //单选分数
            Integer radioSource = source - multiple.values().stream().mapToInt(Integer::intValue).sum();
            //单选
            Map<Integer, Integer> radioMap = list.stream()
                    .filter(e -> e.getQuestionType().equals(QuestionTypeEnum.SingleChoice.getCode()))
                    .collect(Collectors.toMap(Question::getId, Question::getScore));
            selectRandomScores(multiple, radioMap, radioNumber < radioMap.size() ? radioNumber : radioMap.size(), radioSource);
 
//            titleItemsVM.add(examPaperTitleItemVM);
            for (Integer k : multiple.keySet()) {
                ExamPaperQuestionItemObject examPaperQuestionItemObject = new ExamPaperQuestionItemObject();
                examPaperQuestionItemObject.setId(k);
                examPaperQuestionItemObject.setItemOrder(order++);
                examPaperQuestionItemObjectList.add(examPaperQuestionItemObject);
                //titleItemsVM
                QuestionEditRequestVM questionEditRequestVM = new QuestionEditRequestVM();
                questionEditRequestVM.setScore(multiple.get(k).toString());
                questionItems.add(questionEditRequestVM);
            }
 
            examPaperTitleItemObject.setQuestionItems(examPaperQuestionItemObjectList);
 
            //titleItemsVM
            examPaperTitleItemVM.setQuestionItems(questionItems);
            //数量 匹配
            count = multiple.size() != subjectSource.get(key) ? subjectSource.get(key) - multiple.size() : 0;
            //分数匹配
            mark = source != multiple.values().stream().mapToInt(Integer::intValue).sum() ? multiple.values().stream().mapToInt(Integer::intValue).sum() - source : 0;
 
        }
        frameTextContentList.add(examPaperTitleItemObject);
        titleItemsVM.add(examPaperTitleItemVM);
 
        if (count != 0 || mark != 0) {
            throw new QuestionException();
        }
 
    }
 
    public Integer getRandomNumber(Integer a, Set<Integer> generatedNumbers, Random random) {
        if (a <= 0) {
            throw new IllegalArgumentException("a必须为正整数");
        }
 
        int range = a + 1;
 
        if (generatedNumbers.size() >= range) {
            generatedNumbers.clear();  // 清空已生成的数字集合
        }
 
        int randomNumber;
        do {
            randomNumber = random.nextInt(range);
        } while (generatedNumbers.contains(randomNumber));
 
        generatedNumbers.add(randomNumber);
        return randomNumber;
    }
}