package com.ssj.service.conch.opentest;

import com.ssj.bean.conch.conch.dto.OpenTestDto;
import com.ssj.bean.mybatis.KnowledgeMBDto;
import com.ssj.bean.sys.opentest.OpenTestQuestion;
import com.ssj.bean.sys.opentest.OpenTestUnit;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.bean.weixin.zyb.domain.ZuoybKnowHowDetailsSort;
import com.ssj.dao.sys.opentest.OpenTestQuestionDao;
import com.ssj.dao.sys.opentest.OpenTestUnitDao;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybKnowHowDetailsSortDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.service.conch.opentest.dto.Condition1Dto;
import com.ssj.service.conch.opentest.dto.KnowledgeDto;
import com.ssj.service.conch.opentest.request.*;
import com.ssj.service.mapper.RecordQuestionMapper;
import com.ssj.service.sys.opentest.OpenTestQuestionService;
import com.ssj.service.sys.opentest.OpenTestUnitService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.user.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yanghuan
 * @title: RecordQuestionServiceImpl
 * @projectName ssj
 * @description: TODO
 * @date 2020/5/15 10:05
 */
@Service
@Transactional
public class RecordQuestionServiceImpl extends BaseServiceImpl<OpenTestQuestion, String> implements RecordQuestionService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private OpenTestQuestionDao dao;

    @Autowired
    private RecordQuestionMapper recordQuestionMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private IBookManagerService bookManagerService;
    @Autowired
    private OpenTestQuestionService OpenTestQuestionService;

    @Autowired
    private OpenTestUnitService openTestUnitService;

    @Autowired
    private OpenTestQuestionService openTestQuestionService;

    @Autowired
    private OpenTestUnitDao openTestUnitDao;

    @Autowired
    private ZuoybKnowHowDetailsSortDao zuoybKnowHowDetailsSortDao;

    @Override
    public PagingAndSortingRepository<OpenTestQuestion, String> getDao() {
        return dao;
    }
    @Override
    public ResponseEntity addOrEditQuestion(QuestionReuqest req){
        ResponseEntity responseEntity = new ResponseEntity();
        OpenTestQuestion openTestQuestion;
        List<OpenTestQuestion> questionList = openTestQuestionService.findQuestionList(req.getSubject(), req.getGrade(), req.getVersion(), req.getUnit(), 1, req.getType(), req.getSemester());
        if (questionList.size() > 0) {
            return responseEntity.failure("此筛选已有题目发布成功，添加失败");
        }
        if (StringUtils.isNotBlank(req.getQuestionId())) {
            openTestQuestion = OpenTestQuestionService.getById(req.getQuestionId());
            if (null != openTestQuestion) {
                if (!Objects.equals(req.getType(), openTestQuestion.getType())) {
                    return responseEntity.failure("不能更改类型，添加失败");
                }
                 //修改,判断年级，科目，版本是否变化
                 if(Objects.equals(req.getGrade(),openTestQuestion.getGrade())&&Objects.equals(req.getSubject(),openTestQuestion.getSubject())&&
                 Objects.equals(req.getVersion(),openTestQuestion.getVersion())&&Objects.equals(req.getUnit(),openTestQuestion.getUnit())
                         &&Objects.equals(req.getSemester(),openTestQuestion.getSemester())
                 ){
                     //年级科目版本单元都没有任何变化,再判断是大题还是小题
                     //大题
                     if(0==openTestQuestion.getQuestionNum()){
                         //大题变小题
                         if(CollectionUtils.isNotEmpty(req.getOptionList())){
                             //根据sortNo，定位他的题目顺序，后面的题再顺延
                             int sortNo=openTestQuestion.getSortNo();
                             int sort=sortNo+1;
                             OpenTestQuestion question = null;
                             //单元测评
                             if (req.getType() == 2) {
                                 question = dao.findQuestion(req.getSubject(), req.getGrade(), req.getVersion(), req.getUnit(), req.getType(), sort, req.getSemester());
                             } else {
                                 question = dao.findQuestion(req.getSubject(), req.getGrade(), req.getVersion(), req.getType(), sort, req.getSemester());
                             }
                             if(null==question){
                                 openTestQuestion.setQuestionNum(1);
                             }else {
                                 openTestQuestion.setQuestionNum(question.getQuestionNum()-1);
                             }
                             //后面的题号都得顺延，
                             recordQuestionMapper.updateQuestionNum(openTestQuestion, -1);
                             openTestQuestion.setQuestionNum(question.getQuestionNum());
                         }
                         List<String> list=new ArrayList<>();
                         for(QuestionReuqest.Options options:req.getOptionList()){
                             String option=options.getOption();
                             String content=options.getValue();
                             int isAnswer=options.getIsAnswer();
                             String answer=option+"."+content;
                             if(1==isAnswer){
                                 openTestQuestion.setOptionAnswer(option);
                             }
                             list.add(answer);
                         }

                         String  optionContent=list.stream().collect(Collectors.joining("#S"));
                         openTestQuestion.setOptionContent(optionContent);
                         //大题变大题不用管
                     }else {
                         //小题
                         //小题变小题
                         if(CollectionUtils.isNotEmpty(req.getOptionList())){
                             List<String> list=new ArrayList<>();
                             for(QuestionReuqest.Options options:req.getOptionList()){
                                 String option=options.getOption();
                                 String content=options.getValue();
                                 int isAnswer=options.getIsAnswer();
                                 String answer=option+"."+content;
                                 if(1==isAnswer){
                                     openTestQuestion.setOptionAnswer(option);
                                 }
                                 list.add(answer);
                             }

                             String  optionContent=list.stream().collect(Collectors.joining("#S"));
                             openTestQuestion.setOptionContent(optionContent);
                         }else {
                             openTestQuestion.setOptionContent(null);
                             openTestQuestion.setOptionAnswer(null);
                             //后面的题号都得顺延，
                             recordQuestionMapper.updateQuestionNum(openTestQuestion, 1);
                             //小题变大题
                             openTestQuestion.setQuestionNum(0);
                         }

                     }
                     openTestQuestion.setQuestion(req.getQuestion());
                     //改了单元科目等的
                 }else {
                     if(0!=openTestQuestion.getQuestionNum()){
                            //小题改为大小题的
                             recordQuestionMapper.updateQuestionNum(openTestQuestion, 1);
                             this.getOpenTestQuestion(openTestQuestion,req);
                             if(CollectionUtils.isEmpty(req.getOptionList())){
                                 openTestQuestion.setOptionContent(null);
                                 openTestQuestion.setOptionAnswer(null);
                             }
                     }else {
                         //大题改为大小题的
                         this.getOpenTestQuestion(openTestQuestion,req);
                     }
                 }
             }
             openTestQuestion.setModule(req.getModule());
             openTestQuestion.setModuleType(req.getModuleType());
        }else {
            //新增
            openTestQuestion=new OpenTestQuestion();
            this.getOpenTestQuestion(openTestQuestion,req);
        }
        OpenTestQuestionService.save(openTestQuestion);
        return responseEntity.success("成功");
    }

    //题目重新赋值
    private OpenTestQuestion getOpenTestQuestion(OpenTestQuestion openTestQuestion,QuestionReuqest req){
        //查该单元排序最大的编号
        OpenTestQuestion testQuestion = null;
        if (req.getType() == 2) {
            //单元测评
            testQuestion = dao.findQuestion(req.getSubject(), req.getGrade(), req.getVersion(), req.getUnit(), req.getType(), req.getSemester());
        } else {
            testQuestion = dao.findQuestion(req.getSubject(), req.getGrade(), req.getVersion(), req.getType(), req.getSemester());
        }

        if(null==testQuestion){
            openTestQuestion.setSortNo(0);
        }else {
            openTestQuestion.setSortNo(testQuestion.getSortNo()+1);
        }
        openTestQuestion.setQuestion(req.getQuestion());
        //判断插入时题号顺序
        OpenTestQuestion question=null;
        if (req.getType() == 2) {
            question = dao.findQuestionOrderByQuestionNum(req.getSubject(), req.getGrade(), req.getVersion(), req.getUnit(), req.getType(), req.getSemester());
        } else {
            question = dao.findQuestionOrderByQuestionNum(req.getSubject(), req.getGrade(), req.getVersion(), req.getType(), req.getSemester());
        }
        if(CollectionUtils.isNotEmpty(req.getOptionList())){
            if(null==question){
                openTestQuestion.setQuestionNum(1);
            }else {
                openTestQuestion.setQuestionNum(question.getQuestionNum()+1);
            }
            //将选项插入到数据库
            List<String> list=new ArrayList<>();
            for(QuestionReuqest.Options options:req.getOptionList()){
                String option=options.getOption();
                String content=options.getValue();
                int isAnswer=options.getIsAnswer();
                String answer=option+"."+content;
                if(1==isAnswer){
                    openTestQuestion.setOptionAnswer(option);
                }
                list.add(answer);
            }
            String  optionContent=list.stream().collect(Collectors.joining("#S"));
            openTestQuestion.setOptionContent(optionContent);
        }else {
            openTestQuestion.setQuestionNum(0);
        }
        openTestQuestion.setSubject(req.getSubject());
        openTestQuestion.setGrade(req.getGrade());
        openTestQuestion.setVersion(req.getVersion());
        openTestQuestion.setModule(req.getModule());
        openTestQuestion.setModuleType(req.getModuleType());
        openTestQuestion.setUnit(req.getUnit());
        openTestQuestion.setType(req.getType());
        openTestQuestion.setSemester(req.getSemester());
        openTestQuestion.setCreateTime(new Date());
        return openTestQuestion;
    }

    @Override
    public ResponseEntity login(LoginReq req) {
        ResponseEntity responseEntity = new ResponseEntity();

        // 校验账号密码
        User user = userService.getUserByPassword(req.getLoginName(), req.getPassword());
        if (user == null) {
            return responseEntity.failure("账号或密码不正确");
        }

        // 校验录题权限
        TbLibManager libManager = bookManagerService.findByUserIdAndType(user.getId(), 19);
        if (libManager == null) {
            return responseEntity.failure("您还没有录题权限");
        }
        
        String token = tokenManager.getToken(user.getId(), "RECORD_QUESTION");
        if (StringUtil.isBlank(token)) {
            // 生成访问令牌
            token = tokenManager.createToken(null, user.getId(), "RECORD_QUESTION");
        }

        return responseEntity.success(Collections.singletonMap("accessToken", token), "登录成功");
    }

    @Override
    public ResponseEntity deleteQuestion(DeleteReq req) {
        OpenTestQuestion openTestQuestion = this.getById(req.getQuestionId());

        if (openTestQuestion.getUpdateVersion() > -1) {
            // 删除自身
            recordQuestionMapper.deleteQuestion(req.getQuestionId());

            // 题号前移步长
            int step = 1;

            // 最新设计题目之间没有关联性（父子）
//            List<OpenTestQuestion> childQuestionList = recordQuestionMapper.findAllChild(req.getQuestionId());
//            if (CollectionUtils.isNotEmpty(childQuestionList)) {
//                // 删除自己的孩子
//                recordQuestionMapper.deleteChild(req.getQuestionId());
//
//                step = childQuestionList.size();
//                openTestQuestion = childQuestionList.get(0);
//            }

            if (openTestQuestion.getQuestionNum() != null && openTestQuestion.getQuestionNum() > 0) {
                // 更新影响到的题目的题号
                recordQuestionMapper.updateQuestionNum(openTestQuestion, step);
            }

            //失效相关单元
            List<OpenTestUnit> unitList = openTestUnitService.findUnit(openTestQuestion.getGrade(), openTestQuestion.getSubject(), openTestQuestion.getVersion(), openTestQuestion.getUnit(), openTestQuestion.getSemester(), openTestQuestion.getType());
            if (CollectionUtils.isNotEmpty(unitList)) {
                unitList.forEach(e -> {
                    e.setIsValid(0);
                });
                openTestUnitService.save(unitList);
                tokenManager.delString("/api/recordQuestionSys/getConditionInfo/valid");
                //tokenManager.delString("/api/xiaoshuTest/getConditionInfo");
            }
        }

        return new ResponseEntity().success("删除成功");
    }

    @Override
    public ResponseEntity findQuestionList(QuestionUnitRequest req){
        ResponseEntity responseEntity=new ResponseEntity();
        List<OpenTestDto> list=new ArrayList<>();
        Map<String,Object> data=new HashMap<>(16);
        List<OpenTestQuestion> questionList = openTestQuestionService.findQuestionList(req.getSubject(), req.getGrade(), req.getVersion(), req.getUnit(), req.getType(), req.getType1(), req.getSemester());
       if(CollectionUtils.isNotEmpty(questionList)){
           questionList.forEach(a->{
               OpenTestDto dto=new OpenTestDto();
               if(null!=a.getQuestionNum()){
                   dto.setQuestionNo(a.getQuestionNum());
               }
               dto.setQuestionId(a.getId());
               dto.setQuestion(a.getQuestion());
               dto.setModule(a.getModule());
               dto.setAnswer(a.getOptionAnswer());
               dto.setModuleType(a.getModuleType());
               String answerContent=a.getOptionContent();
               List<OpenTestDto.Contents> optionList = new ArrayList<>();
               if (StringUtil.isNotBlank(answerContent)) {
                   String optionAnswer=a.getOptionAnswer();
                   //将选项分离出来
                   String[] options = answerContent.split("#S");
                   String value = "";
                   for (int i = 0; i < options.length; i++) {
                       OpenTestDto.Contents contents = dto.new Contents();
                       String s = options[i];
                       //这里是文字选项
                       switch (i) {
                           case 0:
                               value = s.substring(s.indexOf("A.") + 2);
                               contents.setOption("A");
                               if(Objects.equals(optionAnswer,"A")){
                                   contents.setIsAnswer(1);
                               }else {
                                   contents.setIsAnswer(0);
                               }
                               break;
                           case 1:
                               value = s.substring(s.indexOf("B.") + 2);
                               contents.setOption("B");
                               if(Objects.equals(optionAnswer,"B")){
                                   contents.setIsAnswer(1);
                               }else {
                                   contents.setIsAnswer(0);
                               }
                               break;
                           case 2:
                               value = s.substring(s.indexOf("C.") + 2);
                               contents.setOption("C");
                               if(Objects.equals(optionAnswer,"C")){
                                   contents.setIsAnswer(1);
                               }else {
                                   contents.setIsAnswer(0);
                               }
                               break;
                           case 3:
                               value = s.substring(s.indexOf("D.") + 2);
                               contents.setOption("D");
                               if(Objects.equals(optionAnswer,"D")){
                                   contents.setIsAnswer(1);
                               }else {
                                   contents.setIsAnswer(0);
                               }
                               break;
                           case 4:
                               value = s.substring(s.indexOf("E.") + 2);
                               contents.setOption("E");
                               if(Objects.equals(optionAnswer,"E")){
                                   contents.setIsAnswer(1);
                               }else {
                                   contents.setIsAnswer(0);
                               }
                               break;
                           case 5:
                               value = s.substring(s.indexOf("F.") + 2);
                               contents.setOption("F");
                               if(Objects.equals(optionAnswer,"F")){
                                   contents.setIsAnswer(1);
                               }else {
                                   contents.setIsAnswer(0);
                               }
                               break;
                           case 6:
                               value = s.substring(s.indexOf("G.") + 2);
                               contents.setOption("G");
                               if(Objects.equals(optionAnswer,"G")){
                                   contents.setIsAnswer(1);
                               }else {
                                   contents.setIsAnswer(0);
                               }
                               break;
                           case 7:
                               value = s.substring(s.indexOf("H.") + 2);
                               contents.setOption("H");
                               if(Objects.equals(optionAnswer,"H")){
                                   contents.setIsAnswer(1);
                               }else {
                                   contents.setIsAnswer(0);
                               }
                               break;
                           default:
                               break;
                       }
                       contents.setValue(value);
                       optionList.add(contents);
                   }
                   dto.setOptionList(optionList);
               }
               list.add(dto);
           });
       }
        data.put("list",list);
        responseEntity.success(data,"成功");
        return responseEntity;
    }

    @Override
    public ResponseEntity getConditionInfo(boolean isAll, int platform) {
        ResponseEntity responseEntity = new ResponseEntity();
        Map<String, Object> data;
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (isAll) {
            data = tokenManager.get("/api/recordQuestionSys/getConditionInfo/all", Map.class);
        } else {
            data = tokenManager.get("/api/recordQuestionSys/getConditionInfo/valid", Map.class);
        }
        if (data == null) {
            data = new HashMap<>(16);
        } else {
            return responseEntity.success(data, "成功");
        }
        //测评小程序包含学前的，录题系统不包含
        if (platform == 0) {
            mapList.add(this.getCondition(isAll, 1));
        }
        mapList.add(this.getCondition(isAll, 2));
        mapList.add(this.getCondition(isAll, 3));
        //期中测评筛选
        data.put("list", mapList);
        if (isAll) {
            tokenManager.set("/api/recordQuestionSys/getConditionInfo/all", data);
        } else {
            tokenManager.set("/api/recordQuestionSys/getConditionInfo/valid", data);
        }
        return responseEntity.success(data, "成功");
    }

    /**
     * 获取单元测评的筛选条件
     * @param isAll
     * @return
     */
    private Map<String, Object> getCondition(boolean isAll, int type) {
        List<OpenTestUnit> list = openTestUnitService.findUnit(isAll, type);
        List<Condition1Dto> dtoList = new ArrayList<>();
        Map<String, Condition1Dto> conditionMap = new LinkedHashMap<>(16);
        for (int i = 0; i < list.size(); i++) {
            OpenTestUnit entity = list.get(i);
            String key = entity.getGrade();
            if (i > 0) {
                if (list.get(i).getGrade().equals(list.get(i - 1).getGrade())) {
                    Condition1Dto dto = conditionMap.get(key);
                    conditionMap.put(key, this.getNewCondition(dto, entity, type));
                } else {
                    conditionMap.put(key, this.getNewCondition(entity, type));
                }
            } else {
                conditionMap.put(key, this.getNewCondition(entity, type));
            }
        }
        for (Condition1Dto dto : conditionMap.values()) {
            dtoList.add(dto);
        }
        Map<String, Object> unitMap = new HashMap<>(16);
        String value = "";
        if (type == 1) {
            value = "学前";
        } else if (type == 2) {
            value = "单元";
        } else if (type == 3) {
            value = "期中";
        }
        unitMap.put("type", type);
        unitMap.put("value", value);
        unitMap.put("gradeList", dtoList);
        return unitMap;
    }

    /**
     * 生成一个全新的对象
     * @param entity
     * @return
     */
    private Condition1Dto getNewCondition(OpenTestUnit entity, int type) {
        Condition1Dto dto = new Condition1Dto();
        dto.setGrade(entity.getGrade());
        List<Condition1Dto.Subject> subjectList = new ArrayList<>();
        //年级下设置科目
        Condition1Dto.Subject subjectDto = dto.new Subject();
        subjectDto.setSubject(entity.getSubject());
        //科目下设置类型：只有语文有专题和同步，其余科目都只有同步
        List<Condition1Dto.Subject.Type> typeList = new ArrayList<>();
        if ("语文".equals(entity.getSubject())) {
            Condition1Dto.Subject.Type type1Dto = subjectDto.new Type();
            type1Dto.setType("同步");
            Condition1Dto.Subject.Type type2Dto = subjectDto.new Type();
            type2Dto.setType("专题");
            typeList.add(type1Dto);
            typeList.add(type2Dto);
        } else {
            Condition1Dto.Subject.Type type1Dto = subjectDto.new Type();
            type1Dto.setType("同步");
            typeList.add(type1Dto);
        }
        subjectDto.setTypeList(typeList);
        //科目下设置版本
        List<Condition1Dto.Subject.Version> versionList = new ArrayList<>();
        Condition1Dto.Subject.Version versionDto = subjectDto.new Version();
        versionDto.setVersion(entity.getVersionName());
        //版本下设置学期
        List<Condition1Dto.Subject.Version.Semester> semesterList = new ArrayList<>();
        Condition1Dto.Subject.Version.Semester semesterDto = versionDto.new Semester();
        semesterDto.setSemester(entity.getSemester() == 1 ? "第一学期" : "第二学期");

        List<Condition1Dto.Subject.Version.Semester.Unit> unitList = new ArrayList<>();
        //单元测评
        if (type == 2) {
            //学期下设置单元
            Condition1Dto.Subject.Version.Semester.Unit unitDto = semesterDto.new Unit();
            unitDto.setUnit(entity.getUnit());
            unitList.add(unitDto);
        }

        semesterDto.setUnitList(unitList);
        semesterList.add(semesterDto);

        versionDto.setSemesterList(semesterList);
        versionList.add(versionDto);
        subjectDto.setVersionList(versionList);
        //添加科目实例
        subjectList.add(subjectDto);
        dto.setSubjectList(subjectList);
        return dto;
    }

    /**
     * 在旧对象上添加
     * @param dto
     * @param entity
     * @return
     */
    private Condition1Dto getNewCondition(Condition1Dto dto, OpenTestUnit entity, int type) {
        List<Condition1Dto.Subject> subjectList = dto.getSubjectList();
        boolean addSubject = true;
        boolean addVersion = true;
        boolean addSemester = true;
        Condition1Dto.Subject subjectDto;
        //年级下设置科目,如果科目一样则不再添加新科目
        if (subjectList.get(subjectList.size() - 1).getSubject().equals(entity.getSubject())) {
            subjectDto = subjectList.get(subjectList.size() - 1);
            addSubject = false;
        } else {
            subjectDto = dto.new Subject();
            subjectDto.setVersionList(new ArrayList<>());
            subjectDto.setSubject(entity.getSubject());
        }
        //科目下设置类型：只有语文有专题和同步，其余科目都只有同步
        List<Condition1Dto.Subject.Type> typeList = new ArrayList<>();
        if("语文".equals(entity.getSubject())){
            Condition1Dto.Subject.Type type1Dto = subjectDto.new Type();
            type1Dto.setType("同步");
            Condition1Dto.Subject.Type type2Dto = subjectDto.new Type();
            type2Dto.setType("专题");
            typeList.add(type1Dto);
            typeList.add(type2Dto);
        }else{
            Condition1Dto.Subject.Type type1Dto = subjectDto.new Type();
            type1Dto.setType("同步");
            typeList.add(type1Dto);
        }
        subjectDto.setTypeList(typeList);
        //科目下设置版本
        List<Condition1Dto.Subject.Version> versionList = subjectDto.getVersionList();
        Condition1Dto.Subject.Version versionDto;

        //版本一样则不再添加版本
        if (versionList.size() > 0 && versionList.get(versionList.size() - 1).getVersion().equals(entity.getVersionName())) {
            versionDto = subjectDto.getVersionList().get(versionList.size() - 1);
            addVersion = false;
        } else {
            versionDto = subjectDto.new Version();
            versionDto.setVersion(entity.getVersionName());
            versionDto.setSemesterList(new ArrayList<>());
        }
        //版本下设置学期
        List<Condition1Dto.Subject.Version.Semester> semesterList = versionDto.getSemesterList();
        Condition1Dto.Subject.Version.Semester semesterDto;
        //学期一样则不再添加学期
        if (semesterList.size() > 0 && semesterList.get(semesterList.size() - 1).getSemester().equals(entity.getSemester() == 1 ? "第一学期" : "第二学期")) {
            semesterDto = versionDto.getSemesterList().get(semesterList.size() - 1);
            addSemester = false;
        } else {
            semesterDto = versionDto.new Semester();
            semesterDto.setSemester(entity.getSemester() == 1 ? "第一学期" : "第二学期");
            semesterDto.setUnitList(new ArrayList<>());
        }

        if (type == 2) {
            //版本下设置单元
            List<Condition1Dto.Subject.Version.Semester.Unit> unitList = semesterDto.getUnitList();
            Condition1Dto.Subject.Version.Semester.Unit unitDto = semesterDto.new Unit();
            unitDto.setUnit(entity.getUnit());
            unitList.add(unitDto);
            semesterDto.setUnitList(unitList);
        }

        //无学期则添加新的
        if (addSemester) {
            semesterList.add(semesterDto);
            versionDto.setSemesterList(semesterList);
        }
        //无版本则添加新的
        if (addVersion) {
            versionList.add(versionDto);
            subjectDto.setVersionList(versionList);
        }
        //无科目则填加新的
        if(addSubject){
            subjectList.add(subjectDto);
            dto.setSubjectList(subjectList);
        }
        return dto;
    }

    @Override
    public ResponseEntity getKnowledge(GetKnowledgeReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<KnowledgeDto> dtoList = new ArrayList<>();
        Map<String, Object> data = new HashMap<>(16);
        Map<String, Object> params = new HashMap<>(16);
        List<KnowledgeMBDto> knowledgeDtoList;
        if ("同步".equals(req.getType())) {
            List<OpenTestUnit> list = openTestUnitService.findUnit(req.getGrade(), req.getSubject(), req.getVersion(), req.getUnit(), req.getSemester(), req.getType1());
            if (CollectionUtils.isNotEmpty(list)) {
                List<String> howIds = new ArrayList<>();
                list.forEach(e -> {
                    //非单元测评
                    if (req.getType1() != 2) {
                        if(StringUtil.isNotBlank(e.getHowId())){
                            if (StringUtil.isNotBlank(e.getHowId())) {
                                howIds.addAll(Arrays.asList(e.getHowId().split(",")));
                            }
                        }
                    } else {
                        howIds.add(e.getHowId());
                    }
                });
                params.put("subject", req.getSubject());
                params.put("grade", req.getGrade());
                params.put("semester", req.getUnit().contains("第一学期") ? 1 : 2);
                params.put("version", list.get(0).getVersionType());
                params.put("howIds", howIds);
                knowledgeDtoList = recordQuestionMapper.findKnowledgeList(params);
                knowledgeDtoList.forEach(e -> {
                    KnowledgeDto dto = new KnowledgeDto();
                    dto.setName(e.getName());
                    dto.setKnowledgeList(new ArrayList<>());
                    dtoList.add(dto);
                });
            }
        } else {
            params.put("grade", req.getGrade());
            params.put("semester", req.getUnit().contains("第一学期") ? 1 : 2);
            //专题知识点显示所有
            knowledgeDtoList = recordQuestionMapper.findZtKnowledgeList(params);
            Map<String, KnowledgeDto> knowledgeDtoMap = new LinkedHashMap();
            for (int i = 0; i < knowledgeDtoList.size(); i++) {
                KnowledgeMBDto entity = knowledgeDtoList.get(i);
                String key = entity.getModule();
                if (i > 0) {
                    //去重科目
                    if (entity.getModule().equals(knowledgeDtoList.get(i - 1).getModule())) {
                        KnowledgeDto dto = knowledgeDtoMap.get(key);
                        List<KnowledgeDto.Knowledge> knowledgeList = dto.getKnowledgeList();
                        KnowledgeDto.Knowledge knowledge = dto.new Knowledge();
                        knowledge.setName(entity.getName());
                        knowledgeList.add(knowledge);
                        dto.setKnowledgeList(knowledgeList);
                        knowledgeDtoMap.put(key, dto);
                    } else {
                        KnowledgeDto dto = new KnowledgeDto();
                        dto.setName(entity.getModule());
                        KnowledgeDto.Knowledge knowledge = dto.new Knowledge();
                        knowledge.setName(entity.getName());
                        List<KnowledgeDto.Knowledge> knowledgeList = new ArrayList<>();
                        knowledgeList.add(knowledge);
                        dto.setKnowledgeList(knowledgeList);
                        knowledgeDtoMap.put(key, dto);
                    }
                } else {
                    KnowledgeDto dto = new KnowledgeDto();
                    dto.setName(entity.getModule());
                    KnowledgeDto.Knowledge knowledge = dto.new Knowledge();
                    knowledge.setName(entity.getName());
                    List<KnowledgeDto.Knowledge> knowledgeList = new ArrayList<>();
                    knowledgeList.add(knowledge);
                    dto.setKnowledgeList(knowledgeList);
                    knowledgeDtoMap.put(key, dto);
                }
            }
            for (KnowledgeDto dto : knowledgeDtoMap.values()) {
                dtoList.add(dto);
            }
        }
        data.put("list", dtoList);
        return responseEntity.success(data, "成功");
    }

    @Override
    public ResponseEntity publishQuestion(PublishReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<OpenTestQuestion> questionList = openTestQuestionService.findQuestionList(req.getSubject(), req.getGrade(), req.getVersion(), req.getUnit(), 0, req.getType(), req.getSemester());
        if (CollectionUtils.isNotEmpty(questionList)) {
            questionList.forEach(e -> {
                e.setUpdateVersion(1);
            });
            openTestQuestionService.save(questionList);
        }
        //发布完相应显示对应单元
        List<OpenTestUnit> unitList = openTestUnitService.findUnit(req.getGrade(), req.getSubject(), req.getVersion(), req.getUnit(), req.getSemester(), req.getType(), 0);
        if (CollectionUtils.isNotEmpty(unitList)) {
            unitList.forEach(e -> {
                e.setIsValid(1);
            });
            openTestUnitService.save(unitList);
            tokenManager.delString("/api/recordQuestionSys/getConditionInfo/valid");
            //tokenManager.delString("/api/xiaoshuTest/getConditionInfo");
        }
        return responseEntity.success("发布成功");
    }

    @Override
    public void updateHowId() {
        //单元测评
        List<OpenTestUnit> list = openTestUnitDao.findByHowIdIsNullAndType(2);
        for (OpenTestUnit unit : list) {
            ZuoybKnowHowDetailsSort zuoybKnowHowDetailsSort = zuoybKnowHowDetailsSortDao.findKnowHow(unit.getGrade(), unit.getSubject(), unit.getVersionType(), unit.getSemester(), unit.getKmtUnit());
            if(zuoybKnowHowDetailsSort!=null){
                unit.setHowId(zuoybKnowHowDetailsSort.getHowId());
                openTestUnitService.save(unit);
            }
        }
        //期中测评
        List<OpenTestUnit> list1 = openTestUnitDao.findByHowIdIsNullAndType(3);
        for (OpenTestUnit unit : list1) {
            String[] units = unit.getUnit().split("#S");
            String howIds = "";
            for (String s : units) {
                List<OpenTestUnit> list2 = openTestUnitDao.findUnitRegexp(unit.getGrade(), unit.getSubject(), unit.getVersionName(), s, unit.getSemester(), 2);
                for (OpenTestUnit e : list2) {
                    if (StringUtil.isNotBlank(e.getHowId())) {
                        if (StringUtil.isBlank(howIds)) {
                            howIds = e.getHowId();
                        } else {
                            howIds += "," + e.getHowId();
                        }
                    }
                }
                if (StringUtil.isNotBlank(howIds)) {
                    unit.setHowId(howIds);
                    openTestUnitService.save(unit);
                }
            }
        }
    }

}
