package com.ningdatech.carapi.archives.manage;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.basic.util.NdDateUtils;
import com.ningdatech.basic.util.StrPool;
import com.ningdatech.carapi.archives.assembler.QuestionAssembler;
import com.ningdatech.carapi.archives.entity.ExamPaper;
import com.ningdatech.carapi.archives.entity.ExamPaperQuestion;
import com.ningdatech.carapi.archives.entity.PaperQuestion;
import com.ningdatech.carapi.archives.enums.ExamPaperQualifiedScoreConstant;
import com.ningdatech.carapi.archives.enums.IsRandomEnum;
import com.ningdatech.carapi.archives.model.ExamRuleInfo;
import com.ningdatech.carapi.archives.model.po.ReqExamPaperListPO;
import com.ningdatech.carapi.archives.model.po.ReqExamRulePO;
import com.ningdatech.carapi.archives.model.po.ReqSaveExamPaperPO;
import com.ningdatech.carapi.archives.model.po.ReqSaveExamPaperPO.ExamPaperQuestionIdPO;
import com.ningdatech.carapi.archives.model.po.ReqSaveExamRulePO;
import com.ningdatech.carapi.archives.model.vo.ResExamPaperListVO;
import com.ningdatech.carapi.archives.model.vo.ResExamPaperVO;
import com.ningdatech.carapi.archives.model.vo.ResExamRuleVO;
import com.ningdatech.carapi.archives.model.vo.ResQuestionDetailVO;
import com.ningdatech.carapi.archives.service.IExamPaperQuestionService;
import com.ningdatech.carapi.archives.service.IExamPaperService;
import com.ningdatech.carapi.archives.service.IPaperQuestionService;
import com.ningdatech.carapi.common.contants.DefValConstants;
import com.ningdatech.carapi.common.helper.UserInfoHelper;
import com.ningdatech.carapi.datascope.aop.LambdaDataScope;
import com.ningdatech.carapi.datascope.contants.LambdaDataScopeTypeEnum;
import com.ningdatech.carapi.driver.constant.QuestionTypeEnum;
import com.ningdatech.carapi.sys.entity.ExamRule;
import com.ningdatech.carapi.sys.entity.dto.RegionDTO;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.sys.service.IExamRuleService;
import com.ningdatech.carapi.user.model.vo.UserBasicInfoVO;
import com.ningdatech.carapi.user.security.auth.model.UserInfoDetails;
import com.ningdatech.carapi.user.util.LoginUserUtil;

import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;

/**
 * @author liuxinxin
 * @date 2022/10/17 下午4:28
 */
@Component
@RequiredArgsConstructor
public class ExaminationPaperManage {

    private final IPaperQuestionService iPaperQuestionService;
    private final IExamPaperService iExamPaperService;
    private final IExamPaperQuestionService iExamPaperQuestionService;
    private final UserInfoHelper userInfoHelper;
    private final IExamRuleService iExamRuleService;
    private final RegionsCacheHelper regionsCacheHelper;

