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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.util.DateUtil;
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.TTrainTestQuestions;
import com.testor.module.train.exam.service.TTrainExamChoiceService;
import com.testor.module.train.exam.service.TTrainExamJudgmentService;
import com.testor.module.train.exam.service.TTrainTestQuestionsService;
import com.testor.module.train.examinationManage.dao.TTrainExaminationManageDao;
import com.testor.module.train.examinationManage.model.domain.TTrainExaminationManage;
import com.testor.module.train.examinationManage.model.dto.TTrainExaminationManageDelParam;
import com.testor.module.train.examinationManage.model.dto.TTrainExaminationManageParam;
import com.testor.module.train.examinationManage.service.TTrainExaminationManageService;
import com.testor.module.train.myManagement.model.domain.TTrainMyManagement;
import com.testor.module.train.myManagement.model.domain.TTrainTestQuestionsExercise;
import com.testor.module.train.myManagement.service.TTrainMyManagementService;
import com.testor.module.train.myManagement.service.TTrainTestQuestionsExerciseService;
import com.testor.module.train.paper.model.domain.TTrainPaper;
import com.testor.module.train.paper.model.dto.Options;
import com.testor.module.train.paper.model.dto.ReturnTrainPaper;
import com.testor.module.train.paper.model.dto.TestQuestionsContent;
import com.testor.module.train.paper.service.TTrainPaperService;
import com.testor.module.train.project.model.dto.MyManagement;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 考试管理—安全培训教育Service业务层处理
 *
 * @author testor-framework
 * @date 2022-09-07 11:43:25
 */
@Service
public class TTrainExaminationManageServiceImpl extends SuperServiceImpl<TTrainExaminationManageDao, TTrainExaminationManage> implements TTrainExaminationManageService {
    @Autowired(required = false)
    private TTrainExaminationManageDao tTrainExaminationManageDao;
    @Autowired
    private TTrainMyManagementService tTrainMyManagementService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private TTrainPaperService tTrainPaperService;
    @Autowired
    private TTrainExaminationManageService tTrainExaminationManageService;
    @Autowired
    private TTrainTestQuestionsExerciseService tTrainTestQuestionsExerciseService;
    @Autowired
    private TTrainExamChoiceService tTrainExamChoiceService;
    @Autowired
    private TTrainExamJudgmentService tTrainExamJudgmentService;
    @Autowired
    private TTrainTestQuestionsService tTrainTestQuestionsService;

