package com.ssj.service.sys.homework.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.ssj.bean.kmt.kmt.domain.KmtExerciseBookCourse;
import com.ssj.bean.kmt.kmt.domain.KmtExerciseQuestion;
import com.ssj.bean.kmt.kmt.domain.KmtHomeworkWrongQuestion;
import com.ssj.bean.sys.feedback.domain.Feedback;
import com.ssj.bean.sys.feedback.domain.SconVoiceFeedbackDetail;
import com.ssj.bean.sys.homework.domain.*;
import com.ssj.bean.sys.wrongbook.domain.HomeworkWrongQuestion;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.zyb.domain.ZuoybStudentPush;
import com.ssj.conch.constant.CourseConstant;
import com.ssj.conch.util.enums.HomeworkWrongQuestionTypeEnum;
import com.ssj.dao.sys.homework.dao.*;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybKnowHowDetailsDao;
import com.ssj.enums.HomeworkWorkTypeEnum;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.persistence.DynamicSpecifications;
import com.ssj.framework.core.persistence.SearchFilter;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.conch.parents.dto.*;
import com.ssj.service.conch.parents.service.ParentService;
import com.ssj.service.conch.parents.v1.dto.*;
import com.ssj.service.conch.schoolmaster.util.Constant;
import com.ssj.service.conch.student.dto.AppCorrectDetailDto;
import com.ssj.service.conch.student.dto.RelateKnowledgeDto;
import com.ssj.service.conch.teacher.dto.HomeworkDTO;
import com.ssj.service.conch.utils.ParseUtil;
import com.ssj.service.kmt.service.KmtExerciseBookCourseService;
import com.ssj.service.kmt.service.KmtExerciseQuestionService;
import com.ssj.service.kmt.service.KmtHomeworkWrongQuestionService;
import com.ssj.service.mapper.HomeworkMapper;
import com.ssj.service.mapper.LibManagerMapper;
import com.ssj.service.mapper.ZybStudentWorkMapper;
import com.ssj.service.sys.feedback.service.FeedbackService;
import com.ssj.service.sys.feedback.service.SconVoiceFeedbackDetailService;
import com.ssj.service.sys.homework.service.HomeworkPictureService;
import com.ssj.service.sys.homework.service.HomeworkPictureVagueRecordService;
import com.ssj.service.sys.homework.service.HomeworkService;
import com.ssj.service.sys.homework.service.NoHomeworkRecordService;
import com.ssj.service.sys.template.CommentTemplateMapperService;
import com.ssj.service.sys.wrongbook.service.WrongBookService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.zuoyb.service.ZuoybStudentPushSerivce;
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.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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


@Service(version="1.0")
@Transactional
public class HomeworkServiceImpl extends BaseServiceImpl<Homework, String> implements HomeworkService {

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

    @Autowired
    private HomeworkDao homeworkDao;

    @Autowired
    private HomeworkPictureQueryDao homeworkPictureQueryDao;
    
    @Autowired
    private HomeworkPictureService  homeworkPictureService;
    
    @Autowired
    private ConchDerverService conchDerverService;

    @Autowired
    private ILibVipService vipService;

    @Autowired
    private HomeworkQueryDao homeworkQueryDao;

    @Autowired
    private ZuoybStudentPushSerivce pushService;

    @Autowired
    private ParentService parentService;

    @Autowired
    private IBookManagerService managerService;
    @Autowired
    private HomeworkPictureDao homeworkPictureDao;
    @Autowired
    private WrongBookService wrongBookService;
    @Autowired
    private HomeworkHowDetailsDao homeworkHowDetailsDao;
    @Autowired
    private ZuoybKnowHowDetailsDao zuoybKnowHowDetailsDao;
    @Autowired
    private KmtHomeworkWrongQuestionService kmtHomeworkWrongQuestionService;
    @Autowired
    private KmtExerciseQuestionService kmtExerciseQuestionService;
    @Autowired
    private KmtExerciseBookCourseService kmtExerciseBookCourseService;
    @Autowired
    private HomeworkPictureVagueRecordService homeworkPictureVagueRecordService;
    @Autowired
    private IBookManagerService bookManagerService;
    @Autowired
    private NoHomeworkRecordService noHomeworkRecordService;
    @Autowired
    private CommentTemplateMapperService commentTemplateMapperService;
    @Autowired
    private ZybStudentWorkMapper zybStudentWorkMapper;
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private LibManagerMapper libManagerMapper;
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private SconVoiceFeedbackDetailService sconVoiceFeedbackDetailService;

    @Override
    public PagingAndSortingRepository<Homework, String> getDao() {
        return homeworkDao;
    }


    @Override
    public Homework finishHomework(String parentId, String derver, Long startTime, Long endTime,
                                   Long usedTime) {
        Homework homework = new Homework();
        homework.setDerver(derver);
        homework.setParentId(parentId);
        homework.setEndTime(new Date(endTime));
        //作业用时 分钟为单位，不足一分钟按照一分钟处理
        homework.setUsedTime(usedTime%60000 == 0 ? usedTime/60000 : (usedTime/60000)+1);
        homework.setStartTime(new Date(startTime));
        homework.setCreateTime(new Date());
        String vipId = conchDerverService.findByDerver(derver).getVipId();
        homework.setVipId(vipId);
        homework.setGrade(vipService.getById(vipId).getGrade());
        logger.info("计时完成");
        homework.setWorkType(1);
        homework.setWorkingType(2);
        this.save(homework);
        return homework;
    }

    @Override
    public Homework findByVipIdAndSubject (String vipId, String subject, Date beginTime){
        String date = DateUtil.format_yyyyMMdd(beginTime);
        return homeworkDao.findByVipIdAndSubject(vipId, subject,
                DateUtil.parse_yyyyMMddHHmmss(date + " 00:00:00"),
                DateUtil.parse_yyyyMMddHHmmss(date + " 23:59:59"));
    }

    @Override
    public Homework beginHomeworkRecord (String vipId, String subject, Date beginTime, int type){
    	//在馆老师开始计时
        LibVip vip = vipService.getById(vipId);
        Homework homework = null;
        if (vip != null){
            homework = homeworkDao.findByTodaySubjectHomework(vipId, subject);
            if (homework == null){
                homework = new Homework();
                homework.setSubject(subject);
                homework.setParentId(vip.getUserId());
                homework.setDerver(vip.getDerver());
                homework.setVipId(vipId);
                homework.setStartTime(beginTime);
                homework.setGrade(vip.getGrade());
                homework.setCreateTime(new Date());
            } else {
                homework.setEndTime(null);
                homework.setCorrectTime(null);
            }
            homework.setHomeworkType(type);
            homework = this.save(homework);
        }
        return homework;
    }

    @Override
    public Homework endHomeworkRecord (String vipId, String subject, Date endTime, int costTime){
        Homework homework = homeworkDao.findByTodaySubjectHomework(vipId, subject);
        if (homework != null){
            //以作业吧时间为准
            homework.setEndTime(endTime);
            homework.setUsedTime((long)costTime);
            homework = this.save(homework);
        }
        return homework;
    }

    @Override
    public Homework correctFinishRecord (String vipId, String subject, Date correctTime){
        String date = DateUtil.format_yyyyMMdd(correctTime);
        Homework homework = homeworkDao.findByVipIdAndSubject(vipId, subject,
                DateUtil.parse_yyyyMMddHHmmss(date + " 00:00:00"),
                DateUtil.parse_yyyyMMddHHmmss(date + " 23:59:59"));
        if (homework != null){
            homework.setCorrectTime(new Date());
            homework = this.save(homework);
        }
        return homework;
    }

    @Override
    public Homework manualModificationEndTime (String vipId, String subject, Date endTime, int costTime) {
        String date = DateUtil.format_yyyyMMdd(endTime);
        Homework homework = homeworkDao.findByVipIdAndSubject(vipId, subject,
                DateUtil.parse_yyyyMMddHHmmss(date + " 00:00:00"),
                DateUtil.parse_yyyyMMddHHmmss(date + " 23:59:59"));
        if (homework == null){
            Long beginTime = endTime.getTime() - costTime * 60 * 1000L;
            this.beginHomeworkRecord(vipId, subject, new Date(beginTime), 1);
        }
        return this.endHomeworkRecord(vipId, subject, endTime, costTime);
    }


	@Override
	public Homework findByTodaySubjectHomework(String vipId, String subject) {
		return homeworkDao.findByTodaySubjectHomework(vipId, subject);
	}

    @Override
    public Homework findDateSubjectHomework(String vipId, String subject, Date dateTime) {
        String formateDate = DateUtil.format_yyyyMMdd(dateTime);
        return homeworkDao.findByVipIdAndSubjectAndRangTime(vipId, subject, formateDate, formateDate + " 23:59:59");
    }

    @Override
    public List<Homework> queryDateHomework(String vipId, Date datetime) {
        String date = DateUtil.format_yyyyMMdd(datetime);
        return homeworkDao.findByVipIdAndCreateTimeBetween(vipId, DateUtil.parse_yyyyMMddHHmmss(date + " 00:00:00"),
                DateUtil.parse_yyyyMMddHHmmss(date + " 23:59:59"));
    }

    @Override
    public Page<Map<String, Object>> findDateByVipIdIncludeToday(String vipId, String maxCreateTime, Pageable pageable){
        return homeworkPictureQueryDao.findDateByVipId(vipId, maxCreateTime, pageable);
    }

    @Override
    public List<Map<String, Object>> findDatesLearningTime(String vipId, String beginTime, String endTime) {
        return homeworkQueryDao.findDatesLearningTime(vipId, beginTime, endTime);
    }

    @Override
    public List<Map<String, Object>> findDatesSubjectAndUsedTime(String vipId, String beginTime, String endTime) {
        return zybStudentWorkMapper.countHomeworkDaysAndUsedTime(vipId, beginTime, endTime);
    }

