package com.ssj.service.kmt.kmt.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssj.bean.common.framework.core.domain.BaseEntity;
import com.ssj.bean.kmt.kmt.domain.*;
import com.ssj.bean.kmt.kmt.dto.KmtSysUserAuthDto;
import com.ssj.bean.kmt.kmt.model.QuestionListKnowModel;
import com.ssj.bean.kmt.kmt.request.exercise.KmtHandlingQuestionRequest;
import com.ssj.bean.kmt.kmtsys.domain.KmtSysUser;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.zyb.domain.ZuoybKnowHowDetailsSort;
import com.ssj.conch.util.AIServiceUtils;
import com.ssj.dao.kmt.kmt.dao.KmtQualityQuestionsDao;
import com.ssj.es.service.ExerciseQuestionSearchService;
import com.ssj.es.service.base.BaseSearchService;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.exception.CommonException;
import com.ssj.framework.core.util.*;
import com.ssj.service.kmt.dto.ExerciseBookCourseClassDto;
import com.ssj.service.kmt.dto.ExerciseQuetionDto;
import com.ssj.service.kmt.dto.KnowHowDetailsDTO;
import com.ssj.service.kmt.dto.KnowledgeBaseDto;
import com.ssj.service.kmt.dto.exercise.ExerciseQuestionAnswerStyle;
import com.ssj.service.kmt.dto.exercise.ExerciseQuestionAnswerValue;
import com.ssj.service.kmt.dto.exercise.ExerciseQuestionRollbacks;
import com.ssj.service.kmt.request.*;
import com.ssj.service.kmt.service.*;
import com.ssj.service.mapper.KmtExerciseMapper;
import com.ssj.service.mapper.KmtQualityQuestionsMapper;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.zuoyb.service.ZuoybKnowHowDetailsSortService;
import com.ssj.utils.ExerciseUtil;
import com.ssj.weixin.utils.HttpUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

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

@Transactional
@Service(version ="1.0")
public class KmtQualityQuestionsServiceImpl extends BaseServiceImpl<KmtQualityQuestions, String> implements KmtQualityQuestionsService {

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

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ExerciseQuestionSearchService exerciseQuestionSearchService;

    @Autowired
    private KmtQualityQuestionsDao kmtQualityQuestionsDao;

    @Autowired
    private IBookManagerService bookManagerService;

    @Autowired
    private ZuoybKnowHowDetailsSortService zuoybKnowHowDetailsSortService;

    @Autowired
    private KmtExerciseQuestionKnowService kmtExerciseQuestionKnowService;

    @Autowired
    private BaseSearchService baseSearchService;

    @Autowired
    private KmtQualityQuestionsMapper kmtQualityQuestionsMapper;

    @Autowired
    private KmtExerciseQuestionService kmtExerciseQuestionService;

    @Autowired
    private KmtQualityQuestionRollbackService kmtQualityQuestionRollbackService;

    @Autowired
    private KmtQualityQuestionKnowService kmtQualityQuestionKnowService;
    @Autowired
    private KmtQualityQuestionCommentService kmtQualityQuestionCommentService;
    @Autowired
    private KmtExerciseMapper kmtExerciseMapper;
    @Autowired
    private KmtSysUserService kmtSysUserService;


    @Override
    public PagingAndSortingRepository<KmtQualityQuestions, String> getDao() {
        return kmtQualityQuestionsDao;
    }

    @Override
    public Map<String, Object> getKmtHandlingQuestions(KmtHandlingQuestionRequest request, String userId) {
        Page page = new Page(request.getPageNo(), request.getPageSize());
        List<ExerciseQuetionDto> questions;
        Map<String, Object> originQuestions = null;

        //模糊查询加工审核人
        List<String> userIdList = new ArrayList<>();
        if (StringUtil.isNotBlank(request.getName())) {
//            List<KmtSysUser> users = kmtSysUserService.findByName(request.getName().trim());
            List<TbLibManager> users = bookManagerService.findByNameAndType(request.getName().trim(), 17);
            users.forEach(e -> userIdList.add(e.getUserId()));
            if(userIdList.size()==0){
                userIdList.add("noquestion");
            }
        }
        if (StringUtils.isNotBlank(request.getQuestionId())){
            //如果是小题，查询大题id出来
            request.setQuestionId(request.getQuestionId().trim());
            questions = kmtQualityQuestionsMapper.findKmtQuestionsById(request.getQuestionId(), userId, request.getDealType(), page);
        } else if (StringUtils.isNotBlank(request.getDetailId())){
            //存在知识点id的
//            questions = kmtExerciseMapper.findKmtQuestionByDetailId(request.getDetailId(), request.getPointId(), userId, request.getDealType(),userIdList, page);
            originQuestions = this.findKmtQuestionByDetailId(request, userId, userIdList);
            questions = (List<ExerciseQuetionDto>)originQuestions.get("data");
            page.setTotal(Long.parseLong(originQuestions.get("total").toString()));
        } else if (StringUtils.isNotBlank(request.getGrade())){
//            questions = kmtExerciseMapper.findKmtQuestionByGradeSubjectVersionSemester(request.getGrade(),
//                    request.getSubject(), request.getSemester(), request.getVersionType(), userId, request.getDealType(),userIdList, page);
            originQuestions = this.findKmtQuestionByGradeSubjectVersionSemester(request, userId, userIdList);
            questions = (List<ExerciseQuetionDto>)originQuestions.get("data");
            page.setTotal(Long.parseLong(originQuestions.get("total").toString()));
        } else {
            originQuestions = this.findAllKmtQuestions(userIdList, userId, request);
            questions = (List<ExerciseQuetionDto>)originQuestions.get("data");
            page.setTotal(Long.parseLong(originQuestions.get("total").toString()));
//            questions = kmtExerciseMapper.findAllKmtQuestions(userId, request.getDealType(), userIdList, page);
        }
        questions = this.findAndAppendBigQuestion2List(questions);
        Map<String, Object> data  = new HashMap<>();
        data.put("pageNo", page.getCurrent());
        data.put("pageSize", page.getSize());
        data.put("pages", page.getPages());
        data.put("total", page.getTotal());
        data.put("maxCreateTime", request.getMaxCreateTime());
        data.put("list", kmtExerciseQuestionService.getKmtQualityQuestionGroupList(questions));
        return data;
    }

