package com.ssj.service.sys.homework.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.ssj.bean.conch.conch.dto.HomeworkRecordDto;
import com.ssj.bean.sys.homework.domain.*;
import com.ssj.bean.sys.imlibuser.TbClassTeacher;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.libmy.domain.TbLibSubscribe;
import com.ssj.bean.weixin.push.domain.Miniprogram;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.bean.weixin.zyb.domain.ZuoybStudentPush;
import com.ssj.bean.weixin.zyb.domain.ZuoybStudentWork;
import com.ssj.conch.constant.ConchConstants;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.dao.sys.homework.dao.HomeworkPictureDao;
import com.ssj.dao.sys.homework.dao.HomeworkPictureQueryDao;
import com.ssj.enums.XinGePushBusinessTypeEnum;
import com.ssj.enums.XinGePushMessageTypeEnum;
import com.ssj.framework.basic.utils.DateHelper;
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.core.util.*;
import com.ssj.framework.idworker.IdWorker;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.framework.weixin.util.WxUtil;
import com.ssj.service.ai.model.AiVipIdsModel;
import com.ssj.service.conch.conch.dto.HomeworkPictureCommentDTO;
import com.ssj.service.conch.conch.request.DeleteHomeworkRequest;
import com.ssj.service.conch.conch.request.FindHomeworkRequest;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.conch.conch.service.HomeworkRankingService;
import com.ssj.service.conch.conch.vo.HomeworkFeedbackVO3;
import com.ssj.service.conch.conch.vo.HomeworkFeedbackVO4;
import com.ssj.service.conch.conch.vo.HomeworkFeedbackVO5;
import com.ssj.service.conch.parents.v1.dto.SubjectChartsDto;
import com.ssj.service.conch.teacher.service.TeacherService;
import com.ssj.service.kmt.correctsys.dto.HomeworkPictureDto;
import com.ssj.service.kmt.correctsys.service.KmtCorrectSysService;
import com.ssj.service.sys.feedback.service.FeedbackService;
import com.ssj.service.sys.feedback.vo.TeacherFeedback;
import com.ssj.service.sys.feedback.vo.ToFeedBack;
import com.ssj.service.sys.homework.service.*;
import com.ssj.service.sys.homework.vo.HomeworkExt;
import com.ssj.service.sys.homework.vo.HomeworkFeedback;
import com.ssj.service.sys.imlibuser.service.TbClassTeacherService;
import com.ssj.service.sys.picturepredeal.service.PicturePreDealService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.sys.situation.service.LearningConditionService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.ILibSubscribeService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.library.service.LibVipDocService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.user.service.UserCountService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.service.weixin.zuoyb.service.ZuoybDayService;
import com.ssj.service.weixin.zuoyb.service.ZuoybKnowHowService;
import com.ssj.service.weixin.zuoyb.service.ZuoybStudentPushSerivce;
import com.ssj.service.weixin.zuoyb.service.ZuoybStudentWorkService;
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.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


@Service(version="1.0")
@Transactional
public class HomeworkPictureServiceImpl extends BaseServiceImpl<HomeworkPicture, String> implements HomeworkPictureService {

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

    @Autowired
    private HomeworkService homeworkService;

    @Autowired
    private HomeworkPictureDao homeworkPictureDao;

    @Autowired
    private HomeworkPictureQueryDao homeworkPictureQueryDao;

    @Autowired
    private FeedbackService feedbackService;

    @Autowired
    private UserService userService;

    @Autowired
    private ILibVipService vipService;

    @Autowired
    private ConchDerverService conchDerverService;

    @Autowired
    private IBookManagerService     managerService;

    @Autowired
    private PushTemplateService pushTemplateService;

    @Autowired
    private ZuoybDayService zuoybDayService;
    @Autowired
    private ZuoybStudentPushSerivce zuoybStudentPushSerivce;
    @Autowired
    private ZuoybStudentWorkService zuoybStudentWorkService;
    @Autowired
    private LibVipDocService libVipDocService;

    @Autowired
    private SconXingeService sconXingeService;

    @Autowired
    private ZuoybKnowHowService zuoybKnowHowService;

    @Autowired
    private ILibSubscribeService libSubscribeService;

    @Autowired
    private LibVipServiceService libVipServiceService;
    
    @Autowired
    private TeacherService teacherService;
    
    @Autowired
    private HomeworkRankingService homeworkRankingService;
    @Autowired
    private PicturePreDealService picturePreDealService;
    @Autowired
    private HomeworkPictureVagueRecordService homeworkPictureVagueRecordService;
    @Autowired
    private NoHomeworkRecordService noHomeworkRecordService;
    @Autowired
    private HomeworkPictureCorrectService homeworkPictureCorrectService;
    @Autowired
    private UserCountService userCountService;
    @Autowired
    private KmtCorrectSysService kmtCorrectSysService;
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private TbClassTeacherService tbClassTeacherService;
    @Autowired
    private LearningConditionService learningConditionService;

    @Autowired
    private IBookManagerService bookManagerService;

    @Override
    public PagingAndSortingRepository<HomeworkPicture, String> getDao() {
        return homeworkPictureDao;
    }

    @Override
    public HomeworkPicture save(HomeworkPicture homeworkPicture){
        if(StringUtil.isBlank(homeworkPicture.getId())){
            homeworkPicture.setId(IdWorker.generateId());
        }
        return super.save(homeworkPicture);
    }

    @Override
    public void save(List<HomeworkPicture> list){
        for (HomeworkPicture homeworkPicture:list) {
            if(StringUtil.isBlank(homeworkPicture.getId())){
                homeworkPicture.setId(IdWorker.generateId());
            }
        }
           super.save(list);
    }

    @Override
    public int addHomeworkPicture(String parentId, String childName, String homeworkId, String fileKeys, String derver, Integer type, String derverFileKey, String vipId, Long currentTime, String questionRecommendRecordId,String userId) {
    	//判断fileKeys是否在表中存在
//    	long count = homeworkPictureDao.countByFileKey(fileKeys);
//        if (count > 0) {
//            //如果作业有相同图片则不上传
//            logger.info("有相同的作业上传, fileKeys={}, count={}", fileKeys, count);
//            return;
//        }
//        long count = homeworkPictureDao.countByDerverFileKey(derverFileKey);
        int addIntegral = 0;
        HomeworkPicture temp = homeworkPictureDao.findByDerverFileKeyOrderByCreateTimeDesc(derverFileKey);
        if (temp != null) {
            //如果作业有相同图片则不上传, 直接返回成功给前端
            logger.warn("有相同的作业上传, derverFileKey={}", fileKeys);
            temp.setFileKey(fileKeys);
            this.save(temp);
            return addIntegral;
        }

        logger.info("添加作业图片的贝壳号derver=" + derver + "; vip_id=" + vipId + ";homeworkId=" + homeworkId);

        Homework homework = homeworkService.getById(homeworkId);
        NoHomeworkRecord noHomeworkRecord = null;
        LibVip student = vipService.getById(vipId);
        Date finishDate = new Date();
        noHomeworkRecord = noHomeworkRecordService.saveTodayNoHomeworkRecord(student, homework.getSubject(), homework.getWorkType() == 2 ? 2 : 1, 2, homeworkId);
        if(homework == null) {
        	//如果作业没有计时记录则抛出异常
        	throw new RuntimeException("作业计时已删除,请重新计时拍照");
        } else if (!DateUtil.isSameDay(homework.getCreateTime(), finishDate)){
            logger.error("作业id不是今天的作业, vip_id={}, homeworkId={}", vipId, homeworkId);
            return addIntegral;
        } else if (homework.getWorkType() == 3 || homework.getWorkType() == 4){
            homework.setWorkType(1);
            homeworkService.save(homework);
        }

        //小塾、pad、学生端app计时后上传的图片需要计算排行榜积分
        // 20200612 上传作业不计积分，注释掉
//        if (type != null && type > 1 && type < 4 &&
//                homework.getUsedTime()>0 &&
//                !Objects.equals(homework.getCalculatedIntegral(), 1)) {
//
//            //用时大于0时再计算
//            //计算小塾相机排行榜积分
//            addIntegral = homeworkRankingService.computeAndSaveIntegralByHomeworkUseTime(homework.getVipId(), homework.getId(), homework.getUsedTime(),homework.getSubject());
//            homework.setCalculatedIntegral(1);
//            homeworkService.save(homework);
//
//        }

     //   HomeworkPicture lastHomeworkPicture = homeworkPictureDao.findLastByHomeworkId(homeworkId);

        HomeworkPicture homeworkPicture = this.insertHomeworkPictureV1(parentId, homeworkId, fileKeys, derver, type,
                derverFileKey, vipId, currentTime, homework.getSubject(), noHomeworkRecord.getId(), student.getLibId(), questionRecommendRecordId,null);

        //判断是否需要推送提醒，只在第一次上传图片或间隔超过10分钟才会推送提醒给批改老师
        boolean needSendNotice = false;
        String  lastPictureCreate = tokenManager.getString("homeworkId"+homeworkId);
        if (StringUtil.isBlank(lastPictureCreate)) {
            //第一张图片，需要推送提醒
            needSendNotice = true;
            tokenManager.setString("homeworkId"+homeworkId,System.currentTimeMillis()+"" ,12 * 3600);
        } else {
            long lastPictureCreateTime = Long.parseLong(lastPictureCreate);
            long newPictureCreateTime = homeworkPicture.getCreateTime().getTime();
            if (newPictureCreateTime - lastPictureCreateTime > 10 * 60 * 1000) {
                //距离上一次上传大于10分钟，需要推送提醒
                needSendNotice = true;
                tokenManager.setString("homeworkId"+homeworkId,System.currentTimeMillis()+"" ,12 * 3600);
            }
        }

        //请求ai识别图片
        picturePreDealService.asyncPostRequest2AI(homeworkPicture);
        //此处逻辑已经不再使用，有需要再使用再放开
        /*if (StringUtils.isNotEmpty(vipId) && StringUtils.isNotEmpty(homeworkPicture.getTeacherId())) {
            //给线上批改的老师推送消息，机构自批改老师这里暂时不推送，后续是否需要视业务需要
            if (homeworkPicture.getServiceType() == 1) {
                sendMsg4SubmitWork(vipId, homeworkPicture.getTeacherId());
            }
        }*/

        //这里需要有作业推送提醒给老师
        if (needSendNotice) {
            //推送提醒给在线批改老师
            if (homeworkPicture.getServiceType() == 1) {
                logger.info("给批改老师推送提醒，推送开始");
                if (student != null) {
                    this.sendTempMsg2OnlineTeacher(homeworkPicture.getTeacherId(), student.getChildName(), finishDate, homework.getSubject());

                    List<TbLibManager> libManagerList = managerService.findByUserIdAndTypeIn(homeworkPicture.getTeacherId(), new int[]{8, 11});
                    if (CollectionUtils.isNotEmpty(libManagerList)) {
                        TbLibManager correctTeacher = libManagerList.get(0);
                        String content = "尊敬的" + correctTeacher.getName() + "老师，您负责的" + student.getChildName() + "学生，已经于" + DateUtil.dateTimeToString(finishDate) + "时间完成" + homeworkPicture.getSubject() + "作业，请您尽快完成作业批改！";
                        this.sconXingeService.asynPushThreadTask(homeworkPicture.getTeacherId(), 4, XinGePushMessageTypeEnum.Message.getCode(), XinGePushBusinessTypeEnum.HomeworkCorrectNotice.getCode(), "作业批改提醒", content, "APP_TEACHER", PushConstants.PUSH_OTHER);
                    }
                } else {
                    logger.error("找不到学生记录，没有推送， vipId={}", vipId);
                }
                logger.info("给批改老师推送提醒，推送结束");
            } else if (homeworkPicture.getServiceType() == 2 || homeworkPicture.getServiceType() == 5) {
                //推送提醒给机构自批改老师
                logger.info("给机构自批改老师推送提醒，推送开始");
                if (student != null) {
                    this.sendTempMsg2LibTeacher(homeworkPicture.getTeacherId(), student.getChildName(), finishDate, homework.getSubject());

                    List<TbLibManager> libManagerList = managerService.findByUserIdAndTypeIn(homeworkPicture.getTeacherId(), new int[]{15});
                    if (CollectionUtils.isNotEmpty(libManagerList)) {
                        TbLibManager correctTeacher = libManagerList.get(0);
                        String content = "尊敬的" + correctTeacher.getName() + "老师，您负责的" + student.getChildName() + "学生，已经于" + DateUtil.dateTimeToString(finishDate) + "时间完成" + homeworkPicture.getSubject() + "作业，请您尽快完成作业批改！";
                        this.sconXingeService.asynPushThreadTask(homeworkPicture.getTeacherId(), 4, XinGePushMessageTypeEnum.Message.getCode(), XinGePushBusinessTypeEnum.HomeworkCorrectNotice.getCode(), "作业批改提醒", content, "APP_TEACHER", PushConstants.PUSH_OTHER);
                    }
                } else {
                    logger.error("找不到学生记录，没有推送， vipId={}", vipId);
                }
                logger.info("给机构自批改老师推送提醒，推送结束");
            }
        }
        return addIntegral;
    }

    @Override
    public void sendTempMsg2OnlineTeacher(String teacherId, String childName, Date finishDate, String subject) {
        if (teacherId == null) {
            return;
        }
        //用户记录
     //   User teacher = userService.getById(teacherId);
        //角色记录
        Map<String,Object> kmtTeacher = managerService.findKmtTeacherByUserId(teacherId);
        if ( kmtTeacher != null && StringUtils.isNotBlank((String)kmtTeacher.get("wx_account"))){
            Object teacherName = kmtTeacher.get("name")==null ?kmtTeacher.get("wx_name"):kmtTeacher.get("name");
            Map<String, String> data = new HashMap<String, String>();
            String template_id_short = "OPENTM406811349";
            data.put("first", "尊敬的" + teacherName + "老师，您负责的" + childName + "学生，已经于" + DateUtil.dateTimeToString(finishDate) + "时间完成作业，请您尽快完成作业批改！\n");
            //作业科目
            data.put("keyword1", subject);
            //完成时间
            data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分"));
            data.put("remark", "\n");
            SendTemplateShort sendTemplateShort = new SendTemplateShort(kmtTeacher.get("wx_account").toString(), template_id_short, null, data);
            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
        } else {
            logger.error("老师没有用户记录或者角色记录，没有推送,teacherId={}", teacherId);
        }
    }

