package com.ruoyi.hezhi.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.hezhi.domain.*;
import com.ruoyi.hezhi.domain.vo.TopicImportTemplateVO;
import com.ruoyi.hezhi.mapper.*;
import com.ruoyi.hezhi.service.ITbExamSubjectService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.init.ResourceReader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 考试题目Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-04
 */
@Service
public class TbExamSubjectServiceImpl implements ITbExamSubjectService {
    @Autowired
    private TbExamSubjectMapper tbExamSubjectMapper;
    @Autowired
    private TbExamSubjectAnswerMapper examSubjectAnswerMapper;
    @Autowired
    private TbExamCourseMapper tbExamCourseMapper;
    @Resource
    private TbSubjectWarehouseClassMapper tbSubjectWarehouseClassMapper;
    @Resource
    private TbExamMapper tbExamMapper;
    @Resource
    private SqlSessionFactory sqlSessionFactory;
    @Resource
    private TbExamSubjectFormalMapper tbExamSubjectFormalMapper;
    @Resource
    private TbMemberSubjectAllMapper tbMemberSubjectAllMapper;

    /**
     * 查询考试题目
     *
     * @param examSubjectId 考试题目主键
     * @return 考试题目
     */
    @Override
    public TbExamSubject selectTbExamSubjectByExamSubjectId(Long examSubjectId) {
        return tbExamSubjectMapper.selectTbExamSubjectByExamSubjectId(examSubjectId);
    }

    /**
     * 查询考试题目列表
     *
     * @param tbExamSubject 考试题目
     * @return 考试题目
     */
    @Override
    public List<TbExamSubject> selectTbExamSubjectList(TbExamSubject tbExamSubject) {
        return tbExamSubjectMapper.selectTbExamSubjectList(tbExamSubject);
    }

    /**
     * 新增考试题目
     *
     * @param tbExamSubject 考试题目
     * @return 结果
     */
    @Override
    public int insertTbExamSubject(TbExamSubject tbExamSubject) {
        tbExamSubject.setCreateTime(DateUtils.getNowDate());
        List<TbExamSubjectAnswer> examSubjectAnswerList = tbExamSubject.getExamSubjectAnswerList();
        if (CollectionUtils.isNotEmpty(examSubjectAnswerList)) {
            if (Constants.ONE.equals(tbExamSubject.getSubjectType())) {
                String answer = examSubjectAnswerList.stream().filter(item -> Constants.ONE.equals(item.getIsAnswer())).map(TbExamSubjectAnswer::getSubjectOption).collect(Collectors.joining(","));
                tbExamSubject.setAnswer(answer);
            } else if (Constants.TWO.equals(tbExamSubject.getSubjectType())) {
                String answer = examSubjectAnswerList.stream().filter(item -> Constants.ONE.equals(item.getIsAnswer())).map(TbExamSubjectAnswer::getSubjectOption).collect(Collectors.joining(","));
                tbExamSubject.setAnswer(answer);
            } else if (Constants.FOUR.equals(tbExamSubject.getSubjectType())) {
                String answer = examSubjectAnswerList.stream().map(TbExamSubjectAnswer::getSubjectName).collect(Collectors.joining(","));
                tbExamSubject.setAnswer(answer);
            }
        }
        return tbExamSubjectMapper.insertTbExamSubject(tbExamSubject);
    }

    /**
     * 修改考试题目
     *
     * @param tbExamSubject 考试题目
     * @return 结果
     */
    @Override
    public int updateTbExamSubject(TbExamSubject tbExamSubject) {
        tbExamSubject.setUpdateTime(DateUtils.getNowDate());
        List<TbExamSubjectAnswer> examSubjectAnswerList = tbExamSubject.getExamSubjectAnswerList();
        if (CollectionUtils.isNotEmpty(examSubjectAnswerList)) {
            if (Constants.ONE.equals(tbExamSubject.getSubjectType())) {
                String answer = examSubjectAnswerList.stream().filter(item -> Constants.ONE.equals(item.getIsAnswer())).map(TbExamSubjectAnswer::getSubjectOption).collect(Collectors.joining(","));
                tbExamSubject.setAnswer(answer);
            } else if (Constants.TWO.equals(tbExamSubject.getSubjectType())) {
                String answer = examSubjectAnswerList.stream().filter(item -> Constants.ONE.equals(item.getIsAnswer())).map(TbExamSubjectAnswer::getSubjectOption).collect(Collectors.joining(","));
                tbExamSubject.setAnswer(answer);
            } else if (Constants.FOUR.equals(tbExamSubject.getSubjectType())) {
                String answer = examSubjectAnswerList.stream().map(TbExamSubjectAnswer::getSubjectName).collect(Collectors.joining(","));
                tbExamSubject.setAnswer(answer);
            }
        }
        return tbExamSubjectMapper.updateTbExamSubject(tbExamSubject);
    }