    @Override
    public ResponseEntity submitKmtQuestions2Auditing(AuditingRequest request, String userId) {
        ResponseEntity responseEntity = new ResponseEntity();
        if (CollectionUtils.isEmpty(request.getList())) {
            responseEntity.success(ResponseConstant.CODE_999, "没有选择题目");
        } else {
            int[] types = {17, 18};
            TbLibManager manager = bookManagerService.findTopByUserIdAndTypeIn(userId, types);
            if (manager != null && manager.getType() == 18) {
                request.setType(3);
            }
            for (AuditingBigQuestionRequest bigQuestionRequest : request.getList()) {
                //只有管理员和题目录入老师能录入题目, isNewAdd 并且 （deal_type =3 或者 authority 有7）,则有录入权限
                boolean isNewAdd = isAllQuestionNoId(bigQuestionRequest);
                if (isNewAdd && (request.getType() != 3 && StringUtil.isNotBlank(manager.getAuthority()) && manager.getAuthority().indexOf("7") == -1)) {
                    responseEntity.failure(ResponseConstant.CODE_000, "没有录入权限");
                    return responseEntity;
                }
                if (CollectionUtils.isNotEmpty(bigQuestionRequest.getQuestions())) {
                    //如果有大小题的情况，需要获取第一道题的题目id作为父id和科目
                    String[] conciseIdAndSubject = this.getDetailSortId(bigQuestionRequest);
                    QuestionUpdateRequest questionTmp;
                    if ((isNewAdd && StringUtil.isBlank(conciseIdAndSubject[0])) || (request.getType() == 1 && StringUtil.isBlank(conciseIdAndSubject[0]))) {
                        responseEntity.failure(ResponseConstant.CODE_000, "必须选择知识点");
                        break;
                    }
                    if (bigQuestionRequest.getQuestions().size() == 1) {
                        //如果是单独一道题，不是大小题一起提交的话
                        questionTmp = bigQuestionRequest.getQuestions().get(0);
                        questionTmp.setSubject(StringUtil.isBlank(conciseIdAndSubject[1]) ? questionTmp.getSubject() : conciseIdAndSubject[1]);
                        submitOneQuestion(bigQuestionRequest.getQuestions().get(0), request.getType(), conciseIdAndSubject[0], userId);
                    } else {
                        //大小题
                        questionTmp = bigQuestionRequest.getQuestions().get(0);
                        questionTmp.setSubject(StringUtil.isBlank(conciseIdAndSubject[1]) ? questionTmp.getSubject() : conciseIdAndSubject[1]);
                        KmtQualityQuestions parentQuestion = updateBigQuestion(questionTmp, request.getType(), conciseIdAndSubject[0], userId, isNewAdd);
                        //处理小题的情况
                        for (int i = 1; i < bigQuestionRequest.getQuestions().size(); i++) {
                            questionTmp = bigQuestionRequest.getQuestions().get(i);
                            questionTmp.setSubject(StringUtil.isBlank(conciseIdAndSubject[1]) ? questionTmp.getSubject() : conciseIdAndSubject[1]);
                            this.submitSmallQuestions2Auditing(questionTmp,
                                    conciseIdAndSubject[0], userId, request.getType(), parentQuestion, i, isNewAdd);
                        }
                    }
                    responseEntity.success(ResponseConstant.CODE_999, "提交成功");
                } else {
                    responseEntity.success(ResponseConstant.CODE_999, "成功");
                }
            }
        }
        return responseEntity;
    }

    @Override
    public void save2EsImmediate(KmtQualityQuestions kmtQualityQuestions) {
        try {
            exerciseQuestionSearchService.saveImmediate(JSON.parseObject(JSON.toJSONString(kmtQualityQuestions), new TypeReference<Map<String, Object>>() {
            }));
        } catch (Exception e) {
            redisUtil.lpush(Constant.ES_SAVE_ERROR_QUESTIONS, kmtQualityQuestions.getId());
            logger.error("保存kmt_exercise_questions到ES异常", e);
        }
    }

    @Override
    public boolean saveToEs(KmtQualityQuestions kmtExerciseQuestion) {
        try {
            exerciseQuestionSearchService.save(JSON.parseObject(JSON.toJSONString(kmtExerciseQuestion), new TypeReference<Map<String, Object>>() {}));
            logger.info("保存kmt_exercise_questions到ES：->已完成。");
            return true;
        } catch (Exception e) {
            redisUtil.lpush(Constant.ES_SAVE_ERROR_QUESTIONS, kmtExerciseQuestion.getId());
            logger.error("保存kmt_exercise_questions到ES异常", e);
        }
        return false;
    }

    @Override
    public void deleteKmtQuestion(String questionId, String userId) {
        KmtQualityQuestions kmtQualityQuestions = this.getById(questionId);
        if (kmtQualityQuestions != null){
            kmtQualityQuestions.setDealStatus(6);
            kmtQualityQuestions.setPublishTime(new Date());
            kmtQualityQuestions.setRemark(userId);
            this.save(kmtQualityQuestions);
            this.save2EsImmediate(kmtQualityQuestions);
            //删除题目关联的知识点
            this.deleteQuestionKnowByQuestionId(questionId);
        }
    }

