package com.testor.module.train.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.constant.DefaultRule;
import com.testor.module.duty.util.PoiExcelUtils;
import com.testor.module.train.exam.dao.TTrainTestQuestionsDao;
import com.testor.module.train.exam.model.domain.TTrainExamChoice;
import com.testor.module.train.exam.model.domain.TTrainExamJudgment;
import com.testor.module.train.exam.model.domain.TTrainQuestionBank;
import com.testor.module.train.exam.model.domain.TTrainTestQuestions;
import com.testor.module.train.exam.model.dto.TTrainTestQuestionsDelParam;
import com.testor.module.train.exam.model.dto.TTrainTestQuestionsParam;
import com.testor.module.train.exam.service.TTrainExamChoiceService;
import com.testor.module.train.exam.service.TTrainExamJudgmentService;
import com.testor.module.train.exam.service.TTrainQuestionBankService;
import com.testor.module.train.exam.service.TTrainTestQuestionsService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 管理试题——教育培训Service业务层处理
 *
 * @author testor-framework
 * @date 2022-07-13 15:22:00
 */
@Service
public class TTrainTestQuestionsServiceImpl extends SuperServiceImpl<TTrainTestQuestionsDao, TTrainTestQuestions> implements TTrainTestQuestionsService {
    @Autowired(required = false)
    private TTrainTestQuestionsDao tTrainTestQuestionsDao;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private TTrainExamJudgmentService tTrainExamJudgmentService;
    @Autowired
    private TTrainExamChoiceService tTrainExamChoiceService;
    @Autowired
    private SysRuleService sysRuleService;
    @Autowired
    private TTrainQuestionBankService tTrainQuestionBankService;
    @Autowired
    private TTrainTestQuestionsService tTrainTestQuestionsService;