    @Transactional(rollbackFor = Exception.class)
    public void createExamPaper(ReqSaveExamPaperPO po, ReqExamRulePO examRulePo) {
        // 获取全局试卷规则 校验分数
        ResExamRuleVO examRule = getExamRule(examRulePo);
        // 获取入参
        Long regionId = userInfoHelper.getUserRegionId();

        List<ExamPaperQuestionIdPO> singleChoiceQuestionList = po.getSingleChoiceQuestionList();
        List<ExamPaperQuestionIdPO> multipleChoiceQuestionList = po.getMultipleChoiceQuestionList();
        List<ExamPaperQuestionIdPO> judgmentalQuestionList = po.getJudgmentalQuestionList();
        List<ExamPaperQuestionIdPO> examPaperQuestionIdList = new ArrayList<>();
        examPaperQuestionIdList.addAll(singleChoiceQuestionList);
        examPaperQuestionIdList.addAll(multipleChoiceQuestionList);
        examPaperQuestionIdList.addAll(judgmentalQuestionList);

        List<Long> questionIdList = examPaperQuestionIdList.stream()
                .map(ExamPaperQuestionIdPO::getPaperQuestionId).collect(Collectors.toList());

        List<PaperQuestion> paperQuestionList = iPaperQuestionService
                .list(Wrappers.lambdaQuery(PaperQuestion.class).in(PaperQuestion::getId, questionIdList));
        Map<Long, String> paperQuestionIdTypeMap = paperQuestionList.stream().collect(Collectors.toMap(PaperQuestion::getId, PaperQuestion::getQuestionType));

        // 保存试卷基本信息
        ExamPaper examPaper = new ExamPaper();
        examPaper.setCreateOn(LocalDateTime.now());
        examPaper.setUpdateOn(LocalDateTime.now());
        examPaper.setExamPaperName(po.getExamPaperName());
        examPaper.setFullScore(ExamPaperQualifiedScoreConstant.EXAM_PAPER_FULL_SCORE);
        examPaper.setQualifiedScore(ExamPaperQualifiedScoreConstant.EXAM_PAPER_QUALIFIED_SCORE);
        examPaper.setRegionId(regionId);
        examPaper.setExamRuleJson(JSONObject.toJSONString(examRule));
        examPaper.setIsRandom(IsRandomEnum.NOT_RANDOM_PAPER.getCode());
        iExamPaperService.save(examPaper);

        // 保存试卷题目关联关系
        List<ExamPaperQuestion> saveRecordList = new ArrayList<>();
        for (ExamPaperQuestionIdPO idPo : examPaperQuestionIdList) {
            ExamPaperQuestion examPaperQuestion = new ExamPaperQuestion();
            examPaperQuestion.setExamPaperId(examPaper.getId());
            examPaperQuestion.setPaperQuestionId(idPo.getPaperQuestionId());
            examPaperQuestion.setCreateOn(LocalDateTime.now());
            examPaperQuestion.setUpdateOn(LocalDateTime.now());
            examPaperQuestion.setSortValue(idPo.getSortValue());
            examPaperQuestion.setQuestionType(paperQuestionIdTypeMap.get(idPo.getPaperQuestionId()));
            saveRecordList.add(examPaperQuestion);
        }
        iExamPaperQuestionService.saveBatch(saveRecordList);

        List<Long> questionUsageCntUpdateList = examPaperQuestionIdList.stream().map(ExamPaperQuestionIdPO::getPaperQuestionId).collect(Collectors.toList());
        for (Long questionId : questionUsageCntUpdateList) {
            questionUsageCntUpdate(questionId);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveExamPaper(ReqSaveExamPaperPO request) {
        // 根据登录用户所在区域，获取全局试卷规则
        UserBasicInfoVO userFullInfo = userInfoHelper.getUserFullInfo();
        Long regionId = userFullInfo.getRegionId();
        ReqExamRulePO examRulePo = new ReqExamRulePO();
        examRulePo.setRegionId(regionId);
        ResExamRuleVO examRule = getExamRule(examRulePo);
        // 获取入参
        Long id = request.getId();
        List<ExamPaperQuestionIdPO> singleChoiceQuestionList = request.getSingleChoiceQuestionList();
        List<ExamPaperQuestionIdPO> multipleChoiceQuestionList = request.getMultipleChoiceQuestionList();
        List<ExamPaperQuestionIdPO> judgmentalQuestionList = request.getJudgmentalQuestionList();
        List<Long> questionUsageCntUpdateList = new ArrayList<>();

        // 校验分数
        validExamRule(examRule, singleChoiceQuestionList, multipleChoiceQuestionList, judgmentalQuestionList);

        questionUsageCntUpdateList.addAll(singleChoiceQuestionList.stream().map(ExamPaperQuestionIdPO::getPaperQuestionId).collect(Collectors.toList()));
        questionUsageCntUpdateList.addAll(multipleChoiceQuestionList.stream().map(ExamPaperQuestionIdPO::getPaperQuestionId).collect(Collectors.toList()));
        questionUsageCntUpdateList.addAll(judgmentalQuestionList.stream().map(ExamPaperQuestionIdPO::getPaperQuestionId).collect(Collectors.toList()));

        if (Objects.isNull(id)) {
            createExamPaper(request,examRulePo);
        } else {
            ExamPaper examPaper = iExamPaperService.getById(id);
            if (Objects.isNull(examPaper)) {
                throw new BizException("试卷不存在");
            }
            // 获取入参
            List<ExamPaperQuestionIdPO> examPaperQuestionIdList = new ArrayList<>();
            examPaperQuestionIdList.addAll(singleChoiceQuestionList);
            examPaperQuestionIdList.addAll(multipleChoiceQuestionList);
            examPaperQuestionIdList.addAll(judgmentalQuestionList);

            List<Long> questionIdList = examPaperQuestionIdList.stream()
                    .map(ExamPaperQuestionIdPO::getPaperQuestionId).collect(Collectors.toList());

            List<PaperQuestion> paperQuestionList = iPaperQuestionService
                    .list(Wrappers.lambdaQuery(PaperQuestion.class).in(PaperQuestion::getId, questionIdList));
            Map<Long, String> paperQuestionIdTypeMap = paperQuestionList.stream().collect(Collectors.toMap(PaperQuestion::getId, PaperQuestion::getQuestionType));

            List<ExamPaperQuestion> oldExamPaperQuestionList = iExamPaperQuestionService.list(Wrappers.lambdaQuery(ExamPaperQuestion.class)
                    .eq(ExamPaperQuestion::getExamPaperId, examPaper.getId()));

            // 保存试卷基本信息
            examPaper.setUpdateOn(LocalDateTime.now());
            examPaper.setExamPaperName(request.getExamPaperName());
            examPaper.setFullScore(ExamPaperQualifiedScoreConstant.EXAM_PAPER_FULL_SCORE);
            examPaper.setQualifiedScore(ExamPaperQualifiedScoreConstant.EXAM_PAPER_QUALIFIED_SCORE);
            examPaper.setRegionId(regionId);
            examPaper.setExamRuleJson(JSONObject.toJSONString(examRule));
            examPaper.setIsRandom(IsRandomEnum.NOT_RANDOM_PAPER.getCode());
            iExamPaperService.updateById(examPaper);

            // 删除旧关系 保存新试卷题目关联关系
            iExamPaperQuestionService.remove(Wrappers.lambdaQuery(ExamPaperQuestion.class)
                    .eq(ExamPaperQuestion::getExamPaperId, examPaper.getId()));

            List<ExamPaperQuestion> saveRecordList = new ArrayList<>();
            for (ExamPaperQuestionIdPO po : examPaperQuestionIdList) {
                ExamPaperQuestion examPaperQuestion = new ExamPaperQuestion();
                examPaperQuestion.setExamPaperId(examPaper.getId());
                examPaperQuestion.setPaperQuestionId(po.getPaperQuestionId());
                examPaperQuestion.setCreateOn(LocalDateTime.now());
                examPaperQuestion.setUpdateOn(LocalDateTime.now());
                examPaperQuestion.setSortValue(po.getSortValue());
                examPaperQuestion.setQuestionType(paperQuestionIdTypeMap.get(po.getPaperQuestionId()));
                saveRecordList.add(examPaperQuestion);
            }
            iExamPaperQuestionService.saveBatch(saveRecordList);

            if (CollectionUtil.isNotEmpty(oldExamPaperQuestionList)) {
                questionUsageCntUpdateList.addAll(oldExamPaperQuestionList.stream()
                        .map(ExamPaperQuestion::getPaperQuestionId).collect(Collectors.toList()));
                questionUsageCntUpdateList = questionUsageCntUpdateList.stream().distinct().collect(Collectors.toList());
                for (Long questionId : questionUsageCntUpdateList) {
                    questionUsageCntUpdate(questionId);
                }
            }
        }
    }

    private void validExamRule(ResExamRuleVO examRule, List<ExamPaperQuestionIdPO> singleChoiceQuestionList, List<ExamPaperQuestionIdPO> multipleChoiceQuestionList, List<ExamPaperQuestionIdPO> judgmentalQuestionList) {
        ExamRuleInfo judgmentalQuestionRule = examRule.getJudgmentalQuestionRule();
        ExamRuleInfo multipleChoiceQuestionRule = examRule.getMultipleChoiceQuestionRule();
        ExamRuleInfo singleChoiceQuestionRule = examRule.getSingleChoiceQuestionRule();
        int singleChoiceQuestionNum = singleChoiceQuestionList.size();
        int multipleChoiceQuestionNum = multipleChoiceQuestionList.size();
        int judgmentalQuestionNum = judgmentalQuestionList.size();
        if (singleChoiceQuestionNum != singleChoiceQuestionRule.getQuestionCnt()
                || multipleChoiceQuestionNum != multipleChoiceQuestionRule.getQuestionCnt()
                || judgmentalQuestionNum != judgmentalQuestionRule.getQuestionCnt()) {
            throw new BizException("题目数量不正确，请按规定选择！");
        }
    }

    /**
     * questionId
     *
     * @param questionId
     */
    public void questionUsageCntUpdate(Long questionId) {
        PaperQuestion paperQuestion = iPaperQuestionService.getById(questionId);
        if (Objects.isNull(paperQuestion)) {
            return;
        } else {
            long usage = iExamPaperQuestionService.count(Wrappers.lambdaQuery(ExamPaperQuestion.class)
                    .eq(ExamPaperQuestion::getPaperQuestionId, questionId));
            paperQuestion.setUsageCnt(usage);
            iPaperQuestionService.updateById(paperQuestion);
        }
    }


    public ResExamPaperVO getExamPaperId(Long examPaperId) {
        LambdaQueryWrapper<ExamPaper> wrapper = Wrappers.lambdaQuery(ExamPaper.class);
        ExaminationPaperManage context = (ExaminationPaperManage) AopContext.currentProxy();
        context.buildQuery(wrapper, examPaperId);
        ExamPaper examPaper = iExamPaperService.getOne(wrapper);
        if (Objects.isNull(examPaper)) {
            throw new BizException("未获取到考试试卷!");
        }

        // 判断是否可以考试
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime examStartTime = examPaper.getExamStartTime();
        LocalDateTime examEndTime = examPaper.getExamEndTime();
        // 设置了考试时间
        if (Objects.nonNull(examStartTime) && Objects.nonNull(examEndTime)) {
            String examStartStr = NdDateUtils.format(examStartTime, NdDateUtils.DEFAULT_DATE_FORMAT);
            String examEndStr = NdDateUtils.format(examEndTime, NdDateUtils.DEFAULT_DATE_FORMAT);
            if (now.compareTo(examStartTime) < 0){
                throw new BizException("当前培训考试未开始,考试时间为:" + examStartStr + StrPool.DASH + examEndStr);
            } else if (now.compareTo(examEndTime) > 0) {
                throw new BizException("当前培训考试已结束,考试时间为:" + examStartStr + StrPool.DASH + examEndStr);
            }
        }

        // 获取题目id 列表
        List<ExamPaperQuestion> examPaperQuestionList = iExamPaperQuestionService.list(Wrappers.lambdaQuery(ExamPaperQuestion.class)
                .eq(ExamPaperQuestion::getExamPaperId, examPaperId));
        List<Long> paperQuestionIdList = examPaperQuestionList.stream().map(ExamPaperQuestion::getPaperQuestionId).collect(Collectors.toList());
        List<PaperQuestion> paperQuestionList = iPaperQuestionService
                .list(Wrappers.lambdaQuery(PaperQuestion.class).in(PaperQuestion::getId, paperQuestionIdList));

        Map<QuestionTypeEnum, List<ResQuestionDetailVO>> groupByQuestionTypeList = paperQuestionList.stream().map(QuestionAssembler::buildResQuestionDetailVO)
                .collect(Collectors.groupingBy(ResQuestionDetailVO::getQuestionType));

        // 装配返回
        ResExamPaperVO resExamPaperVO = new ResExamPaperVO();
        resExamPaperVO.setExamPaperName(examPaper.getExamPaperName());
        resExamPaperVO.setResExamRuleVO(JSONObject.parseObject(examPaper.getExamRuleJson(), ResExamRuleVO.class));
        resExamPaperVO.setSingleChoiceQuestionList(groupByQuestionTypeList
                .get(QuestionTypeEnum.SINGLE_CHOICE));
        resExamPaperVO.setMultipleChoiceQuestionList(groupByQuestionTypeList
                .get(QuestionTypeEnum.MULTIPLE_CHOICE));
        resExamPaperVO.setJudgmentalQuestionList(groupByQuestionTypeList
                .get(QuestionTypeEnum.JUDGMENTAL));
        return resExamPaperVO;
    }

    @LambdaDataScope(type = LambdaDataScopeTypeEnum.ONLY_REGION)
    public void buildQuery(LambdaQueryWrapper<ExamPaper> wrapper, Long examPaperId) {
        wrapper.eq(ExamPaper::getId,examPaperId);
    }


    @Transactional(rollbackFor = Exception.class)
    public void saveExamRule(ReqSaveExamRulePO request) {
        // 判断 题目类型 总分是否为100
        ExamRuleInfo jr = request.getJudgmentalQuestionRule();
        ExamRuleInfo mr = request.getMultipleChoiceQuestionRule();
        ExamRuleInfo sr = request.getSingleChoiceQuestionRule();
        if (jr.getPerQuestionScore() * jr.getQuestionCnt() +
                mr.getPerQuestionScore() * mr.getQuestionCnt() +
                sr.getPerQuestionScore() * sr.getQuestionCnt() != 100) {
            throw new BizException("试卷满分不为100分,请重新选择！");
        }
        Long regionId = request.getRegionId();
        saveExamRule(sr, QuestionTypeEnum.SINGLE_CHOICE,regionId);
        saveExamRule(mr, QuestionTypeEnum.MULTIPLE_CHOICE,regionId);
        saveExamRule(jr, QuestionTypeEnum.JUDGMENTAL,regionId);
    }

    public void saveExamRule(ExamRuleInfo examRuleInfo, QuestionTypeEnum questionTypeEnum, Long regionId) {
        ExamRule examRule = iExamRuleService.getOne(Wrappers.lambdaQuery(ExamRule.class)
                .eq(ExamRule::getRegionId,regionId)
                .eq(ExamRule::getQuestionType, questionTypeEnum.name()));
        if (Objects.isNull(examRule)) {
            examRule = new ExamRule();
            examRule.setCreateOn(LocalDateTime.now());
            examRule.setCreateBy(LoginUserUtil.getUserId());
        }
        examRule.setQuestionType(questionTypeEnum.name());
        examRule.setQuestionCnt(examRuleInfo.getQuestionCnt());
        examRule.setPerQuestionScore(examRuleInfo.getPerQuestionScore());
        examRule.setUpdateOn(LocalDateTime.now());
        examRule.setUpdateBy(LoginUserUtil.getUserId());
        examRule.setRegionId(regionId);
        iExamRuleService.saveOrUpdate(examRule);
    }

    public ResExamRuleVO getExamRule(ReqExamRulePO request) {
        Long regionId = request.getRegionId();
        // 判断登录用户区域权限是否包含传入的区域
        UserInfoDetails userDetail = LoginUserUtil.loginUserDetail();
        List<Long> childList = regionsCacheHelper.listChildRegionId(userDetail.getRegionId(), true, true);
        // 传入的区域ID不在登录用户权限内，返回空
        if (!childList.contains(regionId)){
            return null;
        }
        ExamRuleInfo singleChoiceExamRule = getExamRule(QuestionTypeEnum.SINGLE_CHOICE,regionId);
        ExamRuleInfo multipleChoiceExamRule = getExamRule(QuestionTypeEnum.MULTIPLE_CHOICE,regionId);
        ExamRuleInfo judgmentalExamRule = getExamRule(QuestionTypeEnum.JUDGMENTAL,regionId);

        ResExamRuleVO resExamRuleVO = new ResExamRuleVO();
        resExamRuleVO.setSingleChoiceQuestionRule(singleChoiceExamRule);
        resExamRuleVO.setMultipleChoiceQuestionRule(multipleChoiceExamRule);
        resExamRuleVO.setJudgmentalQuestionRule(judgmentalExamRule);
        return resExamRuleVO;
    }

    public ExamRuleInfo getExamRule(QuestionTypeEnum questionTypeEnum,Long regionId) {
        LambdaQueryWrapper<ExamRule> wrapper = Wrappers.lambdaQuery(ExamRule.class);
        wrapper.eq(ExamRule::getQuestionType, questionTypeEnum.name());
        wrapper.eq(ExamRule::getRegionId,regionId);
        // 获取当前区域的试卷规则
        ExamRule examRule = iExamRuleService.getOne(wrapper);
        RegionDTO regionDto = regionsCacheHelper.getByRegionId(regionId);
        Integer regionLevel = regionDto.getRegionLevel();

        // 如果登录用户所属区域没有设置试卷规则,则获取其上一级行政区域的规则
        // 如果是区县一级
        if (DefValConstants.QU_REGION_LEVEL.equals(regionLevel)) {
            // 如果为空，获取市一级的试卷规则
            if (Objects.isNull(examRule)) {
                Long parentRegionId = regionDto.getParentId();
                examRule = getRegionExamRule(questionTypeEnum,parentRegionId);
                // 如果为空，获取省一级的试卷规则
                if (Objects.isNull(examRule)){
                    examRule = getRegionExamRule(questionTypeEnum,DefValConstants.ZJREGION_ID);
                }
            }
        }
        // 如果是市一级
        else if (DefValConstants.CITY_REGION_LEVEL.equals(regionLevel)) {
            // 如果为空，获取省一级的试卷规则
            if (Objects.isNull(examRule)){
                examRule = getRegionExamRule(questionTypeEnum,DefValConstants.ZJREGION_ID);
            }
        }
        
        ExamRuleInfo examRuleInfo = new ExamRuleInfo();
        if (Objects.nonNull(examRule)) {
            examRuleInfo.setQuestionType(QuestionTypeEnum.valueOf(examRule.getQuestionType()));
            examRuleInfo.setQuestionCnt(examRule.getQuestionCnt());
            examRuleInfo.setPerQuestionScore(examRule.getPerQuestionScore());
        }
        return examRuleInfo;
    }

    private ExamRule getRegionExamRule(QuestionTypeEnum questionTypeEnum,Long regionId) {
        ExamRule examRule;
        examRule = iExamRuleService.getOne(Wrappers.lambdaQuery(ExamRule.class)
                .eq(ExamRule::getQuestionType, questionTypeEnum.name())
                .eq(ExamRule::getRegionId, regionId));
        return examRule;
    }

    public PageVo<ResExamPaperListVO> listExamPaper(ReqExamPaperListPO request) {
        Integer pageNumber = request.getPageNumber();
        Integer pageSize = request.getPageSize();
        LambdaQueryWrapper<ExamPaper> wrapper = Wrappers.lambdaQuery(ExamPaper.class);
        ExaminationPaperManage context = (ExaminationPaperManage) AopContext.currentProxy();
        context.buildExamPaperQuery(wrapper, request);
        Page<ExamPaper> page = iExamPaperService.page(new Page<>(pageNumber, pageSize), wrapper);

        PageVo<ResExamPaperListVO> pageVo = new PageVo<>();
        long total = page.getTotal();
        pageVo.setTotal(total);
        if (0 == total) {
            pageVo.setRecords(new ArrayList<>());
            return pageVo;
        }
        List<ExamPaper> records = page.getRecords();
        List<ResExamPaperListVO> resVOList = records.stream().map(r -> {
            ResExamPaperListVO resVO = new ResExamPaperListVO();
            resVO.setId(r.getId());
            resVO.setCreateTime(r.getCreateOn());
            resVO.setPaperName(r.getExamPaperName());
            if (Objects.nonNull(r.getRegionId())) {
                resVO.setRegionId(r.getRegionId());
                resVO.setRegionName(regionsCacheHelper.getDisplayName(r.getRegionId()));
            }
            return resVO;
        }).collect(Collectors.toList());
        pageVo.setRecords(resVOList);
        return pageVo;
    }

    @LambdaDataScope(type = LambdaDataScopeTypeEnum.ONLY_REGION)
    public void buildExamPaperQuery(LambdaQueryWrapper<ExamPaper> wrapper, ReqExamPaperListPO request) {
        // 获取入参
        String paperName = request.getPaperName();
        Long regionId = request.getRegionId();
        List<Long> regionIdList = new ArrayList<>();
        if (Objects.nonNull(regionId)) {
            regionIdList = regionsCacheHelper.listChildRegionId(regionId);
        }
        wrapper.like(StringUtils.isNotBlank(paperName), ExamPaper::getExamPaperName, paperName)
                .eq(ExamPaper::getIsRandom,IsRandomEnum.NOT_RANDOM_PAPER.getCode())
                .in(CollectionUtil.isNotEmpty(regionIdList), ExamPaper::getRegionId, regionIdList)
                .orderByDesc(ExamPaper::getCreateOn);
    }

    public void deleteExamPaper(Long id) {
        iExamPaperService.removeById(id);
        List<ExamPaperQuestion> examPaperQuestionList = iExamPaperQuestionService.list(Wrappers.lambdaQuery(ExamPaperQuestion.class)
                .eq(ExamPaperQuestion::getExamPaperId, id));

        if (CollectionUtil.isNotEmpty(examPaperQuestionList)) {
            List<Long> questionUsageCntUpdateList = examPaperQuestionList.stream()
                    .map(ExamPaperQuestion::getPaperQuestionId).collect(Collectors.toList());
            for (Long questionId : questionUsageCntUpdateList) {
                questionUsageCntUpdate(questionId);
            }
            iExamPaperQuestionService.remove(Wrappers.lambdaQuery(ExamPaperQuestion.class)
                    .eq(ExamPaperQuestion::getExamPaperId, id));
        }
    }
}