    /**
     * 批量删除考试题目
     *
     * @param examSubjectIds 需要删除的考试题目主键
     * @return 结果
     */
    @Override
    public int deleteTbExamSubjectByExamSubjectIds(Long[] examSubjectIds) {
        //查看该题目是否绑定考试，如果有则不能删除
        StringBuilder stringBuilder = new StringBuilder("考试题目编号为：");//这全部只是考虑了正式考试，模拟考试没有考虑
        boolean flag = true;
        for (Long examSubjectId : examSubjectIds) {
            TbExamSubjectFormal params = new TbExamSubjectFormal();
            params.setExamSubjectId(examSubjectId);//根据考试题目编号查询 正式考试题目对象
            List<TbExamSubjectFormal> tbExamSubjectFormals = tbExamSubjectFormalMapper.selectTbExamSubjectFormalList(params);
            if (ObjectUtils.isNotEmpty(tbExamSubjectFormals)) {
                stringBuilder.append(examSubjectId).append(",");
                flag  = false;
            }
        }
        if (!flag){
            throw new ServiceException(stringBuilder +"已绑定考试，不能删除");
        }
        return tbExamSubjectMapper.deleteTbExamSubjectByExamSubjectIds(examSubjectIds);
    }

    /**
     * 删除考试题目信息
     *
     * @param examSubjectId 考试题目主键
     * @return 结果
     */
    @Override
    public int deleteTbExamSubjectByExamSubjectId(Long examSubjectId) {
        return tbExamSubjectMapper.deleteTbExamSubjectByExamSubjectId(examSubjectId);
    }

    /**
     * 查询所有题目
     *
     * @param params 参数
     * @return 结果
     */
    @Override
    public List<Map<String, Object>> queryByParam(Map<String, Object> params) {
//        Long courseId = MapUtils.getLong(params, "courseId");
//        TbExamCourse examCourseDetail = tbExamCourseMapper.getSubjectWarehouseClassIdByCourseId(courseId);
//        if (ObjectUtils.isEmpty(examCourseDetail)) {
//            throw new ServiceException("此课程未添加题库");
//        }
//        params.put("subjectWarehouseClassId", examCourseDetail.getSubjectWarehouseClassId());
        return tbExamSubjectMapper.queryByParam(params);
    }

    /**
     * 题目详情
     *
     * @param params 参数
     * @return 结果
     */
    @Override
    public Map<String, Object> getExamSubjectInfo(Map<String, Object> params) {
        Map<String, Object> examSubjectInfo = tbExamSubjectMapper.getExamSubjectInfo(params);
        if (examSubjectInfo != null) {
            // 题目类型（1-单选，2-多选，3-判断，4-论述）
            int subjectType = MapUtils.getInteger(examSubjectInfo, "subjectType");
            //练习类型
            String practiceType = MapUtils.getString(params, "practiceType");
            String examSubjectNo = examSubjectInfo.get("examSubjectNo").toString();
            if (subjectType != 4) {
                // 选项列表
                List<Map<String, Object>> subjectSelectList = examSubjectAnswerMapper.selectSelectList(null, examSubjectNo);
                examSubjectInfo.put("subjectSelectList", subjectSelectList);
            } else {
                examSubjectInfo.put("subjectSelectList", null);
            }
            String memberUserId = MapUtils.getString(params, "memberUserId");
            params.clear();
            params.put("examSubjectId", examSubjectInfo.get("examSubjectId").toString());
            params.put("memberUserId", memberUserId);
            params.put("practiceType", practiceType);
            //查看我的答案
            examSubjectInfo.put("myAnswer", tbMemberSubjectAllMapper.queryMemberSubjectAllByParam(params));
            // 查询答案列表
            examSubjectInfo.put("subjectAnswerList", examSubjectAnswerMapper.selectAnswerList(null, examSubjectNo));
        }

        return examSubjectInfo;
    }