    @Override
    public BaseResponse<TTrainTestQuestions> imports(MultipartFile file, TTrainTestQuestions tTrainTestQuestions) throws Exception {
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        Workbook workbook = null;
        InputStream inputStream = null;
        BaseResponse<TTrainTestQuestions> response = new BaseResponse<>();
        try {
            inputStream = file.getInputStream();
            // 读取Excel⽂件⼯作表
            workbook = PoiExcelUtils.readFile(inputStream, file.getOriginalFilename());
            //取得第⼀个⼯作表
            Sheet sheet = workbook.getSheetAt(0);
            //报表上传的每条数据
//            List<Map<Integer, Object>> list = PoiExcelUtils.getBody(sheet, 9, 1);
            List<Map<Integer, Object>> list = PoiExcelUtils.getBody(sheet, 10, 1);
            // 返回试题集合
            List<TTrainTestQuestionsParam> arraylist = testQuestionsObj(list);
            for (TTrainTestQuestionsParam testQuestionsParam : arraylist) {
                this.addImport(testQuestionsParam);
            }
            response.setMsg("导入成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    /**
     * 返回试题集合
     *
     * @param list
     * @return
     */
    private List<TTrainTestQuestionsParam> testQuestionsObj(List<Map<Integer, Object>> list) {
        List<TTrainTestQuestionsParam> arrayList = new ArrayList<>();
        for (Map<Integer, Object> map : list) {
            TTrainTestQuestionsParam testQuestionsParam = new TTrainTestQuestionsParam();
            // 题库名称
            String questionBankName = map.get(0).toString();
            //题类型
            String select = map.get(1).toString();
            // 试题内容
            String testQuestionsContent = map.get(2).toString();
            // 试题解析
            String testQuestionsAnalysis = map.get(3).toString();
            if ("单选题".contains(select)) {
                testQuestionsParam.setTestQuestionsType("SELECT");
            }
            if ("多选题".contains(select)) {
                testQuestionsParam.setTestQuestionsType("MORE_SELECT");
            }
            if ("判断题".contains(select)) {
                testQuestionsParam.setTestQuestionsType("JUDGE");
            }
            testQuestionsParam.setTestQuestionsContent(testQuestionsContent);
            testQuestionsParam.setTestQuestionsAnalysis(testQuestionsAnalysis);
            testQuestionsParam.setQuestionBankName(questionBankName);
            String correct = map.get(4).toString();
            Map<String, String> hashMap = new HashMap<>();
            String A = map.get(5).toString();
            String B = map.get(6).toString();
            String C = map.get(7).toString();
            String D = map.get(8).toString();
            String E = map.get(9).toString();
            hashMap.put("A", A);
            hashMap.put("B", B);
            hashMap.put("C", C);
            hashMap.put("D", D);
            hashMap.put("E", E);
            List<TTrainExamChoice> choices = new ArrayList<>();
            for (String s : hashMap.keySet()) {
                if (!"".equals(hashMap.get(s))) {
                    TTrainExamChoice tTrainExamChoice = new TTrainExamChoice();
                    tTrainExamChoice.setOptions(s);
                    tTrainExamChoice.setOptionText(hashMap.get(s));
                    if (correct.contains(s)) {
                        tTrainExamChoice.setIsCorrect("1");
                    } else {
                        tTrainExamChoice.setIsCorrect("0");
                    }
                    choices.add(tTrainExamChoice);
                }
            }
            testQuestionsParam.setTTrainExamChoices(choices);
            arrayList.add(testQuestionsParam);
        }
        return arrayList;
    }

    @Override
    @Transactional
    public BaseResponse<TTrainTestQuestions> addEntity(TTrainTestQuestionsParam addRequest) throws Exception {
        if (ObjectHelper.isEmpty(addRequest)) {
            throw new BusinessException("请求参数有误");
        }
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        BaseResponse<TTrainTestQuestions> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            String id = addRequest.getId();
            TTrainTestQuestionsParam data = BeanHelper.beanToBean(addRequest, TTrainTestQuestionsParam.class);
            if (StringHelper.isEmpty(id)) {
                id = IdHelper.getId32bit();
                data.setCreateByName(loginUser.getUserName());
                List<TTrainTestQuestions> list = this.list(new QueryWrapper<TTrainTestQuestions>()
                        .eq(TTrainTestQuestions.QUESTION_BANK_ID, addRequest.getQuestionBankId())
                        .eq(TTrainTestQuestions.TEST_QUESTIONS_CONTENT, addRequest.getTestQuestionsContent())
                        .ne(TTrainTestQuestions.STATUS, BizConstants.STATUS_DELETE)
                );
                if (ObjectHelper.isNotEmpty(list)) {
                    throw new BusinessException("试题已存在");
                }
            } else {
                data.setUpdateByName(loginUser.getUserName());
                TTrainTestQuestions testQuestions = this.getById(id);
                if (!addRequest.getTestQuestionsContent().equals(testQuestions.getTestQuestionsContent())) {
                    List<TTrainTestQuestions> list = this.list(new QueryWrapper<TTrainTestQuestions>()
                            .eq(TTrainTestQuestions.QUESTION_BANK_ID, addRequest.getQuestionBankId())
                            .eq(TTrainTestQuestions.TEST_QUESTIONS_CONTENT, addRequest.getTestQuestionsContent())
                            .ne(TTrainTestQuestions.STATUS, BizConstants.STATUS_DELETE)
                    );
                    if (ObjectHelper.isNotEmpty(list)) {
                        throw new BusinessException("试题已存在");
                    }
                }
            }
            data.setOrgId(loginUser.getOrgId());
            data.setId(id);
            boolean result = false;
            //获取试题类型
            String testQuestionsType = data.getTestQuestionsType();
            //获取试题选项
            List<TTrainExamChoice> tTrainExamChoices = data.getTTrainExamChoices();
            //效验选项参数
            checkExamChoices(tTrainExamChoices, testQuestionsType);
            List<TTrainExamJudgment> tTrainExamJudgmentList = new ArrayList<>();
            if ("JUDGE".equals(testQuestionsType)) {
                for (TTrainExamChoice tTrainExamChoice : tTrainExamChoices) {
                    String judgmentId = tTrainExamChoice.getId();
                    if (StringHelper.isEmpty(judgmentId)) {
                        judgmentId = IdHelper.getId32bit();
                    } else {
                        tTrainExamJudgmentService.remove(new QueryWrapper<TTrainExamJudgment>().eq(TTrainExamJudgment.TEST_QUESTIONS_ID,id));
                    }
                    TTrainExamJudgment tTrainExamJudgment = BeanHelper.beanToBean(tTrainExamChoice, TTrainExamJudgment.class);
                    tTrainExamJudgment.setTestQuestionsId(id);
                    tTrainExamJudgment.setId(judgmentId);
                    tTrainExamJudgmentList.add(tTrainExamJudgment);
                }
                //保存判断题
                result = tTrainExamJudgmentService.saveOrUpdateBatch(tTrainExamJudgmentList);
            }
            if ("SELECT".equals(testQuestionsType) || "MORE_SELECT".equals(testQuestionsType)) {
                List<TTrainExamChoice> tTrainExamChoices1 = new ArrayList<>();
                for (TTrainExamChoice tTrainExamChoice : tTrainExamChoices) {
                    String choiceId = tTrainExamChoice.getId();
                    if (StringHelper.isEmpty(choiceId)) {
                        choiceId = IdHelper.getId32bit();
                    } else {
                        tTrainExamChoiceService.remove(new QueryWrapper<TTrainExamChoice>().eq(TTrainExamChoice.TEST_QUESTIONS_ID,id));
                    }
                    tTrainExamChoice.setId(choiceId);
                    tTrainExamChoice.setTestQuestionsId(id);
                    tTrainExamChoices1.add(tTrainExamChoice);
                }
                //保存选择题
                result = tTrainExamChoiceService.saveOrUpdateBatch(tTrainExamChoices1);
            }
            //  保存试题
            result = this.saveOrUpdate(data);
            if (result) {
                TTrainTestQuestions newEntity = new TTrainTestQuestions();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }

    private void checkExamChoices(List<TTrainExamChoice> tTrainExamChoices, String testQuestionsType) throws Exception {
        int size = tTrainExamChoices.size();
        if (!"JUDGE".equals(testQuestionsType)) {
            if (size < 3 || size > 5) {
                throw new BusinessException("非判断题最少三个选项，最多五个选项");
            }
        } else {
            if (size != 2) {
                throw new BusinessException("判断题只有两个选项");
            }
        }
        int count = 0;
        for (TTrainExamChoice tTrainExamChoice : tTrainExamChoices) {
            String optionText = tTrainExamChoice.getOptionText();
//            if (ObjectHelper.isEmpty(optionText)) {
//                throw new BusinessException("选项文本内容不能为空");
//            }
            String isCorrect = tTrainExamChoice.getIsCorrect();
            if ("1".equals(isCorrect)) {
                count++;
            }
        }
        if ("SELECT".equals(testQuestionsType)) {
            if (count != 1) {
                throw new BusinessException("单选题只能有一个正确选项");
            }
        }
        if ("MORE_SELECT".equals(testQuestionsType)) {
            if (count < 2) {
                throw new BusinessException("多选题最少有两个正确选项");
            }
        }
    }

    @Override
    public BaseResponse<TTrainTestQuestions> getByIds(String id) throws Exception {
        BaseResponse<TTrainTestQuestions> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TTrainTestQuestions trainTestQuestions = this.getById(id);
            //获取试题类型
            String testQuestionsType = trainTestQuestions.getTestQuestionsType();
            //选择题
            if ("SELECT".equals(testQuestionsType) || "MORE_SELECT".equals(testQuestionsType)) {
                QueryWrapper<TTrainExamChoice> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq(TTrainExamChoice.TEST_QUESTIONS_ID, id);
                List<TTrainExamChoice> list = tTrainExamChoiceService.list(queryWrapper);
                List<TTrainExamChoice> collect = list.stream().sorted(Comparator.comparing(TTrainExamChoice::getOptions)).collect(Collectors.toList());
                TTrainTestQuestionsParam tTrainTestQuestionsParam = BeanHelper.beanToBean(trainTestQuestions, TTrainTestQuestionsParam.class);
                tTrainTestQuestionsParam.setTTrainExamChoices(collect);
                baseResponse.setData(tTrainTestQuestionsParam);
            }
            //判断题
            if ("JUDGE".equals(testQuestionsType)) {
                QueryWrapper<TTrainExamJudgment> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq(TTrainExamJudgment.TEST_QUESTIONS_ID, id);
                List<TTrainExamJudgment> list = tTrainExamJudgmentService.list(queryWrapper);
                List<TTrainExamChoice> tTrainExamChoices = new ArrayList<>();
                for (TTrainExamJudgment tTrainExamJudgment : list) {
                    TTrainExamChoice tTrainExamChoice = BeanHelper.beanToBean(tTrainExamJudgment, TTrainExamChoice.class);
                    tTrainExamChoices.add(tTrainExamChoice);
                }
                List<TTrainExamChoice> collect = tTrainExamChoices.stream().sorted(Comparator.comparing(TTrainExamChoice::getOptions)).collect(Collectors.toList());
                TTrainTestQuestionsParam tTrainTestQuestionsParam = BeanHelper.beanToBean(trainTestQuestions, TTrainTestQuestionsParam.class);
                tTrainTestQuestionsParam.setTTrainExamChoices(collect);
                baseResponse.setData(tTrainTestQuestionsParam);
            }
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> updateEntity(TTrainTestQuestions updateRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            TTrainTestQuestions data = BeanHelper.beanToBean(updateRequest, TTrainTestQuestions.class);
            boolean result = this.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> deleteEntity(TTrainTestQuestionsDelParam deleteRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            TTrainTestQuestions data = new TTrainTestQuestions();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = this.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<List<TTrainTestQuestionsParam>> autoAddTestQuestions(TTrainTestQuestionsParam tTrainTestQuestionsParam) throws Exception {
        BaseResponse<List<TTrainTestQuestionsParam>> baseResponse = new BaseResponse<>();
        QueryWrapper<TTrainTestQuestions> query = createQuery(tTrainTestQuestionsParam);
        List<TTrainTestQuestions> questionsList = this.list(query);
        //所选试题
        List<TTrainTestQuestionsParam> questionsParamList = new ArrayList<>();
        for (TTrainTestQuestions tTrainTestQuestions : questionsList) {
            TTrainTestQuestionsParam tTrainTestQuestionsParam1 = BeanHelper.beanToBean(tTrainTestQuestions, TTrainTestQuestionsParam.class);
            questionsParamList.add(tTrainTestQuestionsParam1);
        }
        //按照试题类型统计数量
        List<TTrainTestQuestionsParam> questionsParamsCount = new ArrayList<>();
        // 按照条件统计题库中试题的数量
        TTrainTestQuestionsParam questionsParam = questionsTypeNum(questionsParamList);
        if ("0".equals(tTrainTestQuestionsParam.getSelectNum().toString()) &&
                "0".equals(tTrainTestQuestionsParam.getMoreSelectNum().toString()) &&
                "0".equals(tTrainTestQuestionsParam.getJudgeNum().toString())) {
            questionsParamsCount.add(questionsParam);
            baseResponse.setData(questionsParamsCount);
            return baseResponse;
        } else {
            // 检查抽取数量合法性
            checkData(tTrainTestQuestionsParam, questionsParam);
            Long selectNum = tTrainTestQuestionsParam.getSelectNum();
            Long moreSelectNum = tTrainTestQuestionsParam.getMoreSelectNum();
            Long judgeNum = tTrainTestQuestionsParam.getJudgeNum();
            //  按照抽取的数量随机统计数据
            List<TTrainTestQuestionsParam> selectList = randomAxtract(questionsParamList, selectNum, "SELECT");
            List<TTrainTestQuestionsParam> moreSelectList = randomAxtract(questionsParamList, moreSelectNum, "MORE_SELECT");
            List<TTrainTestQuestionsParam> judgeList = randomAxtract(questionsParamList, judgeNum, "JUDGE");
            List<TTrainTestQuestionsParam> moreQuestionsParamList = new ArrayList<>();
            if (selectList != null) {
                moreQuestionsParamList.addAll(selectList);
            }
            if (moreSelectList != null) {
                moreQuestionsParamList.addAll(moreSelectList);
            }
            if (judgeList != null) {
                moreQuestionsParamList.addAll(judgeList);
            }
            List<TTrainTestQuestionsParam> collect = moreQuestionsParamList.stream()
                    .sorted(Comparator.comparing(TTrainTestQuestionsParam::getQuestionBankName)
                    .thenComparing(TTrainTestQuestionsParam::getTestQuestionsType).reversed()).collect(Collectors.toList());
            baseResponse.setData(collect);
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<List<TTrainTestQuestions>> handAddTestQuestions(TTrainTestQuestionsParam tTrainTestQuestionsParam) {
        BaseResponse<List<TTrainTestQuestions>> baseResponse = new BaseResponse<>();
        QueryWrapper<TTrainTestQuestions> query = createQuery(tTrainTestQuestionsParam);
        List<TTrainTestQuestions> questionsList = this.list(query);
        List<TTrainTestQuestions> collect = questionsList.stream()
                .sorted(Comparator.comparing(TTrainTestQuestions::getQuestionBankName)
                        .thenComparing(TTrainTestQuestions::getTestQuestionsType).reversed()).collect(Collectors.toList());
        baseResponse.setData(collect);
        return baseResponse;
    }

    /**
     * 检查抽取数量合法性
     *
     * @param tTrainTestQuestionsParam
     * @param questionsParam
     * @throws Exception
     */
    private void checkData(TTrainTestQuestionsParam tTrainTestQuestionsParam, TTrainTestQuestionsParam questionsParam) throws Exception {
        Long selectNum = tTrainTestQuestionsParam.getSelectNum();
        Long moreSelectNum = tTrainTestQuestionsParam.getMoreSelectNum();
        Long judgeNum = tTrainTestQuestionsParam.getJudgeNum();
        if (questionsParam.getSelectNum() != null) {
            if (selectNum > questionsParam.getSelectNum()) {
                throw new BusinessException("抽取数量不能大于试题数量");
            }
        }
        if (questionsParam.getMoreSelectNum() != null) {
            if (moreSelectNum > questionsParam.getMoreSelectNum()) {
                throw new BusinessException("抽取数量不能大于试题数量");
            }
        }
        if (questionsParam.getJudgeNum() != null) {
            if (judgeNum > questionsParam.getJudgeNum()) {
                throw new BusinessException("抽取数量不能大于试题数量");
            }
        }
        if (selectNum < 0 || moreSelectNum < 0 || judgeNum < 0) {
            throw new BusinessException("抽取数量不能小于1");
        }
    }

    /**
     * 根据试卷类型进行分类统计数量
     *
     * @param questionsParamList
     * @return 返回统计好的数据对象
     */
    private TTrainTestQuestionsParam questionsTypeNum(List<TTrainTestQuestionsParam> questionsParamList) {
        //按照试卷类型分组并统计数量
        Map<String, Long> collect = questionsParamList.stream().collect(Collectors.groupingBy(TTrainTestQuestions::getTestQuestionsType, Collectors.counting()));
        //按照试卷类型统计数量并返回
        TTrainTestQuestionsParam questionsParam = new TTrainTestQuestionsParam();
        for (Map.Entry<String, Long> entry : collect.entrySet()) {
            String key = entry.getKey();
            Long value = entry.getValue();
            if ("SELECT".equals(key)) {
                questionsParam.setSelectNum(value);
            }
            if ("MORE_SELECT".equals(key)) {
                questionsParam.setMoreSelectNum(value);
            }
            if ("JUDGE".equals(key)) {
                questionsParam.setJudgeNum(value);
            }
        }
        return questionsParam;
    }

    /**
     * 按照抽取的数量随机统计数据
     *
     * @param num 抽取的数量
     * @return
     */
    private List<TTrainTestQuestionsParam> randomAxtract(List<TTrainTestQuestionsParam> questionsParamList, Long num, String questionsType) {
        // 按照试题类型分组
        Map<String, List<TTrainTestQuestionsParam>> collect = questionsParamList.stream().collect(Collectors.groupingBy(TTrainTestQuestions::getTestQuestionsType));
        List<TTrainTestQuestionsParam> questionsParamList1 = null;
        if ("SELECT".equals(questionsType)) {
            List<TTrainTestQuestionsParam> selectList = collect.get(questionsType);
            // 返回指定类型指定数量集合
            if (selectList != null) {
                questionsParamList1 = assignList(selectList, num);
            }
        }
        if ("MORE_SELECT".equals(questionsType)) {
            List<TTrainTestQuestionsParam> questionsParamList2 = collect.get(questionsType);
            // 返回指定类型指定数量集合
            if (questionsParamList2 != null) {
                questionsParamList1 = assignList(questionsParamList2, num);
            }
        }
        if ("JUDGE".equals(questionsType)) {
            List<TTrainTestQuestionsParam> questionsParamList3 = collect.get(questionsType);
            // 返回指定类型指定数量集合
            if (questionsParamList3 != null) {
                questionsParamList1 = assignList(questionsParamList3, num);
            }
        }
        return questionsParamList1;
    }

    /**
     * 随机统计数据
     *
     * @param selectList
     * @param num
     * @return 返回随机统计的数据
     */
    private List<TTrainTestQuestionsParam> assignList(List<TTrainTestQuestionsParam> selectList, Long num) {
        List<TTrainTestQuestionsParam> list = new ArrayList<>();
        // 生成集合大小范围内的随机数
        int size = selectList.size();
        Random random = new Random();
        HashSet<Integer> set = new HashSet<>();
        while (true) {
            int i = random.nextInt(size);
            set.add(i);
            if (set.size() == num) {
                break;
            }
        }
        for (Integer integer : set) {
            TTrainTestQuestionsParam testQuestionsParam = selectList.get(integer);
            list.add(testQuestionsParam);
        }
        return list;
    }

    private QueryWrapper<TTrainTestQuestions> createQuery(TTrainTestQuestionsParam tTrainTestQuestionsParam) {
        // 所选题库id
        String questionBankId = tTrainTestQuestionsParam.getQuestionBankId();
        // 所选试题类型
        String testQuestionsType = tTrainTestQuestionsParam.getTestQuestionsType();
        String[] split = questionBankId.split(",");
        QueryWrapper<TTrainTestQuestions> queryWrapper = new QueryWrapper<>();
        if (ObjectHelper.isEmpty(questionBankId)) {
            String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_ALL.name());
            if (StringUtils.isNotEmpty(rule)) {
                queryWrapper.apply(rule);
            }
        } else {
            // 按照所选题库进行查询
            queryWrapper.in(TTrainTestQuestions.QUESTION_BANK_ID, split);
        }
        if (ObjectHelper.isNotEmpty(testQuestionsType)) {
            queryWrapper.eq(TTrainTestQuestions.TEST_QUESTIONS_TYPE, testQuestionsType);
        }
        return queryWrapper;
    }

    public BaseResponse<TTrainTestQuestions> addImport(TTrainTestQuestionsParam addRequest) throws Exception {
        if (ObjectHelper.isEmpty(addRequest)) {
            throw new BusinessException("请求参数有误");
        }
        if (StringUtils.isBlank(addRequest.getTestQuestionsType())) {
            throw new BusinessException("上传试题类型错误，试题类型为单选、多选、判断题三种，请编辑后重新上传！！");
        }
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        BaseResponse<TTrainTestQuestions> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            TTrainTestQuestionsParam data = BeanHelper.beanToBean(addRequest, TTrainTestQuestionsParam.class);
            // 题库名称
            String questionBankName = data.getQuestionBankName();
            // 题库的信息
            TTrainQuestionBank questionBankNameList = tTrainQuestionBankService.getOne(new QueryWrapper<TTrainQuestionBank>()
                    .eq(TTrainQuestionBank.QUESTION_BANK_NAME, questionBankName)
                    .eq(TTrainQuestionBank.ORG_ID, sysOrg.getOrgId())
                    .ne(TTrainQuestionBank.STATUS, BizConstants.STATUS_DELETE)
            );
            if (ObjectHelper.isEmpty(questionBankNameList)) {
                throw new BusinessException("题库" + questionBankName + "不存在");
            }
            // 试题内容
            String testQuestionsContent = data.getTestQuestionsContent();
            data.setQuestionBankId(questionBankNameList.getId());
            data.setOrgId(sysOrg.getOrgId());
            // 试题内容相等条件
            QueryWrapper<TTrainTestQuestions> wrapper = new QueryWrapper<TTrainTestQuestions>()
                    .eq(TTrainTestQuestions.TEST_QUESTIONS_CONTENT, testQuestionsContent)
                    .eq(TTrainTestQuestions.QUESTION_BANK_ID, questionBankNameList.getId())
                    .eq(TTrainTestQuestions.ORG_ID, sysOrg.getOrgId())
                    .ne(TTrainTestQuestions.STATUS, BizConstants.STATUS_DELETE);
            // 获取试题内容相等的数据
//            TTrainTestQuestions one = tTrainTestQuestionsService.getOne(wrapper);
            List<TTrainTestQuestions> list = tTrainTestQuestionsService.list(wrapper);
            TTrainTestQuestions one=null;
            if (!CollectionUtils.isEmpty(list)) {
                 one = list.get(0);
            }
            String id = "";
            if (ObjectHelper.isNotEmpty(one)) {
                id = one.getId();
                data.setUpdateByName(loginUser.getUserName());
            } else {
                id = IdHelper.getId32bit();
                data.setCreateByName(loginUser.getUserName());
            }
            data.setId(id);
            boolean result = false;
            //获取试题类型
            String testQuestionsType = data.getTestQuestionsType();
            //获取试题选项
            List<TTrainExamChoice> tTrainExamChoices = data.getTTrainExamChoices();
            //效验选项参数
            checkExamChoices(tTrainExamChoices, testQuestionsType);
            List<TTrainExamJudgment> tTrainExamJudgmentList = new ArrayList<>();
            if ("JUDGE".equals(testQuestionsType)) {
                for (TTrainExamChoice tTrainExamChoice : tTrainExamChoices) {
                    String judgeId = IdHelper.getId32bit();
                    if (ObjectHelper.isNotEmpty(one)) {
                        result = tTrainExamJudgmentService.remove(new QueryWrapper<TTrainExamJudgment>()
                                .eq(TTrainExamJudgment.TEST_QUESTIONS_ID, one.getId())
                                .ne(TTrainExamJudgment.STATUS, BizConstants.STATUS_DELETE));
                    }
                    TTrainExamJudgment tTrainExamJudgment = BeanHelper.beanToBean(tTrainExamChoice, TTrainExamJudgment.class);
                    tTrainExamJudgment.setTestQuestionsId(id);
                    tTrainExamJudgment.setId(judgeId);
                    tTrainExamJudgmentList.add(tTrainExamJudgment);
                }
                //保存判断题
                result = tTrainExamJudgmentService.saveOrUpdateBatch(tTrainExamJudgmentList);
            }
            if ("SELECT".equals(testQuestionsType) || "MORE_SELECT".equals(testQuestionsType)) {
                List<TTrainExamChoice> tTrainExamChoices1 = new ArrayList<>();
                for (TTrainExamChoice tTrainExamChoice : tTrainExamChoices) {
                    String choiceId = IdHelper.getId32bit();
                    if (ObjectHelper.isNotEmpty(one)) {
                        result = tTrainExamChoiceService.remove(new QueryWrapper<TTrainExamChoice>()
                                .eq(TTrainExamChoice.TEST_QUESTIONS_ID, one.getId())
                                .ne(TTrainExamChoice.STATUS, BizConstants.STATUS_DELETE));
                    }
                    tTrainExamChoice.setId(choiceId);
                    tTrainExamChoice.setTestQuestionsId(id);
                    tTrainExamChoices1.add(tTrainExamChoice);
                }
                //保存选择题
                result = tTrainExamChoiceService.saveOrUpdateBatch(tTrainExamChoices1);
            }
            //  保存试题
            result = this.saveOrUpdate(data, wrapper);
            if (result) {
                TTrainTestQuestions newEntity = new TTrainTestQuestions();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }
}