    @Override
    public Map<String, Object> findHomeworkReport(ZuoybStudentPush push) {
       // logger.info("pushId={}", pushId);
        Map<String, Object> result = new HashMap<>();
    //    ZuoybStudentPush push = pushService.getById(pushId);
        if (push != null){
            if (DateUtil.getCurrentDateString().compareTo(CourseConstant.publishDate) >= 0){
                List<Homework> hwList = this.queryDateHomework(push.getVipId(), push.getPushTime());
                if (StringUtils.isNotEmpty(push.getEvaluate()) && push.getLevel() != null && push.getLevel() > 0){
                    result.put("assessed", true);
                } else {
                    result.put("assessed", false);
                }
                result.put("studentInfo", parentService.getMyChildInfo(push.getVipId()));
                result.put("abstractSituation", this.findCommonHistoryTask(push, hwList));
                result.put("learningState", this.findLearningStatus(push));
                String dateStr = DateUtil.format_yyyyMMdd(push.getPushTime()) + " 00:00:00";
                result.put("correctList", getCorrectDetails(push.getVipId(), DateUtil.parse_yyyyMMddHHmmss(dateStr)));
            } else {
                result = parentService.homeworkReport(push.getVipId(), DateUtil.getCurrentDateString());
            }
        }
        return result;
    }