    /**
     * 专项练习（考试标题）
     *
     * @return 结果
     */
    @Override
    public List<Map<String, Object>> getSpecialPracticeList(Map<String, Object> params) {
        Long courseId = MapUtils.getLong(params, "courseId");
        TbExamCourse examCourseDetail = tbExamCourseMapper.getSubjectWarehouseClassIdByCourseId(courseId);
        if (ObjectUtils.isEmpty(examCourseDetail)) {
            throw new ServiceException("管理员未上传该题库信息");
        }
        params.put("subjectWarehouseClassId", examCourseDetail.getSubjectWarehouseClassId());
        return tbExamSubjectMapper.getSpecialPracticeList(params);
    }

    /**
     * 查询练习题数量
     *
     * @return 结果
     */
    @Override
    public List<Map<String, Object>> getPracticeListCount(Map<String, Object> params) {
        Long courseId = MapUtils.getLong(params, "courseId");
        TbExamCourse examCourseDetail = tbExamCourseMapper.getSubjectWarehouseClassIdByCourseId(courseId);
        if (ObjectUtils.isEmpty(examCourseDetail)) {
            throw new ServiceException("管理员未上传该题库信息");
        }
        params.put("subjectWarehouseClassId", examCourseDetail.getSubjectWarehouseClassId());
        return tbExamSubjectMapper.getPracticeListCount(params);
    }

    /**
     * 章节练习（考试标题）
     *
     * @return 结果
     */
    @Override
    public List<Map<String, Object>> getMajorPracticeList() {
        return tbExamSubjectMapper.getMajorPracticeList();
    }