    @Override
    public ResponseEntity findQuestionListByParentId(List<String> parentIds) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<ExerciseQuetionDto> questions = new ArrayList<>();
        List<Map> questionTmps;
        List<ExerciseQuetionDto> exerciseQuetionDtos;
        if (CollectionUtils.isNotEmpty(parentIds)){
            for (String parentId : parentIds){
                questionTmps = exerciseQuestionSearchService.findKmtQuestionsByParentId(parentId);
                exerciseQuetionDtos = this.parseMapToExerciseQuestionList(questionTmps);
                if (CollectionUtils.isNotEmpty(exerciseQuetionDtos)){
                    questions.addAll(exerciseQuetionDtos);
                }
            }
        }
        Map<String, Object> data  = new HashMap<>();
        data.put("list", kmtExerciseQuestionService.getKmtQualityQuestionGroupList(questions));
        responseEntity.success(data, "查询成功");
        return responseEntity;
    }

    @Override
    public ResponseEntity kmtQuestionRollback(String userId, KmtQuestionRollbackRequest request) {
        ResponseEntity responseEntity = new ResponseEntity();
        if (StringUtils.isBlank(request.getReason())){
            responseEntity.failure(ResponseConstant.CODE_000, "请输入打回理由");
            return responseEntity;
        } else if (request.getReason().length() > 100){
            responseEntity.failure(ResponseConstant.CODE_000, "打回理由过长，请精简");
            return responseEntity;
        }
        List<KmtQualityQuestions> kmtExerciseQuestions = kmtQualityQuestionsMapper.findQuestionByParentId(request.getParentIds());
        if (CollectionUtils.isNotEmpty(kmtExerciseQuestions)){
            //批量也是课时的批量
            QuestionRollbackRequest request1 = new QuestionRollbackRequest();
            request1.setDealType(request.getDealType());
            request1.setReason(request.getReason());
            this.updateQuestionRollbackData(request1, userId, kmtExerciseQuestions, true);
            this.updateEsKmtExerciseQuestionKnow(kmtExerciseQuestions);
            responseEntity.success(ResponseConstant.CODE_999, "打回成功");
        } else {
            responseEntity.failure(ResponseConstant.CODE_000, "请选择题目");
        }
        return responseEntity;
    }

    @Override
    public ResponseEntity publishKmtQuestion(KmtQuestionPublishRequest request, String userId) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<KmtQualityQuestions> kmtExerciseQuestions = kmtQualityQuestionsMapper.findQuestionByParentId(request.getParentIds());
        if (CollectionUtils.isNotEmpty(kmtExerciseQuestions)){
            this.updatePublishQuestionData(kmtExerciseQuestions, true);
            this.updateEsKmtExerciseQuestionKnow(kmtExerciseQuestions);
        }
        responseEntity.success(ResponseConstant.CODE_999, "发布成功");
        return responseEntity;
    }


    /**
     * 是否所有题目都没有题目id,没有表示是新录入的题
     *
     * @param bigQuestionRequest
     * @return
     */
    private boolean isAllQuestionNoId(AuditingBigQuestionRequest bigQuestionRequest) {
        boolean result = true;
        if (CollectionUtils.isNotEmpty(bigQuestionRequest.getQuestions())) {
            for (int i = 0; i < bigQuestionRequest.getQuestions().size(); i++) {
                if (StringUtils.isNotBlank(bigQuestionRequest.getQuestions().get(i).getQuestionId())) {
                    return false;
                }
            }
        }
        return result;
    }

    /**
     * 获取题目中的一个知识点的sortId作为整个大小题的conciseId， 可以通过这个id查询题目的年级科目版本上下册
     *
     * @param request
     * @return
     */
    private String[] getDetailSortId(AuditingBigQuestionRequest request) {
        String[] result = new String[2];
        for (QuestionUpdateRequest questionUpdateRequest : request.getQuestions()) {
            if (CollectionUtils.isNotEmpty(questionUpdateRequest.getKnowledges())) {
                result[0] = questionUpdateRequest.getKnowledges().get(0).getId();
                result[1] = StringUtils.isNotEmpty(questionUpdateRequest.getSubject()) ? questionUpdateRequest.getSubject() : this.getDetailSortCourseName(result[0]);
                break;
            }
        }
        return result;
    }

    /**
     * 提交审核的是单独一道题
     */
    private void submitOneQuestion(QuestionUpdateRequest request, int type,
                                   String conciseId, String userId) {
        KmtQualityQuestions question;
        if (StringUtils.isNotEmpty(request.getQuestionId())) {
            question = updateExistQuestion(request, type, conciseId);
            this.deleteQuestionKnowByQuestionId(request.getQuestionId());
        } else {
            question = new KmtQualityQuestions();
            question.setParentId("");
            question.setHandleUserId(userId);
//            录入不分配审核人
//            TbLibManager manager = bookManagerService.findOneManagerBySubject(StringUtils.isNotEmpty(request.getSubject()) ? request.getSubject() : this.getDetailSortCourseName(conciseId));
//            if (manager != null) {
//                question.setAuditingUserId(manager.getUserId());
//            }
            question.setCreateTime(new Date());
            question.setUpdateType(4); //单题的新增就是录入
            question.setConciseBakId(conciseId);
            question = updateCommonQuestion(request, type, conciseId, new Date(), question, true);
        }
        this.updateKmtQuestionKnow(request.getKnowledges(), question);
    }

    /**
     * kmt题目提交更新已存在的题目
     *
     * @param updateRequest
     * @param type
     */
    private KmtQualityQuestions updateExistQuestion(QuestionUpdateRequest updateRequest, int type, String conciseId) {
        KmtQualityQuestions question = null;
        if (StringUtils.isNotEmpty(updateRequest.getQuestionId())) {
            question = this.getById(updateRequest.getQuestionId());
            question = updateCommonQuestion(updateRequest, type, conciseId, new Date(), question, false);
        }
        return question;
    }

    /**
     * 删除旧关联的知识点
     *
     * @param questionId
     */
    private void deleteQuestionKnowByQuestionId(String questionId) {
        List<KmtQualityQuestionKnow> questionKnowsTmp = kmtQualityQuestionsMapper.findQualityQuestionKnowByQuestionId(questionId);
        //先把之前提交的知识点删除
        if (CollectionUtils.isNotEmpty(questionKnowsTmp)) {
            for (KmtQualityQuestionKnow questionKnow : questionKnowsTmp) {
                kmtQualityQuestionKnowService.delete(questionKnow.getId());
            }
            this.deleteEsKmtExerciseQuestionKnow(questionKnowsTmp);
        }
    }

    /**
     * 删除es中的记录
     * @param questionKnows
     */
    private void deleteEsKmtExerciseQuestionKnow (List<KmtQualityQuestionKnow> questionKnows) {
        if (CollectionUtils.isNotEmpty(questionKnows)) {
            //删除es的数据
            List<String> kmtExerciseQuestionKnowIdList = questionKnows.stream().map(KmtQualityQuestionKnow::getId).collect(Collectors.toList());
            baseSearchService.deleteByIdList("kmt_exercise_question_know", kmtExerciseQuestionKnowIdList);
        }
    }

    /**
     * 更新公共内容
     *
     * @param updateRequest
     * @param type
     * @param conciseId
     * @param handleSubmitTime
     * @param question
     * @param isNewAdd         是否是新录入的题目
     * @return
     */
    private KmtQualityQuestions updateCommonQuestion(QuestionUpdateRequest updateRequest, int type, String conciseId,
                                                     Date handleSubmitTime, KmtQualityQuestions question, boolean isNewAdd) {
        question.setCourseName(StringUtils.isNotEmpty(updateRequest.getSubject()) ? updateRequest.getSubject() : this.getDetailSortCourseName(conciseId));
        question.setConciseId(conciseId);
        question.setQuestionText(updateRequest.getQuestionText());
        question.setOptionAnswer(updateRequest.getAnswer());
        question.setAnswerJson(updateRequest.getAnswerJson());
        question.setAnalysis(updateRequest.getQuestionAnalysis());
        question.setAnalysisJson(updateRequest.getAnalysisJson());
        //如果是加工人提交要记录提交时间
        if (type == 0 && (question.getDealStatus() == null || question.getDealStatus() < 2)) {
            question.setHandlerSubmitTime(handleSubmitTime);
        }
        question.setImage(updateRequest.getQuestionImage());
        //发布时把题目图片赋值给question
        if (type == 1 || (type == 3 && isNewAdd)) {
            question.setQuestion("<img src=\"" + PropertiesUtil.getValue("STATIC_FILE_URL") + question.getImage() + "\"/>");
            question.setQuestionJson(JSON.toJSONString(Collections.singletonList(ExerciseUtil.getExerciseQuestionAnswerValue(question.getImage()))));
            question.setPublishTime(new Date());
            question.setDealStatus(4);
        } else if (type == 0) {
            question.setDealStatus(3);
        } else if (question.getDealStatus() == 4 && type == 3){
            question.setQuestion("<img src=\"" + PropertiesUtil.getValue("STATIC_FILE_URL") + question.getImage() + "\"/>");
            question.setQuestionJson(JSON.toJSONString(Collections.singletonList(ExerciseUtil.getExerciseQuestionAnswerValue(question.getImage()))));
        }
        if (CollectionUtils.isNotEmpty(updateRequest.getQuestionTypes())) {
            question.setQuestionType(updateRequest.getQuestionTypes().get(0).getType());
        }

        if (CollectionUtils.isNotEmpty(updateRequest.getDifficultyLevels())) {
            question.setDifficultyLevel(updateRequest.getDifficultyLevels().get(0).getType());
        }

        if (CollectionUtils.isNotEmpty(updateRequest.getRealExamTypes())) {
            List<Integer> types = updateRequest.getRealExamTypes().stream().map(KnowledgeBaseDto::getType).collect(Collectors.toList());
            question.setRealExamType(StringUtils.join(types, ","));
        }

        if (CollectionUtils.isNotEmpty(updateRequest.getTrainingSkills())) {
            List<String> names = updateRequest.getTrainingSkills().stream().map(KnowledgeBaseDto::getName).collect(Collectors.toList());
            question.setTrainingSkill(StringUtils.join(names, ","));
        }

        question.setBeginYear(updateRequest.getBeginYear());
        question.setEndYear(updateRequest.getEndYear());
        question.setQuestionProvince(updateRequest.getQuestionProvince());
        question.setQuestionCity(updateRequest.getQuestionCity());
        question.setQuestionCountry(updateRequest.getQuestionCountry());
        question = this.save(question);
        this.saveKmtQualityQuestionComment(question);
        this.save2EsImmediate(question);
        return question;
    }

    /**
     * 保存题目的开始年份和结束年份
     * @param kmtQualityQuestions
     */
    private void saveKmtQualityQuestionComment (KmtQualityQuestions kmtQualityQuestions){
        KmtQualityQuestionComment comment = kmtQualityQuestionCommentService.findByQuestionId(kmtQualityQuestions.getId());
        if (comment == null){
            //如果年份，地区有一个有就生成记录，否则不生成记录，减少数据量
            if (kmtQualityQuestions.getBeginYear() > 0 || kmtQualityQuestions.getEndYear() > 0 || StringUtil.isNotEmpty(kmtQualityQuestions.getQuestionProvince())){
                comment = new KmtQualityQuestionComment();
                comment.setQuestionId(kmtQualityQuestions.getId());
                comment.setCreateTime(new Date());
                comment.setBeginYear(kmtQualityQuestions.getBeginYear());
                comment.setEndYear(kmtQualityQuestions.getEndYear());
                comment.setQuestionProvince(kmtQualityQuestions.getQuestionProvince());
                comment.setQuestionCity(kmtQualityQuestions.getQuestionCity());
                comment.setQuestionCountry(kmtQualityQuestions.getQuestionCountry());
                kmtQualityQuestionCommentService.save(comment);
            }
        } else {
            comment.setBeginYear(kmtQualityQuestions.getBeginYear());
            comment.setEndYear(kmtQualityQuestions.getEndYear());
            comment.setQuestionProvince(kmtQualityQuestions.getQuestionProvince());
            comment.setQuestionCity(kmtQualityQuestions.getQuestionCity());
            comment.setQuestionCountry(kmtQualityQuestions.getQuestionCountry());
            kmtQualityQuestionCommentService.save(comment);
        }
    }

    /**
     * 获取题目的科目
     * @param id
     * @return
     */
    private String getDetailSortCourseName (String id){
        String courseName = "";
        if (StringUtils.isNotEmpty(id)){
            ZuoybKnowHowDetailsSort sort = zuoybKnowHowDetailsSortService.getById(id);
            if (sort != null){
                courseName = sort.getCourseName();
            }
        }
        return courseName;
    }

    /**
     * 添加题目关联的知识点 kmt_exercise_question_know， zyb_know_how_details_sort
     * @param knowledges
     * @param question
     */
    private void updateKmtQuestionKnow (List<KnowHowDetailsDTO> knowledges, KmtQualityQuestions question){
        //知识点不为空添加知识点
        if (CollectionUtils.isNotEmpty(knowledges)){
            List<KmtQualityQuestionKnow> questionKnows = new ArrayList<>();
            for (KnowHowDetailsDTO detail : knowledges){
                ZuoybKnowHowDetailsSort detailsSort = zuoybKnowHowDetailsSortService.getById(detail.getId());
                if (CollectionUtils.isNotEmpty(detail.getPoints())){
                    //有考点的情况
                    detail.getPoints().forEach(point -> {
                        //添加题目与考点的关联记录
                        KmtQualityQuestionKnow  kmtQualityQuestionKnow = new KmtQualityQuestionKnow();
                        ZuoybKnowHowDetailsSort pointSort = zuoybKnowHowDetailsSortService.getById(point.getId());
                        kmtQualityQuestionKnow.setQuestionId(question.getId());
                        kmtQualityQuestionKnow.setQuestionParentId(question.getParentId());
                        kmtQualityQuestionKnow.setHowDetailsId(detailsSort.getHowDetailsId());
                        kmtQualityQuestionKnow.setHowDetailsKdId(pointSort.getHowDetailsKdId());
                        kmtQualityQuestionKnow.setVersion(detailsSort.getType());
                        kmtQualityQuestionKnow.setLoaded(0);
                        kmtQualityQuestionKnow.setCreateTime(new Date());
                        kmtQualityQuestionKnow.setUpdateTime(new Date());
                        kmtQualityQuestionKnow.setHowDetailSortId(detailsSort.getId());
                        kmtQualityQuestionKnow.setHowDetailKdSortId(pointSort.getId());
                        questionKnows.add(kmtQualityQuestionKnow);

                    });
                } else {
                    //没有考点的情况只记录知识点
                    KmtQualityQuestionKnow  kmtQualityQuestionKnow = new KmtQualityQuestionKnow();
                    kmtQualityQuestionKnow.setQuestionId(question.getId());
                    kmtQualityQuestionKnow.setQuestionParentId(question.getParentId());
                    kmtQualityQuestionKnow.setHowDetailsId(detailsSort.getHowDetailsId());
                    kmtQualityQuestionKnow.setHowDetailSortId(detailsSort.getId());
                    kmtQualityQuestionKnow.setVersion(detailsSort.getType());
                    kmtQualityQuestionKnow.setLoaded(0);
                    kmtQualityQuestionKnow.setCreateTime(new Date());
                    kmtQualityQuestionKnow.setUpdateTime(new Date());
                    questionKnows.add(kmtQualityQuestionKnow);
                }
            }
            kmtQualityQuestionKnowService.save(questionKnows);
            addEsKmtExerciseQuestionKnow(questionKnows, question.getId());
        }
    }

    /**
     * 添加es记录
     * @param questionKnows
     * @param questionId
     */
    private void addEsKmtExerciseQuestionKnow(List<KmtQualityQuestionKnow> questionKnows, String questionId){
        if (CollectionUtils.isNotEmpty(questionKnows)) {
            //添加新数据至es
            try {
                kmtQualityQuestionKnowService.flush();
            } catch (Exception e) {
                logger.warn("kmtQualityQuestionKnowService.flush()异常", e);
            }
            List<Map<String, Object>> dataMapList2Es = kmtQualityQuestionsMapper.findData2EsByQuestionList(Collections.singletonList(questionId));
            if (CollectionUtils.isNotEmpty(dataMapList2Es)) {
                baseSearchService.insertBatch("kmt_exercise_question_know", dataMapList2Es, true);
            }
        }
    }

    /**
     * 更新大标题
     * @param request
     * @return
     */
    private KmtQualityQuestions updateBigQuestion (QuestionUpdateRequest request, int type, String conciseId, String userId, boolean isNewAdd){
        KmtQualityQuestions question;
        if (StringUtils.isNotEmpty(request.getQuestionId())){
            question = this.getById(request.getQuestionId());
            isNewAdd = false;
            this.deleteQuestionKnowByQuestionId(request.getQuestionId());
        } else {
            question = new KmtQualityQuestions();
            question.setHandleUserId(userId);
//            新录入的题目不分配审核人
//            TbLibManager manager = bookManagerService.findOneManagerBySubject(StringUtils.isNotEmpty(request.getSubject()) ? request.getSubject() : this.getDetailSortCourseName(conciseId));
//            if (manager != null){
//                question.setAuditingUserId(manager.getUserId());
//            }
            question.setCreateTime(new Date());
            if (isNewAdd){
                question.setUpdateType(4);
                question.setConciseBakId(conciseId);
            } else {
                question.setUpdateType(3);
                question.setDealStatus(4);
            }
        }
        question.setParentId("");
        question.setQuestionClassType(1);
        question.setNum(0);
        question = updateCommonQuestion(request, type, conciseId, new Date() , question, isNewAdd);
        this.updateKmtQuestionKnow(request.getKnowledges(), question);
        return question;
    }

    /**
     * 单独提交一个题目
     * @param updateRequest
     * @param type
     * @param parentQuestion
     * @param num 排序字段
     * @param isNewAdd 是否是新录入的题
     */
    private KmtQualityQuestions submitSmallQuestions2Auditing (QuestionUpdateRequest updateRequest,
                                                               String conciseId, String userId,
                                                               int type, KmtQualityQuestions parentQuestion, int num,
                                                               boolean isNewAdd){
        KmtQualityQuestions question = null;
        if (StringUtils.isBlank(updateRequest.getQuestionId())){
            question = new KmtQualityQuestions();
            question.setCreateTime(new Date());
            question.setDealStatus(parentQuestion.getDealStatus());
            if (isNewAdd) {
                question.setUpdateType(4);
                question.setConciseBakId(parentQuestion.getConciseBakId());
            } else {
                question.setUpdateType(3);
                question.setDealStatus(parentQuestion.getDealStatus());
            }
            if (StringUtils.isBlank(parentQuestion.getHandleUserId()) && StringUtils.isBlank(parentQuestion.getAuditingUserId())){
                List<Map> list = exerciseQuestionSearchService.findHandleUserIdAndAuditingUserId(parentQuestion.getId());
                if (list != null && list.size() > 0){
                    question.setHandleUserId((String)list.get(0).get("handleUserId"));
                    question.setAuditingUserId((String)list.get(0).get("auditingUserId"));
                } else {
                    question.setHandleUserId(userId);
//                    不随机分配审核人
//                    TbLibManager manager = bookManagerService.findOneManagerBySubject(StringUtils.isNotEmpty(updateRequest.getSubject()) ? updateRequest.getSubject() : this.getDetailSortCourseName(conciseId));
//                    if (manager != null){
//                        question.setAuditingUserId(manager.getUserId());
//                    }
                }
            } else {
                question.setHandleUserId(parentQuestion.getHandleUserId());
                question.setAuditingUserId(parentQuestion.getAuditingUserId());
            }
        } else {
            isNewAdd =false;
            question = this.getById(updateRequest.getQuestionId());
            this.deleteQuestionKnowByQuestionId(updateRequest.getQuestionId());
        }
        question.setParentId(parentQuestion.getId());
        question.setQuestionClassType(2);
        question.setNum(num);
        question.setIsCommonFlag(parentQuestion.getIsCommonFlag());
        question.setConciseBakId(parentQuestion.getConciseBakId());
        question = this.updateCommonQuestion(updateRequest, type, conciseId, parentQuestion.getHandlerSubmitTime(),question, isNewAdd);
        this.updateKmtQuestionKnow(updateRequest.getKnowledges(), question);
        return question;
    }


    /**
     * 根据知识点考点查询kmt题目
     * @param request
     * @param userId
     * @param userIdList
     * @return
     */
    private Map<String, Object> findKmtQuestionByDetailId(KmtHandlingQuestionRequest request, String userId, List<String> userIdList){
        Map<String, String> param = new HashMap<>();
        param.put("dealType", request.getDealType() + "");
        param.put("pageNo", request.getPageNo() + "");
        param.put("pageSize", request.getPageSize() + "");
        param.put("detailId", request.getDetailId());
        param.put("pointId", request.getPointId());
        param.put("beginYear", request.getBeginYear() + "");
        param.put("endYear", request.getEndYear() + "");
        param.put("questionProvince", request.getQuestionProvince());
        param.put("questionCity", request.getQuestionCity());
        param.put("questionCountry", request.getQuestionCountry());
        Map<String, Object> result;
        result = exerciseQuestionSearchService.findKmtQuestionByDetailId(param, userId, userIdList);
        result.put("data", this.parseKnowMapToExerciseQuestionList((List)result.get("data")));
        return result;
    }

    /**
     * es kmt_exercise_question_know 索引的字段转成实体字段
     * @param list
     * @return
     */
    private List<ExerciseQuetionDto> parseKnowMapToExerciseQuestionList (List<Map> list){
        List<ExerciseQuetionDto> result = new ArrayList<>();
        if (list != null){
            for (Map map : list){
                ExerciseQuetionDto temp = new ExerciseQuetionDto();
                temp.setQuestionId(map.getOrDefault("question_id", "").toString());
                temp.setCourseName(map.getOrDefault("course_name", "").toString());
                temp.setHandleUserId(map.getOrDefault("handle_user_id", "").toString());
                temp.setAuditingUserId(map.getOrDefault("auditing_user_id", "").toString());
                temp.setAnalysisUserId(map.getOrDefault("analysis_user_id", "").toString());
                temp.setAnalysisAuditerId(map.getOrDefault("analysis_auditer_id", "").toString());
                temp.setCourseId(map.getOrDefault("book_course_id", "").toString());
                temp.setBigQuestionIndex(map.getOrDefault("bigQuestion_index", "").toString());
                temp.setSmallQuestionIndex(Integer.parseInt(map.getOrDefault("num", "0").toString()) + "");
                temp.setQuestion(map.getOrDefault("question", "").toString());
                temp.setQuestionText(map.getOrDefault("question_text", "").toString());
                temp.setAnswer(map.getOrDefault("option_answer", "").toString());
                temp.setAnswerJson(map.getOrDefault("answer_json", "").toString());
                temp.setQuestionStatus(Integer.parseInt(map.getOrDefault("deal_status", "0").toString()));
//                temp.setCreateTime(map.getOrDefault("create_time", "").toString());
                temp.setReason(map.getOrDefault("remark", "").toString());
                temp.setQuestionAnalysis(map.getOrDefault("analysis", "").toString());
                temp.setAnalysisJson(map.getOrDefault("analysis_json", "").toString());
                temp.setQuestionTypes(Integer.parseInt(map.getOrDefault("question_type", "0").toString()));
                temp.setDifficultyLevels(Integer.parseInt(map.getOrDefault("difficulty_level", "0").toString()));
                temp.setRealExamTypes(map.getOrDefault("real_exam_type", "").toString());
                temp.setTrainingSkills(map.getOrDefault("training_skill", "").toString());
                temp.setParentId(map.getOrDefault("parent_id", "").toString());
                temp.setQuestionImage(map.getOrDefault("image", "").toString());
                temp.setFromUserId(map.getOrDefault("from_user_id", "").toString());
                temp.setToUserId(map.getOrDefault("to_user_id", "").toString());
                temp.setUpdateType(map.getOrDefault("update_type", "").toString());
                temp.setBeginYear((Integer) map.getOrDefault("begin_year", 0));
                temp.setEndYear((Integer)map.getOrDefault("end_year", 0));
                temp.setQuestionProvince(map.getOrDefault("question_province", "").toString());
                temp.setQuestionCity(map.getOrDefault("question_city", "").toString());
                temp.setQuestionCountry(map.getOrDefault("question_country", "").toString());
                result.add(temp);
            }
        }
        return result;
    }

    /**
     * 根据科目年级版本上下册查询kmt题目列表
     * @param request
     * @param userId
     * @param userIdList
     * @return
     */
    private Map<String, Object> findKmtQuestionByGradeSubjectVersionSemester (KmtHandlingQuestionRequest request, String userId, List<String> userIdList){
        Map<String, String> param = new HashMap<>();
        param.put("dealType", request.getDealType() + "");
        param.put("pageNo", request.getPageNo() + "");
        param.put("pageSize", request.getPageSize() + "");
        param.put("courseName", request.getSubject());
        param.put("grade", request.getGrade());
        param.put("semester", request.getSemester() + "");
        param.put("versionType", request.getVersionType() + "");
        param.put("beginYear", request.getBeginYear() + "");
        param.put("endYear", request.getEndYear() + "");
        param.put("questionProvince", request.getQuestionProvince());
        param.put("questionCity", request.getQuestionCity());
        param.put("questionCountry", request.getQuestionCountry());
        Map<String, Object> result;
        result = exerciseQuestionSearchService.findKmtQuestionByGradeSubjectVersionSemester(param, userId, userIdList);
        result.put("data", this.parseKnowMapToExerciseQuestionList((List)result.get("data")));
        return result;
    }

    /**
     * 查询kmt题目列表
     * @param findUserIds
     * @param userId
     * @param request
     * @return
     */
    private Map<String, Object> findAllKmtQuestions(List<String> findUserIds, String userId, KmtHandlingQuestionRequest request){
        Map<String, Object> param = new HashMap<>();
        param.put("findUserIds", findUserIds);
        param.put("userId", userId);
        param.put("dealType", request.getDealType());
        param.put("pageNo", request.getPageNo());
        param.put("pageSize", request.getPageSize());
        param.put("beginYear", request.getBeginYear());
        param.put("endYear", request.getEndYear());
        param.put("questionProvince", request.getQuestionProvince());
        param.put("questionCity", request.getQuestionCity());
        param.put("questionCountry", request.getQuestionCountry());
        Map<String, Object> map = exerciseQuestionSearchService.findAllKmtQuestions(param);
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0L);
        result.put("data", null);
        if (map.size() > 0){
            result.put("total", map.get("total"));
            result.put("data", this.parseMapToExerciseQuestionList((List<Map>)map.get("data")));
        }
        return result;
    }

    /**
     * es字段转成实体字段
     * @param list
     * @return
     */
    public List<ExerciseQuetionDto> parseMapToExerciseQuestionList (List<Map> list){
        List<ExerciseQuetionDto> result = new ArrayList<>();
        if (list != null){
            for (Map map : list){
                ExerciseQuetionDto temp = new ExerciseQuetionDto();
                temp.setQuestionId(map.getOrDefault("id", "").toString());
                temp.setCourseName(map.getOrDefault("courseName", "").toString());
                temp.setHandleUserId(map.getOrDefault("handleUserId", "").toString());
                temp.setAuditingUserId(map.getOrDefault("auditingUserId", "").toString());
                temp.setAnalysisUserId(map.getOrDefault("analysisUserId", "").toString());
                temp.setAnalysisAuditerId(map.getOrDefault("analysisAuditerId", "").toString());
                temp.setCourseId(map.getOrDefault("bookCourseId", "").toString());
                temp.setBigQuestionIndex(map.getOrDefault("bigQuestionIndex", "").toString());
                temp.setSmallQuestionIndex(Integer.parseInt(map.getOrDefault("num", "0").toString()) + "");
                temp.setQuestion(map.getOrDefault("question", "").toString());
                temp.setQuestionText(map.getOrDefault("questionText", "").toString());
                temp.setAnswer(map.getOrDefault("optionAnswer", "").toString());
                temp.setAnswerJson(map.getOrDefault("answerJson", "").toString());
                temp.setQuestionStatus(Integer.parseInt(map.getOrDefault("dealStatus", "").toString()));
                temp.setCreateTime(map.getOrDefault("createTime", "").toString());
                temp.setReason(map.getOrDefault("remark", "").toString());
                temp.setQuestionAnalysis(map.getOrDefault("analysis", "").toString());
                temp.setAnalysisJson(map.getOrDefault("analysisJson", "").toString());
                temp.setQuestionTypes(Integer.parseInt(map.getOrDefault("questionType", "").toString()));
                temp.setDifficultyLevels(Integer.parseInt(map.getOrDefault("difficultyLevel", "").toString()));
                temp.setRealExamTypes(map.getOrDefault("realExamType", "").toString());
                temp.setTrainingSkills(map.getOrDefault("trainingSkill", "").toString());
                temp.setParentId(map.getOrDefault("parentId", "").toString());
                temp.setQuestionImage(map.getOrDefault("image", "").toString());
                temp.setFromUserId(map.getOrDefault("fromUserId", "").toString());
                temp.setToUserId(map.getOrDefault("toUserId", "").toString());
                temp.setUpdateType(map.getOrDefault("updateType", "").toString());
                temp.setBeginYear((Integer)map.getOrDefault("beginYear", 0));
                temp.setEndYear((Integer)map.getOrDefault("endYear", 0));
                temp.setQuestionProvince(map.getOrDefault("questionProvince", "").toString());
                temp.setQuestionCity(map.getOrDefault("questionCity", "").toString());
                temp.setQuestionCountry(map.getOrDefault("questionCountry", "").toString());
                result.add(temp);
            }
        }
        return result;
    }

    /**
     * 遍历列表，添加大题
     * @param questions
     * @return
     */
    private List<ExerciseQuetionDto> findAndAppendBigQuestion2List (List<ExerciseQuetionDto> questions){
        List<ExerciseQuetionDto> result = new ArrayList<>();
        List<String> parentIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(questions)){
            for (ExerciseQuetionDto question : questions){
                if (StringUtils.isNotBlank(question.getParentId()) && !parentIdList.contains(question.getParentId())){
                    ExerciseQuetionDto bigQuestion = kmtQualityQuestionsMapper.findBigQuestionById(question.getParentId());
                    parentIdList.add(question.getParentId());
                    if (bigQuestion != null){
                        result.add(bigQuestion);
                    }
                }
                result.add(question);
            }
        }
        return result;
    }

    /**
     * 更新题目打回的数据
     * @param request
     * @param userId
     * @param kmtExerciseQuestions
     */
    private void updateQuestionRollbackData (QuestionRollbackRequest request, String userId,
                                            List<KmtQualityQuestions> kmtExerciseQuestions,
                                            boolean immediate){
        int dealStatus = 0;
        int dealType = request.getDealType();
        if (dealType == 2){
            dealStatus = 1;
        } else if (dealType == 1){
            dealStatus = 2;
        } else if (dealType == 4) {
            dealStatus = 8;
        } else if (dealType == 5) {
            dealStatus = 10;
        } else {
            dealStatus = 7;
        }
        int fromType = 0;
        TbLibManager manager = bookManagerService.findByUserIdAndType(userId, 18);
        for (KmtQualityQuestions kmtExerciseQuestion : kmtExerciseQuestions) {
            if (manager == null){
                fromType = getFromTypeByDealStatus(kmtExerciseQuestion.getBookId(), kmtExerciseQuestion.getDealStatus());
            }
            kmtExerciseQuestion.setDealStatus(dealStatus);
            kmtExerciseQuestion.setRemark(request.getReason());
            kmtExerciseQuestion.setRepulseTime(new Date());
            this.saveKmtExerciseQuestionRollback(kmtExerciseQuestion, userId, fromType);
            this.save(kmtExerciseQuestion);
            if (immediate){
                this.save2EsImmediate(kmtExerciseQuestion);
            } else {
                this.saveToEs(kmtExerciseQuestion);
            }
        }
//        kmtExerciseQuestionService.save(kmtExerciseQuestions);
//        kmtExerciseQuestionRollbackService.save(exerciseQuestionRollbacks);
    }

    private int getFromTypeByDealStatus (String bookId, int dealStatus){
        int type = 0;
        if (StringUtil.isBlank(bookId)){
            switch (dealStatus){
                case 1: type = 5;break;
                case 3: type = 6; break;
                case 7: type = 6; break;
                default: type = 0; break;
            }
        } else {
            switch (dealStatus){
                case 1: type = 1;break;
                case 2: type = 9; break;
                case 3: type = 2; break;
                case 7: type = 2; break;
                case 5: type = 3; break;
                case 8: type = 3; break;
                case 9: type = 4; break;
                case 10: type = 4; break;
                default: type = 0; break;
            }
        }
        return type;
    }

    /**
     * 生成打回记录, 并往题目记录最新的打回人
     * @param userId
     * @return
     */
    private void saveKmtExerciseQuestionRollback (KmtQualityQuestions kmtExerciseQuestion,  String userId, int fromType){
        KmtQualityQuestionRollback kmtQualityQuestionRollback = new KmtQualityQuestionRollback();
        kmtQualityQuestionRollback.setQuestionId(kmtExerciseQuestion.getId());
        kmtQualityQuestionRollback.setReason(kmtExerciseQuestion.getRemark());
        kmtQualityQuestionRollback.setType(kmtExerciseQuestion.getDealStatus());
        kmtQualityQuestionRollback.setFromUserType(fromType);
        kmtQualityQuestionRollback.setToUserType(getFromTypeByDealStatus(kmtExerciseQuestion.getBookId(), kmtExerciseQuestion.getDealStatus()));
        kmtQualityQuestionRollback.setUserId(userId);
        kmtExerciseQuestion.setFromUserId(userId);
        kmtQualityQuestionRollback.setCreateTime(new Date());
        if (kmtExerciseQuestion.getDealStatus()  == 1){
            kmtQualityQuestionRollback.setToUserId(kmtExerciseQuestion.getHandleUserId());
            kmtExerciseQuestion.setToUserId(kmtExerciseQuestion.getHandleUserId());
        } else if (kmtExerciseQuestion.getDealStatus()  == 7){
            kmtQualityQuestionRollback.setToUserId(kmtExerciseQuestion.getAuditingUserId());
            kmtExerciseQuestion.setToUserId(kmtExerciseQuestion.getAuditingUserId());
        } else if (kmtExerciseQuestion.getDealStatus() == 8){
            kmtQualityQuestionRollback.setToUserId(kmtExerciseQuestion.getAnalysisUserId());
            kmtExerciseQuestion.setToUserId(kmtExerciseQuestion.getAnalysisUserId());
        } else if (kmtExerciseQuestion.getDealStatus() == 10){
            kmtQualityQuestionRollback.setToUserId(kmtExerciseQuestion.getAnalysisAuditerId());
            kmtExerciseQuestion.setToUserId(kmtExerciseQuestion.getAnalysisAuditerId());
        } else if (kmtExerciseQuestion.getDealStatus() == 2){
            kmtExerciseQuestion.setToUserId("1");
        }
        kmtQualityQuestionRollbackService.save(kmtQualityQuestionRollback);
    }

    private void updateEsKmtExerciseQuestionKnow(List<KmtQualityQuestions> questions){
        //添加新数据至es
        List<String> questionId = questions.stream().map(BaseEntity::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(questionId)){
            //添加新数据至es
            try {
                kmtQualityQuestionKnowService.flush();
            } catch (Exception e) {
                logger.warn("kmtQualityQuestionKnowService.flush()异常", e);
            }
            List<Map<String, Object>> dataMapList2Es = kmtQualityQuestionsMapper.findData2EsByQuestionList(questionId);
            if (CollectionUtils.isNotEmpty(dataMapList2Es)) {
                baseSearchService.insertBatch("kmt_exercise_question_know", dataMapList2Es, true);
            }
        }
    }

    public void updatePublishQuestionData (List<KmtQualityQuestions> kmtExerciseQuestions, boolean immediate){
        for (KmtQualityQuestions kmtExerciseQuestion : kmtExerciseQuestions) {
            if (kmtExerciseQuestion == null) {
                logger.warn(String.format("题目不存在（id=%s）", kmtExerciseQuestion.getId()));
                throw new CommonException("题目不存在");
            }
            if (kmtExerciseQuestion.getDealStatus() == 3 || kmtExerciseQuestion.getDealStatus() == 7 || kmtExerciseQuestion.getDealStatus() == 4){
                //kmt的题目发布把题目字段替换成图片
                if (StringUtils.isBlank(kmtExerciseQuestion.getBookId())){
                    if (StringUtil.isBlank(kmtExerciseQuestion.getImage())) {
                        throw new CommonException("请先生成图片再发布");
                    }
                    kmtExerciseQuestion.setQuestion("<img src=\"" + PropertiesUtil.getValue("STATIC_FILE_URL") + kmtExerciseQuestion.getImage() + "\"/>");
                    kmtExerciseQuestion.setQuestionJson(JSON.toJSONString(Collections.singletonList(ExerciseUtil.getExerciseQuestionAnswerValue(kmtExerciseQuestion.getImage()))));
                    kmtExerciseQuestion.setDealStatus(4);
                } else {
                    kmtExerciseQuestion.setDealStatus(5);
                }
                kmtExerciseQuestion.setPublishTime(new Date());
            } else if (kmtExerciseQuestion.getDealStatus() == 0 || kmtExerciseQuestion.getDealStatus() == 1){
                kmtExerciseQuestion.setDealStatus(3);
            } else if ((kmtExerciseQuestion.getDealStatus() == 10 || kmtExerciseQuestion.getDealStatus() == 9)
                    && StringUtils.isNotBlank(kmtExerciseQuestion.getExerciseBookId())){
                kmtExerciseQuestion.setDealStatus(11);
                kmtExerciseQuestion.setAnalysisSubmitTime(new Date());
            } else if (kmtExerciseQuestion.getDealStatus() == 5 || kmtExerciseQuestion.getDealStatus() == 8
                    && StringUtils.isNotBlank(kmtExerciseQuestion.getExerciseBookId())) {
                kmtExerciseQuestion.setDealStatus(9);
            } else {
                logger.warn("题目id={}不是可发布状态，不能发布", kmtExerciseQuestion.getId());
            }
            this.save(kmtExerciseQuestion);
            if (immediate){
                this.save2EsImmediate(kmtExerciseQuestion);
            } else {
                this.saveToEs(kmtExerciseQuestion);
            }
        }
    }

    @Override
    public List<ExerciseQuestionRollbacks> findQuestionRollbackRecord (String questionId){
        List<KmtQualityQuestionRollback> list = kmtQualityQuestionsMapper.findKmtQualityQuestionRollbackListByQuestionId(questionId);
        List<ExerciseQuestionRollbacks> list1=new ArrayList<>();
        List<KmtSysUserAuthDto> authDtos = JSONArray.parseArray(PropertiesUtil.getValue("KMT_SYS_USER_AUTH"), KmtSysUserAuthDto.class);
        list.stream().forEach(a->{
            ExerciseQuestionRollbacks exerciseQuestionRollbacks=new ExerciseQuestionRollbacks();
            String fromUser="";
            String toUser="";
            String fromUserId=a.getUserId();
            TbLibManager tbLibManager= kmtExerciseMapper.findByUserIdAndTypeIn(fromUserId);
            if(null==tbLibManager){
                //来向老用户
                fromUser=this.getOldName(fromUserId,authDtos);
            }else {
                //来向新用户
                fromUser=this.getNewName(tbLibManager,1,a);
            }
            if(null==a.getToUserId()){
                //去向为ai
                toUser="AI";
            }else {
                TbLibManager tbLibManager1=kmtExerciseMapper.findByUserIdAndTypeIn(a.getToUserId());
                if(null==tbLibManager1){
                    //去向老用户
                    toUser=this.getOldName(a.getToUserId(),authDtos);
                }else {
                    //去向新用户
                    toUser=this.getNewName(tbLibManager1,2,a);
                }
            }
            exerciseQuestionRollbacks.setFromUser(fromUser);
            exerciseQuestionRollbacks.setToUser(toUser);
            exerciseQuestionRollbacks.setCreateTime(a.getCreateTime());
            exerciseQuestionRollbacks.setReason(a.getReason());
            exerciseQuestionRollbacks.setId(a.getId());
            list1.add(exerciseQuestionRollbacks);
        });
        Collections.reverse(list1);
        return list1;
    }

    //查询老用户
    private  String getOldName(String userId, List<KmtSysUserAuthDto> authDtos){
        String name="AI";
        //查询老用户
        KmtSysUser user = kmtSysUserService.findKmtSysUserById(userId);
        //老用户里能查到的情况
        if(null!=user){
            if(StringUtils.isNotBlank(user.getType())){
                for(KmtSysUserAuthDto authDto : authDtos){
                    if (user.getType().equals(authDto.getType())){
                        name = "(" + authDto.getName() + ")"+StringUtil.defaultIfEmpty(user.getName(), "");
                    }
                }
            }

        }


        return name;
    }

    //查询新用户
    private String getNewName(TbLibManager tbLibManager,int type,KmtQualityQuestionRollback kmt){
        String name="";
        String prefex="";
        if(1==type){
            prefex=this.getName(kmt.getFromUserType());
        }else {
            prefex=this.getName(kmt.getToUserType());
        }
        name=prefex+StringUtil.defaultIfEmpty(tbLibManager.getName(), "");
        return name;
    }

    private String getName(int type){
        Map<Integer,Object> hashMap=new HashMap<>();
        hashMap.put(0,"管理员");
        hashMap.put(1,"练习册加工员");
        hashMap.put(2,"练习册审核员");
        hashMap.put(3,"练习册解析员");
        hashMap.put(4,"练习册解审员");
        hashMap.put(5,"题库迁移员");
        hashMap.put(6,"题库审核员");
        hashMap.put(7,"题库录入员");
        hashMap.put(9,"AI");
        String typeName=hashMap.get(type).toString();
        return typeName;
    }

}