    private List<CorrectDetailDto> getCorrectDetails(String vipId, Date dateOfBegin) {
        List<CorrectDetailDto> result = new ArrayList<>();
        List<Homework> hwList  = homeworkDao.findByVipIdAndCreateTimeBetween(vipId, dateOfBegin, DateUtil.getDateAfter(dateOfBegin, 1));

        //遍历所有科目，查询对应数据
        for (String subject : CourseConstant.subjectList){
            for (Homework hw : hwList){
                if (subject.equals(hw.getSubject())){
                    //无作业直接过滤
                    if (hw.getWorkType() !=null && hw.getWorkType() == 3){
                        continue;
                    }
                    CorrectDetailDto temp = getCorrectDetailDto(hw);
                    if (temp != null) {
                        result.add(temp);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public AppCorrectDetailDto getAppCorrectDetailDto(String homeworkId){
        Homework hw = this.getById(homeworkId);
        AppCorrectDetailDto result = null;
        if (hw != null){
            List<HomeworkPicture> homeworkPictureList = homeworkPictureDao.queryHomeworkPictureByHomeworkId(hw.getId());

            if (CollectionUtils.isEmpty(homeworkPictureList) && StringUtils.isBlank(hw.getUnFinishedContent())
                    && (hw.getUsedTime() == null || hw.getUsedTime().intValue() == 0)) {
                return null;
            }

            AppCorrectDetailDto temp = new AppCorrectDetailDto();
            String subject = hw.getSubject();
            //科目
            temp.setSubject(subject);

            //作业原图列表
            List<Map<String, Object>> homeworkPictureMapList = new ArrayList<>();
            homeworkPictureList.forEach(homeworkPicture -> {
                HashMap<String, Object> tempMap = new HashMap<>();
                tempMap.put("pictureId", homeworkPicture.getId());
                tempMap.put("url", homeworkPicture.getFileKey());
                int isMark = homeworkPicture.getIsMark();
                tempMap.put("isVague", isMark == 1 || isMark==3 ? isMark : 0);
                homeworkPictureMapList.add(tempMap);
            });
            temp.setHomeworkPictureList(homeworkPictureMapList);

            //错题图片列表
            List<String> homeworkPictureIdList = homeworkPictureList.stream().map(HomeworkPicture::getId).filter(Objects::nonNull).collect(Collectors.toList());
            List<HomeworkWrongQuestion> homeworkWrongQuestionList = wrongBookService.findByHomeworkPictureIdIn(homeworkPictureIdList);
            List<String> wrongQuestionImageList = homeworkWrongQuestionList.stream().map(HomeworkWrongQuestion::getImage).filter(Objects::nonNull).collect(Collectors.toList());
            temp.setWrongItemList(wrongQuestionImageList);

            //错题知识点列表
            List<RelateKnowledgeDto> relateKnowledgeDtoList = new ArrayList<>();
            if (!homeworkWrongQuestionList.isEmpty()) {
                List<String> homeworkWrongQuestionIdList = homeworkWrongQuestionList.stream().map(HomeworkWrongQuestion::getId).filter(Objects::nonNull).collect(Collectors.toList());
                List<HomeworkHowDetail> howDetailsList = homeworkHowDetailsDao.findByWrongQuestionIdIn(homeworkWrongQuestionIdList);
                //把module的null转为""
                howDetailsList.forEach(hd -> {
                    if (StringUtils.isBlank(hd.getModule())) {
                        hd.setModule("");
                    }
                });
                Map<String, List<HomeworkHowDetail>> howDetailsGroupByModule = howDetailsList.stream().collect(Collectors.groupingBy(HomeworkHowDetail::getModule));
                for (Map.Entry<String, List<HomeworkHowDetail>> entry : howDetailsGroupByModule.entrySet()) {
                    RelateKnowledgeDto relateKnowledgeDto = new RelateKnowledgeDto();
                    relateKnowledgeDto.setModule(entry.getKey());
                    List<String> howDetailIdList = entry.getValue().stream().map(HomeworkHowDetail::getHowDetailId).filter(Objects::nonNull).collect(Collectors.toList());
                    List<String> nameList = zuoybKnowHowDetailsDao.findKnowHowDetailsByIds(howDetailIdList);
                    relateKnowledgeDto.setDetails(nameList);

                    relateKnowledgeDtoList.add(relateKnowledgeDto);
                }
            }
            temp.setRelateKnowledgeList(relateKnowledgeDtoList);

            //未完成内容列表
            if (StringUtils.isNotBlank(hw.getUnFinishedContent())) {
                temp.setUnfinishedList(Arrays.asList(hw.getUnFinishedContent().split(",")));
            } else {
                temp.setUnfinishedList(new ArrayList<>());
            }
            result = temp;
        }
        return result;
    }

    @Override
    public CorrectDetailDto getCorrectDetailDto(String homeworkId){
        Homework hw = this.getById(homeworkId);
        CorrectDetailDto result = null;
        if (hw != null){
            result = this.getCorrectDetailDto(hw);
        }
        return result;
    }

    @Override
    public CorrectDetailDto getCorrectDetailDto(Homework hw) {
        if (hw == null){
            return null;
        }

        List<HomeworkPicture> homeworkPictureList = homeworkPictureDao.queryHomeworkPictureByHomeworkId(hw.getId());

        if (CollectionUtils.isEmpty(homeworkPictureList) && StringUtils.isBlank(hw.getUnFinishedContent())
                && (hw.getUsedTime() == null || hw.getUsedTime().intValue() == 0)) {
            return null;
        }

        CorrectDetailDto temp = new CorrectDetailDto();
        String subject = hw.getSubject();
        //科目
        temp.setSubject(subject);

        //作业原图列表
        List<String> homeworkPictureMapList = new ArrayList<>();
        homeworkPictureList.forEach(homeworkPicture -> {
//            HashMap<String, Object> tempMap = new HashMap<>();
//            tempMap.put("pictureId", homeworkPicture.getId());
//            tempMap.put("url", homeworkPicture.getFileKey());
//            Integer isMark = homeworkPicture.getIsMark();
//            tempMap.put("isVague", isMark == null ? 0 : isMark);
            homeworkPictureMapList.add(homeworkPicture.getFileKey());
        });
        temp.setHomeworkList(homeworkPictureMapList);

        //错题图片列表
        List<String> homeworkPictureIdList = homeworkPictureList.stream().map(HomeworkPicture::getId).filter(Objects::nonNull).collect(Collectors.toList());
        List<HomeworkWrongQuestion> homeworkWrongQuestionList = wrongBookService.findByHomeworkPictureIdIn(homeworkPictureIdList);
        List<String> wrongQuestionImageList = homeworkWrongQuestionList.stream().map(HomeworkWrongQuestion::getImage).filter(Objects::nonNull).collect(Collectors.toList());
        temp.setWrongItemList(wrongQuestionImageList);

        //错题知识点列表
        List<RelateKnowledgeDto> relateKnowledgeDtoList = new ArrayList<>();
        if (!homeworkWrongQuestionList.isEmpty()) {
            List<String> homeworkWrongQuestionIdList = homeworkWrongQuestionList.stream().map(HomeworkWrongQuestion::getId).filter(Objects::nonNull).collect(Collectors.toList());
            List<HomeworkHowDetail> howDetailsList = homeworkHowDetailsDao.findByWrongQuestionIdIn(homeworkWrongQuestionIdList);
            //把module的null转为""
            howDetailsList.forEach(hd -> {
                if (StringUtils.isBlank(hd.getModule())) {
                    hd.setModule("");
                }
            });
            Map<String, List<HomeworkHowDetail>> howDetailsGroupByModule = howDetailsList.stream().collect(Collectors.groupingBy(HomeworkHowDetail::getModule));
            for (Map.Entry<String, List<HomeworkHowDetail>> entry : howDetailsGroupByModule.entrySet()) {
                RelateKnowledgeDto relateKnowledgeDto = new RelateKnowledgeDto();
                relateKnowledgeDto.setModule(entry.getKey());
                List<String> howDetailIdList = entry.getValue().stream().map(HomeworkHowDetail::getHowDetailId).filter(Objects::nonNull).collect(Collectors.toList());
                List<String> nameList = zuoybKnowHowDetailsDao.findKnowHowDetailsByIds(howDetailIdList);
                relateKnowledgeDto.setDetails(nameList);

                relateKnowledgeDtoList.add(relateKnowledgeDto);
            }
        }
        temp.setRelateKnowledgeList(relateKnowledgeDtoList);

        //未完成内容列表
        if (StringUtils.isNotBlank(hw.getUnFinishedContent())) {
            temp.setUnfinishedList(Arrays.asList(hw.getUnFinishedContent().split(",")));
        } else {
            temp.setUnfinishedList(new ArrayList<>());
        }
        return temp;
    }

    @Override
    public HistoryTaskDto findCommonHistoryTask(ZuoybStudentPush push, List<Homework> hwList) {
        HistoryTaskDto result = new HistoryTaskDto();
        if (push != null){
            TbLibManager teacher = managerService.findByUserId(push.getTeacherId());
            LibVip vip = vipService.getById(push.getVipId());
            List<NoHomeworkRecord> noHomeworkRecords = noHomeworkRecordService.findDateRecordByVipId(push.getVipId(), push.getPushTime());

            //初始化各科用时
            for (String key : CourseConstant.getSubjectList(vip.getGrade())){
                SubjectTaskDto task = new SubjectTaskDto();
                task.setStatus(1);
                if (noHomeworkRecords != null){
                    for (NoHomeworkRecord noHomeworkRecord : noHomeworkRecords){
                        if (key.equals(noHomeworkRecord.getCourseName())){
                            if (noHomeworkRecord.getType() == 4){
                                task.setStatus(7);
                            } else if (noHomeworkRecord.getType() == 1){
                                task.setStatus(3);
                            } else if (noHomeworkRecord.getType() == 3){
                                task.setStatus(1);
                            } else {
                                task.setStatus(noHomeworkRecord.getType());
                            }
                        }
                    }
                }
                task.setSubject(key);
                task.setCostTime(0);
                result.addSubjectTask(task);
            }

            //查询作业列表塞入各科用时
            if (hwList != null){
                for (Homework hw : hwList){
                    for (SubjectTaskDto std : result.getSubjectTaskList()){
                        if (std.getSubject().equals(hw.getSubject())){
                            std.setHomeworkTime(this.getHomeworkTime(hw));
                            std.setCostTime(hw.getUsedTime() == null ? 0 :hw.getUsedTime().intValue());
                        }
                    }
                }
            }
            //时间，星期， 老师评语等
            result.setDate(DateUtil.format_yyyyMMdd(push.getPushTime()));
            result.setWeek(DateUtil.getWeekDateToStr(push.getPushTime()));
            result.setPushId(push.getId());
            result.setTeacherAdvice(push.getSuggest());
            //新加语音
            Feedback feedback = feedbackService.findByBizId(push.getId());
            if(null!=feedback){
                List<SconVoiceFeedbackDetail> voiceList = sconVoiceFeedbackDetailService.findByFeedbackIdOrderByNumAsc(feedback.getId());
                List<Map<String, String>> voiceListMap = new ArrayList<>();
                if (voiceList != null && voiceList.size() > 0) {
                    for (SconVoiceFeedbackDetail voice : voiceList) {
                        Map<String, String> voiceMap = new HashMap<>();
                        voiceMap.put("voiceKey", voice.getFileKey());
                        voiceMap.put("duration", voice.getDuration());
                        voiceListMap.add(voiceMap);
                    }
                }
                result.setVoiceKeyList(voiceListMap);
            }
            if (teacher != null){
                result.setTeacherName(ParseUtil.getName(teacher.getName(), teacher.getUserId()));
                result.setTeacherImg(ParseUtil.getPhotoPath(teacher.gettPhoto(), teacher.getUserId()));
            }
        }
        return result;
    }


    @Override
    public List<Map<String, String>> findLearningStatus(ZuoybStudentPush push) {
        List<Map<String, String>> result = new ArrayList<>();
        Map<String, String> map;

        if (push != null){
            Integer workingActivity = push.getWorkingActivity();
            if (workingActivity != null) {
                map = new HashMap<>();
                map.put("name", "积极性");
                map.put("type", workingActivity.toString());
                result.add(map);
            }

            Integer workingAutomaticity = push.getWorkingAutomaticity();
            if (workingAutomaticity != null) {
                map = new HashMap<>();
                map.put("name", "自律性");
                map.put("type", workingAutomaticity.toString());
                result.add(map);
            }

            Integer workingConcentration = push.getWorkingConcentration();
            if (workingConcentration != null) {
                map = new HashMap<>();
                map.put("name", "专注度");
                map.put("type", workingConcentration.toString());
                result.add(map);
            }

            Integer workingSpeed = push.getWorkingSpeed();
            if (workingSpeed != null) {
                map = new HashMap<>();
                map.put("name", "作业速度");
                map.put("type", workingSpeed.toString());
                result.add(map);
            }

        }
        return result;
    }

    @Override
    public List<AppCorrectDetailDto> findCorrectDetails(List<Homework> hwList) {
        List<AppCorrectDetailDto> result = new ArrayList<>();
        if (hwList != null) {
            //作业id
            List<String> hwIds = new ArrayList<>();
            for (Homework hw : hwList){
                hwIds.add(hw.getId());
            }

            //作业原图
            List<HomeworkPicture> hpList = homeworkPictureService.findHomeworkPictureByHomeworkIds(hwIds);
        }
        return result;
    }

    @Override
    public Page<Map<String, Object>> findHomeworkPageByVipId(String vipId, String maxCreateTime, Pageable pageable) {
        return homeworkQueryDao.findHomeworkPageByVipId(vipId, maxCreateTime, pageable);
    }

    @Override
    public void deleteNoPictureHomework() {
        homeworkDao.deleteNoPictureHomework();
    }

    @Override
    public Map<String, Object> findHomeworkReport2(String pushId) {
        Map<String, Object> result = new HashMap<>();
        ZuoybStudentPush push = pushService.getById(pushId);
        if (push != null){
            if (DateUtil.getCurrentDateString().compareTo(CourseConstant.publishDate) >= 0){
                List<Homework> hwList = queryDateHomework(push.getVipId(), push.getPushTime());
                if (StringUtils.isNotBlank(push.getEvaluate()) && push.getLevel() != null && push.getLevel() > 0){
                    result.put("assessed", true);
                } else {
                    result.put("assessed", false);
                }
                result.put("studentInfo", parentService.getMyChildInfo(push.getVipId()));
                result.put("abstractSituation", this.findCommonHistoryTask(push, hwList));
                result.put("learningState", this.findLearningStatus(push));
                String dateStr = DateUtil.format_yyyyMMdd(push.getPushTime()) + " 00:00:00";
                result.put("correctList", getCorrectDetails2(push.getVipId(), DateUtil.parse_yyyyMMddHHmmss(dateStr)));
            } else {
                result = parentService.homeworkReport(push.getVipId(), DateUtil.getCurrentDateString());
            }
        }
        return result;
    }

    private List<CorrectDetailDto2> getCorrectDetails2(String vipId, Date beginDate) {
        List<CorrectDetailDto2> result = new ArrayList<>();
        List<Homework> hwList  = homeworkDao.findByVipIdAndCreateTimeBetween(vipId, beginDate, DateUtil.getDateAfter(beginDate, 1));

        //遍历所有科目，查询对应数据
        CourseConstant.subjectList.forEach(subject -> hwList.forEach(homework -> {
            if (homework != null && subject.equals(homework.getSubject())) {
                CorrectDetailDto2 temp = getCorrectDetailDto2(homework);

                if (temp != null) {
                    result.add(temp);
                }
            }
        }));
        return result;
    }

    @Override
    public CorrectDetailDto2 getCorrectDetailDto2(Homework homework) {
        CorrectDetailDto2 temp = null;
        if (homework != null && !Objects.equals(homework.getWorkType(), 3)) {
            List<HomeworkPicture> homeworkPictureList = homeworkPictureDao.queryHomeworkPictureByHomeworkId(homework.getId());

            if (CollectionUtils.isEmpty(homeworkPictureList) && StringUtils.isBlank(homework.getUnFinishedContent())
                    && (homework.getUsedTime() == null || homework.getUsedTime().intValue() == 0)) {
                return null;
            }

            temp = new CorrectDetailDto2();
            temp.setSubject(homework.getSubject());//科目
            temp.setHomeworkId(homework.getId());
            if (CollectionUtils.isNotEmpty(homeworkPictureList)) {
                temp.setCorrectTeacherId(homeworkPictureList.get(0).getTeacherId());
            }
            temp.setCorrectionStatus(this.isCorrected(homework.getId()));

            //作业原图列表
            List<Object> homeworkPictureUrlList = homeworkPictureList.stream().map(HomeworkPicture::getFileKey).filter(StringUtils::isNotBlank).collect(Collectors.toList());
            temp.setHomeworkList(homeworkPictureUrlList);

            //作业原图批注列表
            List<String> homeworkCommentList = homeworkPictureList.stream().map(HomeworkPicture::getCorrectedPictureUrl).filter(StringUtils::isNotBlank).collect(Collectors.toList());
            temp.setHomeworkCommentList(homeworkCommentList);

            //查询错题和未完成的题目
            List<KmtHomeworkWrongQuestion> kmtHomeworkWrongQuestionList = kmtHomeworkWrongQuestionService.findByHomeworkId(homework.getId());
            if (CollectionUtils.isNotEmpty(kmtHomeworkWrongQuestionList)) {
                List<KmtHomeworkWrongQuestion> wrongQuestionList = kmtHomeworkWrongQuestionList.stream().filter(it -> it.getType().equals(HomeworkWrongQuestionTypeEnum.WrongAnswer.getCode())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(wrongQuestionList)) {//有错题
                    Set<String> wrongQuestionIdSet = wrongQuestionList.stream().map(KmtHomeworkWrongQuestion::getQuestionId).filter(Objects::nonNull).collect(Collectors.toSet());
                    temp.setWrongQuestionCount(wrongQuestionIdSet.size());
                    List<Map<String, Object>> wrongQuestionListGroupByBook = new ArrayList<>();
                    List<KmtExerciseQuestion> kmtExerciseQuestionList = kmtExerciseQuestionService.findByIdIn(new ArrayList<>(wrongQuestionIdSet));
                    Map<String, List<KmtExerciseQuestion>> kmtExerciseQuestionMapGroupByBook = kmtExerciseQuestionList.stream().collect(Collectors.groupingBy(KmtExerciseQuestion::getBookId));
                    kmtExerciseQuestionMapGroupByBook.forEach((key, value) -> {
                        List<WrongQuestionTempDTO> wrongQuestionDTOList = new ArrayList<>();
                        Map<String, List<KmtExerciseQuestion>> kmtExerciseQuestionMap = value.stream().collect(Collectors.groupingBy(KmtExerciseQuestion::getBookCourseId));
                        final String[] bookName = {""};
                        kmtExerciseQuestionMap.forEach((key2, value2) -> {
                            value2.sort((o1, o2) -> {
                                Integer num1 = o1.getNum();
                                if (num1 == null) {
                                    return -1;
                                }
                                Integer num2 = o2.getNum();
                                if (num2 == null) {
                                    return 1;
                                }
                                return num1.compareTo(num2);
                            });

                            KmtExerciseBookCourse kmtExerciseBookCourse = kmtExerciseBookCourseService.getById(key2);
                            if (StringUtils.isBlank(bookName[0])) {
                                bookName[0] = kmtExerciseBookCourse.getBookName();
                            }

                            WrongQuestionTempDTO wrongQuestionDTO = new WrongQuestionTempDTO();
                            wrongQuestionDTO.setUnit(kmtExerciseBookCourse.getUnit());
                            wrongQuestionDTO.setPeriod(kmtExerciseBookCourse.getPeriod());
                            List<Map<String, Object>> questionList = new ArrayList<>();
                            value2.forEach(kmtExerciseQuestion -> {
                                Map<String, Object> questionMap = new HashMap<>();
                                questionMap.put("bigQuestionIndex", kmtExerciseQuestion.getBigQuestionIndex());
                                String smallQuestionName = kmtExerciseQuestion.getSmallQuestionName();
                                if (Objects.equals("(0)", smallQuestionName)) {
                                    smallQuestionName = "0";
                                }
                                questionMap.put("smallQuestionIndex", smallQuestionName);
                                Optional<KmtHomeworkWrongQuestion> optional = wrongQuestionList.stream().filter(it -> Objects.equals(it.getQuestionId(), kmtExerciseQuestion.getId())).findFirst();
                                String spaceIndex = "";
                                if (optional.isPresent()) {
                                    KmtHomeworkWrongQuestion kmtHomeworkWrongQuestion = optional.get();
                                    spaceIndex = kmtHomeworkWrongQuestion.getSpaceIndex();
                                }
                                questionMap.put("spaceIndex", spaceIndex == null ? "" : spaceIndex);
                                questionList.add(questionMap);
                            });
                            wrongQuestionDTO.setQuestionList(questionList);
                            wrongQuestionDTOList.add(wrongQuestionDTO);
                        });

                        Map<String, Object> tempMap = new HashMap<>();
                        tempMap.put("bookName", bookName[0]);
                        tempMap.put("bookCourseList", wrongQuestionDTOList);
                        tempMap.put("wrongQuestionNum", value.size());
                        wrongQuestionListGroupByBook.add(tempMap);
                    });

                    temp.setWrongItemList(wrongQuestionListGroupByBook);
                }
            }

            //错题知识点列表
            List<Map<String, Object>> howDetailsMapList = new ArrayList<>(homeworkQueryDao.findDetailsByHomeworkId(homework.getId()));
            if (CollectionUtils.isNotEmpty(howDetailsMapList)) {
                List<RelateKnowledgeDto> relateKnowledgeDtoList = new ArrayList<>();
                howDetailsMapList.forEach(howDetailsMap -> {
                    String module = String.valueOf(howDetailsMap.get("module"));
                    Optional<RelateKnowledgeDto> optional = relateKnowledgeDtoList.stream().filter(it -> Objects.equals(it.getModule(), module)).findFirst();
                    String alias = String.valueOf(howDetailsMap.get("alias"));
                    if (optional.isPresent()) {
                        RelateKnowledgeDto relateKnowledgeDto = optional.get();
                        List<String> details = relateKnowledgeDto.getDetails();
                        if (details.contains(alias)) {
                            return;
                        }
                        details.add(alias);
                    } else {
                        RelateKnowledgeDto relateKnowledgeDto = new RelateKnowledgeDto();
                        relateKnowledgeDto.setModule(module);
                        List<String> tempAliasList = new ArrayList<>();
                        tempAliasList.add(alias);
                        relateKnowledgeDto.setDetails(tempAliasList);
                        relateKnowledgeDtoList.add(relateKnowledgeDto);
                    }
                });
                temp.setRelateKnowledgeList(relateKnowledgeDtoList);
            }

            //未完成内容列表
            if (StringUtils.isNotBlank(homework.getUnFinishedContent())) {
                temp.setUnfinishedList(Arrays.asList(homework.getUnFinishedContent().split(",")));
            } else {
                temp.setUnfinishedList(new ArrayList<>());
            }
        }

        return temp;
    }

    @Override
    @Transactional
    public Integer isCorrected(String homeworkId) {
        List<HomeworkPicture> homeworkPictureList = homeworkPictureService.findAllByHomeworkId(homeworkId);

        //如果存在非模糊的未批改图片，则视为作业未批改
        if (homeworkPictureList.stream().anyMatch(it -> !Objects.equals(1, it.getIsDelete()) &&
                !Objects.equals(1, it.getIsMark()) &&
                !Objects.equals(3, it.getIsMark()) &&
                Objects.equals(0, it.getIsFeedback()))) {
            return 0;
        }

        return 1;
    }

    @Override
    public Page<HomeworkDTO> findByTeacherIdAndType(String teacherId, Integer type, String beginDateTimeStr, String endDateTimeStr, Pageable pageable) {
        //校区批改老师只显示老师和学生同一个馆的作业
        List<String> libIdList = libManagerMapper.findLibIdByUserIdType(teacherId, Constant.SELF_CORRECT_TYPE);
        return homeworkQueryDao.findByTeacherIdAndType(teacherId, type, beginDateTimeStr, endDateTimeStr, pageable, libIdList);
    }

    @Override
    public Map<String, Object> findHomeworkInfoById(String homeworkId) {
        return homeworkQueryDao.findHomeworkInfoById(homeworkId);
    }

    @Override
    public void startCorrectTiming(String homeworkId) {
        /*ZybCorrectTimeRecord correctTimeRecord = correctTimeRecordDao.findByHomeworkId(homeworkId);

        if (correctTimeRecord == null) {
            correctTimeRecord = new ZybCorrectTimeRecord();
            correctTimeRecord.setHomeworkId(homeworkId);
            correctTimeRecord.setStartTime(new Date());
            correctTimeRecordDao.save(correctTimeRecord);
        }*/
    }

    @Override
    public Integer stopCorrectTiming(String homeworkId) {


        /*ZybCorrectTimeRecord correctTimeRecord = correctTimeRecordDao.findByHomeworkId(homeworkId);

        if (correctTimeRecord != null) {
            correctTimeRecord.setEndTime(new Date());
            correctTimeRecordDao.save(correctTimeRecord);

            return (int) ((correctTimeRecord.getEndTime().getTime() - correctTimeRecord.getStartTime().getTime()) / 1000);
        }*/

        return -1;
    }

    @Override
    public Map<String, Object> findHomeworkReport3(String pushId, String parentId) {
        Map<String, Object> result = new HashMap<>();
        ZuoybStudentPush push = pushService.getById(pushId);
        if (push != null){
            if (DateUtil.getCurrentDateString().compareTo(CourseConstant.publishDate) >= 0){
                List<Homework> hwList = queryDateHomework(push.getVipId(), push.getPushTime());
                if (StringUtils.isNotBlank(push.getEvaluate()) && push.getLevel() != null && push.getLevel() > 0){
                    result.put("assessed", true);
                } else {
                    result.put("assessed", false);
                }
                result.put("studentInfo", parentService.getMyChildInfo(push.getVipId()));
                result.put("abstractSituation", this.findCommonHistoryTask(push, hwList));
                result.put("learningState", this.findLearningStatus(push));
                String dateStr = DateUtil.format_yyyyMMdd(push.getPushTime()) + " 00:00:00";
                result.put("correctList", getCorrectDetails3(push.getVipId(), DateUtil.parse_yyyyMMddHHmmss(dateStr)));
            } else {
                result = parentService.homeworkReport(push.getVipId(), DateUtil.getCurrentDateString());
            }
        }
        return result;
    }

    @Override
    public Homework findByVipIdStartTimeSubject(String vipId, Date startTime, String subject) {
        return homeworkDao.findByVipIdStartTimeSubject(vipId, DateUtil.format_yyyyMMdd(startTime), subject);
    }

    @Override
    public Page<Homework> findByCreateTimeBetween(String beginTimeStr, String endTimeStr, Pageable pageable) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("GT_createTime", beginTimeStr);
        paramMap.put("LT_createTime", endTimeStr);
        Map<String, SearchFilter> searchFilterMap = SearchFilter.parse(paramMap);
        Specification<Homework> specification = DynamicSpecifications.bySearchFilter(searchFilterMap.values(), Homework.class);
        return homeworkDao.findAll(specification, pageable);
    }

    private List<CorrectDetailDto3> getCorrectDetails3(String vipId, Date beginDate) {
        List<CorrectDetailDto3> result = new ArrayList<>();
        List<Homework> hwList  = homeworkDao.findByVipIdAndCreateTimeBetween(vipId, beginDate, DateUtil.getDateAfter(beginDate, 1));

        //遍历所有科目，查询对应数据
        CourseConstant.subjectList.forEach(subject -> hwList.forEach(homework -> {
            if (homework != null && subject.equals(homework.getSubject())) {
                CorrectDetailDto3 temp;
                if (Objects.equals(HomeworkWorkTypeEnum.NoHomeworkOnPaper.getCode(), homework.getWorkType())) {
                    //无纸面作业
                    temp = new CorrectDetailDto3();
                    temp.setCorrectionStatus(7);
                    temp.setSubject(homework.getSubject());
                } else {
                    temp = getCorrectDetailDto3(homework);
                }

                if (temp != null) {
                    result.add(temp);
                }
            }
        }));
        return result;
    }

    @Override
    public CorrectDetailDto3 getCorrectDetailDto3(Homework homework) {
        CorrectDetailDto3 temp = null;
        if (homework != null && (homework.getWorkType() == null || homework.getWorkType() != 3)) {
            List<HomeworkPicture> homeworkPictureList = homeworkPictureDao.queryHomeworkPictureByHomeworkId(homework.getId());

            if (CollectionUtils.isEmpty(homeworkPictureList) && StringUtils.isBlank(homework.getUnFinishedContent())
                    && (homework.getUsedTime() == null || homework.getUsedTime().intValue() == 0)) {
                return temp;
            }

            temp = new CorrectDetailDto3();
            temp.setSubject(homework.getSubject());//科目
            temp.setHomeworkId(homework.getId());
            if (CollectionUtils.isNotEmpty(homeworkPictureList)) {
                temp.setCorrectTeacherId(homeworkPictureList.get(0).getTeacherId());
            }

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            if (Objects.equals(simpleDateFormat.format(new Date()), simpleDateFormat.format(homework.getCreateTime()))) {
                temp.setCorrectionStatus(this.isCorrected(homework.getId()));

                //如果是未批改，需要判断是否是补拍的情况
                if (Objects.equals(0, temp.getCorrectionStatus()) && homework.getCorrectTime() != null) {
                    temp.setCorrectionStatus(2);
                }
            } else {
                if (homework.getCorrectTime() != null && Objects.equals(0, this.isCorrected(homework.getId()))) {
                    //补拍的情况下
                    temp.setCorrectionStatus(2);
                } else {
                    //普通情况下，历史记录中的批改详情，只要有一张图片批改了，那就认为本次作业已批改
                    boolean existCorrectedPicture = homeworkPictureList.stream().anyMatch(it -> Objects.equals(it.getIsFeedback(), 1) || Objects.equals(it.getIsMark(), 1) || Objects.equals(it.getIsMark(), 3));
                    if (existCorrectedPicture) {
                        temp.setCorrectionStatus(1);
                    } else {
                        temp.setCorrectionStatus(0);
                    }
                }
            }

            //作业登记、原图列表及批注列表
            List<HomeworkPictureDto> homeworkPictureDtoList = new LinkedList<>();
            List<HomeworkCommentDto> homeworkCommentDtoList = new LinkedList<>();
            ZuoybStudentPush zuoybStudentPush = pushService.findByVipIdAndDate(homework.getVipId(), DateUtil.format_yyyyMMddHHmmss(Optional.ofNullable(homework.getStartTime()).orElse(homework.getCreateTime())));
            if (zuoybStudentPush != null) {
                String enrollmentImgStr = zuoybStudentPush.getImg();
                if (StringUtils.isNotBlank(enrollmentImgStr)) {
                    Arrays.asList(enrollmentImgStr.split(",")).forEach(enrollmentImg -> {
                        HomeworkPictureDto homeworkPictureDto = new HomeworkPictureDto();
                        homeworkPictureDto.setHomeworkPictureUrl(enrollmentImg);
                        homeworkPictureDto.setIsVague(0);
                        homeworkPictureDto.setStatus(3);
                        homeworkPictureDtoList.add(homeworkPictureDto);
                    });
                }
            }
            homeworkPictureList.forEach(homeworkPicture -> {
                HomeworkPictureDto homeworkPictureDto = new HomeworkPictureDto();
                homeworkPictureDto.setHomeworkPictureId(homeworkPicture.getId());
                homeworkPictureDto.setHomeworkPictureUrl(homeworkPicture.getFileKey());
                homeworkPictureDto.setIsVague(homeworkPicture.getIsMark() == 1 ? 1:  homeworkPicture.getIsMark() == 3 ?4: 0);
                if (homework.getCorrectTime() != null
                        && Objects.equals(0, homeworkPicture.getIsFeedback())
                        && !Objects.equals(1, homeworkPicture.getIsMark())
                        && !Objects.equals(3, homeworkPicture.getIsMark())) {
                    homeworkPictureDto.setStatus(2);
                } else {
                    int status = homeworkPicture.getIsMark() > 0 && homeworkPicture.getIsMark() != 2
                            ? homeworkPicture.getIsMark() == 3 ? 4 : homeworkPicture.getIsMark() : 0;
                    homeworkPictureDto.setStatus(status);
                }
                homeworkPictureDtoList.add(homeworkPictureDto);

                String correctedPictureUrl = homeworkPicture.getCorrectedPictureUrl();
                if (StringUtils.isNotBlank(correctedPictureUrl)) {
                    HomeworkCommentDto homeworkCommentDto = new HomeworkCommentDto();
                    homeworkCommentDto.setHomeworkCommentUrl(correctedPictureUrl);
                    homeworkCommentDto.setIsComposition(homeworkPicture.getIsComposition());
                    String compositionComment = homeworkPicture.getCompositionComment();
                    if (StringUtils.isNotBlank(compositionComment)) {
                        homeworkCommentDto.setCompositionCommentList(Arrays.asList(compositionComment.split(",")));
                    }
                    if(StringUtils.isNotBlank(homeworkPicture.getHomeworkComment())){
                        homeworkCommentDto.setHomeworkComment(homeworkPicture.getHomeworkComment());
                    }
                    homeworkCommentDtoList.add(homeworkCommentDto);
                }
            });
            temp.setHomeworkList(homeworkPictureDtoList);
            temp.setHomeworkCommentList(homeworkCommentDtoList);

            //查询错题和未完成的题目
            List<KmtHomeworkWrongQuestion> kmtHomeworkWrongQuestionList = kmtHomeworkWrongQuestionService.findByHomeworkId(homework.getId());
            if (CollectionUtils.isNotEmpty(kmtHomeworkWrongQuestionList)) {
                List<KmtHomeworkWrongQuestion> wrongQuestionList = kmtHomeworkWrongQuestionList.stream().filter(it -> it.getType().equals(HomeworkWrongQuestionTypeEnum.WrongAnswer.getCode())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(wrongQuestionList)) {//有错题
                    Set<String> wrongQuestionIdSet = wrongQuestionList.stream().map(KmtHomeworkWrongQuestion::getQuestionId).filter(Objects::nonNull).collect(Collectors.toSet());
                    temp.setWrongQuestionCount(wrongQuestionIdSet.size());
                    List<Map<String, Object>> wrongQuestionListGroupByBook = new ArrayList<>();
                    List<KmtExerciseQuestion> kmtExerciseQuestionList = kmtExerciseQuestionService.findByIdIn(new ArrayList<>(wrongQuestionIdSet));
                    Map<String, List<KmtExerciseQuestion>> kmtExerciseQuestionMapGroupByBook = kmtExerciseQuestionList.stream().collect(Collectors.groupingBy(KmtExerciseQuestion::getBookId));
                    kmtExerciseQuestionMapGroupByBook.forEach((key, value) -> {
                        List<WrongQuestionTempDTO> wrongQuestionDTOList = new ArrayList<>();
                        Map<String, List<KmtExerciseQuestion>> kmtExerciseQuestionMap = value.stream().collect(Collectors.groupingBy(KmtExerciseQuestion::getBookCourseId));
                        final String[] bookName = {""};
                        kmtExerciseQuestionMap.forEach((key2, value2) -> {
                            value2.sort((o1, o2) -> {
                                Integer num1 = o1.getNum();
                                if (num1 == null) {
                                    return -1;
                                }
                                Integer num2 = o2.getNum();
                                if (num2 == null) {
                                    return 1;
                                }
                                return num1.compareTo(num2);
                            });

                            KmtExerciseBookCourse kmtExerciseBookCourse = kmtExerciseBookCourseService.getById(key2);
                            if (StringUtils.isBlank(bookName[0])) {
                                bookName[0] = kmtExerciseBookCourse.getBookName();
                            }

                            WrongQuestionTempDTO wrongQuestionDTO = new WrongQuestionTempDTO();
                            wrongQuestionDTO.setUnit(kmtExerciseBookCourse.getUnit());
                            wrongQuestionDTO.setPeriod(kmtExerciseBookCourse.getPeriod());
                            List<Map<String, Object>> questionList = new ArrayList<>();
                            value2.forEach(kmtExerciseQuestion -> {
                                Map<String, Object> questionMap = new HashMap<>();
                                questionMap.put("bigQuestionIndex", kmtExerciseQuestion.getBigQuestionIndex());
                                String smallQuestionName = kmtExerciseQuestion.getSmallQuestionName();
                                if (Objects.equals("(0)", smallQuestionName)) {
                                    smallQuestionName = "0";
                                }
                                questionMap.put("smallQuestionIndex", smallQuestionName);
                                Optional<KmtHomeworkWrongQuestion> optional = wrongQuestionList.stream().filter(it -> Objects.equals(it.getQuestionId(), kmtExerciseQuestion.getId())).findFirst();
                                String spaceIndex = "";
                                if (optional.isPresent()) {
                                    KmtHomeworkWrongQuestion kmtHomeworkWrongQuestion = optional.get();
                                    spaceIndex = kmtHomeworkWrongQuestion.getSpaceIndex();
                                }
                                questionMap.put("spaceIndex", spaceIndex == null ? "" : spaceIndex);
                                questionList.add(questionMap);
                            });
                            wrongQuestionDTO.setQuestionList(questionList);
                            wrongQuestionDTOList.add(wrongQuestionDTO);
                        });

                        Map<String, Object> tempMap = new HashMap<>();
                        tempMap.put("bookName", bookName[0]);
                        tempMap.put("bookCourseList", wrongQuestionDTOList);
                        tempMap.put("wrongQuestionNum", value.size());
                        wrongQuestionListGroupByBook.add(tempMap);
                    });

                    temp.setWrongItemList(wrongQuestionListGroupByBook);
                }
            }

            //错题知识点列表
            List<Map<String, Object>> howDetailsMapList = new ArrayList<>(homeworkQueryDao.findDetailsByHomeworkId(homework.getId()));
            if (CollectionUtils.isNotEmpty(howDetailsMapList)) {
                List<RelateKnowledgeDto> relateKnowledgeDtoList = new ArrayList<>();
                howDetailsMapList.forEach(howDetailsMap -> {
                    String module = String.valueOf(howDetailsMap.get("module"));
                    Optional<RelateKnowledgeDto> optional = relateKnowledgeDtoList.stream().filter(it -> Objects.equals(it.getModule(), module)).findFirst();
                    String alias = String.valueOf(howDetailsMap.get("alias"));
                    if (optional.isPresent()) {
                        RelateKnowledgeDto relateKnowledgeDto = optional.get();
                        List<String> details = relateKnowledgeDto.getDetails();
                        if (details.contains(alias)) {
                            return;
                        }
                        details.add(alias);
                    } else {
                        RelateKnowledgeDto relateKnowledgeDto = new RelateKnowledgeDto();
                        relateKnowledgeDto.setModule(module);
                        List<String> tempAliasList = new ArrayList<>();
                        tempAliasList.add(alias);
                        relateKnowledgeDto.setDetails(tempAliasList);
                        relateKnowledgeDtoList.add(relateKnowledgeDto);
                    }
                });
                temp.setRelateKnowledgeList(relateKnowledgeDtoList);
            }

            //未完成内容列表
            if (StringUtils.isNotBlank(homework.getUnFinishedContent())) {
                temp.setUnfinishedList(Arrays.asList(homework.getUnFinishedContent().split(",")));
            } else {
                temp.setUnfinishedList(new ArrayList<>());
            }
        }

        return temp;
    }

    @Override
    public AdminCorretionDetailDto getAdminCorrectDetail(Homework homework) {
        AdminCorretionDetailDto temp = null;
        if (homework != null && (homework.getWorkType() == null || homework.getWorkType() != 3)) {
            List<HomeworkPicture> homeworkPictureList = homeworkPictureDao.queryHomeworkPictureByHomeworkId(homework.getId());

            if (CollectionUtils.isEmpty(homeworkPictureList) && StringUtils.isBlank(homework.getUnFinishedContent())
                    && (homework.getUsedTime() == null || homework.getUsedTime().intValue() == 0)) {
                return temp;
            }

            temp = new AdminCorretionDetailDto();
            temp.setSubject(homework.getSubject());//科目
            temp.setHomeworkId(homework.getId());
            if (CollectionUtils.isNotEmpty(homeworkPictureList)) {
                //批改老师
                String teacherId = homeworkPictureList.get(0).getTeacherId();
                temp.setCorrectTeacherId(teacherId);
                TbLibManager teacher = bookManagerService.findByUserId(teacherId, Constant.KMT_122_TEACHER_TYPE);
                if (teacher != null){
                    temp.setTeacherName(teacher.getName());
                }
            }

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            if (Objects.equals(simpleDateFormat.format(new Date()), simpleDateFormat.format(homework.getCreateTime()))) {
                temp.setCorrectionStatus(this.isCorrected(homework.getId()));
            } else {
                //历史记录中的批改详情，只要有一张图片批改了，那就认为本次作业已批改
                boolean existCorrectedPicture = homeworkPictureList.stream().anyMatch(it -> Objects.equals(it.getIsFeedback(), 1));
                if (existCorrectedPicture) {
                    temp.setCorrectionStatus(1);
                } else {
                    temp.setCorrectionStatus(0);
                }
            }

            //原图列表及批注列表
            List<AdminHomeworkPictureDto> homeworkPictureDtoList = new LinkedList<>();
            List<HomeworkCommentDto> homeworkCommentDtoList = new LinkedList<>();
            homeworkPictureList.forEach(homeworkPicture -> {
                if (homeworkPicture.getIsMark() != 0){
                    List<HomeworkPictureVagueRecord> vagueRecords = homeworkPictureVagueRecordService.findByHomeworkPictureId(homeworkPicture.getId());
                    if (vagueRecords != null){
                        vagueRecords.forEach(homeworkPictureVagueRecord -> {
                            AdminHomeworkPictureDto homeworkPictureDto = new AdminHomeworkPictureDto();
                            homeworkPictureDto.setHomeworkPictureId(homeworkPicture.getId());
                            homeworkPictureDto.setHomeworkPictureUrl(homeworkPictureVagueRecord.getPictureVaguePath());
                            //都是模糊图片
                            homeworkPictureDto.setType(1);
                            homeworkPictureDto.setCreateTime(DateUtil.format_yyyyMMddHHmmss(homeworkPictureVagueRecord.getPictureVagueUploadTime()));
                            homeworkPictureDto.setCorrectTime(DateUtil.format_yyyyMMddHHmmss(homeworkPictureVagueRecord.getPictureVagueTime()));
                            homeworkPictureDtoList.add(homeworkPictureDto);
                        });
                    }
                    if (homeworkPicture.getIsMark() == 2){
                        AdminHomeworkPictureDto homeworkPictureDto = new AdminHomeworkPictureDto();
                        homeworkPictureDto.setHomeworkPictureId(homeworkPicture.getId());
                        homeworkPictureDto.setHomeworkPictureUrl(homeworkPicture.getFileKey());
                        homeworkPictureDto.setType(homeworkPicture.getIsMark());
                        homeworkPictureDto.setCreateTime(DateUtil.format_yyyyMMddHHmmss(homeworkPicture.getCreateTime()));
                        if (homeworkPicture.getCorrectTime() != null){
                            homeworkPictureDto.setCorrectTime(DateUtil.format_yyyyMMddHHmmss(homeworkPicture.getCorrectTime()));
                        }
                        homeworkPictureDtoList.add(homeworkPictureDto);
                    }
                } else {
                    AdminHomeworkPictureDto homeworkPictureDto = new AdminHomeworkPictureDto();
                    homeworkPictureDto.setHomeworkPictureId(homeworkPicture.getId());
                    homeworkPictureDto.setHomeworkPictureUrl(homeworkPicture.getFileKey());
                    homeworkPictureDto.setType(homeworkPicture.getIsMark());
                    homeworkPictureDto.setCreateTime(DateUtil.format_yyyyMMddHHmmss(homeworkPicture.getCreateTime()));
                    if (homeworkPicture.getCorrectTime() != null){
                        homeworkPictureDto.setCorrectTime(DateUtil.format_yyyyMMddHHmmss(homeworkPicture.getCorrectTime()));
                    }
                    homeworkPictureDtoList.add(homeworkPictureDto);
                }
                String correctedPictureUrl = homeworkPicture.getCorrectedPictureUrl();
                if (StringUtils.isNotBlank(correctedPictureUrl)) {
                    HomeworkCommentDto homeworkCommentDto = new HomeworkCommentDto();
                    homeworkCommentDto.setHomeworkCommentUrl(correctedPictureUrl);
                    homeworkCommentDtoList.add(homeworkCommentDto);
                }
            });
            temp.setHomeworkList(homeworkPictureDtoList);
            temp.setHomeworkCommentList(homeworkCommentDtoList);

            //查询错题和未完成的题目
            List<KmtHomeworkWrongQuestion> kmtHomeworkWrongQuestionList = kmtHomeworkWrongQuestionService.findByHomeworkId(homework.getId());
            if (CollectionUtils.isNotEmpty(kmtHomeworkWrongQuestionList)) {
                List<KmtHomeworkWrongQuestion> wrongQuestionList = kmtHomeworkWrongQuestionList.stream().filter(it -> it.getType().equals(HomeworkWrongQuestionTypeEnum.WrongAnswer.getCode())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(wrongQuestionList)) {//有错题
                    Set<String> wrongQuestionIdSet = wrongQuestionList.stream().map(KmtHomeworkWrongQuestion::getQuestionId).filter(Objects::nonNull).collect(Collectors.toSet());
                    temp.setWrongQuestionCount(wrongQuestionIdSet.size());
                    List<Map<String, Object>> wrongQuestionListGroupByBook = new ArrayList<>();
                    List<KmtExerciseQuestion> kmtExerciseQuestionList = kmtExerciseQuestionService.findByIdIn(new ArrayList<>(wrongQuestionIdSet));
                    Map<String, List<KmtExerciseQuestion>> kmtExerciseQuestionMapGroupByBook = kmtExerciseQuestionList.stream().collect(Collectors.groupingBy(KmtExerciseQuestion::getBookId));
                    kmtExerciseQuestionMapGroupByBook.forEach((key, value) -> {
                        List<WrongQuestionTempDTO> wrongQuestionDTOList = new ArrayList<>();
                        Map<String, List<KmtExerciseQuestion>> kmtExerciseQuestionMap = value.stream().collect(Collectors.groupingBy(KmtExerciseQuestion::getBookCourseId));
                        final String[] bookName = {""};
                        kmtExerciseQuestionMap.forEach((key2, value2) -> {
                            value2.sort((o1, o2) -> {
                                Integer num1 = o1.getNum();
                                if (num1 == null) {
                                    return -1;
                                }
                                Integer num2 = o2.getNum();
                                if (num2 == null) {
                                    return 1;
                                }
                                return num1.compareTo(num2);
                            });

                            KmtExerciseBookCourse kmtExerciseBookCourse = kmtExerciseBookCourseService.getById(key2);
                            if (StringUtils.isBlank(bookName[0])) {
                                bookName[0] = kmtExerciseBookCourse.getBookName();
                            }

                            WrongQuestionTempDTO wrongQuestionDTO = new WrongQuestionTempDTO();
                            wrongQuestionDTO.setUnit(kmtExerciseBookCourse.getUnit());
                            wrongQuestionDTO.setPeriod(kmtExerciseBookCourse.getPeriod());
                            List<Map<String, Object>> questionList = new ArrayList<>();
                            value2.forEach(kmtExerciseQuestion -> {
                                Map<String, Object> questionMap = new HashMap<>();
                                questionMap.put("bigQuestionIndex", kmtExerciseQuestion.getBigQuestionIndex());
                                String smallQuestionName = kmtExerciseQuestion.getSmallQuestionName();
                                if (Objects.equals("(0)", smallQuestionName)) {
                                    smallQuestionName = "0";
                                }
                                questionMap.put("smallQuestionIndex", smallQuestionName);
                                Optional<KmtHomeworkWrongQuestion> optional = wrongQuestionList.stream().filter(it -> Objects.equals(it.getQuestionId(), kmtExerciseQuestion.getId())).findFirst();
                                String spaceIndex = "";
                                if (optional.isPresent()) {
                                    KmtHomeworkWrongQuestion kmtHomeworkWrongQuestion = optional.get();
                                    spaceIndex = kmtHomeworkWrongQuestion.getSpaceIndex();
                                }
                                questionMap.put("spaceIndex", spaceIndex == null ? "" : spaceIndex);
                                questionList.add(questionMap);
                            });
                            wrongQuestionDTO.setQuestionList(questionList);
                            wrongQuestionDTOList.add(wrongQuestionDTO);
                        });

                        Map<String, Object> tempMap = new HashMap<>();
                        tempMap.put("bookName", bookName[0]);
                        tempMap.put("bookCourseList", wrongQuestionDTOList);
                        tempMap.put("wrongQuestionNum", value.size());
                        wrongQuestionListGroupByBook.add(tempMap);
                    });

                    temp.setWrongItemList(wrongQuestionListGroupByBook);
                }
            }

            //错题知识点列表
            List<Map<String, Object>> howDetailsMapList = new ArrayList<>(homeworkQueryDao.findDetailsByHomeworkId(homework.getId()));
            if (CollectionUtils.isNotEmpty(howDetailsMapList)) {
                List<RelateKnowledgeDto> relateKnowledgeDtoList = new ArrayList<>();
                howDetailsMapList.forEach(howDetailsMap -> {
                    String module = String.valueOf(howDetailsMap.get("module"));
                    Optional<RelateKnowledgeDto> optional = relateKnowledgeDtoList.stream().filter(it -> Objects.equals(it.getModule(), module)).findFirst();
                    String alias = String.valueOf(howDetailsMap.get("alias"));
                    if (optional.isPresent()) {
                        RelateKnowledgeDto relateKnowledgeDto = optional.get();
                        List<String> details = relateKnowledgeDto.getDetails();
                        if (details.contains(alias)) {
                            return;
                        }
                        details.add(alias);
                    } else {
                        RelateKnowledgeDto relateKnowledgeDto = new RelateKnowledgeDto();
                        relateKnowledgeDto.setModule(module);
                        List<String> tempAliasList = new ArrayList<>();
                        tempAliasList.add(alias);
                        relateKnowledgeDto.setDetails(tempAliasList);
                        relateKnowledgeDtoList.add(relateKnowledgeDto);
                    }
                });
                temp.setRelateKnowledgeList(relateKnowledgeDtoList);
            }

            //未完成内容列表
            if (StringUtils.isNotBlank(homework.getUnFinishedContent())) {
                temp.setUnfinishedList(Arrays.asList(homework.getUnFinishedContent().split(",")));
            } else {
                temp.setUnfinishedList(new ArrayList<>());
            }
        }

        return temp;
    }


    @Override
    public Page<Map<String, Object>> findHomeworkByPage(Map<String, Object> searchParam, Pageable pageable) {
        return homeworkQueryDao.findHomeworkByPage(searchParam, pageable);
    }

    @Override
    public void beginHomeworkCorrection(String homeworkId) {
        Homework homework = this.getById(homeworkId);
        if (homework != null && homework.getCorrectBeginTime() == null){
            homework.setCorrectBeginTime(new Date());
            this.save(homework);
        }
    }

    @Override
    public String getHomeworkTime(Homework homework) {
        String homeworkTime = "";
        if (homework.getUsedTime() != null && homework.getUsedTime() > 0) {
            Date startTime = homework.getStartTime();
            Date endTime = homework.getEndTime();
            if (startTime != null && endTime != null) {
                if (startTime.getTime() == endTime.getTime()) {
                    return homeworkTime;
                }
                homeworkTime = DateUtil.format_HHmm(startTime) + "-" + DateUtil.format_HHmm(endTime);
            }
        }
        return homeworkTime;
    }

    @Override
    public void endHomeworkRecord(String vipId, String subject) {
        Homework homework = homeworkDao.findByTodaySubjectHomework(vipId, subject);
        if (homework.getUsedTime() == null || homework.getUsedTime() <= 0) {
            Date endTime = new Date();
            homework.setEndTime(endTime);
            long usedTime = endTime.getTime() - homework.getStartTime().getTime();
            //作业用时转为分钟，不足一分钟按一分钟算
            usedTime = (long) Math.ceil(usedTime / (1000 * 60.0));
            homework.setUsedTime(usedTime);
            homeworkDao.save(homework);
        }
    }

    @Override
    public List<String> findIdPictureNotUpload(String vipId) {
        return homeworkQueryDao.findIdPictureNotUpload(vipId);
    }

    @Override
    public List<Homework> findRangHomeworkList(String vipId, Date beginTime, Date endTime) {
        String beginTimeStr = DateUtil.format_yyyyMMdd(beginTime);
        String endTimeStr = DateUtil.format_yyyyMMdd(endTime) + " 23:59:59";
        return homeworkDao.findByVipIdAndCreateTimeBetween(vipId, beginTimeStr, endTimeStr);
    }

    @Override
    public Map<String, Object> findHomeworkReport4(ZuoybStudentPush push, String parentId, boolean hideReportIfAbsent) {
        Map<String, Object> result = new HashMap<>();
     //   ZuoybStudentPush push = pushService.getById(studentPushId);
        if (push != null){
            if (DateUtil.getCurrentDateString().compareTo(CourseConstant.publishDate) >= 0){
                List<Homework> hwList = queryDateHomework(push.getVipId(), push.getPushTime());
                if (StringUtils.isNotBlank(push.getEvaluate()) && push.getLevel() != null && push.getLevel() > 0){
                    result.put("assessed", true);
                } else {
                    result.put("assessed", false);
                }
                result.put("studentInfo", parentService.getMyChildInfo(push.getVipId()));
                if (hideReportIfAbsent && Objects.equals(4, push.getType())) {
                    result.put("abstractSituation", new HistoryTaskDto());
                    result.put("learningState", Collections.emptyList());
                } else {
                    result.put("abstractSituation", this.findCommonHistoryTask(push, hwList));
                    result.put("learningState", this.findLearningStatus(push));
                }
                String dateStr = DateUtil.format_yyyyMMdd(push.getPushTime()) + " 00:00:00";
                result.put("correctList", this.getCorrectDetails4(push.getVipId(), DateUtil.parse_yyyyMMddHHmmss(dateStr)));
            } else {
                result = parentService.homeworkReport(push.getVipId(), DateUtil.getCurrentDateString());
            }
        }
        return result;
    }

    @Override
    public List<CorrectDetailDto4> getCorrectDetails4(String vipId, Date pushDate) {
        List<CorrectDetailDto4> result = new ArrayList<>();
        List<Homework> hwList  = homeworkDao.findByVipIdAndCreateTimeBetween(vipId, pushDate, DateUtil.getDateAfter(pushDate, 1));

        //遍历所有科目，查询对应数据
        CourseConstant.subjectList.forEach(subject -> hwList.forEach(homework -> {
            if (homework != null && subject.equals(homework.getSubject())) {
                CorrectDetailDto4 temp;
                if (Objects.equals(HomeworkWorkTypeEnum.NoHomeworkOnPaper.getCode(), homework.getWorkType())) {
                    //无纸面作业
                    temp = new CorrectDetailDto4();
                    temp.setCorrectionStatus(7);
                    temp.setSubject(homework.getSubject());
                } else {
                    temp = this.getRedisCorrectDetail(vipId, subject, pushDate);
                    if (temp == null){
                        temp = this.getCorrectDetailDto4(homework);
                    }
                }

                if (temp != null) {
                    result.add(temp);
                }
            }
        }));
        return result;
    }

    @Override
    public CorrectDetailDto4 getCorrectDetailDto4(Homework homework) {
        if (homework == null || homework.getWorkType() == null || homework.getWorkType() == 3) {
            return null;
        }
        CorrectDetailDto4 temp = null;
        List<HomeworkPicture> homeworkPictureList = homeworkMapper.findHomeworkCorrectDetailByHomeworkId(homework.getId());
        String redisKey = this.getCorrectDetailRedisKey(homework.getVipId(), homework.getSubject(), homework.getCreateTime());
        if (CollectionUtils.isEmpty(homeworkPictureList)) {
            return null;
        }

        temp = new CorrectDetailDto4();
        temp.setSubject(homework.getSubject());
        temp.setHomeworkId(homework.getId());
        temp.setHomeworkTime(this.getHomeworkTime(homework));
        if (CollectionUtils.isNotEmpty(homeworkPictureList)) {
            temp.setCorrectTeacherId(homeworkPictureList.get(0).getTeacherId());
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        boolean existCorrectedPicture = homeworkPictureList.stream().anyMatch(it -> Objects.equals(it.getIsFeedback(), 1) || Objects.equals(it.getIsMark(), 1) || Objects.equals(it.getIsMark(), 3));
        if (Objects.equals(simpleDateFormat.format(new Date()), simpleDateFormat.format(homework.getCreateTime()))) {
            temp.setCorrectionStatus(this.isCorrected(homework.getId()));

            //如果是未批改，需要判断是否是补拍的情况
            if (Objects.equals(0, temp.getCorrectionStatus()) && homework.getCorrectTime() != null) {
                temp.setCorrectionStatus(2);
            } else if (existCorrectedPicture) {
                temp.setCorrectionStatus(1);
            }
        } else {
            if (homework.getCorrectTime() != null && Objects.equals(0, this.isCorrected(homework.getId()))) {
                //补拍的情况下
                temp.setCorrectionStatus(2);
            } else {
                //普通情况下，历史记录中的批改详情，只要有一张图片批改了，那就认为本次作业已批改
                if (existCorrectedPicture) {
                    temp.setCorrectionStatus(1);
                } else {
                    temp.setCorrectionStatus(0);
                }
            }
        }

        //作业登记、原图列表及批注列表
        List<HomeworkPictureDto> homeworkPictureDtoList = new LinkedList<>();
        List<HomeworkCommentDto2> homeworkCommentDtoList = new LinkedList<>();
        ZuoybStudentPush zuoybStudentPush = pushService.findByVipIdAndDate(homework.getVipId(), DateUtil.format_yyyyMMddHHmmss(homework.getCreateTime()));
        if (zuoybStudentPush != null) {
            String enrollmentImgStr = zuoybStudentPush.getImg();
            if (StringUtils.isNotBlank(enrollmentImgStr)) {
                Arrays.asList(enrollmentImgStr.split(",")).forEach(enrollmentImg -> {
                    HomeworkPictureDto homeworkPictureDto = new HomeworkPictureDto();
                    homeworkPictureDto.setHomeworkPictureUrl(enrollmentImg);
                    homeworkPictureDto.setIsVague(0);
                    homeworkPictureDto.setStatus(3);
                    homeworkPictureDtoList.add(homeworkPictureDto);
                });
            }
        }
        homeworkPictureList.forEach(homeworkPicture -> {
            HomeworkPictureDto homeworkPictureDto = new HomeworkPictureDto();
            homeworkPictureDto.setHomeworkPictureId(homeworkPicture.getId());
            homeworkPictureDto.setHomeworkPictureUrl(homeworkPicture.getFileKey());
            homeworkPictureDto.setIsVague(homeworkPicture.getIsMark() == 1 ? 1:  homeworkPicture.getIsMark() == 3 ?4: 0);
            if (homework.getCorrectTime() != null
                    && Objects.equals(0, homeworkPicture.getIsFeedback())
                    && !Objects.equals(1, homeworkPicture.getIsMark())
                    && !Objects.equals(3, homeworkPicture.getIsMark())) {
                homeworkPictureDto.setStatus(2);
            } else {
                int status = homeworkPicture.getIsMark() > 0 && homeworkPicture.getIsMark() != 2
                        ? homeworkPicture.getIsMark() == 3 ? 4 : homeworkPicture.getIsMark() : 0;
                homeworkPictureDto.setStatus(status);
            }
            homeworkPictureDtoList.add(homeworkPictureDto);

            String correctedPictureUrl = homeworkPicture.getCorrectedPictureUrl();
            if (StringUtils.isNotBlank(correctedPictureUrl)) {
                HomeworkCommentDto2 homeworkCommentDto = new HomeworkCommentDto2();
                homeworkCommentDto.setHomeworkCommentUrl(correctedPictureUrl);
                homeworkCommentDto.setIsComposition(homeworkPicture.getIsComposition());
                if (homeworkPicture.getIsComposition() == 1) {
                    //有作文，查询作文评语
                    homeworkCommentDto.setCompositionCommentModuleList(commentTemplateMapperService.getCompositionCommentModuleDTOList(homeworkPicture.getId()));
                }
                if(StringUtils.isNotBlank(homeworkPicture.getHomeworkComment())){
                  homeworkCommentDto.setHomeworkComment(homeworkPicture.getHomeworkComment());
                }
                homeworkCommentDtoList.add(homeworkCommentDto);
            }

        });
        temp.setHomeworkList(homeworkPictureDtoList);
        temp.setHomeworkCommentList(homeworkCommentDtoList);

        //查询错题和未完成的题目
        Map<String, String> wrongQuestionAndDetails = tokenManager.hget("correctDetail_part_" + homework.getId());
        if (wrongQuestionAndDetails != null && !wrongQuestionAndDetails.isEmpty()){
            temp.setWrongItemList(JSON.parseObject(wrongQuestionAndDetails.get("wrong_questions"), List.class));
            temp.setRelateKnowledgeList(JSON.parseObject(wrongQuestionAndDetails.get("wrong_details"), List.class));
        } else {
            temp.setWrongItemList(this.findWrongQuestionAndSetRedis(homework.getId()));
            //错题知识点列表
            temp.setRelateKnowledgeList(this.findWrongHowDetailAndSetRedis(homework.getId()));
        }

        //未完成内容列表
        if (StringUtils.isNotBlank(homework.getUnFinishedContent())) {
            temp.setUnfinishedList(Arrays.asList(homework.getUnFinishedContent().split(",")));
        } else {
            temp.setUnfinishedList(new ArrayList<>());
        }
        if (DateUtil.compareDate(homework.getCreateTime(), DateUtil.parse_yyyyMMdd(getQueryBeginDate()))){
            tokenManager.set(redisKey, temp, 90 * 24 * 3600);
        }
        return temp;
    }

    /**
     * 获取查询作业列表的开始时间
     * @return
     */
    private String getQueryBeginDate(){
        String beginTime;
        if (DateUtil.getHour(new Date()) < 14) {
            beginTime=DateUtil.format_yyyyMMdd(DateUtil.addDays(new Date(), -1));
        } else {
            beginTime=DateUtil.format_yyyyMMdd(DateUtil.getTodatDate());
        }
        return beginTime;
    }

    /**
     * 查询缓存中的批改详情
     * @param vipId
     * @param subject
     * @param date
     * @return
     */
    public CorrectDetailDto4 getRedisCorrectDetail (String vipId, String subject, Date date){
        //超过14点，昨天的批改详情可以查询缓存，今日的详情不查询缓存
        CorrectDetailDto4 temp = null;
        if (DateUtil.compareDate(date, DateUtil.parse_yyyyMMdd(getQueryBeginDate()))){
            temp = tokenManager.get(this.getCorrectDetailRedisKey(vipId, subject, date), CorrectDetailDto4.class);
        }
        return temp;
    }

    /**
     * 作业批改后更新单科批改详情
     * @param vipId
     * @param subject
     * @param date
     */
    public void removeRedisCorrectDetailDto4 (String vipId, String subject, Date date){
        String key = this.getCorrectDetailRedisKey(vipId, subject, date);
        CorrectDetailDto4 temp = tokenManager.get(key, CorrectDetailDto4.class);
        if (temp != null){
            tokenManager.delString(key);
        }
    }

    /**
     * 查询单科批改详情的redis key
     * @param vipId
     * @param subject
     * @param date
     * @return
     */
    private String getCorrectDetailRedisKey (String vipId, String subject, Date date){
        StringBuilder redisKey = new StringBuilder();
        redisKey.append(vipId).append("_correctDetail").append("_")
                .append(CourseConstant.getAllSubjectList().indexOf(subject))
                .append("_").append(DateUtil.format_yyyyMMdd(date));
        return redisKey.toString();
    }


    @Override
    public void updateHomework2NoHomework(String homeworkId) {
        homeworkDao.updateHomework2NoHomework(homeworkId);
    }

    @Override
    public List<Map<String, Object>> findWrongQuestionAndSetRedis(String homeworkId) {
        List<Map<String, Object>> wrongQuestionListGroupByBook = new ArrayList<>();
        List<KmtHomeworkWrongQuestion> kmtHomeworkWrongQuestionList = kmtHomeworkWrongQuestionService.findByHomeworkId(homeworkId);
        if (CollectionUtils.isNotEmpty(kmtHomeworkWrongQuestionList)) {
            List<KmtHomeworkWrongQuestion> wrongQuestionList = kmtHomeworkWrongQuestionList.stream().filter(it -> it.getType().equals(HomeworkWrongQuestionTypeEnum.WrongAnswer.getCode())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(wrongQuestionList)) {//有错题
                Set<String> wrongQuestionIdSet = wrongQuestionList.stream().map(KmtHomeworkWrongQuestion::getQuestionId).filter(Objects::nonNull).collect(Collectors.toSet());
                List<KmtExerciseQuestion> kmtExerciseQuestionList = kmtExerciseQuestionService.findByIdIn(new ArrayList<>(wrongQuestionIdSet));
                Map<String, List<KmtExerciseQuestion>> kmtExerciseQuestionMapGroupByBook = kmtExerciseQuestionList.stream().collect(Collectors.groupingBy(KmtExerciseQuestion::getBookId));
                kmtExerciseQuestionMapGroupByBook.forEach((key, value) -> {
                    List<WrongQuestionTempDTO> wrongQuestionDTOList = new ArrayList<>();
                    Map<String, List<KmtExerciseQuestion>> kmtExerciseQuestionMap = value.stream().collect(Collectors.groupingBy(KmtExerciseQuestion::getBookCourseId));
                    final String[] bookName = {""};
                    kmtExerciseQuestionMap.forEach((key2, value2) -> {
                        value2.sort((o1, o2) -> {
                            Integer num1 = o1.getNum();
                            if (num1 == null) {
                                return -1;
                            }
                            Integer num2 = o2.getNum();
                            if (num2 == null) {
                                return 1;
                            }
                            return num1.compareTo(num2);
                        });

                        KmtExerciseBookCourse kmtExerciseBookCourse = kmtExerciseBookCourseService.getById(key2);
                        if (StringUtils.isBlank(bookName[0])) {
                            bookName[0] = kmtExerciseBookCourse.getBookName();
                        }

                        WrongQuestionTempDTO wrongQuestionDTO = new WrongQuestionTempDTO();
                        wrongQuestionDTO.setUnit(kmtExerciseBookCourse.getUnit());
                        wrongQuestionDTO.setPeriod(kmtExerciseBookCourse.getPeriod());
                        List<Map<String, Object>> questionList = new ArrayList<>();
                        value2.forEach(kmtExerciseQuestion -> {
                            Map<String, Object> questionMap = new HashMap<>();
                            questionMap.put("bigQuestionIndex", kmtExerciseQuestion.getBigQuestionIndex());
                            String smallQuestionName = kmtExerciseQuestion.getSmallQuestionName();
                            if (Objects.equals("(0)", smallQuestionName)) {
                                smallQuestionName = "0";
                            }
                            questionMap.put("smallQuestionIndex", smallQuestionName);
                            Optional<KmtHomeworkWrongQuestion> optional = wrongQuestionList.stream().filter(it -> Objects.equals(it.getQuestionId(), kmtExerciseQuestion.getId())).findFirst();
                            String spaceIndex = "";
                            if (optional.isPresent()) {
                                KmtHomeworkWrongQuestion kmtHomeworkWrongQuestion = optional.get();
                                spaceIndex = kmtHomeworkWrongQuestion.getSpaceIndex();
                            }
                            questionMap.put("spaceIndex", spaceIndex == null ? "" : spaceIndex);
                            questionList.add(questionMap);
                        });
                        wrongQuestionDTO.setQuestionList(questionList);
                        wrongQuestionDTOList.add(wrongQuestionDTO);
                    });

                    Map<String, Object> tempMap = new HashMap<>();
                    tempMap.put("bookName", bookName[0]);
                    tempMap.put("bookCourseList", wrongQuestionDTOList);
                    tempMap.put("wrongQuestionNum", value.size());
                    wrongQuestionListGroupByBook.add(tempMap);
                });
                Map<String, String> data = new HashMap<>();
                data.put("wrong_questions", JSON.toJSONString(wrongQuestionListGroupByBook));
                tokenManager.hset("correctDetail_part_" + homeworkId, data, 48 * 3600);
            }
        }
        return wrongQuestionListGroupByBook;
    }

    @Override
    public List<RelateKnowledgeDto> findWrongHowDetailAndSetRedis(String homeworkId) {
        List<RelateKnowledgeDto> relateKnowledgeDtoList = new ArrayList<>();
        List<Map<String, Object>> howDetailsMapList = new ArrayList<>(homeworkQueryDao.findDetailsByHomeworkId(homeworkId));
        if (CollectionUtils.isNotEmpty(howDetailsMapList)) {
            howDetailsMapList.forEach(howDetailsMap -> {
                String module = String.valueOf(howDetailsMap.get("module"));
                Optional<RelateKnowledgeDto> optional = relateKnowledgeDtoList.stream().filter(it -> Objects.equals(it.getModule(), module)).findFirst();
                String alias = String.valueOf(howDetailsMap.get("alias"));
                if (optional.isPresent()) {
                    RelateKnowledgeDto relateKnowledgeDto = optional.get();
                    List<String> details = relateKnowledgeDto.getDetails();
                    if (details.contains(alias)) {
                        return;
                    }
                    details.add(alias);
                } else {
                    RelateKnowledgeDto relateKnowledgeDto = new RelateKnowledgeDto();
                    relateKnowledgeDto.setModule(module);
                    List<String> tempAliasList = new ArrayList<>();
                    tempAliasList.add(alias);
                    relateKnowledgeDto.setDetails(tempAliasList);
                    relateKnowledgeDtoList.add(relateKnowledgeDto);
                }
            });
            Map<String, String> data = new HashMap<>();
            data.put("wrong_details", JSON.toJSONString(relateKnowledgeDtoList));
            tokenManager.hset("correctDetail_part_" + homeworkId, data, 48 * 3600);
        }
        return relateKnowledgeDtoList;
    }

    public void deleteByVipId(String vipId){
        homeworkDao.deleteByVipId(vipId);
    }
}