xiangpei
2024-06-28 abd1516fa39da87f70d4f69dc4ec35f8f81946f1
src/main/java/com/ycl/jxkg/service/impl/ExamPaperServiceImpl.java
@@ -1,13 +1,35 @@
package com.ycl.jxkg.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.TextContent;
import com.ycl.jxkg.enums.ExamPaperTypeEnum;
import com.ycl.jxkg.domain.exam.ExamPaperQuestionItemObject;
import com.ycl.jxkg.domain.exam.ExamPaperTitleItemObject;
import com.ycl.jxkg.domain.entity.ExamPaper;
import com.ycl.jxkg.domain.entity.Question;
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.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.ExamPaperEditRequestVO;
import com.ycl.jxkg.domain.vo.admin.exam.ExamPaperPageRequestVO;
import com.ycl.jxkg.domain.vo.admin.exam.ExamPaperTitleItemVO;
import com.ycl.jxkg.domain.vo.admin.exam.ExamResponseVO;
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.mapper.ExamPaperMapper;
import com.ycl.jxkg.mapper.QuestionMapper;
@@ -15,28 +37,17 @@
import com.ycl.jxkg.service.QuestionService;
import com.ycl.jxkg.service.SubjectService;
import com.ycl.jxkg.service.TextContentService;
import com.ycl.jxkg.service.enums.ActionEnum;
import com.ycl.jxkg.utils.DateTimeUtil;
import com.ycl.jxkg.utils.JsonUtil;
import com.ycl.jxkg.domain.vo.admin.exam.ExamPaperEditRequestVO;
import com.ycl.jxkg.domain.vo.admin.exam.ExamPaperPageRequestVO;
import com.ycl.jxkg.domain.vo.admin.exam.ExamPaperTitleItemVO;
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.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ycl.jxkg.domain.entity.ExamPaper;
import com.ycl.jxkg.domain.entity.User;
import com.ycl.jxkg.utils.PageInfoHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
@Service
@@ -52,16 +63,159 @@
    @Override
    public PageInfo<ExamPaper> page(ExamPaperPageRequestVO requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                examPaperMapper.page(requestVM));
    @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();
            //题目配置里配的试卷类型
            List<Integer> types = questionSetting.stream().map(PaperQuestionSettingDTO::getQuestionType).collect(Collectors.toList());
            Map<Integer, List<Integer>> map = questionMapper.selectBySubject(form.getSubjectId(), types)
                    .stream().collect(Collectors.groupingBy(RandomQuestionDTO::getQuestionType, Collectors.mapping(RandomQuestionDTO::getQuestionId, Collectors.toList())));
            for (PaperQuestionSettingDTO settingDTO : questionSetting) {
                Integer num = settingDTO.getNum();
                Integer questionType = settingDTO.getQuestionType();
                //需要配置的题目数量为0则跳过
                if(num ==null || num ==0 )continue;
                List<Integer> questions = map.get(questionType);
                if(CollectionUtils.isEmpty(questions) || num > questions.size())return Result.fail(SystemCode.InnerError.getCode(), QuestionTypeEnum.fromCode(questionType).getName()+"题目数量不足");
            }
            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 {
            //随序试卷
            Integer subjectId = form.getSubjectId();
            //题目配置
            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(), "试卷题目类型不能为空");
            }
            Map<Integer, List<Integer>> map = questionMapper.selectBySubject(subjectId, types)
                    .stream().collect(Collectors.groupingBy(RandomQuestionDTO::getQuestionType, Collectors.mapping(RandomQuestionDTO::getQuestionId, Collectors.toList())));
            List<PaperFixQuestionDTO> questionTitleList = new ArrayList<>();
            // 遍历map
            for (Integer questionType : map.keySet()) {
                //数据库里的这个类型的题目
                List<Integer> questionIdList = map.get(questionType);
                Result result = createQuestion(questionSetting, questionTitleList, questionType, questionIdList,QuestionTypeEnum.fromCode(questionType).getCode());
                if (result != null) return result;
            }
            examPaper.setContent(JSON.toJSONString(questionTitleList));
            baseMapper.insert(examPaper);
            return Result.ok();
        }
    }
    //生成题目
    private Result createQuestion(List<PaperQuestionSettingDTO> questionSetting, List<PaperFixQuestionDTO> questionTitleList, Integer questionType, List<Integer> questionIdList , Integer questionEnumCode) {
        if (questionType.equals(questionEnumCode)) {
            //循环找到对应题目
            PaperQuestionSettingDTO settingDTO = new PaperQuestionSettingDTO();
            for (PaperQuestionSettingDTO dto : questionSetting) {
                if (dto.getQuestionType().equals(questionType)) {
                    settingDTO = dto;
                }
            }// 需要生成的题目数量
            Integer num = settingDTO.getNum();
            if(num ==null || num ==0 ){
                //题目配置此类型数量为0,跳过,不生成题目。
                return null;
            }
            if (CollectionUtils.isEmpty(questionIdList) || num > questionIdList.size()) {
                return Result.fail(SystemCode.InnerError.getCode(), QuestionTypeEnum.fromCode(questionType).getName()+"题目数量不足");
            }
            // 使用Random类生成不重复的随机索引
            Set<Integer> indexes = new HashSet<>();
            Random random = new Random();
            while (indexes.size() < num) {
                int index = random.nextInt(questionIdList.size());
                indexes.add(index);
            }
            // 根据索引获取题目
            List<Integer> questionIds = new ArrayList<>();
            for (int index : indexes) {
                questionIds.add(questionIdList.get(index));
            }
            QueryWrapper<Question> wrapper = new QueryWrapper<>();
            wrapper.in("id",questionIds);
            List<Question> questions = questionMapper.selectList(wrapper);
            List<PaperQuestion> questionList = new ArrayList<>();
            for (Question question : questions) {
                PaperQuestion paperQuestion = new PaperQuestion();
                BeanUtils.copyProperties(question,paperQuestion);
                paperQuestion.setScore(settingDTO.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);
            }
            PaperFixQuestionDTO dto = new PaperFixQuestionDTO();
            dto.setTitle(settingDTO.getTitle());
            dto.setQuestionType(questionType);
            dto.setQuestionList(questionList);
            questionTitleList.add(dto);
        }
        return null;
    }
    @Override
    public PageInfo<ExamPaper> taskExamPage(ExamPaperPageRequestVO requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                examPaperMapper.taskExamPage(requestVM));
    public Result updateExamPaper(ExamPaperForm form) {
        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) {
        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) {
@@ -70,69 +224,54 @@
    }
    @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:待完成