    /**
     * 筛选条件下单选、多选、判断、论述题目数
     *
     * @param params 参数
     * @return 结果
     */
    @Override
    public Map<String, Object> getExamSubjectNum(Map<String, Object> params) {
        return tbExamSubjectMapper.getExamSubjectNum(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<TopicImportTemplateVO> list, String username) {
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("导入数据不能为空");
        }
        Map<String, List<TbSubjectWarehouseClass>> subjectWarehouseClassMap = new HashMap<>();
        Map<String, List<TbExam>> examClassMap = new HashMap<>();
        //获取考试集合
        List<TbSubjectWarehouseClass> allSubjectWarehouseCalssList = tbSubjectWarehouseClassMapper.getAllSubjectWarehouseCalssList();
        if (!CollectionUtils.isEmpty(allSubjectWarehouseCalssList)) {
            subjectWarehouseClassMap = allSubjectWarehouseCalssList.stream().collect(Collectors.groupingBy(TbSubjectWarehouseClass::getName));
        }
        //获取考试列表
        TbExam tbExam = new TbExam();
        tbExam.setDelFlag(Constants.ZERO);
        List<TbExam> tbExams = tbExamMapper.selectTbExamList(tbExam);
        if (!CollectionUtils.isEmpty(tbExams)) {
            examClassMap = tbExams.stream().collect(Collectors.groupingBy(TbExam::getName));
        }
        for (int i = 0; i < list.size(); i++) {
            TopicImportTemplateVO topicImportTemplateVO = list.get(i);
            int rowNum = 2 + i;
            if (ObjectUtils.isEmpty(topicImportTemplateVO.getExamType())) {
                throw new ServiceException("第" + rowNum + "行的考试类型为空");
            }
            if (ObjectUtils.isEmpty(topicImportTemplateVO.getAnswer())) {
                throw new ServiceException("第" + rowNum + "行的答案为空");
            }
            if (ObjectUtils.isEmpty(topicImportTemplateVO.getLevel())) {
                throw new ServiceException("第" + rowNum + "行的等级为空");
            }
            if (ObjectUtils.isEmpty(topicImportTemplateVO.getScore())) {
                throw new ServiceException("第" + rowNum + "行的分数为空");
            }
            if (ObjectUtils.isEmpty(topicImportTemplateVO.getQuestion())) {
                throw new ServiceException("第" + rowNum + "行的题目为空");
            }
            if (ObjectUtils.isEmpty(topicImportTemplateVO.getSubjectType())) {
                throw new ServiceException("第" + rowNum + "行的题目类型为空");
            }
            TbExamSubject tbExamSubject = new TbExamSubject();
            tbExamSubject.setExamSubjectNo(IdUtils.fastSimpleUUID());
            if ("3".equals(topicImportTemplateVO.getExamType())) {
                tbExamSubject.setExamType("0,1");
                if (ObjectUtils.isEmpty(topicImportTemplateVO.getExamName())) {
                    throw new ServiceException("第" + rowNum + "行的考试为空");
                }
                if (ObjectUtils.isEmpty(topicImportTemplateVO.getSubjectWarehouseClassName())) {
                    throw new ServiceException("第" + rowNum + "行的模拟考试为空");
                }
                if (!CollectionUtils.isEmpty(examClassMap.get(topicImportTemplateVO.getExamName()))) {
                    tbExamSubject.setExamId(examClassMap.get(topicImportTemplateVO.getExamName()).get(0).getExamId());
                }
                if (!CollectionUtils.isEmpty(subjectWarehouseClassMap.get(topicImportTemplateVO.getSubjectWarehouseClassName()))) {
                    tbExamSubject.setSubjectWarehouseClassId(subjectWarehouseClassMap.get(topicImportTemplateVO.getSubjectWarehouseClassName()).get(0).getSubjectWarehouseClassId());
                }
            } else if ("0".equals(topicImportTemplateVO.getExamType())) {
                if (ObjectUtils.isEmpty(topicImportTemplateVO.getExamName())) {
                    throw new ServiceException("第" + rowNum + "行的考试为空");
                }
                if (!CollectionUtils.isEmpty(examClassMap.get(topicImportTemplateVO.getExamName()))) {
                    tbExamSubject.setExamId(examClassMap.get(topicImportTemplateVO.getExamName()).get(0).getExamId());
                }
                tbExamSubject.setExamType(topicImportTemplateVO.getExamType());
            } else if ("1".equals(topicImportTemplateVO.getExamType())) {
                if (ObjectUtils.isEmpty(topicImportTemplateVO.getSubjectWarehouseClassName())) {
                    throw new ServiceException("第" + rowNum + "行的模拟考试为空");
                }
                tbExamSubject.setExamType(topicImportTemplateVO.getExamType());

                if (!CollectionUtils.isEmpty(subjectWarehouseClassMap.get(topicImportTemplateVO.getSubjectWarehouseClassName()))) {
                    tbExamSubject.setSubjectWarehouseClassId(subjectWarehouseClassMap.get(topicImportTemplateVO.getSubjectWarehouseClassName()).get(0).getSubjectWarehouseClassId());
                }
            }

            tbExamSubject.setQuestion(topicImportTemplateVO.getQuestion());
            tbExamSubject.setSubjectType(topicImportTemplateVO.getSubjectType());
            tbExamSubject.setIsSelected(Constants.ZERO);
            tbExamSubject.setAnswer(topicImportTemplateVO.getAnswer());
            tbExamSubject.setSubjectExplain(topicImportTemplateVO.getSubjectExplain());
            tbExamSubject.setScore(topicImportTemplateVO.getScore());
            tbExamSubject.setLevel(topicImportTemplateVO.getLevel());
            tbExamSubject.setType(Constants.ZERO);
            tbExamSubject.setExamineStatus(Constants.ONE);
            tbExamSubject.setStatus(Constants.ZERO);
            tbExamSubject.setDelFlag(Constants.ZERO);
            tbExamSubject.setCreateBy(username);
            tbExamSubject.setCreateTime(new Date());
            tbExamSubjectMapper.insertTbExamSubject(tbExamSubject);

            //处理选项
            List<TbExamSubjectAnswer> answerList = handleOption(tbExamSubject.getExamSubjectNo(), tbExamSubject.getExamSubjectId(), topicImportTemplateVO, username);

            if (!CollectionUtils.isEmpty(answerList)) {
                try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
                    TbExamSubjectAnswerMapper mapper = sqlSession.getMapper(TbExamSubjectAnswerMapper.class);
                    answerList.forEach(mapper::insertTbExamSubjectAnswer);
                    sqlSession.commit();
                    sqlSession.clearCache();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ServiceException("数据批量更新失败");
                }
            }

        }
        return "导入成功";
    }

    @Override
    public void importTemplate(HttpServletResponse response) throws IOException {
        InputStream inputStream = ResourceReader.class.getClassLoader().getResourceAsStream("testPaperImport/考试试卷导入模板.xlsx");
        XSSFWorkbook workbook = this.write(inputStream);

        // 将Excel写入到输出流
        try (OutputStream out = response.getOutputStream()) {
            workbook.write(out);
            // 设置响应头
            response.setHeader("Content-Disposition", "attachment; filename=" + "考试试卷导入模板.xlsx");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
    }

    /**
     * 设置下拉选数据
     * @param inputStream
     * @return
     * @throws IOException
     */
    public XSSFWorkbook write(InputStream inputStream) throws IOException {
        // 使用 XSSFWorkbook 来处理 .xlsx 文件
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);  // 获取第一个工作表
        //获取考试集合
        String[] allSubjectWarehouseClass = new String[] { "" };
        String[] exams = new String[] { "" };
        List<TbSubjectWarehouseClass> allSubjectWarehouseCalssList = tbSubjectWarehouseClassMapper.getAllSubjectWarehouseCalssList();
        if (!CollectionUtils.isEmpty(allSubjectWarehouseCalssList)) {
            allSubjectWarehouseClass = allSubjectWarehouseCalssList.stream().map(TbSubjectWarehouseClass::getName).toArray(String[]::new);
        }
        //获取考试列表
        TbExam tbExam = new TbExam();
        tbExam.setDelFlag(Constants.ZERO);
        List<TbExam> tbExams = tbExamMapper.selectTbExamList(tbExam);
        if (!CollectionUtils.isEmpty(tbExams)) {
            exams=tbExams.stream().map(TbExam::getName).toArray(String[]::new);
        }

        // 创建数据验证的区域（0-9行，0列）
        CellRangeAddressList regions = new CellRangeAddressList(1, 1048575, 1, 1);
        CellRangeAddressList regions1 = new CellRangeAddressList(1, 1048575, 2, 2);

        // 使用 XSSFDataValidationHelper 创建数据验证约束
        XSSFDataValidationHelper dataValidationHelper = new XSSFDataValidationHelper(sheet);
        DataValidationConstraint constraint = dataValidationHelper.createExplicitListConstraint(allSubjectWarehouseClass);
        DataValidationConstraint constraint1 = dataValidationHelper.createExplicitListConstraint(exams);

        // 使用 helper 创建数据验证对象
        DataValidation dataValidation = dataValidationHelper.createValidation(constraint, regions);
        DataValidation dataValidation1 = dataValidationHelper.createValidation(constraint1, regions1);

        // 将数据验证规则应用到工作表
        sheet.addValidationData(dataValidation);
        sheet.addValidationData(dataValidation1);

        return workbook; // 返回修改后的工作簿
    }

    /**
     * 处理选项
     *
     * @param examSubjectId         题目id
     * @param topicImportTemplateVO 选项
     * @param username              用户名
     * @return 结果
     */
    private List<TbExamSubjectAnswer> handleOption(String examSubjectNo, Long examSubjectId, TopicImportTemplateVO topicImportTemplateVO, String username) {
        Map<String, String> optMap = new HashMap<>();
        String subjectNameA = topicImportTemplateVO.getSubjectNameA();
        String subjectNameB = topicImportTemplateVO.getSubjectNameB();
        String subjectNameC = topicImportTemplateVO.getSubjectNameC();
        String subjectNameD = topicImportTemplateVO.getSubjectNameD();
        String subjectNameE = topicImportTemplateVO.getSubjectNameE();
        String subjectNameF = topicImportTemplateVO.getSubjectNameF();
        String subjectNameG = topicImportTemplateVO.getSubjectNameG();
        if (StringUtils.isNotEmpty(subjectNameA)) {
            optMap.put("A", subjectNameA);
        }
        if (StringUtils.isNotEmpty(subjectNameB)) {
            optMap.put("B", subjectNameB);
        }
        if (StringUtils.isNotEmpty(subjectNameC)) {
            optMap.put("C", subjectNameC);
        }
        if (StringUtils.isNotEmpty(subjectNameD)) {
            optMap.put("D", subjectNameD);
        }
        if (StringUtils.isNotEmpty(subjectNameE)) {
            optMap.put("E", subjectNameE);
        }
        if (StringUtils.isNotEmpty(subjectNameF)) {
            optMap.put("F", subjectNameF);
        }
        if (StringUtils.isNotEmpty(subjectNameG)) {
            optMap.put("G", subjectNameG);
        }
        //答案
        List<TbExamSubjectAnswer> tbExamSubjectAnswers = new ArrayList<>();
        //单选
        if (Constants.ONE.equals(topicImportTemplateVO.getSubjectType())) {
            //校验选项
            if (optMap.size() < 2) {
                throw new ServiceException("单选的选项数量必须大于1");
            }

            for (Map.Entry<String, String> entry : optMap.entrySet()) {
                List<String> answerList = Arrays.asList(topicImportTemplateVO.getAnswer().split(","));
                if (answerList.size() > 1) {
                    throw new ServiceException("单选的答案数量只能是1个");
                }

                //处理选项
                TbExamSubjectAnswer tbExamSubjectAnswer = new TbExamSubjectAnswer();
                tbExamSubjectAnswer.setExamSubjectId(examSubjectId);
                tbExamSubjectAnswer.setExamSubjectNo(examSubjectNo);
                tbExamSubjectAnswer.setSubjectType(topicImportTemplateVO.getSubjectType());
                tbExamSubjectAnswer.setSubjectOption(entry.getKey());
                tbExamSubjectAnswer.setSubjectName(entry.getValue());
                if (answerList.contains(entry.getKey())) {
                    tbExamSubjectAnswer.setIsAnswer(Constants.ONE);
                } else {
                    tbExamSubjectAnswer.setIsAnswer(Constants.ZERO);
                }
                tbExamSubjectAnswer.setScore(topicImportTemplateVO.getScore());
                tbExamSubjectAnswer.setLevel(topicImportTemplateVO.getLevel());
                tbExamSubjectAnswer.setType(Constants.ZERO);
                tbExamSubjectAnswer.setExamineStatus(Constants.ONE);
                tbExamSubjectAnswer.setSort(Constants.ZERO);
                tbExamSubjectAnswer.setStatus(Constants.ZERO);
                tbExamSubjectAnswer.setDelFlag(Constants.ZERO);
                tbExamSubjectAnswer.setCreateBy(username);
                tbExamSubjectAnswer.setCreateTime(new Date());
                tbExamSubjectAnswers.add(tbExamSubjectAnswer);
            }
            //多选
        } else if (Constants.TWO.equals(topicImportTemplateVO.getSubjectType())) {
            if (optMap.size() < 2) {
                throw new ServiceException("多选的选项数量必须大于2");
            }
            for (Map.Entry<String, String> entry : optMap.entrySet()) {
                List<String> answerList = Arrays.asList(topicImportTemplateVO.getAnswer().split(","));
                if (answerList.size() < 2) {
                    throw new ServiceException("多选的答案数量必须大于1");
                }
                //处理选项
                TbExamSubjectAnswer tbExamSubjectAnswer = new TbExamSubjectAnswer();
                tbExamSubjectAnswer.setExamSubjectId(examSubjectId);
                tbExamSubjectAnswer.setExamSubjectNo(examSubjectNo);
                tbExamSubjectAnswer.setSubjectType(topicImportTemplateVO.getSubjectType());
                tbExamSubjectAnswer.setSubjectOption(entry.getKey());
                tbExamSubjectAnswer.setSubjectName(entry.getValue());
                if (answerList.contains(entry.getKey())) {
                    tbExamSubjectAnswer.setIsAnswer(Constants.ONE);
                } else {
                    tbExamSubjectAnswer.setIsAnswer(Constants.ZERO);
                }
                tbExamSubjectAnswer.setScore(topicImportTemplateVO.getScore());
                tbExamSubjectAnswer.setLevel(topicImportTemplateVO.getLevel());
                tbExamSubjectAnswer.setType(Constants.ZERO);
                tbExamSubjectAnswer.setExamineStatus(Constants.ONE);
                tbExamSubjectAnswer.setSort(Constants.ZERO);
                tbExamSubjectAnswer.setStatus(Constants.ZERO);
                tbExamSubjectAnswer.setDelFlag(Constants.ZERO);
                tbExamSubjectAnswer.setCreateBy(username);
                tbExamSubjectAnswer.setCreateTime(new Date());
                tbExamSubjectAnswers.add(tbExamSubjectAnswer);
            }
        } else if (Constants.THREE.equals(topicImportTemplateVO.getSubjectType())) {
            if (!"正确".equals(topicImportTemplateVO.getAnswer()) && !"错误".equals(topicImportTemplateVO.getAnswer())) {
                throw new ServiceException("判断题输入的答案有误，只可输入正确或者错误");
            }
            TbExamSubjectAnswer subjectAnswerA = new TbExamSubjectAnswer();
            subjectAnswerA.setExamSubjectId(examSubjectId);
            subjectAnswerA.setExamSubjectNo(examSubjectNo);
            subjectAnswerA.setSubjectType(topicImportTemplateVO.getSubjectType());
            subjectAnswerA.setSubjectOption("A");
            subjectAnswerA.setSubjectName("正确");
            if ("正确".equals(topicImportTemplateVO.getAnswer())) {
                subjectAnswerA.setIsAnswer(Constants.ONE);
            } else {
                subjectAnswerA.setIsAnswer(Constants.ZERO);
            }
            tbExamSubjectAnswers.add(subjectAnswerA);

            TbExamSubjectAnswer subjectAnswerB = new TbExamSubjectAnswer();
            subjectAnswerB.setExamSubjectId(examSubjectId);
            subjectAnswerB.setExamSubjectNo(examSubjectNo);
            subjectAnswerB.setSubjectType(topicImportTemplateVO.getSubjectType());
            subjectAnswerB.setSubjectOption("B");
            subjectAnswerB.setSubjectName("错误");
            if ("错误".equals(topicImportTemplateVO.getAnswer())) {
                subjectAnswerB.setIsAnswer(Constants.ONE);
            } else {
                subjectAnswerB.setIsAnswer(Constants.ZERO);
            }
            tbExamSubjectAnswers.add(subjectAnswerB);
        } else if (Constants.FOUR.equals(topicImportTemplateVO.getSubjectType())) {
            Map<String, BigDecimal> fractionMap = new HashMap<>();
            BigDecimal fractionA = topicImportTemplateVO.getFractionA();
            BigDecimal fractionB = topicImportTemplateVO.getFractionB();
            BigDecimal fractionC = topicImportTemplateVO.getFractionC();
            BigDecimal fractionD = topicImportTemplateVO.getFractionD();
            BigDecimal fractionE = topicImportTemplateVO.getFractionE();
            BigDecimal fractionF = topicImportTemplateVO.getFractionF();
            BigDecimal fractionG = topicImportTemplateVO.getFractionD();
            if (ObjectUtils.isNotEmpty(fractionA)) {
                fractionMap.put("A", fractionA);
            }
            if (ObjectUtils.isNotEmpty(fractionB)) {
                fractionMap.put("B", fractionB);
            }
            if (ObjectUtils.isNotEmpty(fractionC)) {
                fractionMap.put("C", fractionC);
            }
            if (ObjectUtils.isNotEmpty(fractionD)) {
                fractionMap.put("D", fractionD);
            }
            if (ObjectUtils.isNotEmpty(fractionE)) {
                fractionMap.put("E", fractionE);
            }
            if (ObjectUtils.isNotEmpty(fractionF)) {
                fractionMap.put("F", fractionF);
            }
            if (ObjectUtils.isNotEmpty(fractionG)) {
                fractionMap.put("G", fractionG);
            }
            for (Map.Entry<String, String> entry : optMap.entrySet()) {
                //处理选项
                TbExamSubjectAnswer tbExamSubjectAnswer = new TbExamSubjectAnswer();
                tbExamSubjectAnswer.setExamSubjectId(examSubjectId);
                tbExamSubjectAnswer.setExamSubjectNo(examSubjectNo);
                tbExamSubjectAnswer.setSubjectType(topicImportTemplateVO.getSubjectType());
                tbExamSubjectAnswer.setSubjectName(entry.getValue());
                tbExamSubjectAnswer.setIsAnswer(Constants.ONE);
                BigDecimal fraction = fractionMap.get(entry.getKey());
                if (ObjectUtils.isEmpty(fraction)) {
                    throw new ServiceException("论述题的答案分数不能为空");
                }
                tbExamSubjectAnswer.setScore(fraction);
                tbExamSubjectAnswer.setLevel(topicImportTemplateVO.getLevel());
                tbExamSubjectAnswer.setType(Constants.ZERO);
                tbExamSubjectAnswer.setExamineStatus(Constants.ONE);
                tbExamSubjectAnswer.setSort(Constants.ZERO);
                tbExamSubjectAnswer.setStatus(Constants.ZERO);
                tbExamSubjectAnswer.setDelFlag(Constants.ZERO);
                tbExamSubjectAnswer.setCreateBy(username);
                tbExamSubjectAnswer.setCreateTime(new Date());
                tbExamSubjectAnswers.add(tbExamSubjectAnswer);
            }
        }
        return tbExamSubjectAnswers;
    }
}