    @Override
    @Transactional
    public BaseResponse<Map<String, String>> addEntity(TTrainExaminationManageParam addRequest) throws Exception {
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        BaseResponse<Map<String, String>> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            // 当保存补考记录的时候进行判断，只能添加一次补考
            if (StringHelper.isNotEmpty(addRequest.getParentId()) && "1".equals(addRequest.getIsRepair())) {
                String orgId = loginUser.getOrgId();
                List<TTrainExaminationManage> list = this.list(new QueryWrapper<TTrainExaminationManage>()
                        .eq(TTrainExaminationManage.PARENT_ID, addRequest.getParentId())
                        .eq(TTrainExaminationManage.ORG_ID, orgId)
                        .eq(TTrainExaminationManage.IS_REPAIR,addRequest.getIsRepair())
                        .ne(TTrainExaminationManage.STATUS, BizConstants.STATUS_DELETE)
                );
                if (list.size() > 0) {
                    throw new BusinessException("补考只能添加一次");
                }
            }
            String id = addRequest.getId();
            if (ObjectHelper.isEmpty(id)) {
                id = IdHelper.getId32bit();
            } else if(!ObjectHelper.isEmpty(id)&& !"3".equals(addRequest.getExamWay())) {
                // 获得考试计划
                TTrainExaminationManage management = this.getById(id);
                // 考试开始时间
                //String startTime = management.getExamStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                String startTime = DateUtil.convertDateToStr(management.getExamStartTime(), "yyyy-MM-dd HH:mm:ss");

                // 当前时间
                String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                if (currentTime.compareTo(startTime) > 0) {
                    throw new BusinessException("考试计划已经开始不能修改");
                }
                tTrainMyManagementService.deletePerson(addRequest.getId());
            }
            // 获取培训计划人员调用人员接口进行存储
            List<MyManagement> myManagements = addRequest.getMyManagements();
            if(!"3".equals(addRequest.getExamWay())){
                if (myManagements.size() == 0) {
                    throw new BusinessException("请添加参训人员");
                }
            }
            // 存储人员id 及 我的考试是计划主键id
            Map<String, String> map = new HashMap<>();
            String temp = id;
            myManagements.stream().forEach(item -> {
                String myId = IdHelper.getId32bit();
                item.setId(myId);
                map.put(item.getPersonId(), myId);
                item.setTaskId(temp);
                item.setTabStatus("2");
                item.setVisitStartTime(addRequest.getExamStartTime());
                item.setVisitEndTime(addRequest.getExamEndTime());
                item.setTaskName(addRequest.getExamName());
                item.setLearnWay(addRequest.getExamWay());
                item.setTaskType(addRequest.getExamType());
                item.setTestPaperId(addRequest.getPaperId());
                item.setExamDuration(addRequest.getExamDuration());
                item.setCurrentStatus("0");
                item.setPercentage("0");
            });
            TTrainMyManagement myManagement = tTrainMyManagementService.addEntity(myManagements).getData();
            String myId = "";
            if (ObjectHelper.isNotEmpty(myManagement)) {
                myId = myManagement.getId();
            }
            TTrainExaminationManage data = BeanHelper.beanToBean(addRequest, TTrainExaminationManage.class);
            data.setOrgName(sysOrg.getOrgName());
            data.setOrgId(loginUser.getOrgId());
            data.setShouldTestNumber(Integer.toString(myManagements.size()));
            if (StringHelper.isEmpty(addRequest.getParentId())) {
                data.setIsRepair("0");
            }
            data.setId(id);
            boolean result = this.saveOrUpdate(data);
            if (result) {
                TTrainExaminationManage newEntity = new TTrainExaminationManage();
                newEntity.setId(id);
                newEntity.setParentId(myId);
                baseResponse.setData(map);
            }
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<TTrainExaminationManageParam> getByIds(String id) {
        BaseResponse<TTrainExaminationManageParam> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TTrainExaminationManage data = this.getById(id);
            TTrainExaminationManageParam tTrainProjectParam = BeanHelper.beanToBean(data, TTrainExaminationManageParam.class);
            // 培训计划id
            String projectParamId = tTrainProjectParam.getId();
            // 试卷id
            String testPaperId = tTrainProjectParam.getPaperId();
            // 获取人员集合
            List<TTrainMyManagement> personList = tTrainMyManagementService.getPerson(projectParamId);
            List<MyManagement> collect = personList.stream().map(bean -> bean.beanToBean(MyManagement.class)).collect(Collectors.toList());
            // 获取试卷名称
            String testPaperName = tTrainPaperService.getTestPaperName(testPaperId);
            tTrainProjectParam.setMyManagements(collect);
            tTrainProjectParam.setTestPaperName(testPaperName);
            baseResponse.setData(tTrainProjectParam);
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<TTrainExaminationManageParam> getByCondition(String id, String orgId, String name, String status) {
        BaseResponse<TTrainExaminationManageParam> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TTrainExaminationManage data = this.getById(id);
            TTrainExaminationManageParam tTrainProjectParam = BeanHelper.beanToBean(data, TTrainExaminationManageParam.class);
            // 培训计划id
            String projectParamId = tTrainProjectParam.getId();
            // 试卷id
            String testPaperId = tTrainProjectParam.getPaperId();
            // 获取人员集合
            List<TTrainMyManagement> personList = tTrainMyManagementService.getPerson(projectParamId, orgId, name, status);
            List<MyManagement> collect = personList.stream().map(bean -> bean.beanToBean(MyManagement.class)).collect(Collectors.toList());
            // 获取试卷名称
            String testPaperName = tTrainPaperService.getTestPaperName(testPaperId);
            tTrainProjectParam.setMyManagements(collect);
            tTrainProjectParam.setTestPaperName(testPaperName);
            baseResponse.setData(tTrainProjectParam);
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> deleteEntity(TTrainExaminationManageDelParam deleteRequest) throws Exception{
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            // 获得考试计划
            TTrainExaminationManage management = this.getById(deleteRequest.getId());
            if(!"3".equals(management.getExamWay())){
                // 考试开始时间
               // String startTime = management.getExamStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                String startTime = DateUtil.convertDateToStr(management.getExamStartTime(), "yyyy-MM-dd HH:mm:ss");

                // 当前时间
                String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                if (currentTime.compareTo(startTime) > 0) {
                    throw new BusinessException("考试计划已经开始不能删除");
                }
            }

            TTrainExaminationManage data = this.getById(deleteRequest.getId());
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = this.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @Override
    public IPage<TTrainExaminationManageParam> getExamAffiliation(TTrainExaminationManageParam param, String parentIds, String orgId) {
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TTrainExaminationManageParam> resultPage = new Page<>(page, limit);
        return tTrainExaminationManageDao.getExamAffiliation(resultPage, param, parentIds, orgId);
    }

    @Override
    public BaseResponse<TTrainExaminationManageParam> addRepairExam(String id) {
        BaseResponse<TTrainExaminationManageParam> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            // 获取考试计划
            TTrainExaminationManage data = this.getById(id);
            TTrainExaminationManageParam tTrainProjectParam = BeanHelper.beanToBean(data, TTrainExaminationManageParam.class);
            // 试卷id
            String testPaperId = tTrainProjectParam.getPaperId();
            // 获取人员集合
            List<TTrainMyManagement> personList = tTrainMyManagementService.getPerson(id);
            List<MyManagement> collect = personList.stream().filter(item->item.getPercentage().equals("2")).map(bean -> bean.beanToBean(MyManagement.class)).collect(Collectors.toList());
            // 获取试卷名称
            String testPaperName = tTrainPaperService.getTestPaperName(testPaperId);
            tTrainProjectParam.setMyManagements(collect);
            tTrainProjectParam.setTestPaperName(testPaperName);
            baseResponse.setData(tTrainProjectParam);
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<TTrainExaminationManageParam> relevantRepairExam(String id) {
        BaseResponse<TTrainExaminationManageParam> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TTrainExaminationManage data = this.getById(id);
            TTrainExaminationManage one = this.getOne(new QueryWrapper<TTrainExaminationManage>()
                    .eq(TTrainExaminationManage.PARENT_ID, data.getParentId())
                    .ne(TTrainExaminationManage.STATUS, BizConstants.STATUS_DELETE)
            );
            TTrainExaminationManageParam tTrainProjectParam = BeanHelper.beanToBean(one, TTrainExaminationManageParam.class);
            // 培训计划id
            String projectParamId = tTrainProjectParam.getId();
            // 试卷id
            String testPaperId = tTrainProjectParam.getPaperId();
            // 获取人员集合
            List<TTrainMyManagement> personList = tTrainMyManagementService.getPerson(projectParamId);
            List<MyManagement> collect = personList.stream().map(bean -> bean.beanToBean(MyManagement.class)).collect(Collectors.toList());
            // 获取试卷名称
            String testPaperName = tTrainPaperService.getTestPaperName(testPaperId);
            tTrainProjectParam.setMyManagements(collect);
            tTrainProjectParam.setTestPaperName(testPaperName);
            baseResponse.setData(tTrainProjectParam);
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<TTrainExaminationManage> randomAdd(String id) throws Exception{
        BaseResponse<TTrainExaminationManage> response = new BaseResponse<>();
        // 随机线上考试计划
        TTrainExaminationManage examinationManage = this.getById(id);
        UserInfo loginUser = ContextUtils.getLoginUser();
        String userId = loginUser.getUserId();
        TTrainMyManagement one = tTrainMyManagementService.getOne(new QueryWrapper<TTrainMyManagement>()
                .eq(TTrainMyManagement.TASK_ID, id).eq(TTrainMyManagement.PERSON_ID,userId));
        TTrainExaminationManage tTrainExaminationManage = new TTrainExaminationManage();
        if (ObjectHelper.isEmpty(one)) {
            // 所属企业
            SysOrg org = sysOrgService.getById(loginUser.getOrgId());
            MyManagement myManagement = new MyManagement();
            myManagement.setTaskId(id);
            myManagement.setTabStatus("2");
            myManagement.setVisitStartTime(examinationManage.getExamStartTime());
            myManagement.setVisitEndTime(examinationManage.getExamEndTime());
            myManagement.setTaskName(examinationManage.getExamName());
            myManagement.setLearnWay(examinationManage.getExamWay());
            myManagement.setTaskType(examinationManage.getExamType());
            myManagement.setTestPaperId(examinationManage.getPaperId());
            myManagement.setCurrentStatus("0");
            myManagement.setPercentage("0");
            myManagement.setPersonId(loginUser.getUserId());
            myManagement.setCompany(org.getOrgName());
            myManagement.setDeptName(loginUser.getOrgName());
            myManagement.setOrgId(loginUser.getOrgId());
            myManagement.setPersonName(loginUser.getUserName());
            List<MyManagement> list = new ArrayList<>();
            list.add(myManagement);
            BaseResponse<TTrainMyManagement> tTrainMyManagementBaseResponse = tTrainMyManagementService.addEntity(list);
            String id1 = tTrainMyManagementBaseResponse.getData().getId();
            tTrainExaminationManage.setId(id1);
            response.setData(tTrainExaminationManage);
        } else {
            tTrainExaminationManage.setId(one.getId());
            response.setData(tTrainExaminationManage);
        }
        return response;
    }

    /**
     * 考试计划试题导出
     * @param dsName
     * @param datasetName
     * @param parameters
     * @return
     */
    public List<TTrainTestQuestions> getExportExamProject(String dsName, String datasetName, Map<String, Object> parameters) throws Exception {
        // 考试计划id
        String id = parameters.get("id").toString();
        // 一条考试计划
        TTrainExaminationManage examinationManage = tTrainExaminationManageService.getById(id);
        // 获取试卷id
        String paperId = examinationManage.getPaperId();
        // 获取试卷TTrainPaperParam paperParam =
        ReturnTrainPaper paperParam = tTrainPaperService.detail(paperId).getData();
        // 获取所有试题
        List<TestQuestionsContent> questions = paperParam.getTestQuestionsContent();
        // 存储试题及答案
        List<TTrainTestQuestions> list = new ArrayList<>();
        for (TestQuestionsContent question : questions) {
            TTrainTestQuestions tTrainTestQuestions = new TTrainTestQuestions();
            // 拼接正确选项
            String options = "";
            //  试题内容
            tTrainTestQuestions.setTestQuestionsContent(question.getTestQuestionsContent());
            // 获取正确选项
            for (Options option : question.getOptions()) {
                if ("1".equals(option.getIsCorrect())) {
                    options += option.getOptions() + "、";
                }
            }
            // 存储正确选项
            tTrainTestQuestions.setTestQuestionsType(options);
            list.add(tTrainTestQuestions);
        }
        return list;
    }

    /**
     * 考试计划人员导出
     * @param dsName
     * @param datasetName
     * @param parameters
     * @return
     * @throws Exception
     */
    public List<TTrainTestQuestions> getExportExamProjectPerson(String dsName, String datasetName, Map<String, Object> parameters) throws Exception {
        // 考试计划id
        String id = parameters.get("id").toString();
        // 获取登录用户
        String userId = parameters.get("userId").toString();
        // 获取计划关联的人员
        List<TTrainMyManagement> personList = tTrainMyManagementService.list(new QueryWrapper<TTrainMyManagement>().eq(TTrainMyManagement.TASK_ID, id));
        // 存储已选试题和人员
        List<TTrainTestQuestions> arrayList = new ArrayList<>();
        // 获取人员的答题情况
        for (TTrainMyManagement tTrainMyManagement : personList) {
            ReturnTrainPaper trainPaper = getTestPaperDetail(tTrainMyManagement.getId(),userId);
            // 试题
            for (TestQuestionsContent testQuestionsContent : trainPaper.getTestQuestionsContent()) {
                TTrainTestQuestions tTrainTestQuestions = new TTrainTestQuestions();
                // 拼接已选选项
                String options = "";
                for (Options option : testQuestionsContent.getOptions()) {
                    if ("1".equals(option.getIsSelect())) {
                        options += option.getOptions() + "、";
                    }
                }
                // 选项
                tTrainTestQuestions.setTestQuestionsType(options);
                // 人员姓名
                tTrainTestQuestions.setUpdateByName(tTrainMyManagement.getPersonName());
                arrayList.add(tTrainTestQuestions);
            }
        }
        return arrayList ;
    }

    /**
     * 获取试卷
     * @param id
     * @param userId
     * @return
     */
    private ReturnTrainPaper getTestPaperDetail(String id, String userId) {
        ReturnTrainPaper returnTrainPaper = new ReturnTrainPaper();
        if (StringHelper.isNotEmpty(id)) {
            // 获取考试计划
            TTrainMyManagement management = tTrainMyManagementService.getById(id);
            String testPaperId = management.getTestPaperId();
            if (StringHelper.isNotEmpty(testPaperId)) {
                TTrainPaper trainPaper = tTrainPaperService.getById(testPaperId);
                String[] testQuestionsId = trainPaper.getTestQuestionsId().split(",");
                List<TTrainTestQuestions> questions = tTrainTestQuestionsService.list(new QueryWrapper<TTrainTestQuestions>()
                        .in(TTrainTestQuestions.ID, testQuestionsId)
                        .ne(TTrainTestQuestions.STATUS, BizConstants.STATUS_DELETE)
                );
                List<TestQuestionsContent> allTest = getAllTest(questions, id,userId);
                // 获取答题正确和错误的数量
                AtomicInteger trueNum = new AtomicInteger();
                AtomicInteger falseNum = new AtomicInteger();
                allTest.stream().forEach(item->{
                    if ("1".equals(item.getIsCorrect()) && "1".equals(item.getIsSelect())) {
                        trueNum.getAndIncrement();
                    }
                    if("0".equals(item.getIsCorrect()) && "1".equals(item.getIsSelect())){
                        falseNum.getAndIncrement();
                    }
                });
                returnTrainPaper.setTrueNum(String.valueOf(trueNum));
                returnTrainPaper.setFalseNum(String.valueOf(falseNum));
                returnTrainPaper.setPassScore(trainPaper.getPassScore());
                returnTrainPaper.setFullScore(trainPaper.getFullScore());
                returnTrainPaper.setTestPaperName(trainPaper.getTestPaperName());
                returnTrainPaper.setTestScore(management.getTestScore());
                returnTrainPaper.setTestQuestionsContent(allTest);
            }
        }
        return returnTrainPaper;
    }

    /**
     * 返回题库或试卷中试题的详细信息
     *
     * @param records 试题的集合
     * @return
     * @Param myid 个人中心主键id
     */

    private List<TestQuestionsContent> getAllTest(List<TTrainTestQuestions> records, String myid, String userId) {
        // 试卷中的所有试题
        List<TestQuestionsContent> testQuestionsContents = new ArrayList<>();
//        int num = 0;
        for (TTrainTestQuestions tTrainTestQuestions : records) {
            String testQuestionsType = tTrainTestQuestions.getTestQuestionsType();
            //试题id
            String questionsId = tTrainTestQuestions.getId();
//            num++;
            if ("SELECT".equals(testQuestionsType) || "MORE_SELECT".equals(testQuestionsType)) {
                // 每一个题目
                TestQuestionsContent testQuestionsContent = BeanHelper.beanToBean(tTrainTestQuestions, TestQuestionsContent.class);
                QueryWrapper<TTrainExamChoice> wrapper = new QueryWrapper<>();
                wrapper.eq(TTrainExamChoice.TEST_QUESTIONS_ID, questionsId);
                // 当前题目包含的所有选项
                List<TTrainExamChoice> list1 = tTrainExamChoiceService.list(wrapper);
                // 按照选项排序
                list1 = list1.stream().sorted(Comparator.comparing(TTrainExamChoice::getOptions))
                        .collect(Collectors.toList());
                List<Options> optionsList = new ArrayList<>();
                for (TTrainExamChoice tTrainExamChoice : list1) {
                    Options options = BeanHelper.beanToBean(tTrainExamChoice, Options.class);
                    String optionsTest = options.getOptions() + ": " + options.getOptionText();
                    options.setOptionText(optionsTest);
                    optionsList.add(options);
                }
                String testQuestionsContent1 =testQuestionsContent.getTestQuestionsContent();
                testQuestionsContent.setTestQuestionsContent(testQuestionsContent1);
                testQuestionsContent.setOptions(optionsList);
                String score = "";
                TTrainMyManagement management = tTrainMyManagementService.getById(myid);
                String testPaperId = management.getTestPaperId();
                if (StringHelper.isNotEmpty(testPaperId)) {
                    TTrainPaper trainPaper = tTrainPaperService.getById(testPaperId);
                    if ("SELECT".equals(testQuestionsType)) {
                        score = "(单选题、" + trainPaper.getSingleScore() + "分)";
                    }
                    if ("MORE_SELECT".equals(testQuestionsType)) {
                        score = "(多选题、" + trainPaper.getMoreScore() + "分)";
                    }
                }
                testQuestionsContent.setScore(score);
                testQuestionsContent.setDictKey(testQuestionsType);
                testQuestionsContents.add(testQuestionsContent);
            }
            if ("JUDGE".equals(testQuestionsType)) {
                // 每一个题目
                TestQuestionsContent testQuestionsContent = BeanHelper.beanToBean(tTrainTestQuestions, TestQuestionsContent.class);
                QueryWrapper<TTrainExamJudgment> wrapper = new QueryWrapper<>();
                wrapper.eq(TTrainExamJudgment.TEST_QUESTIONS_ID, questionsId);
                // 当前题目包含的所有选项
                List<TTrainExamJudgment> list1 = tTrainExamJudgmentService.list(wrapper);
                // 按照选项排序
                list1 = list1.stream().sorted(Comparator.comparing(TTrainExamJudgment::getOptions))
                        .collect(Collectors.toList());
                List<Options> optionsList = new ArrayList<>();
                for (TTrainExamJudgment tTrainExamChoice : list1) {
                    Options options = BeanHelper.beanToBean(tTrainExamChoice, Options.class);
                    String optionsTest = options.getOptions() + ": " + options.getOptionText();
                    options.setOptionText(optionsTest);
                    optionsList.add(options);
                }
                String testQuestionsContent1 =  testQuestionsContent.getTestQuestionsContent();
                testQuestionsContent.setTestQuestionsContent(testQuestionsContent1);
                testQuestionsContent.setOptions(optionsList);
                String score = "";
                TTrainMyManagement management = tTrainMyManagementService.getById(myid);
                String testPaperId = management.getTestPaperId();
                if (StringHelper.isNotEmpty(testPaperId)) {
                    TTrainPaper trainPaper = tTrainPaperService.getById(testPaperId);
                    if ("JUDGE".equals(testQuestionsType)) {
                        score = "(判断题、" + trainPaper.getJudgeScore() + "分)";
                    }
                }
                testQuestionsContent.setScore(score);
                testQuestionsContent.setDictKey(testQuestionsType);
                testQuestionsContents.add(testQuestionsContent);
            }
        }
//        UserInfo loginUser = ContextUtils.getLoginUser();
        //得到已经做过的题目
        List<TTrainTestQuestionsExercise> list = tTrainTestQuestionsExerciseService.list(new QueryWrapper<TTrainTestQuestionsExercise>()
                .eq(TTrainTestQuestionsExercise.MY_ID, myid)
                .eq(TTrainTestQuestionsExercise.PERSON_ID, userId)
        );
        for (TestQuestionsContent test : testQuestionsContents) {
            for (TTrainTestQuestionsExercise tTrain : list) {
                if (test.getId().equals(tTrain.getTestQuestionsId())) {
                    test.setIsSelect("1");
                    test.setIsCorrect(tTrain.getIsCorrect());
                    if (StringHelper.isNotEmpty(tTrain.getOptionsId())) {
                        String[] split = tTrain.getOptionsId().split(",");
                        for (Options option : test.getOptions()) {
                            for (String s : split) {
                                if (option.getId().equals(s)) {
                                    option.setIsSelect("1");
                                }
                            }
                        }
                    }
                }
            }
        }
        List<TestQuestionsContent> collect = testQuestionsContents.stream().
                sorted(Comparator.comparing(TestQuestionsContent::getDictKey).reversed()).collect(Collectors.toList());
        AtomicInteger num = new AtomicInteger(1);
        collect.stream().forEach(item->{
            item.setTestQuestionsContent(num.getAndIncrement() +"."+item.getTestQuestionsContent());
        });
        return collect;
    }

    @Override
    public List<TTrainExaminationManageParam> getExamProjectPerson(String s) {
        return tTrainExaminationManageDao.getExamProjectPerson(s);
    }

    @Override
    public List<TTrainExaminationManageParam> getRepairExaminationManage(String id) {
        return baseMapper.getRepairExaminationManage(id);
    }
}