//    @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;
    }
//            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);
        //TODO:待完成
//        TextContent frameTextContent = textContentService.getById(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);
//        List<ExamPaperTitleItemVO> examPaperTitleItemVOS = examPaperTitleItemObjects.stream().map(t -> {
//            ExamPaperTitleItemVO tTitleVM = new ExamPaperTitleItemVO();
//            BeanUtils.copyProperties(t, tTitleVM);
//            List<QuestionEditRequestVO> questionItemsVM = t.getQuestionItems().stream().map(i -> {
//                Question question = questions.stream().filter(q -> q.getId().equals(i.getId())).findFirst().get();
//                QuestionEditRequestVO questionEditRequestVO = questionService.getQuestionEditRequestVM(question);
//                questionEditRequestVO.setItemOrder(i.getItemOrder());
//                return questionEditRequestVO;
//            }).collect(Collectors.toList());
//            tTitleVM.setQuestionItems(questionItemsVM);
//            return tTitleVM;
//        }).collect(Collectors.toList());
//        vo.setTitleItems(examPaperTitleItemVOS);
//        vo.setScore(ExamUtil.scoreToVM(examPaper.getScore()));
//        if (ExamPaperTypeEnum.Random == ExamPaperTypeEnum.fromCode(examPaper.getPaperType())) {
//            List<String> limitDateTime = Arrays.asList(DateTimeUtil.dateFormat(examPaper.getLimitStartTime()), DateTimeUtil.dateFormat(examPaper.getLimitEndTime()));
//            vo.setLimitDateTime(limitDateTime);
//        }
        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;
    }
@@ -159,8 +298,9 @@
        }).collect(Collectors.toList());
    }
    private void examPaperFromVM(ExamPaperEditRequestVO examPaperEditRequestVO, ExamPaper examPaper, List<ExamPaperTitleItemVO> titleItemsVM) {
        //TODO:待完成
        //TODO:
//        Integer gradeLevel = subjectService.levelBySubjectId(examPaperEditRequestVO.getSubjectId());
//        Integer questionCount = titleItemsVM.stream()
//                .mapToInt(t -> t.getQuestionItems().size()).sum();
@@ -178,23 +318,23 @@
//        }
    }
    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());
    }
//    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) {