    /**
     * 推送给自批改老师
     * @param teacherId
     * @param childName
     * @param finishDate
     * @param subject
     */
    private void sendTempMsg2LibTeacher(String teacherId, String childName, Date finishDate, String subject) {
        if (teacherId == null) return;
        //角色记录
        TbLibManager libTeacher = managerService.findByUserIdAndType(teacherId, 15);
        User user = userService.getById(teacherId);
        if (libTeacher != null && user != null && StringUtils.isNotBlank(user.getAccount())) {
            String teacherName = libTeacher.getName() == null ? user.getName() : libTeacher.getName();
            Map<String, String> data = new HashMap<String, String>();
            String template_id_short = "OPENTM406811349";
            data.put("first", "尊敬的" + teacherName + "老师，您负责的" + childName + "学生，已经于" + DateUtil.dateTimeToString(finishDate) + "时间完成作业，请您尽快完成作业批改！\n");
            //作业科目
            data.put("keyword1", subject);
            //完成时间
            data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分"));
            data.put("remark", "\n");
            SendTemplateShort sendTemplateShort = new SendTemplateShort(user.getAccount(), template_id_short, null, data);
            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
        } else {
            logger.error("老师没有用户记录或者角色记录，没有推送,teacherId={}", teacherId);
        }
    }




    private HomeworkPicture insertHomeworkPicture(String parentId, String homeworkId, String fileKeys, String derver,
                                                  Integer type, String derverFileKey,String vipId,Long currentTime,
                                                  String subject, String homeworkRecordId) {
        HomeworkPicture homeworkPicture = new HomeworkPicture();
        //查询小孩的作业服务(平台，机构，家长)
        homeworkPicture.setServiceType(1);
        homeworkPicture.setParentId(parentId);
        homeworkPicture.setFileKey(fileKeys);
        homeworkPicture.setHomeworkId(homeworkId);
        homeworkPicture.setDerver(derver);
        homeworkPicture.setVipId(vipId);
        homeworkPicture.setHomeworkRecordId(homeworkRecordId);

        if(StringUtils.isBlank(subject)) {
        	subject = "数学";
//        	try {
//                subject = FaceReqUtil.result(fileKeys);
//                homeworkPicture.setSubject(subject);
//            } catch (Exception e) {
//                homeworkPicture.setSubject(subject);
//            }
            homeworkPicture.setSubject(subject);
        }else {
        	homeworkPicture.setSubject(subject);
        }
        homeworkPicture.setGrade(1);
        homeworkPicture.setCommentNums(0);
        homeworkPicture.setCreateTime(new Date());
        homeworkPicture.setIsDelete(0);
        homeworkPicture.setDerverFileKey(derverFileKey);
        homeworkPicture.setIsFeedback(ConchConstants.ISFEEDBACK_NO);
        homeworkPicture.setIsShare(ConchConstants.ISSHARE_NO);

        if (type != null) {
            homeworkPicture.setType(type);
        }

        //如果没有作业吧服务则不分配老师
        int count = libVipServiceService.checkIsZybServiceByVipId(vipId);
        if (count > 0) {
            homeworkPicture.setAllotTime(new Date());
            String homeworkTeacherId = teacherService.getHomeworkTeacherId(vipId, subject);
            homeworkPicture.setTeacherId(homeworkTeacherId);
            if (StringUtils.isNotBlank(homeworkTeacherId)) {
                //更新选定批改老师的实时权重和批改图片总数
                managerService.updateCorrectHomeworkNum(vipId, homeworkTeacherId, 1);
            }
        }
        homeworkPicture = this.save(homeworkPicture);
        if(StringUtils.isNotBlank(homeworkPicture.getTeacherId())){
            //有分配老师则scon_homework_picture_correct插入记录
            HomeworkPictureCorrect homeworkPictureCorrect = new HomeworkPictureCorrect();
            homeworkPictureCorrect.setType(Constant.KMT_122_TEACHER_TYPE);
            homeworkPictureCorrect.setCreateTime(new Date());
            homeworkPictureCorrect.setHomeworkPictureId(homeworkPicture.getId());
            homeworkPictureCorrect.setHomeworkId(homeworkPicture.getHomeworkId());
            homeworkPictureCorrect.setStartTime(null);
            homeworkPictureCorrect.setEndTime(null);
            homeworkPictureCorrect.setAllotTime(homeworkPicture.getAllotTime());
            homeworkPictureCorrectService.save(homeworkPictureCorrect);
        }
        return homeworkPicture;
    }

    /**
     * 插入作业数据
     * @param parentId
     * @param homeworkId
     * @param fileKeys
     * @param derver
     * @param type
     * @param derverFileKey
     * @param vipId
     * @param currentTime
     * @param subject
     * @param homeworkRecordId
     * @param libId 小孩绑定的图书馆
     * @param questionRecommendRecordId
     * @return
     */
    private HomeworkPicture insertHomeworkPictureV1(String parentId, String homeworkId, String fileKeys, String derver,
                                                    Integer type, String derverFileKey, String vipId, Long currentTime,
                                                    String subject, String homeworkRecordId, String libId, String questionRecommendRecordId,String userId) {
        HomeworkPicture homeworkPicture = new HomeworkPicture();
        //查询小孩的作业服务(0无服务，1平台服务(家长购买)，2校区服务，3家长，4平台服务（机构购买），5校区永久批改服务)
        int serviceType = libVipServiceService.getCurrentCorrectService(vipId);
        homeworkPicture.setServiceType(serviceType);
        homeworkPicture.setParentId(parentId);
        homeworkPicture.setFileKey(fileKeys);
        homeworkPicture.setHomeworkId(homeworkId);
        homeworkPicture.setDerver(derver);
        homeworkPicture.setVipId(vipId);
        homeworkPicture.setHomeworkRecordId(homeworkRecordId);

        if (StringUtils.isBlank(subject)) {
            subject = "数学";
//            try {
//                subject = FaceReqUtil.result(fileKeys);
//                homeworkPicture.setSubject(subject);
//            } catch (Exception e) {
//                homeworkPicture.setSubject(subject);
//            }
            homeworkPicture.setSubject(subject);
        } else {
            homeworkPicture.setSubject(subject);
        }
        homeworkPicture.setGrade(1);
        homeworkPicture.setCommentNums(0);
        homeworkPicture.setCreateTime(new Date());
        homeworkPicture.setIsDelete(0);
        homeworkPicture.setDerverFileKey(derverFileKey);
        homeworkPicture.setIsFeedback(ConchConstants.ISFEEDBACK_NO);
        homeworkPicture.setIsShare(ConchConstants.ISSHARE_NO);

        if (type != null) {
            homeworkPicture.setType(type);
        }

        //如果没有相关服务则不分配老师
        if (serviceType > 0) {
            homeworkPicture.setAllotTime(new Date());
            //作业分配老师
            String homeworkTeacherId = null;
            if (serviceType == 1) {
                //这里是平台批改分配老师逻辑
                homeworkTeacherId = teacherService.getHomeworkTeacherId(vipId, subject);

            } else if (serviceType == 2 || serviceType == 5) {
                //图书馆为空无法分配老师，这个可能是小孩未绑定图书馆
                if (StringUtil.isBlank(libId)) {
                    homeworkTeacherId = null;
                } else {
                    //这里是自批改分配老师逻辑
                    //判断是否是管理老师端上传的，然后判断其是否有自批改身份
                    if(1==type){
                        TbLibManager tbLibManager=bookManagerService.findByUserId(userId,15);
                        if(null==tbLibManager){
                            homeworkTeacherId = teacherService.getHomeworkLibTeacherId(vipId, homeworkId, subject);
                        }else {
                            homeworkTeacherId = userId;
                        }
                    }else {
                        homeworkTeacherId = teacherService.getHomeworkLibTeacherId(vipId, homeworkId, subject);
                    }
                }
                homeworkPicture.setIsNeedingKnow(0);
            } else if (serviceType == 3) {
                //这里是家长自批改分配逻辑，作业分配给家长userId
                homeworkTeacherId = vipService.getById(vipId).getUserId();
                homeworkPicture.setIsNeedingKnow(0);
            }
            if (StringUtils.isNotBlank(homeworkTeacherId)) {
                //更新选定批改老师的实时权重和批改图片总数
                managerService.updateCorrectHomeworkNum(vipId, homeworkTeacherId, 1);
            }
            if (StringUtils.isNotBlank(homeworkTeacherId)) {
                //更新选定批改老师的实时权重和批改图片总数
                managerService.updateCorrectHomeworkNum(vipId, homeworkTeacherId, 1);
            }
            homeworkPicture.setTeacherId(homeworkTeacherId);
        }
        homeworkPicture.setQuestionRecommendRecordId(questionRecommendRecordId);
        homeworkPicture = this.save(homeworkPicture);

        if (StringUtils.isNotBlank(homeworkPicture.getTeacherId())) {
            //有分配老师则scon_homework_picture_correct插入记录
            HomeworkPictureCorrect homeworkPictureCorrect = new HomeworkPictureCorrect();
            homeworkPictureCorrect.setType(managerService.findCorrectTeacherType(homeworkPicture.getTeacherId()));
            homeworkPictureCorrect.setCreateTime(new Date());
            homeworkPictureCorrect.setHomeworkPictureId(homeworkPicture.getId());
            homeworkPictureCorrect.setHomeworkId(homeworkPicture.getHomeworkId());
            homeworkPictureCorrect.setStartTime(null);
            homeworkPictureCorrect.setEndTime(null);
            homeworkPictureCorrect.setAllotTime(homeworkPicture.getAllotTime());
            homeworkPictureCorrectService.save(homeworkPictureCorrect);
        }

        return homeworkPicture;
    }

    @Override
    public  String getTeacherId (String vipId, String subject) {
        //通过vip_id和科目判断今天是否上传过相同的科目作业，如果有，则分配的老师为之前随机的
        HomeworkPicture subjectHomeWork = homeworkPictureDao.findTop(vipId, subject);
        String result = null;
        if (subjectHomeWork != null) {
            result = subjectHomeWork.getTeacherId();
        } else {
            Map<String,Object> kmtTeacher = null;
            LibVip vip = vipService.getById(vipId);
            if (vip != null && StringUtils.isNotBlank((vip.getGrade()))){
                kmtTeacher = managerService.findRandomByCourseNameAndGrade(subject, vip.getGrade());
                if (kmtTeacher == null) {
                    kmtTeacher = managerService.findRandomByCourseName(subject);
                }
            } else {
                //自动随机分配该科目对应的一名老师
                kmtTeacher = managerService.findRandomByCourseName(subject);
            }

            if(kmtTeacher != null) {
               result = kmtTeacher.get("user_id").toString();
            }
        }
        logger.info("学生id={},科目={}, 分配老师id={}", vipId, subject, result);
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public HomeworkPicture findStudentSubjectHomework(String vipId, String subject) {
        return homeworkPictureDao.findTop(vipId, subject);
    }

    @Override
    public void deleteHomework(DeleteHomeworkRequest request) {
        // TODO Auto-generated method stub
        homeworkPictureDao.updatePictureAsDelete(request.getHomeworkId());

    }

    @Override
    public HomeworkFeedback findHomeworkInfo(FindHomeworkRequest request, String userId, String userType) {

        HomeworkFeedback homeworkFeedback = new HomeworkFeedback();
        String parentId = null;
        //1:孩子 2:家长
        if ("2".equals(userType)) {
            parentId = userId;
        } else if ("1".equals(userType)) {
            //通过孩子的userId获取家长的userId
            parentId = conchDerverService.findByChildUserId(userId).getUserId();
        }

        HomeworkPicture homeworkPicture = this.getById(request.getHomeworkId());
        TeacherFeedback teacherFeedback = feedbackService.getHomeworkFeedback(homeworkPicture);
        homeworkFeedback.setTeacherFeedback(teacherFeedback);

        homeworkFeedback.setFileKey(homeworkPicture.getFileKey());
        homeworkFeedback.setParentId(parentId);
        homeworkFeedback.setIsShare(homeworkPicture.getIsShare());
        homeworkFeedback.setHomeworkId(homeworkPicture.getId());
        return homeworkFeedback;
    }

    @Override
    public Map<String, Object> searchToFeedbackHomeworkList(Map<String, Object> params, Pageable pageable, List<String> pids) {

        List<User> userlist = userService.findByIdIn(pids);
        Map<String, SearchFilter> filters = SearchFilter.parse(params);
        Specification<HomeworkPicture> specification = DynamicSpecifications.bySearchFilter(filters.values(),
                HomeworkPicture.class);
        List<ToFeedBack> list = new ArrayList<ToFeedBack>();
        Map<String, User> userInfoMap = userlist.stream().collect(Collectors.toMap(User::getId,
                n -> n));

        Page<HomeworkPicture> page = homeworkPictureDao.findAll(specification, pageable);
        if (page != null && page.getSize() > 0) {
            for (HomeworkPicture homeworkPicture : page.getContent()) {
                ToFeedBack toFeedBack = new ToFeedBack();
                toFeedBack.setBizId(homeworkPicture.getId());
                toFeedBack.setBizType(ConchConstants.BIZ_TYPE_HOMEWORK);
                toFeedBack.setFileKey(homeworkPicture.getFileKey());
                toFeedBack.setIsFeedback(homeworkPicture.getIsFeedback());
                toFeedBack.setParentId(homeworkPicture.getParentId());
                User sconUserInfo = userInfoMap.get(homeworkPicture.getParentId());
                if (sconUserInfo != null) {
                    toFeedBack.setStudentNickname(sconUserInfo.getUserName());
                    toFeedBack.setStudentImageKey(sconUserInfo.getPhoto());
                }
                toFeedBack.setClassifyTime(homeworkPicture.getCreateTime());
                list.add(toFeedBack);
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("pages", page.getTotalElements());
        data.put("list", list);
        data.put("pageSize", pageable.getPageSize());
        data.put("pageNo", pageable.getPageNumber() + 1);
        return data;
    }

    @Override
    public Map<String, Object> searchHomeworkListByParentIdForTeacher(String parentId, Map<String, Object> params,
                                                                      Pageable pageable) {
        // TODO Auto-generated method stub
        User userInfo = userService.getById(parentId);
        Map<String, SearchFilter> filters = SearchFilter.parse(params);
        Specification<HomeworkPicture> specification = DynamicSpecifications.bySearchFilter(filters.values(),
                HomeworkPicture.class);
        List<ToFeedBack> list = new ArrayList<ToFeedBack>();

        Page<HomeworkPicture> page = homeworkPictureDao.findAll(specification, pageable);
        if (page != null && page.getSize() > 0) {
            for (HomeworkPicture homeworkPicture : page.getContent()) {
                ToFeedBack toFeedBack = new ToFeedBack();
                toFeedBack.setBizId(homeworkPicture.getId());
                toFeedBack.setBizType(ConchConstants.BIZ_TYPE_HOMEWORK);
                toFeedBack.setFileKey(homeworkPicture.getFileKey());
                toFeedBack.setIsFeedback(homeworkPicture.getIsFeedback());
                toFeedBack.setStudentNickname(userInfo.getUserName());
                toFeedBack.setStudentImageKey(userInfo.getPhoto());
                toFeedBack.setClassifyTime(homeworkPicture.getCreateTime());
                toFeedBack.setParentId(homeworkPicture.getParentId());
                list.add(toFeedBack);
            }
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("pages", page.getTotalElements());
        data.put("list", list);
        data.put("pageSize", pageable.getPageSize());
        data.put("pageNo", pageable.getPageNumber() + 1);
        return data;

    }

    @Override
    public Map<String, Object> searchHomeworkList(Map<String, Object> params, Pageable pageable) {
        // TODO Auto-generated method stub
        Map<String, SearchFilter> filters = SearchFilter.parse(params);
        Specification<HomeworkPicture> specification = DynamicSpecifications.bySearchFilter(filters.values(),
                HomeworkPicture.class);

        Page<HomeworkPicture> page = homeworkPictureDao.findAll(specification, pageable);

        List<HomeworkExt> extList = new ArrayList<>();
      //  List<String> problemIds = new ArrayList<String>();
        if (page.getSize() > 0) {
            for (HomeworkPicture homeworkPicture : page.getContent()) {
                HomeworkExt ext = new HomeworkExt();
                ext.setCreateTime(homeworkPicture.getCreateTime());
                ext.setParentId(homeworkPicture.getParentId());
                ext.setFileKey(homeworkPicture.getFileKey());
                ext.setIsFeedback(homeworkPicture.getIsFeedback());
                ext.setHomeworkId(homeworkPicture.getId());
                ext.setWeekday(DateUtil.getWeekDateToStr(homeworkPicture.getCreateTime()));
                extList.add(ext);
              //  problemIds.add(homeworkPicture.getId());
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("pages", page.getTotalElements());
        data.put("list", extList);
        data.put("pageSize", pageable.getPageSize());
        data.put("pageNo", pageable.getPageNumber() + 1);
        return data;
    }

//    @Override
//    public HomeworkFeedbackForTeacher findHomeworkInfoForTeacher(String userId,FindHomeworkRequest request) {
//        HomeworkPicture homeworkPicture = this.getById(request.getHomeworkId());
//        TeacherFeedback teacherFeedback = feedbackService.getHomeworkFeedback(homeworkPicture.getParentId(),userId,
//                                                                          ConchConstants.BIZ_TYPE_HOMEWORK,
//                                                                          request.getHomeworkId());
//
//        HomeworkFeedbackForTeacher homeworkFeedbackForTeacher = new HomeworkFeedbackForTeacher();
//        homeworkFeedbackForTeacher.setFileKey(homeworkPicture.getFileKey());
//        homeworkFeedbackForTeacher.setParentId(homeworkPicture.getParentId());
//        homeworkFeedbackForTeacher.setHomeworkId(request.getHomeworkId());
//        homeworkFeedbackForTeacher.setTeacherFeedback(teacherFeedback);
//        homeworkFeedbackForTeacher.setCreatTime(homeworkPicture.getCreateTime());
//        return homeworkFeedbackForTeacher;
//    }

    @Override
    public HomeworkFeedback queryHomeworkFeedbackByHomeworkId(String parentId, String homeworkId) {
        HomeworkFeedback homeworkFeedback = new HomeworkFeedback();
        HomeworkPicture picture = this.getById(homeworkId);
        TeacherFeedback teacherFeedback = feedbackService.getHomeworkFeedback(picture);

        homeworkFeedback.setTeacherFeedback(teacherFeedback);

        homeworkFeedback.setFileKey(picture.getFileKey());
        homeworkFeedback.setParentId(parentId);
        homeworkFeedback.setHomeworkId(picture.getId());
        homeworkFeedback.setIsShare(picture.getIsShare());
        return homeworkFeedback;
    }

    @Override
    public void delZybWorkPic(String id) {

        homeworkPictureDao.delZybWorkPic(id);
    }

    @Override
    public long countByTeacherIdAndIsFeedback(String userId, int i) {

        return homeworkPictureDao.countByTeacherIdAndIsFeedback(userId, i);
    }

    @Override
    public void updateStat(String zybworkId) {
        homeworkPictureDao.updateStat(zybworkId);
    }

    @Override
    public List<HomeworkPicture> findTodayHomeworkPictureByIsFeedbackAndLibIds(int isFeedback, List<String> libIds) {
        return homeworkPictureDao.findByIsFeedbackAndLibIdInAndCreateTimeAfterOrderByCreateTimeAsc(isFeedback, libIds);
    }

    @Override
    public List<HomeworkPicture> findTodayNotFeedbackByMasterId(List<String> libIds) {
        return homeworkPictureDao.findTodayNotFeebackHomeworkByMaster(0, libIds);
    }

    @Override
    public List<HomeworkPicture> queryHomeworkPictureByHomeworkId(String homeworkId) {
        return homeworkPictureDao.queryHomeworkPictureByHomeworkId(homeworkId);
    }

    @Override
    public List<Map<String, Object>> queryTodayhomeworkRecord(String derver, String today, String tomorrow) {
        return homeworkPictureQueryDao.queryTodayhomeworkRecord(derver, today, tomorrow);
    }

    @Override
    public HomeworkPicture findLastHomeworkPicture (String teacherId, String vipId) {
        return homeworkPictureDao.findFirstByTeacherIdAndVipIdOrderByCreateTimeDesc(teacherId, vipId);
    }

    @Override
    public List<String> findZybWorkIdByHomeworkRecord(String derver, String subject, String today, String tomorrow) {
        return homeworkPictureDao.findZybWorkIdByHomeworkRecord(derver, subject, today, tomorrow);
    }

    @Override
    public List<HomeworkPicture> findSortById (String subject, String beginTime, String endTime, String vipId){
        return homeworkPictureDao.findSortById(subject,beginTime, endTime, vipId);
    }

    @Override
    public void deleteByVipId (String vipId){
         homeworkPictureDao.deleteByVipId( vipId);
    }

    @Override
    public boolean canPush(String vipId, Date date) {
        boolean result = false;
        List<HomeworkPicture> list = homeworkPictureDao.findDateNotFeedback(vipId, DateUtil.format_yyyyMMdd(date));
        if (list == null || list.size() == 0){
            ZuoybStudentPush push = zuoybStudentPushSerivce.findByVipIdAndDate(vipId, DateUtil.format_yyyyMMddHHmmss(date));
            if (push == null) {
                push = new ZuoybStudentPush();
                push.setType(4);
                push.setVipId(vipId);
                push.setPushTime(date);
                push.setCourseHour("A");
                List<LibVipService> libVipServices= libVipServiceService.getByVipIdAndSpecies(vipId, "S003");
                if (libVipServices != null && libVipServices.size() > 0){
                    push.setLibId(libVipServices.get(0).getLibId());
                }
                zuoybStudentPushSerivce.save(push);
            } else if (push.getType() != 2){
                result = true;
            }
        }
        return result;
    }

    @Override
    public boolean isSubjectFinishedAndNotPush (String vipId, String subject, Date date){
        boolean result = true;
        List<HomeworkPicture> list = homeworkPictureDao.findDateNotFeedbackAndNotPushHomework(vipId, subject, DateUtil.format_yyyyMMdd(date));
        if (list != null && list.size() > 0){
            result = false;
        }
        return result;
    }


    @Override
    public HomeworkPicture setFeedBack(String pid, String zybworkId) {
        HomeworkPicture result = this.getById(pid);
        result.setIsFeedback(1);
        if (StringUtils.isNotEmpty(zybworkId)) {
            result.setZybWorkId(zybworkId);
        }
        this.save(result);//设置为已批改
        return result;
    }

    @Override
    public void pushCorrect2Conch(String derver,String vipId) {
        if (StringUtils.isNotEmpty(derver) && !"1".equals(derver)) {
            Map<String, Object> conchMap = new HashMap<String, Object>();
            conchMap.put("type", "FEEDBACK_HOMEWORK");
            conchMap.put("time", new Date());
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("content", "您的作业有老师批改啦,请在作业记录中查看!");
            conchMap.put("data", map2);
            
            String content = JSON.toJSONString(conchMap);
            //推送贝壳
            sconXingeService.asynPushThreadTask(derver,vipId,1,content,PushConstants.PUSH_OTHER);
        }
    }

    @Override
    public void pushCorrect2ParentAccount(String vipId, Date date) {
        ZuoybStudentPush push = zuoybStudentPushSerivce.findByVipIdAndDate(vipId, DateUtil.format_yyyyMMdd(date));
        //在馆老师已完成编辑提交的，这里推送
        if (push.getType() == 3) {
            zuoybDayService.saveToday(vipId, 1, DateUtil.format_yyyyMMdd(push.getPushTime()));
            logger.info("zyb_day更新type为2");
            this.push2Parent(push, vipId, 2);
        } else if (push.getType() == 2) {
            logger.info("已经推送过一次, 不再推送");
//            this.push2Parent(push, vipId, teacherId);
        } else {
            //线上批改已完成
            push.setType(4);
            push.setUpdateTime(new Date());
            zuoybStudentPushSerivce.save(push);
        }
    }

    /**
     * 没有签到记录的学生学科批改完之后要推送家长app
     * @param vipId
     * @param subject
     * @param date
     */
    @Override
    public void subjectFinishPushParent(String vipId, String subject, Date date, Date correctTime) {
        TbLibSubscribe ls = libSubscribeService.findTheDayByVipId(vipId, date);
        //没有签到记录
        if (StringUtils.isNotBlank(vipId) && ls == null) {
            LibVip vip = vipService.getById(vipId);
            if (vip != null) {
                StringBuilder sb = new StringBuilder();
                sb.append("尊敬的").append(vip.getChildName()).append("家长，");
                sb.append("老师已经完成您孩子").append(subject).append("科目批改，请及时查看老师对").append(vip.getChildName()).append("的批改结果。");
                sconXingeService.asynPushThreadTask(vip.getUserId(), null, 2 , sb.toString(),PushConstants.PUSH_HOMEWORK);
                User parent = userService.getById(vip.getUserId());
                if (parent != null) {
                    this.pushToParentByWx(parent.getAccount(), vip.getChildName(), subject, correctTime);
                }
            }
        }
    }

    /**
     * 学科批改结束推送贝壳端, 如果作业不是贝壳的作业是不会推送的
     * @param derver
     * @param homeworkIds
     */
    @Override
    public void subjectFinishPushDerver (String derver,String vipId, List<String> homeworkIds){
        if (StringUtils.isNotBlank(derver) && homeworkIds != null && homeworkIds.size() > 0){
            List<HomeworkFeedbackVO4> list = new ArrayList<>();
            homeworkIds.forEach(id -> {
                HomeworkFeedbackVO4 content = conchDerverService.homeworkFeedbackDetails4(id, 0);
                if (content != null) {
                    list.add(content);
                }
            });
            if (!list.isEmpty()) {
                Map<String, Object> dataMap = new HashMap<>();
                Map<String, Object> result = new HashMap<>();
                dataMap.put("list", list);
                result.put("type", "FEEDBACK_HOMEWORK");
                result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
                result.put("data", dataMap);
                sconXingeService.asynPushThreadTask(derver,vipId,1,JSON.toJSONString(result),PushConstants.PUSH_OTHER);
            }
        }
    }

    /**
     * 批改结束推送三科到贝壳端
     * @param hwList
     */
    @Override
    public void correctFinishPushDerver (List<Homework> hwList,String vipId){
        if (hwList != null && hwList.size() > 0) {
            List<String> homeworkIds = hwList.stream().map(Homework :: getId).collect(Collectors.toList());
            this.subjectFinishPushDerver(hwList.get(0).getDerver(),vipId, homeworkIds);
        }
    }

    @Override
    public void push2Parent(ZuoybStudentPush push, String vipId, int newType) {
        LibVip vip = vipService.getById(vipId);
        //设置已推送转态
        push.setType(newType);
        push.setUpdateTime(new Date());
        push = zuoybStudentPushSerivce.save(push);

        logger.info("zyb_student_push更新reportType为2，已推送");
        //推送给家长
        StringBuffer sb = new StringBuffer();
        sb.append("尊敬的").append(vip.getChildName()).append("家长，您孩子今日的作业反馈报告已生成");
        try {
            //推送家长app
            sconXingeService.asynPushThreadTask(vip.getUserId(), null ,2 , sb.toString(), PushConstants.PUSH_HOMEWORK);
            //推送小程序
            this.sendTemplateTeacher(userService.getAccount(vip.getUserId()),
                    vip.getChildName(), WxUtil.map.get("jzdAppId"),vip.getId(), push.getPushTime());
            //推送馆长
//            if (StringUtils.isNotBlank(push.getLibId())){
//                zuoybStudentWorkService.sendHomeworkReport2LibManager(push.getLibId(),  vip.getChildName(),  push.getId(),WxUtil.map.get("lsdAppId"));
//            }
            //合作馆会推送指定的16个老师
//            zuoybStudentWorkService.sendTemplate2CooperateLibTeacher(vipId, vip.getChildName(),  push.getId(), WxUtil.map.get("lsdAppId"));
        }catch (Exception e) {
            logger.error("小程序推送失败，异常信息：", e);
        }
    }

    @Override
    public void push2LibTeacher (String vipId,String subject){
        ZuoybStudentPush push = zuoybStudentPushSerivce.findByVipIdToDay(vipId);

        if (push != null && StringUtils.isNotBlank(push.getTeacherId())){
            Map<String, String> data = new HashMap<String, String>();
            String template_id_short = "OPENTM414077970";
            try{
                LibVip vip = vipService.getById(vipId);
                String teacherName = null;
                User teacher = userService.getById(push.getTeacherId());
                TbLibManager libTeacher = managerService.findByUserId(push.getTeacherId(), Constant.TEACHER_TYPE);
                teacherName = libTeacher.getName();
                if (StringUtils.isEmpty(teacherName)){
                    teacherName = teacher.getName();
                }

                int count = homeworkPictureDao.countByVipIdAndSubjectOfToday(vipId,subject);
                String context = "尊敬的" + teacherName + "老师，您收到一则" + vip.getChildName() + "学生的"+subject+"作业批改成果，请及时查看\n";
                data.put("first", context);
                data.put("keyword1", DateHelper.format(new Date(), "yyyy/MM/dd"));
                data.put("keyword2", count + "");
                data.put("remark", "\n我们和每一个学员将衷心感谢您的付出！");
                Miniprogram miniprogram = new Miniprogram();
                miniprogram.setAppid(WxUtil.map.get("lsdAppId"));
                SendTemplateShort sendTemplateShort = new SendTemplateShort(teacher.getAccount(), template_id_short, null, data);
                pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
                logger.info("推送在馆老师:"+context);
            } catch (Exception e){
                logger.error("推送在馆老师失败：", e);
            }
        }
    }

    @Override
    public void push2LibTeacher4VagueImg (HomeworkPicture p) {
        ZuoybStudentPush push = zuoybStudentPushSerivce.findByVipIdToDay(p.getVipId());

        if (push == null || StringUtils.isBlank(push.getTeacherId())){
            logger.info("在zybstudentpush表里没有在馆记录，不用推送");
            return;
        }
        Map<String, String> data = new HashMap<String, String>();
        String template_id_short = "OPENTM414077970";

        try{
            LibVip vip = vipService.getById(p.getVipId());
            String teacherName = null;
            User teacher = userService.getById(push.getTeacherId());
            TbLibManager libTeacher = managerService.findByUserId(push.getTeacherId(), Constant.TEACHER_TYPE);
            teacherName = libTeacher.getName();
            if (StringUtils.isEmpty(teacherName)){
                teacherName = teacher.getName();
            }
            
            if(p.getIsMark()==1){
            	data.put("first", teacherName + "老师你好，您收到" + vip.getChildName() + "学生的模糊拍照，请尽快重新拍照上传!\n");
            	data.put("remark", "批改状态：图片模糊\n\n我们和每一个学员将衷心感谢您的付出！");
            }else{
            	data.put("first", teacherName + "老师你好，您收到" + vip.getChildName() + "学生的作业不全拍照，请尽快重新拍照上传!\n");
            	data.put("remark", "批改状态：图片作业不全\n\n我们和每一个学员将衷心感谢您的付出！");
            }
            data.put("keyword1", DateHelper.format(new Date(), "yyyy/MM/dd"));
        	data.put("keyword2", "1");
            
            SendTemplateShort sendTemplateShort = new SendTemplateShort(teacher.getAccount(), template_id_short, null, data);
            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
            logger.info("推送在馆老师成功");
        } catch (Exception e){
            logger.error("推送在馆老师失败：" + e);
        }
    }

    @Override
    public void pushOnlineTeacher (HomeworkPicture p) {
        this.pushOnlineTeacherPublic(p, 1);
    }

    @Override
    public void pushOnlineTeacher(HomeworkPicture p, int num) {
        this.pushOnlineTeacherPublic(p, num);
    }

    private void pushOnlineTeacherPublic(HomeworkPicture p, int num){
        if(StringUtils.isNotBlank(p.getTeacherId())) {
            Map<String, String> data = new HashMap<>();
            String template_id_short = "OPENTM414077970";
            try {
                LibVip vip = vipService.getById(p.getVipId());
                String teacherName = null;
                User teacher = userService.getById(p.getTeacherId());
                TbLibManager libTeacher = managerService.findByUserId(p.getTeacherId(), Constant.KMT_122_TEACHER_TYPE);
                if (libTeacher != null){
                    teacherName = libTeacher.getName();
                    if (StringUtils.isEmpty(teacherName)) {
                        teacherName = teacher.getName();
                    }
                    data.put("first", teacherName + "老师您好，您收到" + vip.getChildName() + "学生纠正过来的作业，请尽快批改!\n");
                    data.put("keyword1", DateHelper.format(new Date(), "yyyy/MM/dd"));
                    data.put("keyword2", String.valueOf(num));
                    data.put("remark", "批改状态：纠正学科\n\n我们和每一个学员将衷心感谢您的付出！");
                    SendTemplateShort sendTemplateShort = new SendTemplateShort(teacher.getAccount(), template_id_short, null, data);
                    pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
                    logger.info("推送线上老师成功");
                }
            } catch (Exception e){
                logger.error("推送线上老师失败：" + e);
            }
        }
    }


    @Override
    public int isSubHomeWorkPic(String zybWorkId) {
        return homeworkPictureDao.isSubHomeWorkPic(zybWorkId);
    }

    @Override
    public int getNotFeedbackCount(String teacherId, String beginDateTimeStr, String endDateTimeStr){
        return homeworkPictureDao.countByTeacherIdNotFeedback(teacherId, beginDateTimeStr, endDateTimeStr);
    }

    @Override
    public void sendMsg4SubmitWork(String vipId, String teacherId) {
       /* int count = homeworkPictureDao.countByVipIdOfToday(vipId);
        int notCorrectCount = homeworkPictureDao.countByTeacherIdNotFeedback(teacherId);
        LibVip vip = vipService.getById(vipId);
        JSONObject data = new JSONObject();
        data.put("type", 1);
        if (count  > 0){
            data.put("workCount", notCorrectCount);
            data.put("isNew", false);
            data.put("msg", vip.getChildName() + "同学又上传作业啦,快点帮他批改！");
        } else {
            data.put("workCount", notCorrectCount);
            data.put("isNew", true);
            data.put("msg", vip.getChildName() + "同学已上传作业,快点帮他批改！");
        }

        logger.info("推送的内容：" + data);
//        webSocketHandler.sendMessageToUser(teacherId, new TextMessage(data.toString()));
        logger.info("已推送给在线老师客户端");*/
    }

    @Override
    @Transactional
    public void recordBeginTime(String pid) {
        HomeworkPictureCorrect record = homeworkPictureCorrectService.findByHomeworkPictureIdAndType(pid,8);
        if (record == null){
            record = new HomeworkPictureCorrect();

            record.setHomeworkPictureId(pid);
        }
        record.setStartTime(new Date());
        homeworkPictureCorrectService.save(record);
    }

    @Override
    public int recordEndTime(String pid) {
        HomeworkPictureCorrect record = homeworkPictureCorrectService.findByHomeworkPictureIdAndType(pid,8);
        Date endTime = new Date();
        int result = 0;
        if (record != null) {
            record.setEndTime(endTime);
            homeworkPictureCorrectService.save(record);
            result = (int)((endTime.getTime() - record.getStartTime().getTime()) / 1000);
        }

        return result;
    }

	@Override
	public HomeworkPicture findByFileKeyAndVipAndSubject(String fileKey, String vipId, String courseName) {
		
		return homeworkPictureDao.findByFileKeyAndVipAndSubject(fileKey,vipId,courseName);
	}

	@Override
	public void delZybWorkPic(String vipId, String fileKey) {
		homeworkPictureDao.delZybWorkPic(vipId,fileKey);

	}
	
	public void sendTemplateTeacher(String openId, String name, String appId,String vipId, Date workDate) {
		if(openId!=null){
			Map<String,String> data =new HashMap<String, String>();
			data.put("first", "尊敬的" + name +  "家长，您孩子今日的作业反馈报告已生成\n");
			data.put("keyword1",name);
			data.put("keyword2", "作业吧");
			data.put("keyword3", DateHelper.format(workDate,"yyyy年MM月dd日"));
			data.put("remark", "\n快来看看老师对宝贝作业的反馈吧!");
			String template_id=(String) SystemResourceLocator.getValue("sendTemplate55");
			Miniprogram miniprogram =new  Miniprogram();
			miniprogram.setAppid(appId);
			miniprogram.setPagepath("pages/homework_report/homework_report?type=8&vipId="+vipId+"&date="+DateHelper.format(workDate,"yyyy-MM-dd"));
			SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id, null, data, miniprogram);
			pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
		}
	}

    @Override
    public String getZybWorkId(String pid) {
        HomeworkPicture p  = this.getById(pid);
        String result = null;
        if (StringUtils.isNotEmpty(p.getZybWorkId())){
            result = p.getZybWorkId();
        } else {
            ZuoybStudentWork work = zuoybStudentWorkService.saveZybStudentWork(p.getVipId(), p.getTeacherId(), p.getSubject(), 2);
            result = work.getId();
            p.setZybWorkId(result);
            this.save(p);
        }
        return result;
    }

    @Override
    public void recordZybLearningSituation(String vipId, String data) {
        try{
            JSONArray array = JSONArray.parseArray(data);
            JSONArray howDetailIds = null;
            Map<String, Integer> result = new HashMap<>();
            Integer countTemp = null;
            //计算每个知识点的错题数，放入result 中
            for (Object object : array) {
                JSONObject obj = (JSONObject) object;
                howDetailIds = obj.getJSONArray("how_details_id");
                for (Object detailId : howDetailIds){
                    countTemp = result.get(detailId.toString());
                    if (countTemp == null){
                        result.put(detailId.toString(), 1);
                    } else {
                        result.put(detailId.toString(), countTemp++);
                    }
                }
            }

            //循环调用接口
            if(result.size() > 0){
                for (String howDetailId : result.keySet()){
                    libVipDocService.saveZuoybDocByVipId(vipId, howDetailId, result.get(howDetailId));
                }
            }
        } catch (Exception e){
            logger.error("调用稳哥接口异常", e);
        }
    }

	@Override
	public Page<HomeworkPicture> findAll(Specification<HomeworkPicture> specification, Pageable page) {
		return homeworkPictureDao.findAll(specification, page);
	}

    @Override
    public List<HomeworkPicture> findHomeworkPictureByHomeworkIds(List<String> homeworkIds) {
        return homeworkPictureDao.findByHomeworkIdIn(homeworkIds);
    }

    @Override
    public List<HomeworkPicture> findTodayNotFeedbackHomeworkPicture(String teacherId) {
        return homeworkPictureDao.findByIsDeleteAndIsFeedbackAndTeacherId(0, 0, teacherId);
    }

    @Override
    public ResponseEntity saveNoWrong (String homeworkPictureId, String userId, String data){
        ResponseEntity responseEntity = new ResponseEntity();
        logger.info("没有错题的pictureId:" + homeworkPictureId);
        try {
            HomeworkPicture homeworkPicture = this.getById(homeworkPictureId);
            if (homeworkPicture.getIsFeedback() == 1) {
                logger.warn("作业已批改，不能重复批改");
                responseEntity.success(ResponseConstant.CODE_999, "作业已批改，不能重复批改");
                return responseEntity;
            }
            this.recordEndTime(homeworkPictureId);  //保存批改完成的时间

            homeworkPicture.setIsFeedback(1);
            homeworkPicture = this.save(homeworkPicture);//已批改
            logger.info("保存后的homeworkPicture={}", JSON.toJSON(homeworkPicture));
            Thread.sleep(1000);

            //保存作业关联的知识点
            zuoybKnowHowService.saveWorkRelateKnowHow(data, homeworkPicture.getHomeworkId());

            //需要通知前端是否该学员的作业都已经批改完
            boolean isFinish = false;
            String vipId = homeworkPicture.getVipId();
            if (this.isSubjectFinishedAndNotPush(vipId, homeworkPicture.getSubject(), homeworkPicture.getCreateTime())){
                homeworkService.correctFinishRecord(vipId, homeworkPicture.getSubject(), new Date());
                Homework homework = homeworkService.getById(homeworkPicture.getHomeworkId());
                this.subjectFinishPushParent(vipId, homeworkPicture.getSubject(), homeworkPicture.getCreateTime(), homework.getCorrectTime());
                this.subjectFinishPushDerver(homeworkPicture.getDerver(),homeworkPicture.getVipId(), Arrays.asList(homeworkPicture.getHomeworkId()));
            }
            logger.info("保存记录后的homeworkPicture={}", JSON.toJSON(homeworkPicture));

            if (this.canPush(vipId, homeworkPicture.getCreateTime())) {//XinGePushUtils
                isFinish = true;
                //信鸽推送 作业批改提醒
                //推送家长公众号
                this.pushCorrect2ParentAccount(vipId, homeworkPicture.getCreateTime());
                //推送爸妈说到小塾
                this.pushCorrect2Conch(homeworkPicture.getDerver(),homeworkPicture.getVipId());
                //推送在馆老师
                this.push2LibTeacher(homeworkPicture.getVipId(),homeworkPicture.getSubject());
            }

            //没有错题也要推送家长作业反馈
            responseEntity.success(isFinish, "操作成功");
        } catch (Exception e) {
            logger.error("没有错题异常", e);
            responseEntity.failure("查询异常");
        }
        return responseEntity;
    }

    @Override
    public ResponseEntity saveCorrectResult (String homeworkPictureId, String userId, String vipId, String data) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            HomeworkPicture homeworkPicture = this.getById(homeworkPictureId);
            if (homeworkPicture.getIsFeedback() == 1) {
                logger.warn("作业已批改，不能重复批改");
                responseEntity.success(ResponseConstant.CODE_000, "作业已批改，不能重复批改");
                return responseEntity;
            }
            //调用稳哥的接口保存学情数据
            this.recordZybLearningSituation(vipId, data);

            this.recordEndTime(homeworkPictureId);  //保存批改完成的时间
            if (StringUtils.isNotEmpty(data)) {//保存批改的错题信息
                zuoybKnowHowService.saveCorrectResult(data, homeworkPicture);
            }
            //推送小塾     ----    收到作业批改，点击查看
            homeworkPicture.setIsFeedback(1); //设为已反馈
            this.save(homeworkPicture);
            logger.info("homeworkpicture表已更新feedback字段和zyb_work_id");
            Thread.sleep(1000);

            if (this.isSubjectFinishedAndNotPush(vipId, homeworkPicture.getSubject(), homeworkPicture.getCreateTime())){
                homeworkService.correctFinishRecord(vipId, homeworkPicture.getSubject(), new Date());
                Homework homework = homeworkService.getById(homeworkPicture.getHomeworkId());
                this.subjectFinishPushParent(vipId, homeworkPicture.getSubject(), homeworkPicture.getCreateTime(), homework.getCorrectTime());
                this.subjectFinishPushDerver(homeworkPicture.getDerver(), homeworkPicture.getVipId(),Arrays.asList(homeworkPicture.getHomeworkId()));
            }

            if (this.canPush(vipId, homeworkPicture.getCreateTime())) {//XinGePushUtils
                logger.info("学生vip_id("+ vipId + ")的作业已全部批改完");
                //信鸽推送 作业批改提醒
                //推送家长公众号
                this.pushCorrect2ParentAccount(vipId, homeworkPicture.getCreateTime());
                //推送爸妈说到小塾
                this.pushCorrect2Conch(homeworkPicture.getDerver(),homeworkPicture.getVipId());
                logger.info("推送小塾成功, derver为1是作业吧的数据， derver=" + homeworkPicture.getDerver());
                //推送在馆老师
                this.push2LibTeacher(homeworkPicture.getVipId(),homeworkPicture.getSubject());

            } else {
                logger.info("学生vip_id("+ vipId + ")的作业未完全批改完");
            }
            responseEntity.success("批改成功");
        } catch (Exception e) {
            logger.error("异常信息", e);
            responseEntity.failure("查询异常");
        }
        return responseEntity;
    }

	@Override
	public List<AiVipIdsModel> findHomeworkPictureByVipIds(String[] vipIds,String date) {
		return homeworkPictureQueryDao.findHomeworkPictureByVipIds(vipIds, date);
	}

    @Override
    public List<HomeworkPicture> findDerverPictureByWorkId(String homeworkId) {
        return homeworkPictureDao.findByHomeworkIdAndDerverFileKeyIsNotNull(homeworkId);
    }

    @Override
    public void updateTodayHomeworkTeacherId(String teacherId) {
        List<HomeworkPicture> list = homeworkPictureDao.findTodayNotFeedbackHomeworkPicture();
        List<HomeworkPicture> yesList = homeworkPictureDao.findDateNotFeedbackHomeworkPicture(DateUtil.format_yyyyMMdd(DateUtil.addDays(new Date(), -1)));
        list.addAll(yesList);
        if (list != null) {
            list.forEach(hp -> {
                hp.setTeacherId(teacherId);
            });
            this.save(list);
        }
    }

    @Override
    public List<HomeworkPicture> findAllByHomeworkId(String homeworkId) {
        return homeworkPictureDao.queryHomeworkPictureByHomeworkId(homeworkId);
    }

    @Override
    public Integer countByVipIdAndIsMark(String studentId) {
        return homeworkPictureDao.countByVipIdAndIsMark(studentId, 1);
    }

    @Override
    public Integer countTodayByVipId(String studentId) {
        return homeworkPictureDao.countTodayByVipId(studentId);
    }

    @Override
    public List<Map<String, Object>> findTeacherCorrectList(String teacherId, String date) {
        return homeworkPictureQueryDao.findTeacherCorrectList(teacherId, date);
    }

    @Override
    public ResponseEntity replaceVagueImgAndPushConch(HomeworkPicture homeworkPicture, String fileKey, String derverFileId) {
        this.push2conch4vagueImgCorrected(homeworkPicture, fileKey);
        return this.replaceVagueImg(homeworkPicture, fileKey, derverFileId);
    }

    @Override
    public ResponseEntity replaceVagueImg(HomeworkPicture homeworkPicture, String fileKey,String derverFileId) {
        ResponseEntity responseEntity = new ResponseEntity();
        if (homeworkPicture == null) {
            responseEntity.failure("该图片不存在");
        } else {
            if (!Objects.equals(homeworkPicture.getIsMark(), 1) && !Objects.equals(homeworkPicture.getIsMark(), 3)) {
                return responseEntity.failure("此图片不是模糊图片或作业不全，不需要更换");
            }
            logger.info("模糊替换前的数据={}", JSON.toJSONString(homeworkPicture));
            int serviceType = homeworkPicture.getServiceType();
            //更换图片
            homeworkPicture.setIsMark(2);
            homeworkPicture.setFileKey(fileKey);
//            homeworkPicture.setDerverFileKey(derverFileId);
            homeworkPicture.setIsCorrect(0);
            Date finishDate = new Date();
            homeworkPicture.setCreateTime(finishDate);
            //模糊更替更新allotTime
            homeworkPicture.setAllotTime(finishDate);
            homeworkPicture.setIsCheckError(0);
            homeworkPicture.setCheckDate(null);
            homeworkPicture.setChecker(null);
            homeworkPicture.setErrorReason(null);
            int teacherType = 8;
            if (Objects.equals(serviceType, 2)) {
                //homeworkPicture.setDerver(null);
                teacherType = Constant.LIB_TEACHER_TYPE;
            }
            homeworkPicture = this.save(homeworkPicture);
            //请求ai识别图片
            picturePreDealService.asyncPostRequest2AI(homeworkPicture);
            //清除模糊的开始结束时间
            HomeworkPictureCorrect homeworkPictureCorrect =  homeworkPictureCorrectService.findByHomeworkPictureIdAndType(homeworkPicture.getId(), teacherType);
            homeworkPictureCorrect.setAllotTime(finishDate);
            homeworkPictureCorrect.setStartTime(null);
            homeworkPictureCorrect.setEndTime(null);
            homeworkPictureCorrect.setCheckEndTime(null);
            homeworkPictureCorrectService.save(homeworkPictureCorrect);

            //给线上批改的老师推送消息
            String vipId = homeworkPicture.getVipId();
            if (StringUtils.isNotEmpty(homeworkPicture.getTeacherId()) && StringUtils.isNotBlank(vipId)) {
                LibVip student = vipService.getById(vipId);
                if (student != null) {
                    List<TbLibManager> libManagerList = managerService.findByUserIdAndTypeIn(homeworkPicture.getTeacherId(), new int[]{8, 11, Constant.LIB_TEACHER_TYPE});
                    if (CollectionUtils.isNotEmpty(libManagerList)) {
                        TbLibManager correctTeacher = libManagerList.get(0);

                        //模糊图片补拍之前不要分走 ，学生再补拍的时候 去判断老师是否在线，如不在线，再次分配(需要服务类型为平台作业批改).
                        if (correctTeacher.getIsOnline() == 1) {
                            this.sendTempMsg2OnlineTeacher(homeworkPicture.getTeacherId(), student.getChildName(), finishDate, homeworkPicture.getSubject());

                            String content = "尊敬的" + correctTeacher.getName() + "老师，您负责的" + student.getChildName() + "学生，已经于" + DateUtil.dateTimeToString(finishDate) + "时间完成" + homeworkPicture.getSubject() + "作业，请您尽快完成作业批改！";
                            this.sconXingeService.asynPushThreadTask(homeworkPicture.getTeacherId(), 4, XinGePushMessageTypeEnum.Message.getCode(), XinGePushBusinessTypeEnum.HomeworkCorrectNotice.getCode(), "作业批改提醒", content, "APP_TEACHER", PushConstants.PUSH_OTHER);
                        } else if (Objects.equals(serviceType, 1)){
                            //再次分配
                            //查找该科目该年级当前待批改作业最少的老师 （这里要过滤当前老师）
                            teacherService.allotOtherOnlineTeacherByHomeworkPicture(homeworkPicture, correctTeacher, student);
                        }
                    }
                } else {
                    logger.error("找不到学生记录，没有推送， vipId={}", vipId);
                }
            }

            responseEntity.success("更换成功");
        }

        return responseEntity;
    }


    @Override
    public HomeworkPicture findByHomeworkIdAndFileKey(String homeworkId, String fileKey) {
        return homeworkPictureDao.findByHomeworkIdAndFileKey(homeworkId, fileKey);
    }

    @Override
    public void push2conch4vagueImg(HomeworkPicture homeworkPicture, int type) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("markType", type);
        dataMap.put("homeworkId", homeworkPicture.getHomeworkId());
        dataMap.put("fileKeyList", Collections.singleton(homeworkPicture.getFileKey()));
        Map<String, String> pictures = new HashMap<>();
        pictures.put("derverFileId", homeworkPicture.getDerverFileKey());
        dataMap.put("pictures", Arrays.asList(pictures));

        result.put("type", "PICTURE_VAGUE");
        result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
        result.put("data", dataMap);

        sconXingeService.asynPushThreadTask(homeworkPicture.getDerver(),homeworkPicture.getVipId(),1, JSON.toJSONString(result), PushConstants.PUSH_OTHER);
    }

    @Override
    public void push2pad4vagueImg(HomeworkPicture homeworkPicture, int type) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("markType", type);
        dataMap.put("homeworkId", homeworkPicture.getHomeworkId());
        dataMap.put("fileKeyList", Collections.singleton(homeworkPicture.getFileKey()));

        result.put("type", "PICTURE_VAGUE");
        result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
        result.put("data", dataMap);

        StringBuilder sb =  new StringBuilder();
        sb.append("你有作业图片拍摄").append(type == 1 ? "模糊" : type == 3 ? "不全" : "有问题").append("，请及时补拍。");
        sconXingeService.asynPushPadThreadTask(homeworkPicture.getVipId(),sb.toString(), result);
    }

    @Override
    public void push2conch4vagueImgCorrected(HomeworkPicture homeworkPicture, String newFileKey) {
        if (StringUtils.isNotBlank(homeworkPicture.getDerverFileKey())){
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("markType", homeworkPicture.getIsMark());
            dataMap.put("homeworkId", homeworkPicture.getHomeworkId());
            dataMap.put("fileKey", homeworkPicture.getFileKey());
            dataMap.put("newFileKey", newFileKey);
            dataMap.put("derverFileId", homeworkPicture.getDerverFileKey());

            result.put("type", "PICTURE_VAGUE_CORRECTED");
            result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
            result.put("data", dataMap);

            sconXingeService.asynPushThreadTask(homeworkPicture.getDerver(),homeworkPicture.getVipId(),1, JSON.toJSONString(result), PushConstants.PUSH_OTHER);
        }
    }

    @Override
    @Transactional
    public void judgeTodayHomeworkFinishAndPush(String vipId, String subject, Date date) {
        LibVip vip = vipService.getById(vipId);
        TbLibSubscribe ls = libSubscribeService.findTheDayByVipId(vipId, date);
        
        //查询当天该学科的作业计时记录
        Homework homework = homeworkService.findByTodaySubjectHomework(vipId, subject);
        //单科结束推送贝壳、记录作业结束时间
        if (this.isSubjectFinishedAndNotPush(vipId, subject, date)){
            logger.info("{}{}学科批改结束，并且没有推送", vipId, subject);
            homeworkService.correctFinishRecord(vipId, subject, date);
            this.subjectFinishPushDerver(vip.getDerver(),vip.getId(), Collections.singletonList(homework.getId()));
            if (ls == null){
                logger.info("{}没有签到, 推送家长", vipId);
                //不再馆单科结束推送家长
                this.subjectFinishPushParent(vipId, subject, date, homework.getCorrectTime());
            } else if (this.canPush(vipId, date)) {
                    logger.info("学生vip_id("+ vipId + ")的作业已全部批改完");
                    //推送家长公众号
                    this.pushCorrect2ParentAccount(vipId, date);
                    //推送爸妈说到小塾
                    this.pushCorrect2Conch(vip.getDerver(),vip.getId());
                    //推送在馆老师
                    this.push2LibTeacher(vipId,subject);
            }
        } else {
            logger.info("{}{}学科结束，有推送", vipId, subject);
        }
    }

//    public ResponseEntity vagueHomeworkPicture_bak(String homeworkPictureId) {
//        HomeworkPicture homeworkPicture = homeworkPictureDao.findById(homeworkPictureId);
//        ResponseEntity responseEntity = new ResponseEntity();
//        if (homeworkPicture.getIsFeedback() == 1){
//            responseEntity.failure("作业已批改");
//            return responseEntity;
//        } else {
//        	//修改作业为模糊
//        	homeworkPicture.setIsMark(1);
//        	homeworkPictureDao.save(homeworkPicture);//修改科目
//        	
//            //如果学生有贝壳则推送贝壳作业反馈报告
//            if (StringUtils.isNotBlank(homeworkPicture.getDerver())) {
//            	this.push2conch4vagueImg(homeworkPicture);
//            }
//            //推送在馆老师
//            this.push2LibTeacher4VagueImg(homeworkPicture);
//            this.judgeTodayHomeworkFinishAndPush(homeworkPicture.getVipId(), homeworkPicture.getSubject(), homeworkPicture.getCreateTime());
//            responseEntity.success(ResponseConstant.CODE_999, "模糊替换成功");
//        }
//        return responseEntity;
//    }
    
    @Override
    public ResponseEntity vagueHomeworkPicture(String homeworkPictureId,Integer markType,String accessToken) {
    	//兼容旧版app，标为模糊图片
    	if(markType==null){
    		markType=1;
    	}else if(markType==1){
    		markType=3;
    	}else{
    		markType=1;
    	}
        HomeworkPicture homeworkPicture = homeworkPictureDao.findOne(homeworkPictureId);
        ResponseEntity responseEntity = new ResponseEntity();
        if (homeworkPicture.getIsFeedback() == 1){
            responseEntity.failure("作业已批改，不能更替");
            return responseEntity;
        } else if (homeworkPicture.getIsMark() == 1 || homeworkPicture.getIsMark() == 3){
            responseEntity.failure(ResponseConstant.CODE_000, "作业已模糊/不全，无需重复更替");
            return responseEntity;
        } else if (!DateUtil.isSameDay(homeworkPicture.getCreateTime(), new Date())){
            return responseEntity.failure(ResponseConstant.CODE_000, "不是当天的作业， 不能模糊/不全更替");
        } else {
        	//更新选定批改老师的实时权重和批改图片总数
            managerService.updateCorrectHomeworkNum(homeworkPicture.getVipId(), homeworkPicture.getTeacherId(),-1);

            //修改作业为 markType 1：模糊 3：作业不全
            homeworkPicture.setLocking(0);
            homeworkPicture.setIsMark(markType);
            homeworkPicture.setIsNeedingKnow(0);

            //添加模糊记录
            this.insertVagueRecord(homeworkPicture);
            homeworkPictureDao.save(homeworkPicture);

            //如果学生有贝壳则推送贝壳模糊提醒或作业不全
            if (StringUtils.isNotBlank(homeworkPicture.getDerverFileKey())) {
                this.push2conch4vagueImg(homeworkPicture, homeworkPicture.getIsMark());
            }

            //推送到小塾学伴pad
            this.push2pad4vagueImg(homeworkPicture, homeworkPicture.getIsMark());

            TbLibSubscribe libSubscribe = libSubscribeService.findTodaySignedHistoryByVipId(homeworkPicture.getVipId());
            if (libSubscribe != null) {
                //推送模糊提醒给在馆老师
                this.push2LibTeacher4VagueImg(homeworkPicture);
            } else {
                //推送模糊提醒给家长
                this.push2Parent4VagueImg(homeworkPicture);
            }
            String teacherId = tokenManager.getUserId(accessToken);

            //作业转给其他老师，删除该老师的批改时间记录
            homeworkPictureCorrectService.saveCorrectionEndTime4Record(homeworkPicture, managerService.findCorrectTeacherType(teacherId));
            //单科结束推送小熟相机,家长，在馆老师推送记录
            this.pushTodayFinishHomework(homeworkPicture, markType);
            userCountService.saveUserCount(teacherId,homeworkPicture.getVipId(),markType==0?2:3);
            logger.info("{}模糊更替成功,snomyc", homeworkPictureId);
            responseEntity.success(ResponseConstant.CODE_999, "模糊标记成功");
        }
        return responseEntity;
    }

    private void push2Parent4VagueImg(HomeworkPicture homeworkPicture) {
        Map<String, String> data = new HashMap<>();
        String template_id_short = "OPENTM414077970";

        try {
            String vipId = homeworkPicture.getVipId();
            LibVip vip = vipService.getById(vipId);
            if (vip == null) {
                logger.warn("未查询到对应学生，拒绝推送，vipId={}", vipId);
                return;
            }
            String parentOpenId = userService.getAccount(vip.getUserId());

            if(homeworkPicture.getIsMark()==1){
            	data.put("first", "尊敬的" + vip.getChildName() + "家长，您孩子今日的" + homeworkPicture.getSubject() + "作业照片有模糊，请尽快督促孩子重新拍照上传。\n");
            }else{
            	data.put("first", "尊敬的" + vip.getChildName() + "家长，您孩子今日的" + homeworkPicture.getSubject() + "作业照片作业不全，请尽快督促孩子重新拍照上传。\n");
            }
            data.put("keyword1", DateHelper.format(new Date(), "yyyy/MM/dd"));
            data.put("keyword2", "1");
            data.put("remark", "");
            SendTemplateShort sendTemplateShort = new SendTemplateShort(parentOpenId, template_id_short, null, data);
            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
            logger.info("推送模糊提醒给家长成功");
        } catch (Exception e){
            logger.error("推送模糊提醒给家长失败：" + e);
        }
    }

    private void insertVagueRecord (HomeworkPicture homeworkPicture) {
        HomeworkPictureVagueRecord vagueRecord = new HomeworkPictureVagueRecord();
        vagueRecord.setHomeworkPictureId(homeworkPicture.getId());
        vagueRecord.setPictureVaguePath(homeworkPicture.getFileKey());
        vagueRecord.setPictureVagueUploadTime(homeworkPicture.getCreateTime());
        vagueRecord.setPictureVagueTime(new Date());
        vagueRecord.setUserId(homeworkPicture.getTeacherId());
        vagueRecord.setType(homeworkPicture.getIsMark());
        homeworkPictureVagueRecordService.save(vagueRecord);
    }

    @Override
    public void  pushTodayFinishHomework(HomeworkPicture homeworkPicture, int type) {

        String vipId = homeworkPicture.getVipId();
        LibVip vip = vipService.getById(vipId);
        logger.info("pushTodayFinishHomework分配知识点匹配老师前:"+JSONObject.toJSONString(homeworkPicture));
        if (homeworkPicture.getIsFeedback() == 1 && (homeworkPicture.getIsMark() == 0 || homeworkPicture.getIsMark() == 2)
                && homeworkPicture.getIsNeedingKnow() > 0){
            //分配知识点老师
            try {
                teacherService.allotKnowTeacherByHomeworkPicture(homeworkPicture, vip);
            } catch (Exception e){
                logger.error("分配匹配老师异常{}", e);
            }
        }

        //判断是否有未完成的该科作业，如果有false，没有true(推送家长和贝壳端反馈信息)
        boolean flag =  this.findByNoFinishHomework(homeworkPicture.getVipId(),homeworkPicture.getHomeworkId(),homeworkPicture.getId());
        Date now = new Date();

        //如果都批改完成 贝壳拍照的作业则推送贝壳端作业反馈报告， 需求1.0.1， 一张批改推送一次, 只有提交 或者该科目作业已经批改完的批改才推送小塾
        if ( (flag || type ==2) && StringUtils.isNotBlank(homeworkPicture.getDerver()) && !"1".equals(homeworkPicture.getDerver())){
            this.singleSujectPushConche(homeworkPicture, flag, now);
        }
    	if(flag) {
            logger.info("完成作业批改推送作业报告:vipId={}",homeworkPicture.getVipId());
            //作业日历
            zuoybDayService.saveToday(vipId, 1, DateUtil.format_yyyyMMdd(homeworkPicture.getCreateTime()));

            this.singleSujectPushPad(homeworkPicture, now);
            String subject = homeworkPicture.getSubject();
            TbLibSubscribe ls = libSubscribeService.findTheDayByVipId(vipId, homeworkPicture.getCreateTime());

            //查询当天该学科的作业计时记录,更新作业计时中的批改完成时间
            List<Homework> homeworkList = homeworkService.queryDateHomework(vipId, homeworkPicture.getCreateTime());
            boolean isHomeworkPush = true;
            boolean isReportPush = true;

            //单科作业插入结束时间，不能合并以下两个循环，合并会有在馆老师提交不了反馈报告的问题出现
            Homework homework = null;
            for (Homework tempHomework : homeworkList){
                if (homeworkPicture.getSubject().equals(tempHomework.getSubject())){
                    homework = tempHomework;

                    if (tempHomework.getCorrectTime() == null){
                        isHomeworkPush = false;
                    }
                    tempHomework.setCorrectTime(now);
                    homeworkService.save(tempHomework);
                    break;
                }
            }

            //判断三科作业是否完成
            if  (type == 5){
                //纠正学科不能推送报告
                isReportPush = false;
            } else {
                isReportPush = this.isReportNeedPush(homeworkList);
            }

            if (ls == null){
                //没有签到记录,不在馆单科结束推送家长
                if (vip != null && !isHomeworkPush) {
                    logger.info("{}没有签到, 推送家长", vipId);
                    StringBuilder sb = new StringBuilder();
                    sb.append("尊敬的").append(vip.getChildName()).append("家长，");
                    sb.append("老师已经完成您孩子").append(subject).append("科目批改，请及时查看老师对").append(vip.getChildName()).append("的批改结果。");
                    sconXingeService.asynPushThreadTask(vip.getUserId(), null, 2 , sb.toString(),PushConstants.PUSH_HOMEWORK);
                    User parent = userService.getById(vip.getUserId());
                    if (parent != null) {
                        this.pushToParentByWx(parent.getAccount(), vip.getChildName(), subject, now);
                    }
                }
            } else {
                //推送在馆老师
                this.push2LibTeacher(vipId,subject);
            }
            // 不管有没有签到，只要管理老师提交了就会生成报告
            this.judgeAndPushReport(homeworkPicture, isReportPush);

            try {
                learningConditionService.generateWrongQuestionKnowledge(homeworkPicture.getHomeworkId());
            } catch (Exception e) {
                logger.error("homeworkId=[{}]", homeworkPicture.getHomeworkId());
                logger.error("生成错题知识点记录并统计该知识点错题相关信息异常", e);
            }

            if (homework != null &&
                    !Objects.equals(DateUtil.format_yyyyMMdd(homework.getCreateTime()), LocalDate.now().toString())) {
                try {
                    learningConditionService.refreshHomeworkCount(homeworkPicture.getHomeworkId());
                } catch (Exception e) {
                    logger.error("homeworkId=[{}]", homeworkPicture.getHomeworkId());
                    logger.error("刷新每日作业批改数据统计异常", e);
                }
            }
        }

        this.correctCreatePushRecord(vipId, DateUtil.format_yyyyMMddHHmmss(homeworkPicture.getCreateTime()));
    }

    /**
     * 没有push记录新建push记录
     * @param vipId 学生id
     * @param dateTimeStr 日期时间
     */
    private void correctCreatePushRecord(String vipId, String dateTimeStr){
        ZuoybStudentPush push = zuoybStudentPushSerivce.findByVipIdAndDate(vipId, dateTimeStr);
        if (push == null) {
            push = new ZuoybStudentPush();
            push.setType(4);
            push.setVipId(vipId);
            push.setPushTime(DateUtil.parse_yyyyMMddHHmmss(dateTimeStr));
            push.setCourseHour("A");
            zuoybStudentPushSerivce.save(push);
        }
    }


    @Override
    public boolean isReportNeedPush(List<Homework> homeworkList) {
        boolean isReportPush = true;
        for (Homework homework : homeworkList){
            if ((homework.getWorkType() == 1 || homework.getWorkType() == 2) && homework.getCorrectTime() == null){
                long homeworkPictureCount = this.countByHomeworkId(homework.getId());
                if (homeworkPictureCount == 0){
                    isReportPush = false;
                    break;
                }
            }
        }
        return isReportPush;
    }

    @Override
    public void judgeAndPushReport(HomeworkPicture homeworkPicture, boolean isReportNeedPush) {
        Date now = homeworkPicture.getCreateTime();
        int count = homeworkPictureDao.findTodaySubjectNotFeedback(homeworkPicture.getVipId(), homeworkPicture.getId(), DateUtil.format_yyyyMMdd(now));
        if (count == 0 && isReportNeedPush){
            ZuoybStudentPush push = zuoybStudentPushSerivce.findByVipIdAndDate(homeworkPicture.getVipId(), DateUtil.format_yyyyMMddHHmmss(now));
            if (push != null) {
                if (push.getType() != 2) {
                    //推送贝壳反馈报告
                    if (!"1".equals(homeworkPicture.getDerver()) && StringUtils.isNotBlank(homeworkPicture.getDerver())) {
                        Map<String, Object> conchMap = new HashMap<String, Object>();
                        conchMap.put("type", "FEEDBACK_HOMEWORK");
                        conchMap.put("time", now);
                        Map<String, Object> map2 = new HashMap<String, Object>();
                        map2.put("content", "您的作业有老师批改啦,请在作业记录中查看!");
                        conchMap.put("data", map2);

                        String content = JSON.toJSONString(conchMap);
                        //推送贝壳
                        sconXingeService.asynPushThreadTask(homeworkPicture.getDerver(), homeworkPicture.getVipId(), 1, content, PushConstants.PUSH_OTHER);
                    }

                    //在馆老师已完成编辑提交的，这里推送
                    if (push.getType() == 3) {
                        //推送家长公众号
                        this.push2Parent(push, homeworkPicture.getVipId(), 2);
                    } else {
                        //线上批改已完成
                        push.setType(4);
                        push.setUpdateTime(now);
                        zuoybStudentPushSerivce.save(push);
                    }
                }
            }
        }
    }

    @Override
    public void singleSujectPushConche (HomeworkPicture homeworkPicture, boolean flag, Date now){
        //若存在非模糊且非不全的图片，则需要推送报告给小塾
        boolean needSendNotice2Conch = true;
        if (Objects.equals(1, homeworkPicture.getIsMark()) || Objects.equals(3, homeworkPicture.getIsMark())) {
            needSendNotice2Conch = homeworkPictureDao.countByHomeworkIdAndIsMarkNotInAndIdNot(homeworkPicture.getHomeworkId(), Arrays.asList(1, 3), homeworkPicture.getId()) > 0;
        }
        if (needSendNotice2Conch) {
            //保留此推送以兼容旧版本小塾
            List<HomeworkFeedbackVO4> list = new ArrayList<>();
            HomeworkFeedbackVO4 content = conchDerverService.homeworkFeedbackDetails4(homeworkPicture.getHomeworkId(), flag ? 1 : 0);
            if (content != null) {
                //前面已经判断是否批改完成，直接设置为1（已批改），防止因为操作模糊更替时先推送后保存数据造成的影响
                //content.setIsFeedback(1);
                String correctedPictureUrl = homeworkPicture.getCorrectedPictureUrl();
                if (StringUtils.isNotBlank(correctedPictureUrl)) {
                    List<String> homeworkCommentList = content.getHomeworkCommentList();
                    Optional<String> optional = homeworkCommentList.stream().filter(it -> Objects.equals(it, correctedPictureUrl)).findFirst();
                    if (!optional.isPresent()) {
                        homeworkCommentList.add(correctedPictureUrl);
                    }
                }
                list.add(content);
            }
            if (!list.isEmpty()) {
                Map<String, Object> dataMap = new HashMap<>();
                Map<String, Object> result = new HashMap<>();
                dataMap.put("list", list);
                result.put("type", "FEEDBACK_HOMEWORK");
                result.put("time", DateUtil.format_yyyyMMddHHmmss(now));
                result.put("data", dataMap);
                sconXingeService.asynPushThreadTask(homeworkPicture.getDerver(),homeworkPicture.getVipId(),1,JSON.toJSONString(result),PushConstants.PUSH_OTHER);
            }

            List<HomeworkFeedbackVO5> list2 = new ArrayList<>();
            HomeworkFeedbackVO5 content2 = conchDerverService.homeworkFeedbackDetails5(homeworkPicture.getHomeworkId(), flag ? 1 : 0);
            if (content2 != null) {
                String correctedPictureUrl = homeworkPicture.getCorrectedPictureUrl();
                if (StringUtils.isNotBlank(correctedPictureUrl)) {
                    List<HomeworkPictureCommentDTO> homeworkCommentList = content2.getHomeworkCommentList();
                    Optional<HomeworkPictureCommentDTO> optional = homeworkCommentList.stream().filter(it -> Objects.equals(it.getHomeworkCommentUrl(), correctedPictureUrl)).findFirst();
                    if (!optional.isPresent()) {
                        HomeworkPictureCommentDTO homeworkPictureCommentDTO = new HomeworkPictureCommentDTO();
                        homeworkPictureCommentDTO.setHomeworkCommentUrl(correctedPictureUrl);
                        homeworkPictureCommentDTO.setCompositionVideoPath(homeworkPicture.getCompositionCommentPath());
                        homeworkPictureCommentDTO.setIsComposition(homeworkPicture.getIsComposition());
                        if (StringUtils.isNotBlank(homeworkPicture.getCompositionComment())) {
                            homeworkPictureCommentDTO.setCompositionCommentList(Arrays.asList(homeworkPicture.getCompositionComment().split(",")));
                        }
                        homeworkCommentList.add(homeworkPictureCommentDTO);
                    }
                }
                list2.add(content2);
            }
            if (!list2.isEmpty()) {
                logger.info("批改完推送小塾2={}", JSON.toJSON(list2));
                Map<String, Object> dataMap = new HashMap<>();
                Map<String, Object> result = new HashMap<>();
                dataMap.put("list", list2);
                result.put("type", "FEEDBACK_HOMEWORK_2");
                result.put("time", DateUtil.format_yyyyMMddHHmmss(now));
                result.put("data", dataMap);
                sconXingeService.asynPushThreadTask(homeworkPicture.getDerver(),homeworkPicture.getVipId(),1,JSON.toJSONString(result),PushConstants.PUSH_OTHER);
            }
        }
    }

    @Override
    public void singleSujectPushPad (HomeworkPicture homeworkPicture, Date now){
        HomeworkRecordDto padData = conchDerverService.findOneHomeworkRecord(homeworkPicture.getHomeworkId());
        if (padData != null){
            logger.info("批改完推送pad={}", JSON.toJSON(padData));
            Map<String, Object> result = new HashMap<>();
            result.put("type", "FEEDBACK_HOMEWORK_2");
            result.put("time", DateUtil.format_yyyyMMddHHmmss(now));
            result.put("data", padData);
            sconXingeService.asynPushPadThreadTask(homeworkPicture.getVipId(), "你的" + homeworkPicture.getSubject() + "作业批改完成， 赶快来看看吧！", result);
        }
    }

    @Override
    public List<HomeworkPicture> findNotFeedbackHomework(String teacherId) {
        return homeworkPictureQueryDao.findTeacherNotFeedbackHomework(teacherId, DateUtil.format_yyyyMMdd(new Date()));
    }

    @Override
    public List<HomeworkPicture> findByIdInAndIsDelete(List<String> homeworkPictureIdList, Integer isDelete) {
        return homeworkPictureDao.findByIdInAndIsDelete(homeworkPictureIdList, isDelete);
    }

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

	@Override
	public long countByHomeworkId(String homeworkId) {
		return homeworkPictureDao.countByHomeworkId(homeworkId);
	}

	@Override
	public boolean findByNoFinishHomework(String vipId, String homeworkId, String homeworkPictureId) {
		int count = homeworkPictureDao.findByNoFinishHomework(vipId, homeworkId, homeworkPictureId);
		if(count == 0) {
			return true;
		}
		return false;
	}

    @Override
    public void confirmPushTodayFinishHomework(String homeworkId, String derver, String vipId, String subject, Date date, Date correctTime) {
        TbLibSubscribe ls = libSubscribeService.findTheDayByVipId(vipId, date);
        //作业日历
        zuoybDayService.saveToday(vipId, 1, DateUtil.format_yyyyMMdd(date));
        //如果都批改完成 贝壳拍照的作业则推送贝壳端作业反馈报告
        if (StringUtils.isNotBlank(derver) && !"1".equals(derver)){
            List<HomeworkFeedbackVO3> list = new ArrayList<>();
            HomeworkFeedbackVO3 content = conchDerverService.homeworkFeedbackDetails3(homeworkId);
            if (content != null) {
                list.add(content);
            }
            if (!list.isEmpty()) {
                Map<String, Object> dataMap = new HashMap<>();
                Map<String, Object> result = new HashMap<>();
                dataMap.put("list", list);
                result.put("type", "FEEDBACK_HOMEWORK");
                result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
                result.put("data", dataMap);
                sconXingeService.asynPushThreadTask(derver,vipId,1,JSON.toJSONString(result),PushConstants.PUSH_OTHER);
            }
        }

        if (ls == null){
            logger.info("{}没有签到, 推送家长", vipId);
            //没有签到记录,不在馆单科结束推送家长
            LibVip vip = vipService.getById(vipId);
            if (vip != null) {
                StringBuilder sb = new StringBuilder();
                sb.append("尊敬的").append(vip.getChildName()).append("家长，");
                sb.append("老师已经完成您孩子").append(subject).append("科目批改，请及时查看老师对").append(vip.getChildName()).append("的批改结果。");
                sconXingeService.asynPushThreadTask(vip.getUserId(), null,2, sb.toString(), PushConstants.PUSH_HOMEWORK);
                User parent = userService.getById(vip.getUserId());
                if (parent != null) {
                    this.pushToParentByWx(parent.getAccount(), vip.getChildName(), subject, correctTime);
                }
            }
        } else {
        	//如果有签到记录，判断作业其他科是否全部完成并且没有再次推送
        	int count = homeworkPictureDao.findTodayOtherSubjectNotFeedback(vipId, homeworkId,DateUtil.format_yyyyMMdd(date));
            if (count == 0){
                 ZuoybStudentPush push = zuoybStudentPushSerivce.findByVipIdAndDate(vipId, DateUtil.format_yyyyMMddHHmmss(date));
                 if (push != null){
                	 if(push.getType() !=2) {
                		//推送贝壳反馈报告
                    	 if ( !"1".equals(derver) && StringUtils.isNotBlank(derver)) {
                             Map<String, Object> conchMap = new HashMap<String, Object>();
                             conchMap.put("type", "FEEDBACK_HOMEWORK");
                             conchMap.put("time", new Date());
                             Map<String, Object> map2 = new HashMap<String, Object>();
                             map2.put("content", "您的作业有老师批改啦,请在作业记录中查看!");
                             conchMap.put("data", map2);

                             String content = JSON.toJSONString(conchMap);
                             //推送贝壳
                             sconXingeService.asynPushThreadTask(derver,vipId,1,content,PushConstants.PUSH_OTHER);
                         }

                    	 //在馆老师已完成编辑提交的，这里推送
                         if (push.getType() == 3) {
                             //推送家长公众号
                             this.push2Parent(push, vipId, 2);
                         } else {
                             //线上批改已完成
                             push.setType(4);
                             push.setUpdateTime(new Date());
                             zuoybStudentPushSerivce.save(push);
                         }

                         //推送在馆老师
                         this.push2LibTeacher(vipId,subject);
                	 }
                 }else {
                	 push = new ZuoybStudentPush();
                     push.setType(4);
                     push.setVipId(vipId);
                     push.setPushTime(date);
                     push.setCourseHour("A");
                     List<LibVipService> libVipServices= libVipServiceService.getByVipIdAndSpecies(vipId, "S003");
                     if (libVipServices != null && libVipServices.size() > 0){
                         push.setLibId(libVipServices.get(0).getLibId());
                     }
                     zuoybStudentPushSerivce.save(push);
                 }
            }
        }
	}

    @Override
    public void push2conch4updateSubject(String homeworkId, String derver, String vipId, String derverFileKey, String newSubject) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("derverFileId", derverFileKey);
        String changeSubject = "YUWEN";
        switch (newSubject) {
            case "语文":
                break;
            case "数学":
                changeSubject = "SHUXUE";
                break;
            case "英语":
                changeSubject = "YINGYU";
                break;
            default:
                changeSubject = "YUWEN";
        }
        dataMap.put("changeSubject", changeSubject);
        dataMap.put("homeworkId", homeworkId);

        result.put("type", "HOMEWORK_CORRECT");
        result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
        result.put("data", dataMap);

        sconXingeService.asynPushThreadTask(derver,vipId,1, JSON.toJSONString(result), PushConstants.PUSH_OTHER);
    }

    @Override
    public void push2pad4updateSubject(String homeworkId, String derver, String vipId, String derverFileKey, String newSubject) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("derverFileId", derverFileKey);
        String changeSubject = "YUWEN";
        switch (newSubject) {
            case "语文":
                break;
            case "数学":
                changeSubject = "SHUXUE";
                break;
            case "英语":
                changeSubject = "YINGYU";
                break;
            default:
                changeSubject = "YUWEN";
        }
        dataMap.put("changeSubject", changeSubject);
        dataMap.put("homeworkId", homeworkId);

        result.put("type", "HOMEWORK_CORRECT");
        result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
        result.put("data", dataMap);

        sconXingeService.asynPushPadThreadTask(vipId,"你有一张作业图片纠正到" + newSubject + "学科，快来查看吧！", result);
    }

    /**
     * 推送作业批改完成公众号信息至家长微信
     */
    private void pushToParentByWx(String openId, String childName, String subject, Date correctTime) {
        Map<String, String> data = new HashMap<>(16);
        String template_id_short = "OPENTM415477531";
        data.put("first", "尊敬的" + childName + "家长，老师已经完成您孩子" + subject + "科目批改，请及时查看老师对" + childName + "的批改结果。");
        data.put("keyword1", subject);
        data.put("keyword2", "日常作业");
        data.put("keyword3", DateHelper.format(correctTime, "yyyy-MM-dd HH:mm"));
        data.put("remark", "");
        SendTemplateShort sendTemplateShort = new SendTemplateShort(openId, template_id_short, null, data);
        pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
    }

	@Override
	public List<Map<String, Object>> findByTeacherIdGroupBySubjectAndVipId(String teacherId) {
		return homeworkPictureQueryDao.findByTeacherIdGroupBySubjectAndVipId(teacherId);
	}

	@Override
	public List<Map<String, Object>> findByKnowTeacherIdGroupBySubjectAndVipId(String teacherId) {
		return homeworkPictureQueryDao.findByKnowTeacherIdGroupBySubjectAndVipId(teacherId);
	}

	@Override
	public List<HomeworkPicture> findNoFeedbackByHomeworkId(String homeworkId) {
		// TODO Auto-generated method stub
		return homeworkPictureDao.findNoFeedbackByHomeworkId(homeworkId);
	}

	@Override
	public List<HomeworkPicture> findByTodayTeacherHomeworkPicture(String teacherId, String subject, String vipId) {
		return homeworkPictureDao.findByTodayTeacherHomeworkPicture(teacherId, subject, vipId);
	}
	
	@Override
	public List<HomeworkPicture> findByTodayHomeworkPicture(String homeworkId, String subject, String vipId){
		return homeworkPictureDao.findByTodayHomeworkPicture(homeworkId, subject, vipId);
	}
	
	

	@Override
	public List<HomeworkPicture> findByTodayKnowTeacherHomeworkPicture(String teacherId, String subject, String vipId) {
		return homeworkPictureDao.findByTodayKnowTeacherHomeworkPicture(teacherId, subject, vipId);
	}


    @Override
    public List<HomeworkPictureDto> findCheckHomeworkPictureByHomeworkId(String homeworkId) {
        return homeworkPictureQueryDao.findCheckPictureByHomeworkId(8, homeworkId);
    }

    @Override
    public List<HomeworkPictureDto> findKnowCheckHomeworkPictureByHomeworkId(String homeworkId) {
        return homeworkPictureQueryDao.findKnowCheckPictureByHomeworkId(homeworkId);
    }

    @Override
    public ResponseEntity beginHomeworkPictureCorrection(String userId, String homeworkPictureId) {
        ResponseEntity  responseEntity = new ResponseEntity();
        HomeworkPicture homeworkPicture = this.getById(homeworkPictureId);

        //质检员开始批改直接过滤
        List<TbLibManager> managers = managerService.findByUserIdAndTypeIn(userId, new int[]{Constant.CORRECT_MANAGER, Constant.HOMEWORK_CHECK_TYPE});
        if (CollectionUtils.isNotEmpty(managers) && !userId.equals(homeworkPicture.getTeacherId())){
            logger.info("{}开始批改成功，批改员{}", homeworkPictureId, userId);
            responseEntity.success(ResponseConstant.CODE_999, "记录开始批改成功");
            return responseEntity;
        }

        int type = managerService.findCorrectTeacherType(userId);
        if (type > 0){
            Date now = new Date();
            if (homeworkPicture != null){
                Map<String, Integer> data = new HashMap<>();
                data.put("type", 0);
                data.put("status", 0);
                data.put("secondType", 0);
                int correctCheckType = kmtCorrectSysService.getHomeworkCheckStatus(homeworkPicture.getHomeworkId(), userId, type);
                if (type == Constant.KMT_122_TEACHER_TYPE && homeworkPicture.getIsFeedback() == 1 && correctCheckType == 1){
                    data.put("type", 14);
                    data.put("status", 14);
                } else if (type == Constant.KMT_122_TEACHER_TYPE && homeworkPicture.getIsKnowFeedback() == 1 && correctCheckType == 2) {
                    data.put("type", 13);
                    data.put("status", 13);
                } else if (userId.equals(homeworkPicture.getTeacherId()) || userId.equals(homeworkPicture.getKnowTeacherId())) {
                    logger.info("{}开始了作业图片{}的批改", userId, homeworkPictureId);
                    HomeworkPictureCorrect zybCorrectTimeRecord = homeworkPictureCorrectService.findByHomeworkPictureIdAndType(homeworkPictureId, type);
                    if (zybCorrectTimeRecord == null) {
                        zybCorrectTimeRecord = new HomeworkPictureCorrect();
                        zybCorrectTimeRecord.setType(type);
                        zybCorrectTimeRecord.setCreateTime(now);
                        zybCorrectTimeRecord.setHomeworkPictureId(homeworkPictureId);
                        zybCorrectTimeRecord.setHomeworkId(homeworkPicture.getHomeworkId());
                        zybCorrectTimeRecord.setStartTime(now);
                        zybCorrectTimeRecord.setEndTime(null);
                        homeworkPictureCorrectService.save(zybCorrectTimeRecord);
                    } else if (zybCorrectTimeRecord.getStartTime() == null) {
                        zybCorrectTimeRecord.setStartTime(now);
                        zybCorrectTimeRecord.setEndTime(null);
                        homeworkPictureCorrectService.save(zybCorrectTimeRecord);
                    } else {
                        logger.info("{}已存在批改记录{}", homeworkPictureId, JSON.toJSON(zybCorrectTimeRecord));
                    }
                } else if (homeworkPicture.getIsCorrect() != 12) {
                    if (homeworkPicture.getIsFeedback() == 1){
                        data.put("type", 8);
                    } else {
                        data.put("type", 9);
                    }
                    data.put("status", 5);
                } else {
                    data.put("type", 12);
                    data.put("status", 12);
                }
                responseEntity.success(data, "成功");
            } else {
                responseEntity.failure(ResponseConstant.CODE_000, "作业记录不存在");
            }
        } else {
            logger.info("pictureId={}, userId={}", homeworkPictureId, userId);
            responseEntity.failure(ResponseConstant.CODE_000, "您不是在线老师");
        }

        return responseEntity;
    }

    @Override
    public List<HomeworkPicture> findUncorrectedByHomeworkId(String homeworkId) {
        return homeworkPictureDao.findByHomeworkIdAndTypeInAndIsFeedbackAndIsDelete(homeworkId, new int[]{0, 2}, 0, 0);
    }

    @Override
    public List<HomeworkPicture> findByHomeworkIdAndIsFeedbackAndIsDelete(String homeworkId, int isFeedback, int isDelete) {
        return homeworkPictureDao.findByHomeworkIdAndIsFeedbackAndIsDelete(homeworkId,isFeedback,isDelete);
    }

    @Override
    public List<Map<String, Object>> schoolHomeworkPictureTotal(String schoolName, String startTime, String endTime) {
        return homeworkPictureQueryDao.schoolHomeworkPictureTotal(schoolName,startTime,endTime);
    }
    @Override
    public List<HomeworkPicture> findByHomeworkIdAndTeacherId(String homeworkId, String teacherId) {
        return homeworkPictureDao.findByHomeworkIdAndTeacherId(homeworkId, teacherId);
    }
    @Override
    public List<HomeworkPicture> findByHomeworkIdAndKnowTeacherId(String homeworkId, String teacherId) {
        return homeworkPictureDao.findByHomeworkIdAndKnowTeacherIdAndIsFeedbackAndIsNeedingKnowAndTeacherIdIsNotNull(homeworkId, teacherId, 1, 1);
    }

    @Override
    public int countUnfeedbackCount(String beginTime, String teacherId) {
        return homeworkPictureDao.countByCreateTimeAndTeacherId(beginTime, teacherId);
    }

    @Override
    public int countKnowUnfeedbackCount(String beginTime, String teacherId) {
        return homeworkPictureDao.countByCreateTimeAndKnowTeacherId(beginTime, teacherId);
    }

	@Override
	public List<SubjectChartsDto> findSubjectCharts(String startTime,String endTime) {
		List<SubjectChartsDto> list=new ArrayList<SubjectChartsDto>();


        SubjectChartsDto yuwen=new SubjectChartsDto();
        SubjectChartsDto shuxu=new SubjectChartsDto();
        SubjectChartsDto yingyu=new SubjectChartsDto();
		List<Map<String, Object>> maps=homeworkPictureQueryDao.findSubjectCharts(startTime,endTime);
		for (Map<String, Object> map : maps) {
		    if("语文".equals(String.valueOf(map.get("subject")))){
                String hours=String.valueOf(map.get("hours"));
                if(hours.startsWith("0") && hours.length()>=2){
                    hours=hours.substring(1);
                }
                yuwen.setSubject("语文");
                yuwen.addSeries(Integer.parseInt(hours), Integer.valueOf(map.get("count").toString()));
            }else if("数学".equals(String.valueOf(map.get("subject")))){
                String hours=String.valueOf(map.get("hours"));
                if(hours.startsWith("0") && hours.length()>=2){
                    hours=hours.substring(1);
                }
                shuxu.setSubject("数学");
                shuxu.addSeries(Integer.parseInt(hours), Integer.valueOf(map.get("count").toString()));
            }else if("英语".equals(String.valueOf(map.get("subject")))){
                String hours=String.valueOf(map.get("hours"));
                if(hours.startsWith("0") && hours.length()>=2){
                    hours=hours.substring(1);
                }
                yingyu.setSubject("英语");
                yingyu.addSeries(Integer.parseInt(hours), Integer.valueOf(map.get("count").toString()));
            }

		}
        list.add(yuwen);list.add(shuxu);list.add(yingyu);
		return list; 
	}



    @Override
    public List<HomeworkPicture> findLastTowByHomeworkId(String homeworkId) {
        return homeworkPictureDao.findLastTowByHomeworkId(homeworkId);
    }

    @Override
    public void updateResetCheckHomework(String homeworkPictureId, int type) {
        homeworkPictureDao.updateResetCheckHomework(homeworkPictureId,type);
    }

    @Override
    public long findTeacherErrorCount(String teacherId, int type, int isCheckError, int isErrorRead) {
        return homeworkPictureDao.findTeacherErrorCount(teacherId,type,isCheckError,isErrorRead);
    }
   @Override
    public  HomeworkPicture findByIdAndTypeIn(String id,int[] type){
        return homeworkPictureDao.findByIdAndTypeIn(id,type);
   }

    @Override
    public  HomeworkPicture findByIdAndType(String id,int type){
        return homeworkPictureDao.findByIdAndType(id,type);
    }

	@Override
	public void updateHomeworkPictureByKnowTeacherId(String id,String knowTeacherId) {
		 homeworkPictureDao.updateHomeworkPictureByKnowTeacherId(id,knowTeacherId);
	}

    @Override
    public long countByVipIdAndCreateTimeAndIsDelete(Date createTime, String vipId, String homeworkPictureId) {
        return homeworkPictureDao.countByVipIdAndCreateTimeAndIsDelete(createTime, vipId, 0, homeworkPictureId);
    }

    @Override
    public void WorkOvertimeAllot() {
        //查询15分钟还没进行批改的作业今日
        List<HomeworkPicture> pictures = homeworkPictureDao.queryOvertimeList();
        Map<String,String> homeworkMap = new HashMap<String,String>();
        if(pictures !=null && pictures.size()>0){
            for (HomeworkPicture picture:pictures){
                String teacherId = null;
                if(homeworkMap.containsKey(picture.getHomeworkId())){ //如果之前有老师则分配给这个老师
                    teacherId = homeworkMap.get(picture.getHomeworkId());
                }else{
                    teacherId = teacherService.getOverTimeTeacherId(picture.getTeacherId(),picture.getSubject(),picture.getVipId(),picture.getHomeworkId());
                }

                picture.setTeacherId(teacherId);
                if(teacherId !=null){
                    picture.setAllotTime(new Date());
                    homeworkMap.put(picture.getHomeworkId(),teacherId);
                }
                HomeworkPictureCorrect homeworkPictureCorrect=homeworkPictureCorrectService.findByHomeworkPictureIdAndType(picture.getId(),Constant.KMT_122_TEACHER_TYPE);
                if(homeworkPictureCorrect!=null){
                    homeworkPictureCorrect.setAllotTime(new Date());
                    homeworkPictureCorrectService.save(homeworkPictureCorrect);
                }
            }
            this.save(pictures);
        }

    }

    @Override
    public HomeworkPicture findStudentSubjectHomeworkNotThis(String vipId, String subject, String teacherId) {
        return homeworkPictureDao.findStudentSubjectHomeworkNotThis(vipId,subject,teacherId);
    }

    @Override
    public List<HomeworkPicture> findAllIncludingDeleteByHomeworkId(String homeworkId) {
        return homeworkPictureDao.findByHomeworkId(homeworkId);
    }

    @Override
    public int countByHomeworkIdAndIsDelete(String homeworkId, int isDelete) {
        return homeworkPictureDao.countByHomeworkIdAndIsDelete(homeworkId, isDelete);
    }


    @Override
    public int countByVipId(String vipId) {
        return homeworkPictureDao.countByVipId(vipId);
    }

    @Override
    public void allotLibHomework(String libId, String teacherId, String classId) {
        TbLibManager teacher = managerService.findByLibIdAndUserIdAndType(libId, teacherId, 15);
        //所有科目
        List<String> subjects;
        if (teacher != null) {
            subjects = Arrays.asList(teacher.getCourseName().split(","));
        } else {
            return;
        }
        //作业有效开始时间
        String beginTime = this.getBeginTime();
        //查找该老师下所有班级
        if (StringUtil.isBlank(classId)) {
            List<TbClassTeacher> classTeacherList = tbClassTeacherService.getTbLibImTeacherBylibId(teacher.getLibId(), teacherId);
            classTeacherList.forEach(e -> {
                //查找指定班级下的指定科目的未分配校区批改老师的作业列表
                List<HomeworkPicture> list = homeworkPictureDao.findUnallocatedHomeworkList(subjects, e.getClassId(), beginTime);
                list.forEach(homeworkPicture -> {
                    //分配老师
                    homeworkPicture.setTeacherId(teacherId);
                    HomeworkPictureCorrect homeworkPictureCorrect = homeworkPictureCorrectService.findByHomeworkPictureIdAndType(homeworkPicture.getId(),15);
                    if (homeworkPictureCorrect == null) {
                        //插入分配记录
                        homeworkPictureCorrect = new HomeworkPictureCorrect();
                        homeworkPictureCorrect.setType(managerService.findCorrectTeacherType(homeworkPicture.getTeacherId()));
                        homeworkPictureCorrect.setCreateTime(new Date());
                        homeworkPictureCorrect.setHomeworkPictureId(homeworkPicture.getId());
                        homeworkPictureCorrect.setHomeworkId(homeworkPicture.getHomeworkId());
                    }
                    homeworkPictureCorrect.setStartTime(null);
                    homeworkPictureCorrect.setEndTime(null);
                    homeworkPictureCorrect.setAllotTime(homeworkPicture.getAllotTime());
                    homeworkPictureCorrectService.save(homeworkPictureCorrect);
                });
                this.save(list);
            });
        } else {
            //查找指定班级下的指定科目的未分配校区批改老师的作业列表
            List<HomeworkPicture> list = homeworkPictureDao.findUnallocatedHomeworkList(subjects, classId, beginTime);
            list.forEach(homeworkPicture -> {
                //分配老师
                homeworkPicture.setTeacherId(teacherId);
                HomeworkPictureCorrect homeworkPictureCorrect = homeworkPictureCorrectService.findByHomeworkPictureIdAndType(homeworkPicture.getId(),15);
                if (homeworkPictureCorrect == null) {
                    //插入分配记录
                    homeworkPictureCorrect = new HomeworkPictureCorrect();
                    homeworkPictureCorrect.setType(managerService.findCorrectTeacherType(homeworkPicture.getTeacherId()));
                    homeworkPictureCorrect.setCreateTime(new Date());
                    homeworkPictureCorrect.setHomeworkPictureId(homeworkPicture.getId());
                    homeworkPictureCorrect.setHomeworkId(homeworkPicture.getHomeworkId());
                }
                homeworkPictureCorrect.setStartTime(null);
                homeworkPictureCorrect.setEndTime(null);
                homeworkPictureCorrect.setAllotTime(homeworkPicture.getAllotTime());
                homeworkPictureCorrectService.save(homeworkPictureCorrect);
            });
            this.save(list);
        }
    }

    @Override
    public void allotLibHomework(String vipId) {
        List<HomeworkPicture> list = homeworkPictureDao.findUnallocatedHomeworkList(vipId, this.getBeginTime());
        this.allotLibHomework(list);
    }

    @Override
    public void allotUncorrectedLibHomework(String vipId) {
        List<HomeworkPicture> list = homeworkPictureDao.findUncorrectedHomeworkListByVipId(vipId, this.getBeginTime());
        this.allotLibHomework(list);
    }

    @Override
    public void allotUncorrectedLibHomework(String teacherId, List<String> subjects) {
        List<HomeworkPicture> list;
        if (subjects == null || subjects.size() == 0) {
            list = homeworkPictureDao.findUncorrectedHomeworkList(teacherId, this.getBeginTime());
        } else {
            list = homeworkPictureDao.findUncorrectedHomeworkList(teacherId, this.getBeginTime(), subjects);
        }
        this.allotLibHomework(list);
    }

    @Override
    public void allotUncorrectedSomeLibHomework(String libId,String teacherId, List<String> subjects) {
        List<HomeworkPicture> list;
        if (subjects == null || subjects.size() == 0) {
            list = homeworkPictureDao.findUncorrectedLibHomeworkList(teacherId, this.getBeginTime(),libId);
        } else {
            list = homeworkPictureDao.findUncorrectedLibHomeworkList(teacherId, this.getBeginTime(), subjects,libId);
        }
        this.allotLibHomework(list);
    }
    private void allotLibHomework(List<HomeworkPicture> list) {
        list.forEach(homeworkPicture -> {
            //分配老师
            String teacherId = teacherService.getHomeworkLibTeacherId(homeworkPicture.getVipId(), homeworkPicture.getHomeworkId(), homeworkPicture.getSubject());
            homeworkPicture.setTeacherId(teacherId);
            HomeworkPictureCorrect homeworkPictureCorrect = homeworkPictureCorrectService.findByHomeworkPictureIdAndType(homeworkPicture.getId(),15);
            if (homeworkPictureCorrect == null) {
                //插入分配记录
                homeworkPictureCorrect = new HomeworkPictureCorrect();
                homeworkPictureCorrect.setType(managerService.findCorrectTeacherType(homeworkPicture.getTeacherId()));
                homeworkPictureCorrect.setCreateTime(new Date());
                homeworkPictureCorrect.setHomeworkPictureId(homeworkPicture.getId());
                homeworkPictureCorrect.setHomeworkId(homeworkPicture.getHomeworkId());
            }
            homeworkPictureCorrect.setStartTime(null);
            homeworkPictureCorrect.setEndTime(null);
            homeworkPictureCorrect.setAllotTime(homeworkPicture.getAllotTime());
            homeworkPictureCorrectService.save(homeworkPictureCorrect);
        });
        this.save(list);
    }

    private String getBeginTime() {
        Date now = new Date();
        String nowString = DateUtil.format_yyyyMMddHHmmss(now);
        String today = DateUtil.format_yyyyMMdd(now);
        String today2pm = today + " 14:00:00";
        String beginTime;
        if (nowString.compareTo(today2pm) >= 0) {
            //超过下午2点获取今天的数据
            beginTime = today;
        } else {
            //获取昨天
            beginTime = DateUtil.format_yyyyMMdd(DateUtil.addDays(now, -1));
        }
        return beginTime;
    }
}
