package com.ssj.service.sys.problem.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.sys.feedback.domain.*;
import com.ssj.bean.sys.picturepredeal.domain.ProblemSimilarPredeal;
import com.ssj.bean.sys.problem.domain.ProblemPicture;
import com.ssj.bean.sys.problem.dto.ProblemPictureListDto;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.push.domain.Miniprogram;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.bean.weixin.zyb.domain.ZuoybKnowHowDetails;
import com.ssj.bean.weixin.zyb.domain.ZuoybStudentPush;
import com.ssj.conch.constant.ConchConstants;
import com.ssj.conch.constant.CourseConstant;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.dao.sys.problem.dao.ProblemPictureDao;
import com.ssj.dao.sys.problem.dao.ProblemPictureQueryDao;
import com.ssj.dao.weixin.library.dao.LibVipBindDao;
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.util.Constant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.weixin.util.AmrToMp3Util;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.framework.weixin.util.ExecLinuxCMD;
import com.ssj.framework.weixin.util.WxUtil;
import com.ssj.mapper.problem.ProblemMapper;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.conch.parents.dto.AnsweredProblemDto;
import com.ssj.service.conch.parents.dto.UnAnsweredProblemDto;
import com.ssj.service.conch.parents.request.DeleteProblemRequest;
import com.ssj.service.conch.parents.request.FeedbackProblemRequest;
import com.ssj.service.conch.parents.request.FindProblemRequest;
import com.ssj.service.conch.parents.request.version4.ProblemKnowHowReq;
import com.ssj.service.conch.teacher.request.teacherorg.*;
import com.ssj.service.conch.utils.ParseUtil;
import com.ssj.service.kmt.dto.ProblemDetailDto;
import com.ssj.service.kmt.dto.ProblemDto;
import com.ssj.service.kmt.dto.StudentProblemDto;
import com.ssj.service.kmt.dto.SubjectStudentDto;
import com.ssj.service.sys.feedback.service.*;
import com.ssj.service.sys.feedback.vo.TeacherFeedback;
import com.ssj.service.sys.feedback.vo.ToFeedBack;
import com.ssj.service.sys.feedback.vo.ToFeedBackProblem;
import com.ssj.service.sys.picturepredeal.service.ProblemSimilarPreDealService;
import com.ssj.service.sys.problem.service.IBanbenDetailService;
import com.ssj.service.sys.problem.service.ProblemPictureService;
import com.ssj.service.sys.problem.vo.*;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.library.service.LibVipBindService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.service.weixin.zuoyb.service.ZuoybDayService;
import com.ssj.service.weixin.zuoyb.service.ZuoybKnowHowDetailsService;
import com.ssj.service.weixin.zuoyb.service.ZuoybStudentPushSerivce;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

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


@Service(version="1.0")
@Transactional
public class ProblemPictureServiceImpl extends BaseServiceImpl<ProblemPicture, String> implements ProblemPictureService {

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

    @Autowired
    private ProblemPictureDao                problemPictureDao;

    @Autowired
    private ProblemPictureQueryDao problemPictureQueryDao;

    @Autowired
    private FeedbackService           feedbackService;

    @Autowired
    private UserService       userService;

	@Autowired
	private ConchDerverService conchDerverService;

    @Autowired
    private IBookManagerService     managerService;

	@Autowired
    private SconKnowFeedbackDetailService sconKnowFeedbackDetailService;

    @Autowired
    private ZuoybKnowHowDetailsService zuoybKnowHowDetailsService;

    @Autowired
    private SconTextFeedbackDetailService sconTextFeedbackDetailService;

    @Autowired
    private SconPhotoFeedbackDetailService sconPhotoFeedbackDetailService;

    @Autowired
    private SconVoiceFeedbackDetailService sconVoiceFeedbackDetailService;

    @Autowired
    private PushTemplateService pushTemplateService;

    @Autowired
    private ZuoybStudentPushSerivce pushSerivce;

    @Autowired
    private ILibVipService libVipService;

    @Autowired
    private SconXingeService sconXingeService;

    @Autowired
    private SconSynthVoiceFeedbackDetailService sconSynthVoiceFeedbackDetailService;

    @Autowired
    private ZuoybDayService zuoybDayService;

    @Autowired
    private LibVipBindDao libVipBindDao;

    @Autowired
    private LibVipBindService libVipBindService;

    @Autowired
    private IBanbenDetailService banbenDetailService;
    @Autowired
    private ProblemMapper problemMapper;
    @Autowired
    private ProblemSimilarPreDealService problemSimilarPreDealService;

    @Override
    public PagingAndSortingRepository<ProblemPicture, String> getDao() {
        return problemPictureDao;
    }

    @Override
    public String addProblem(String parentId, String childName,String fileKey, String derver,Integer type,
                           String derverFileKey,String vipId,String courseName) throws Exception {
    	//判断fileKeys是否在表中存在
		long count = problemPictureDao.countByFileKey(fileKey);
    	if(count > 0) {
    		//如果作业有相同图片则不上传
    		return "";
    	}

        ProblemPicture problemPicture = this.insertProblem(parentId, fileKey,derver, type, derverFileKey,vipId,courseName);



        //极光推送老师端通知
        //String contentMessage = "尊敬的"+teacherName+"老师，在"+DateUtil.dateTimeToString(new Date())+"时间，收到一条难题解答，请您尽快完成解答任务";
        //sconXingeService.asynPushThreadTask(problemPicture.getTeacherId(), 2 , contentMessage);

        //推送线上老师
        //this.sendMsg2KmtTeacher(problemPicture.getVipId(), problemPicture.getTeacherId());

        problemSimilarPreDealService.asyncPostRequest2AI(problemPicture);

        //推送通知至家长端app
        String template_id_short="OPENTM414529612";
        if (StringUtil.isNotBlank(parentId)){
            String parentContentMessage = String.format("您的孩子%s上传了一张难题，赶快来看看吧！", childName);
            sconXingeService.asynPushThreadTask(parentId, null,2 , parentContentMessage,PushConstants.PUSH_PROBLEM);
            //公众号提醒家长
            User parent = userService.getById(parentId);
            Map<String,String> data =new HashMap<String, String>();
            data.put("first", parentContentMessage+"\n");
            data.put("keyword1", childName+"学生");
            data.put("keyword2", problemPicture.getSubject()+"题目");
            data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日  HH时mm分"));
            data.put("remark", "老师在努力的整理本次难题解答内容，稍后会由系统推送给您，请您留意，感谢\n");
            SendTemplateShort sendTemplateShort=new SendTemplateShort(parent.getAccount(), template_id_short, null, data);
            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
        }

        //推送难题，通知老师
        //获取老师信息
        LibVip libVip= libVipService.getById(vipId);
        if(StringUtils.isNotBlank(libVip.getLibId())) {
            String libId=libVip.getLibId();
            List<String> orgTeacherIdList = problemMapper.findOrgTeacherIdByVipIdAndSubject(vipId, problemPicture.getSubject(),libId);
            for (String teacherId : orgTeacherIdList) {
                //推送通知消息至老师端app
                User teacher = userService.getById(teacherId);
                String teacherMessageContent = String.format("您名下的学生%s上传了一张难题，赶快来看看吧！", childName);
                sconXingeService.asynPushThreadTask(teacherId, 4,
                        XinGePushMessageTypeEnum.Message.getCode(), null, "难题提醒", teacherMessageContent, "APP_TEACHER", PushConstants.PUSH_OTHER);
                //小程序提醒老师
                Map<String,String> data1 =new HashMap<>();
                data1.put("first", teacherMessageContent);
                data1.put("keyword1", childName+"学生");
                data1.put("keyword2", problemPicture.getSubject()+"题目");
                data1.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日  HH时mm分"));
                data1.put("remark", "");
                SendTemplateShort sendTemplateShort = new SendTemplateShort(teacher.getAccount(), template_id_short, null, data1);
                pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
            }
        }

        return problemPicture.getId();
    }

    private ProblemPicture insertProblem(String parentId, String fileKey,String derver,
                                         Integer type, String derverFileKey,String vipId,String courseName) throws Exception{
        ProblemPicture problem = new ProblemPicture();
        problem.setDerver(derver);
        problem.setVipId(vipId);
        problem.setParentId(parentId);
        problem.setFileKey(fileKey);
        problem.setSubject(Constant.getSubjectFromRequest(courseName));
        problem.setIsDelete(0);
        problem.setGrade(0);
        if (type != null) {
            problem.setType(type);
        }
        problem.setCommentNums(0);
        problem.setCreateTime(new Date());
        problem.setStatus(ConchConstants.PROBLEM_STATUS_NO_SETTLE);
        problem.setDerverFileKey(derverFileKey);
        // problem.setLastUpdateTime(problem.getCreateTime());
        problem.setIsFeedback(ConchConstants.ISFEEDBACK_NO);
        problem.setIsShare(ConchConstants.ISSHARE_NO);
        //自动随机分配该科目对应的一名老师->修改为绑定的机构老师
        //problem.setTeacherId(getTeacherId(vipId, problem.getSubject()));
//        LibVipBind libVipBind = libVipBindService.findByVipIdAndSubject(vipId, problem.getSubject());
//        if (libVipBind != null) {
//            problem.setTeacherId(libVipBind.getTeacherId());
//        }
        /*if (libVipBind == null || StringUtil.isEmpty(libVipBind.getTeacherId())) {
            throw new Exception("绑定老师不存在，上传失败！");
        }else{
            problem.setTeacherId(libVipBind.getTeacherId());
        }*/
        return this.save(problem);

    }

    public  String getTeacherId (String vipId, String subject) {
        //通过vip_id和科目判断今天是否上传过相同的科目作业，如果有，则分配的老师为之前随机的
        ProblemPicture subjectHomeWork = problemPictureDao.findTop(vipId, subject);
        String result = null;
        if (subjectHomeWork != null) {
            result = subjectHomeWork.getTeacherId();
        } else {
            Map<String,Object> kmtTeacher = null;
            LibVip vip = libVipService.getById(vipId);
            if (vip != null && StringUtils.isNotEmpty(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();
            }
        }
        return result;
    }

    @Override
    public void deleteCustomById(String parentId, List<String> ids, String userCode) {
        // TODO Auto-generated method stub

    }

    @Override
    public void deleteProblem(DeleteProblemRequest request) {
        // TODO Auto-generated method stub
    	problemPictureDao.deleteById(request.getProblemId());
    }

    @Override
    public ProblemDetailFeedback findProblemInfo(FindProblemRequest request,String userId,String userType) {
    	ProblemDetailFeedback problemFeedback = new ProblemDetailFeedback();

        String parentId = null;

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

        TeacherFeedback teacherFeedback = feedbackService.getProblemFeedback(parentId, null,
                                                                          ConchConstants.BIZ_TYPE_PROBLEM,
                                                                          request.getProblemId());
        problemFeedback.setTeacherFeedback(teacherFeedback);
        ProblemPicture problemPicture = this.getById(request.getProblemId());

        problemFeedback.setFileKey(problemPicture.getFileKey());
        problemFeedback.setParentId(parentId);
        problemFeedback.setIsShare(problemPicture.getIsShare());
        problemFeedback.setProblemId(problemPicture.getId());
        problemFeedback.setCreatTime(problemPicture.getCreateTime());
        return problemFeedback;
    }

    @Override
    public Map<String, Object> searchProblemList(Map<String, Object> params, Pageable pageable) {

        Map<String, SearchFilter> filters = SearchFilter.parse(params);
        Specification<ProblemPicture> specification = DynamicSpecifications.bySearchFilter(filters.values(),ProblemPicture.class);
        Page<ProblemPicture> page = problemPictureDao.findAll(specification, pageable);

        List<ProblemExt> extList = new ArrayList<>();
      //  List<String> problemIds = new ArrayList<String>();
        if (page.getSize() > 0) {
            for (ProblemPicture problemPicture : page.getContent()) {
                ProblemExt ext = new ProblemExt();
                ext.setCreateTime(problemPicture.getCreateTime());
                ext.setParentId(problemPicture.getParentId());
                ext.setFileKey(problemPicture.getFileKey());
                ext.setIsFeedback(problemPicture.getIsFeedback());
                ext.setProblemId(problemPicture.getId());
                ext.setWeekday(DateUtil.getWeekDateToStr(problemPicture.getCreateTime()));
                extList.add(ext);
            //    problemIds.add(problemPicture.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 Map<String, Object> searchProblemListOfParent(Map<String, Object> params, Pageable pageable){
        Page<Map<String, Object>> page =  problemPictureQueryDao.findProblemListOfParent(params, pageable);
        Map<String, Object> data = new HashMap<String, Object>();
        int type = (int)params.get("type");
        if (page.getSize() > 0) {
            if(type == 0){
                List<UnAnsweredProblemDto> probList = new ArrayList<>();
                for (Map<String, Object> pageMap : page.getContent()) {
                    UnAnsweredProblemDto problem = new UnAnsweredProblemDto();
                    problem.setFileKey((String) pageMap.get("file_key"));//难题图片路径
                    problem.setProblemId((String) pageMap.get("id"));//难题id
                    problem.setCourseName((String) pageMap.get("subject"));//难题科目
                    problem.setCreateTime((String) pageMap.get("create_time"));//创建时间
                    probList.add(problem);
                }
                data.put("list", probList);
            } else if(type == 1){//已解决难题
                List<AnsweredProblemDto> probList = new ArrayList<>();
                for (Map<String, Object> pageMap : page.getContent()) {
                    AnsweredProblemDto problem = new AnsweredProblemDto();
                    problem.setFileKey((String) pageMap.get("file_key"));//难题图片路径
                    problem.setProblemId((String) pageMap.get("id"));//难题id
                    problem.setCourseName((String) pageMap.get("subject"));//难题科目
                    problem.setCreateTime((String) pageMap.get("feedback_time"));//反馈时间
                    problem.setContent((String) pageMap.get("content"));//难题老师建议
                    probList.add(problem);
                }
                data.put("list", probList);
            }
        }
        data.put("pages", page.getTotalElements());
        data.put("pageNo", pageable.getPageNumber()+1);
        data.put("pageSize", pageable.getPageSize());

        return data;
    }

    @Override
    public Map<String, Object> searchProblemListOfParent(Map<String, Object> params) {
        List<Map<String, Object>> list =  problemPictureQueryDao.findProblemListOfParent(params);
        Map<String, Object> data = new HashMap<>(16);
        if (list != null && list.size() > 0) {
            List<AnsweredProblemDto> probList = new ArrayList<>();
            for (Map<String, Object> map : list) {
                AnsweredProblemDto problem = new AnsweredProblemDto();
                //难题图片路径
                problem.setFileKey((String) map.get("file_key"));
                //难题id
                problem.setProblemId((String) map.get("id"));
                //难题科目
                problem.setCourseName((String) map.get("subject"));
                //创建时间
                problem.setCreateTime((String) map.get("create_time"));
                //难题老师建议
                problem.setContent((String) map.get("content"));
                probList.add(problem);
            }
            data.put("list", probList);
        }
        return data;
    }

    @Override
    public Map<String, Object> findKownHowOfParent(ProblemKnowHowReq request){
        Map<String, Object> data = new HashMap<String, Object>();
        List<Map<String, Object>> list = problemPictureQueryDao.findKownHowOfParent(request);
        data.put("list",list);
        return data;
    }

    @Override
    public Map<String, Object> searchToFeedbackProblemList(Map<String, Object> params, Pageable pageable,
                                                           List<String> pids) {
        // TODO Auto-generated method stub

        // List<SconUserInfo> userlist = sconUserInfoDao.findByUserTypeAndHmId(ConchConstants.USER_TYPE_PARENT,
        // ExecutionContext.getUserId());

        // List<SconUserInfo> userlist =
        // sconUserBindCenterService.findParentUserByTeacherUserId(ExecutionContext.getUserId());
        // List<String> parentIds = new ArrayList<>();
        // for (SconUserInfo sconUserInfo : userlist) {
        // parentIds.add(sconUserInfo.getId());
        // }
        // params.put("IN_parentId", parentIds);
        List<User> userlist = userService.findByIdIn(pids);
        Map<String, SearchFilter> filters = SearchFilter.parse(params);
        Specification<ProblemPicture> specification = DynamicSpecifications.bySearchFilter(filters.values(),
                                                                                           ProblemPicture.class);
        List<ToFeedBack> list = new ArrayList<ToFeedBack>();
        Map<String, User> userInfoMap = userlist.stream().collect(Collectors.toMap(User::getId,
                                                                                           n -> n));
        Page<ProblemPicture> page = problemPictureDao.findAll(specification, pageable);
        if (page != null && page.getSize() > 0) {
            for (ProblemPicture problemPicture : page.getContent()) {
                ToFeedBack toFeedBack = new ToFeedBack();
                toFeedBack.setBizId(problemPicture.getId());
                toFeedBack.setBizType(ConchConstants.BIZ_TYPE_PROBLEM);
                toFeedBack.setFileKey(problemPicture.getFileKey());
                toFeedBack.setIsFeedback(problemPicture.getIsFeedback());
                toFeedBack.setParentId(problemPicture.getParentId());
                User sconUserInfo = userInfoMap.get(problemPicture.getParentId());
                if (sconUserInfo != null) {
                    toFeedBack.setStudentNickname(sconUserInfo.getUserName());
                    toFeedBack.setStudentImageKey(sconUserInfo.getPhoto());
                }
                toFeedBack.setClassifyTime(problemPicture.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> searchProblemListByParentIdForTeacher(String parentId, Map<String, Object> params,
                                                                     Pageable pageable) {
        User sconUserInfo = userService.getById(parentId);
        Map<String, SearchFilter> filters = SearchFilter.parse(params);
        Specification<ProblemPicture> specification = DynamicSpecifications.bySearchFilter(filters.values(),
                                                                                           ProblemPicture.class);
        List<ToFeedBack> list = new ArrayList<ToFeedBack>();

        Page<ProblemPicture> page = problemPictureDao.findAll(specification, pageable);
        if (page != null && page.getSize() > 0) {
            for (ProblemPicture problemPicture : page.getContent()) {
                ToFeedBack toFeedBack = new ToFeedBack();
                toFeedBack.setBizId(problemPicture.getId());
                toFeedBack.setBizType(ConchConstants.BIZ_TYPE_PROBLEM);
                toFeedBack.setFileKey(problemPicture.getFileKey());
                toFeedBack.setIsFeedback(problemPicture.getIsFeedback());
                toFeedBack.setStudentNickname(sconUserInfo.getUserName());
                toFeedBack.setStudentImageKey(sconUserInfo.getPhoto());
                toFeedBack.setClassifyTime(problemPicture.getCreateTime());
                toFeedBack.setParentId(problemPicture.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 ProblemFeedbackForTeacher findProblemInfoForTeacher(FindProblemRequest request,String userId) {
        // TODO Auto-generated method stub
        ProblemPicture problemPicture = this.getById(request.getProblemId());
        TeacherFeedback teacherFeedback = feedbackService.getProblemFeedback(problemPicture.getParentId(),userId,
                                                                          ConchConstants.BIZ_TYPE_PROBLEM,
                                                                          request.getProblemId());

        ProblemFeedbackForTeacher problemFeedbackForTeacher = new ProblemFeedbackForTeacher();
        problemFeedbackForTeacher.setFileKey(problemPicture.getFileKey());
        problemFeedbackForTeacher.setParentId(problemPicture.getParentId());
        problemFeedbackForTeacher.setProblemId(request.getProblemId());
        problemFeedbackForTeacher.setTeacherFeedback(teacherFeedback);
        problemFeedbackForTeacher.setCreatTime(problemPicture.getCreateTime());

        return problemFeedbackForTeacher;
    }

    @Override
    public ProblemDetailFeedback queryProblemFeedbackByProblemId(String parentId, String problemId) {
        // TODO Auto-generated method stub
    	ProblemDetailFeedback problemFeedback = new ProblemDetailFeedback();
        TeacherFeedback teacherFeedback = feedbackService.getProblemFeedbackForStudent(parentId, null,
                                                                          ConchConstants.BIZ_TYPE_PROBLEM, problemId);

        problemFeedback.setTeacherFeedback(teacherFeedback);
        ProblemPicture picture = this.getById(problemId);

        problemFeedback.setFileKey(picture.getFileKey());
        problemFeedback.setParentId(parentId);
        problemFeedback.setIsShare(picture.getIsShare());
        problemFeedback.setProblemId(picture.getId());
        return problemFeedback;
    }

	@Override
	public Map<String, Object> childProblemReviewList(String parentId, String time,String derver) {
		List<ProblemPicture> problemList = problemPictureDao.findProblemReviewByTime(parentId, derver, time);
		Map<String, Object> map = new HashMap<String,Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (ProblemPicture problemPicture : problemList) {
			Map<String, Object> map1 = new HashMap<String,Object>();
			map1.put("problemId", problemPicture.getId());
			//map1.put("createTime", problemPicture.getCreateTime());
			map1.put("createTime",  DateHelper.format(problemPicture.getCreateTime(), "HH:mm"));
			list.add(map1);
		}
		map.put("list", list);
		return map;
	}

	@Override
	public ProblemReviewExt problemReviewInfo(String parentId, String vipId) {
		//查询最近一次难题反馈的记录
		ProblemPicture problemPicture = problemPictureDao.findTopByisDeleteAndParentIdAndVipIdOrderByCreateTimeDesc(0, parentId, vipId);
		if(problemPicture == null) {
			return null;
		}

		ProblemReviewExt ext = new ProblemReviewExt();
		ext.setProblemId(problemPicture.getId());
		ext.setFileKey(problemPicture.getFileKey());
		ext.setCreateTime(problemPicture.getCreateTime());
		ext.setIsFeedback(problemPicture.getIsFeedback());

		if(problemPicture.getIsFeedback() == 1) {
			Feedback feedback = feedbackService.findByBizId(problemPicture.getId());
			// 获取老师的反馈信息
	        // 获取老师返回的文字信息
	        SconTextFeedbackDetail text = sconTextFeedbackDetailService.findByFeedbackIdAndType(feedback.getId(),"4");
	        if(text != null) {
	        	//老师解答时间
	            ext.setAnswerTime(feedback.getCreateTime());
	        	//反馈时间
	            ext.setFeedBackTime(text.getCreateTime());
	             //总体建议
	            ext.setContent(text.getContent());
	        }else {
	        	//老师解答时间
	            ext.setAnswerTime(feedback.getCreateTime());
	        	//反馈时间
	            ext.setFeedBackTime(feedback.getCreateTime());
	        }

	        //获取老师反馈的知识点信息
	        List<SconKnowFeedbackDetail> knowList = sconKnowFeedbackDetailService.findByFeedbackId(feedback.getId());
	        if(CollectionUtils.isNotEmpty(knowList)) {
	        	List<String> idsList = new ArrayList<String>();
	            for (SconKnowFeedbackDetail know : knowList) {
	            	idsList.add(know.getKnowHowDetailsId());
	            }
	            List<ZuoybKnowHowDetails> detailsList = zuoybKnowHowDetailsService.findByIds(idsList);
	            StringBuffer sb = new StringBuffer();
	            for (ZuoybKnowHowDetails zuoybKnowHowDetails : detailsList) {
	                sb.append(zuoybKnowHowDetails.getName()).append(",");
	    		}
	            if(StringUtils.isNotBlank(sb.toString())) {
	            	ext.setKnowHow(sb.substring(0, sb.length()-1));
	    		}
	        }
		}
		return ext;
	}
	@Override
	public Map<String, Object> searchProblemListByStudentSubject(Map<String, Object> params,Pageable pageable) {

        Map<String, SearchFilter> filters = SearchFilter.parse(params);
        Specification<ProblemPicture> specification = DynamicSpecifications.bySearchFilter(filters.values(),
                                                                                           ProblemPicture.class);
        List<ToFeedBackProblem> list = new ArrayList<ToFeedBackProblem>();

        Page<ProblemPicture> page = problemPictureDao.findAll(specification, pageable);
        if (page != null && page.getSize() > 0) {
            for (ProblemPicture problemPicture : page.getContent()) {
            	ToFeedBackProblem toFeedBack = new ToFeedBackProblem();
                toFeedBack.setBizId(problemPicture.getId());
                toFeedBack.setBizType(ConchConstants.BIZ_TYPE_PROBLEM);
                toFeedBack.setFileKey(problemPicture.getFileKey());
                toFeedBack.setIsFeedback(problemPicture.getIsFeedback());
                toFeedBack.setCreateTime(problemPicture.getCreateTime());
                toFeedBack.setParentId(problemPicture.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 void updateByIsFeedback(String id) {
		problemPictureDao.updateByIsFeedback(id);
	}

	@Override
	public float count() {

		return problemPictureDao.count();
	}

	@Override
	public List<ProblemPicture> findByisDeleteAndTeacherIdAndIsFeedbackAndCreateTimeAfterOrderByCreateTimeAsc(int i,
			String teacherUserId, int isFeedback, Date todatDate) {

		return problemPictureDao.findByisDeleteAndTeacherIdAndIsFeedbackAndCreateTimeAfterOrderByCreateTimeAsc(i,teacherUserId,isFeedback,todatDate);
	}

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

		return problemPictureDao.countByTeacherIdAndIsFeedback(userId,i);
	}

	@Override
	public Map<String, Object> searchProblemListByParent(Map<String, Object> params, Pageable pageable) {

		Page<Map<String, Object>> page =  problemPictureQueryDao.findByProblemListByParent(params, pageable);
		List<ProblemListExt> list = new ArrayList<ProblemListExt>();
		if(CollectionUtils.isNotEmpty(page.getContent())) {
			List<String> problemIds = new ArrayList<String>();
			for (Map<String, Object> pageMap : page.getContent()) {
				if((Integer)pageMap.get("is_feedback") == 1) {
					problemIds.add((String)pageMap.get("id"));
				}
			}

			List<Map<String,Object>> feedbackList = null;
			Map<Object, Object> feedbackMap = null;
			if(CollectionUtils.isNotEmpty(problemIds)) {
				feedbackList = feedbackService.findTextFeedbackByProblemIds(problemIds);
				feedbackMap = feedbackList.stream().collect(Collectors.toMap(n -> n.get("biz_id"),n -> n));
			}

			for (Map<String, Object> pageMap : page.getContent()) {
				ProblemListExt ext = new ProblemListExt();
				ext.setProblemId((String)pageMap.get("id"));
				ext.setFileKey((String)pageMap.get("file_key"));
				ext.setCreateTime((Date)pageMap.get("create_time"));
				ext.setIsFeedback((Integer)pageMap.get("is_feedback"));

	        	if((Integer)pageMap.get("is_feedback") == 1){

	        		Map<Object, Object> feedback = (Map<Object, Object>) feedbackMap.get(pageMap.get("id"));

	        		//为防止出现反馈的时候没有type= 4总体建议的情况 后台报错
	        		String feedBackId = null;
	        		if(feedback == null) {
	        			Feedback back = feedbackService.findByBizId(pageMap.get("id").toString());
	        			 //老师解答时间
		        		ext.setAnswerTime(back.getCreateTime());
		        		//反馈时间
		            	ext.setFeedBackTime(back.getCreateTime());
		            	feedBackId = back.getId();
	        		}else {
	        			 //老师解答时间
		        		ext.setAnswerTime((Date)feedback.get("answer_time"));
		        		//反馈时间
		            	ext.setFeedBackTime((Date)feedback.get("feedback_time"));
		            	//总体建议
		        		ext.setContent((String)feedback.get("content"));
		        		feedBackId = feedback.get("id").toString();
	        		}

	                //获取老师反馈的知识点信息
	                List<SconKnowFeedbackDetail> knowList = sconKnowFeedbackDetailService.findByFeedbackId(feedBackId);
	                if(CollectionUtils.isNotEmpty(knowList)) {
	                	List<String> idsList = new ArrayList<String>();
	                	for (SconKnowFeedbackDetail know : knowList) {
	                    	idsList.add(know.getKnowHowDetailsId());
	                    }
	                    List<ZuoybKnowHowDetails> detailsList = zuoybKnowHowDetailsService.findByIds(idsList);
	                    StringBuffer sb = new StringBuffer();
	                    for (ZuoybKnowHowDetails zuoybKnowHowDetails : detailsList) {
	                        sb.append(zuoybKnowHowDetails.getName()).append(",");
	            		}
	                    if(StringUtils.isNotBlank(sb.toString())) {
	            			ext.setKnowHow(sb.substring(0, sb.length()-1));
	            		}
	                }
	        	}
	            list.add(ext);
			}
		}
        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 List<ProblemPicture> findTodayPPLibIdAndFeeback(int isFeedback, List<String> libIds) {
        return problemPictureDao.findByIsFeedbackAndLibIdInAndCreateTimeAfterOrderByCreateTimeAsc(isFeedback, libIds);
    }

    @Override
    public List<ProblemPicture> findNotFeedbackList(List<String> libIds) {
        return problemPictureDao.findNotFeedbackList(0, libIds);
    }

    @Override
    public ProblemPicture findLastNotFeedback (String teacherId, String vipId){
        return problemPictureDao.findFirstByTeacherIdAndVipIdOrderByCreateTimeDesc(teacherId, vipId);
    }

	@Override
	public ProblemDetailFeedback findProblemInfoForParent(FindProblemRequest request, String userId) {
		ProblemDetailFeedback problemFeedback = new ProblemDetailFeedback();

        TeacherFeedback teacherFeedback = feedbackService.getProblemFeedback(userId, null,
                                                                          ConchConstants.BIZ_TYPE_PROBLEM,
                                                                          request.getProblemId());
        problemFeedback.setTeacherFeedback(teacherFeedback);
        ProblemPicture problemPicture = this.getById(request.getProblemId());
        problemFeedback.setFileKey(problemPicture.getFileKey());
        problemFeedback.setParentId(userId);
        problemFeedback.setIsShare(problemPicture.getIsShare());
        problemFeedback.setProblemId(problemPicture.getId());
        problemFeedback.setCreatTime(problemPicture.getCreateTime());
        return problemFeedback;
	}

	@Override
	public ProblemDetailFeedback findProblemInfoForStudent(FindProblemRequest request, String userId) {

		ProblemDetailFeedback problemFeedback = new ProblemDetailFeedback();
        String parentId = conchDerverService.findByChildUserId(userId).getUserId();
        TeacherFeedback teacherFeedback = feedbackService.getProblemFeedbackForStudent(parentId, null,
                                                                          ConchConstants.BIZ_TYPE_PROBLEM,
                                                                          request.getProblemId());
        problemFeedback.setTeacherFeedback(teacherFeedback);
        ProblemPicture problemPicture = this.getById(request.getProblemId());

        problemFeedback.setFileKey(problemPicture.getFileKey());
        problemFeedback.setParentId(parentId);
        problemFeedback.setIsShare(problemPicture.getIsShare());
        problemFeedback.setProblemId(problemPicture.getId());
        problemFeedback.setCreatTime(problemPicture.getCreateTime());
        return problemFeedback;
	}

	@Override
    public void feedbackToProblem(FeedbackProblemRequest request) {
        ProblemPicture pp  = this.getById(request.getBizId());
        //为了保存feedback, 没有会新增
        feedbackService.getFeedback(request.getBizId());
        this.saveTextList(request.getBizId(), request.getContentList());
        this.savePhotoList(request.getBizId(), request.getPhotoKeyList());
        this.saveKnowList(request.getBizId(), request.getKnowHowList());
        this.saveVoiceList(request.getBizId(), request.getVoiceKeyList());
        if (request.getType() == 1){
            this.setFeedbakcAndPush(request.getBizId());
            feedbackService.feedback2Conch(request.getBizId());
        }
        //小程序答疑推送一下线上老师刷线页面
        this.sendPictureMsg2KmtTeacher(request.getBizId(), pp.getTeacherId());
    }

    @Override
    public void feedbackToProblem(SaveAnswerReq request) {
        //为了保存feedback, 没有会新增
        feedbackService.getFeedback(request.getProblemId());
        if (StringUtils.isNotBlank(request.getContent())) {
            List<Map<String, String>> contentList = new ArrayList<>();
            Map<String, String> contentMap = new HashMap<>(16);
            contentMap.put("type", String.valueOf(4));
            contentMap.put("content", request.getContent());
            contentList.add(contentMap);
            this.saveTextList(request.getProblemId(), contentList);
        }
        List<Map<String, String>> photoKeyList = new ArrayList<>();
        if (request.getFileKeys() != null && request.getFileKeys().size() > 0) {
            for (String photoKey : request.getFileKeys()) {
                Map<String, String> photoMap = new HashMap<>(16);
                photoMap.put("type", String.valueOf(4));
                photoMap.put("photoKey", photoKey);
                photoKeyList.add(photoMap);
            }
        }
        this.savePhotoList(request.getProblemId(), photoKeyList);
        this.saveKnowList(request.getProblemId(), request.getKnowHowList());
        this.saveVoiceList(request.getProblemId(), request.getVoiceKeyList());
        this.setFeedbakcAndPush(request.getProblemId());
        feedbackService.feedback2Conch(request.getProblemId(), Constant.ORG_TEACHER_TYPE);
    }

    @Override
    public Map<String, Object> findProblemPartDetail(String pid){
        Map<String, Object> data = new HashMap<String, Object>();
        ProblemDetailDto result = null;
        ProblemPicture pp = this.getById(pid);
        if (pp != null){
            result = new ProblemDetailDto();
            if (StringUtils.isNotEmpty(pid)){
                result.setPictureId(pid);
                result.setProblemImage(pp.getFileKey());
                result.setCreateTime(DateUtil.format_yyyyMMddHHmmss(pp.getCreateTime()));
                this.injectTextList(result, pid);
                this.injectImageList(result, pid);
                this.injectKnowList(result, pid);
                this.injectVoices(result, pid);
            } else {
                data.put("msg", "pid不能为空");
            }
        } else {
            data.put("msg", "查不到改难题");
        }
        data.put("data", result);

        return data;
    }

    /**
     * 保存小程序的文字描述
     * @param pid
     * @param contentList
     */
    private void saveTextList (String pid, List<Map<String, String>> contentList){
        String[] textList = new String[4];
        if (contentList != null){
            for (Map<String, String> map : contentList){
                textList[Integer.parseInt(map.get("type")) - 1] = map.get("content");
            }
        }
        this.saveAnswerText(pid, JSONObject.toJSONString(textList));
    }

    /**
     * 保存图片
     * @param pid
     * @param photoKeyList
     */
    private void savePhotoList (String pid, List<Map<String, String>> photoKeyList){
        List[] photoList = new ArrayList[4];
        if (photoKeyList != null){
            int type = 0;
            for (Map<String, String> map : photoKeyList){
                type = Integer.parseInt(map.get("type")) - 1;
                if (photoList[type] == null){
                    photoList[type] = new ArrayList<String>();
                }
                photoList[type].add(map.get("photoKey"));
            }
        }
        this.saveAnswerPhoto(pid, JSONObject.toJSONString(photoList));
    }

    /**
     * 保存图片
     * @param feedbackId
     * @param photoKeyList
     */
    private void savePhotoListV1(String feedbackId, List<String> photoKeyList) {
        if (CollectionUtils.isEmpty(photoKeyList)) {
            return;
        }
        logger.info("图片列表photoKeyList={}", photoKeyList);
        List<SconPhotoFeedbackDetail> voiceFeedbackList = sconPhotoFeedbackDetailService.findByFeedbackIdOrderByNumAsc(feedbackId);
        //删除之前所有语音结果
        voiceFeedbackList.forEach(e -> sconPhotoFeedbackDetailService.delete(e));
        Date now = new Date();
        //保存语音信息
        for (int i = 0; i < photoKeyList.size(); i++) {
            SconPhotoFeedbackDetail photo = new SconPhotoFeedbackDetail();
            photo.setFeedbackId(feedbackId);
            photo.setFileKey(photoKeyList.get(i));
            photo.setCreateTime(now);
            //排序
            photo.setNum(i + 1);
            sconPhotoFeedbackDetailService.save(photo);
        }
    }

    /**
     * 保存知识点
     * @param pid
     * @param knowList
     */
    private void saveKnowList (String  pid, List<Map<String, String>> knowList){
        List<String> knowDetailList = new ArrayList<String>();
        if (knowList != null){
            for (Map<String, String> map : knowList){
                knowDetailList.add(map.get("knowHowDetailsId"));
            }
        }
        this.saveAnswerKnowledge(pid, JSONObject.toJSONString(knowDetailList));
    }

    /**
     * 保存语音列表
     * @param pid
     * @param voiceList
     */
    private void saveVoiceList (String pid, List<Map<String, String>> voiceList){
        if (voiceList == null || voiceList.size() == 0) {
            return;
        }
        logger.info("语音列表voiceList={}", voiceList);
        List<String> list =new ArrayList<String>();
        Feedback fd = feedbackService.getFeedback(pid);
        List<SconVoiceFeedbackDetail> voiceIndbList = sconVoiceFeedbackDetailService.findByFeedbackId(fd.getId());
        // 保存语音信息
        for (int i = 0; i < voiceList.size(); i++) {
            Map<String, String> map = voiceList.get(i);
            SconVoiceFeedbackDetail voice = null;
            if (voiceIndbList != null) {
                for (SconVoiceFeedbackDetail item : voiceIndbList) {
                    if (item.getType().equals(map.get("type"))) {
                        voice = item;
                        break;
                    }
                }
            }
            if (voice == null) {
                voice = new SconVoiceFeedbackDetail();
            }
            voice.setFeedbackId(fd.getId());
            voice.setFileKey(map.get("voiceKey"));
            voice.setDuration(map.get("duration"));
            voice.setType(map.get("type"));
            voice.setCreateTime(new Date());
            //排序
            voice.setNum(i + 1);
            sconVoiceFeedbackDetailService.save(voice);
            list.add(map.get("voiceKey"));
        }

        SconSynthVoiceFeedbackDetail synthVoice = sconSynthVoiceFeedbackDetailService.findByFeedbackId(fd.getId());
        if ( synthVoice == null){
            synthVoice = new SconSynthVoiceFeedbackDetail();
        }

        if(voiceList.size() > 1) {
            //合成语音  后面改成异步
            String path= ExecLinuxCMD.mergeToMp3(list);
            double time =AmrToMp3Util.getMp3durationNew(path);
            if (time > 0) {
                BigDecimal bg = new BigDecimal(time);
                String realTime = bg.divide(new BigDecimal(2)).setScale(0,BigDecimal.ROUND_HALF_UP).toString();
                synthVoice.setFeedbackId(fd.getId());
                synthVoice.setFileKey(path);
                synthVoice.setDuration(realTime);
                synthVoice.setCreateTime(new Date());
                sconSynthVoiceFeedbackDetailService.save(synthVoice);
            }
        }else {
            Map<String, String> map = voiceList.get(0);
            String fileKey = map.get("voiceKey");
            String duration = map.get("duration");
            if (StringUtils.isNotEmpty(duration) && Integer.parseInt(duration) > 0){
                synthVoice.setFeedbackId(fd.getId());
                synthVoice.setFileKey(fileKey);
                synthVoice.setDuration(duration);
                synthVoice.setCreateTime(new Date());
                sconSynthVoiceFeedbackDetailService.save(synthVoice);
            }
        }
    }

    /**
     * 保存语音列表
     * @param feedbackId
     * @param voiceList
     */
    private void saveVoiceListV1(String feedbackId, List<Map<String, String>> voiceList) {
        if (CollectionUtils.isEmpty(voiceList)) {
            return;
        }
        logger.info("语音列表voiceList={}", voiceList);
        List<SconVoiceFeedbackDetail> voiceFeedbackList = sconVoiceFeedbackDetailService.findByFeedbackId(feedbackId);
        //删除之前所有语音结果
        voiceFeedbackList.forEach(e -> sconVoiceFeedbackDetailService.delete(e));
        Date now = new Date();
        //保存语音信息
        for (int i = 0; i < voiceList.size(); i++) {
            Map<String, String> map = voiceList.get(i);
            SconVoiceFeedbackDetail voice = new SconVoiceFeedbackDetail();
            voice.setFeedbackId(feedbackId);
            voice.setFileKey(map.get("voiceKey"));
            voice.setDuration(map.get("duration"));
            voice.setCreateTime(now);
            //排序
            voice.setNum(i + 1);
            sconVoiceFeedbackDetailService.save(voice);
        }
    }



	public List<Map<String, Object>> findProblemList (String teacherId) {
        List<Map<String, Object>> result = null;
        if (StringUtils.isNotEmpty(teacherId)){
            String beginTime = DateUtil.format_yyyyMMddHHmmss(DateUtil.getTodatDate());
            //加上历史未解答的数据，目前先这么处理
            result = problemPictureQueryDao.findHistoryNotFeedbackProblem(teacherId, beginTime);
            result.addAll(problemPictureQueryDao.findProblemByTeacher(teacherId, beginTime));
        } else {
            logger.error("查询的老师Id为空");
        }
        return result;
    }

    @Override
    public Map<String, Object> findSubjectList (String teacherId){
        List<Map<String, Object>> problemList = findProblemList(teacherId);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", parseToFrontFormat(problemList));
        data.put("totalNotFeedback", countNotFeedbackVip(teacherId));
        return data;
    }

    @Override
    public Map<String, Object> findHistorySubjectList (String teacherId){
        Map<String, Object> data = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(teacherId)){
            String beginTime = DateUtil.format_yyyyMMddHHmmss(DateUtil.getTodatDate());
            List<Map<String, Object>> problemList = problemPictureQueryDao.findHistoryNotFeedbackProblem(teacherId, beginTime);
            data.put("list", parseToFrontFormat(problemList));
            data.put("totalNotFeedback", countNotFeedbackVip(teacherId));
        }
        return data;
    }

    @Override
    public List<SubjectStudentDto> parseToFrontFormat (List<Map<String, Object>> list) {
        List<SubjectStudentDto>  result = new ArrayList<SubjectStudentDto>();
        SubjectStudentDto target = null;
        StudentProblemDto stuTarget = null;
        ProblemDto problem  = null;

        for (Map<String, Object> map : list){
            problem = new ProblemDto();
            problem.setPid(map.get("pid") + "");
            problem.setpPath(map.get("file_key") + "");
            String editpath = (String)map.get("editpath");
            if (StringUtils.isBlank(editpath)){
                problem.setEditPath((String)map.get("path"));
            } else {
                problem.setEditPath(editpath);
            }
            Integer isMark = (Integer) map.get("is_mark");
            problem.setIsVague(isMark == 1 || isMark == 3 ? isMark :  0);
            problem.setDefaultBookId((String)map.get("book_id"));
            problem.setDefaultUnitId((String)map.get("unit_id"));
            problem.setDefaultPeriodId((String)map.get("module_id"));
            if (map.get("book_page_no") != null){
                JSONArray pageNoArray = JSON.parseArray(map.get("book_page_no").toString());
                problem.setDefaultPageNo(pageNoArray.toJavaList(String.class));
            }
            problem.setIsFeedback(StringUtils.isEmpty(map.get("is_feedback") + "") ? 0 : Integer.parseInt(map.get("is_feedback") + ""));
            target = getSubjectStudent(result, (String) map.get("subject"),
                    (Date)map.get("create_time"));
            stuTarget = getStudentProblem(target.getList(), map, (Date)map.get("create_time"));
            stuTarget.addProblem(problem);
        }
        return result;
    }

    @Override
    public int countNotFeedbackVip (String teacherId) {
        return problemPictureDao.countNotFeedbackVip(teacherId);
    }

    /**
     * 遍历学科列表,如果没有该学科的节点，则新增节点并加入
     * @param result
     * @param subject
     * @return
     */
    public SubjectStudentDto getSubjectStudent (List<SubjectStudentDto>  result, String subject, Date date) {
        Iterator<SubjectStudentDto> itSub = result.iterator();
        SubjectStudentDto target = null;

        //遍历学科列表,如果没有该学科的节点，则新增节点并加入
        while (itSub.hasNext()){
            target = itSub.next();
            if (target.getName().equals(subject) && DateUtil.isSameDay(DateUtil.parse_yyyyMMddHHmmss(target.getTime()), date)){
                break;
            } else {
                target = null;
            }
        }

        if (target == null){
            target = new SubjectStudentDto(subject, date);
            result.add(target);
        }

        return target;
    }

    /**
     * 遍历学生列表,如果没有该学生的节点，则新增节点并加入
     * @param list
     * @param data
     * @return
     */
    public StudentProblemDto getStudentProblem (List<StudentProblemDto> list, Map<String, Object> data, Date date) {
        String vipId = (String)data.get("vip_id");
        Iterator<StudentProblemDto> itStu = list.iterator();
        ZuoybStudentPush push = pushSerivce.findByVipIdAndDate(vipId, DateUtil.format_yyyyMMdd(date));
        StudentProblemDto target = null;
        //遍历学生列表,如果没有该学生的节点，则新增节点并加入
        while (itStu.hasNext()){
            target = itStu.next();
            if (target.getVipId().equals(vipId)){
                break;
            } else {
                target = null;
            }
        }

        if (target == null){
            target = new StudentProblemDto();
            if (push != null && StringUtil.isNotBlank(push.getImg())){
                String[] imgs = push.getImg().split(",");
                for (String img : imgs){
                    ProblemDto pic = new ProblemDto();
                    pic.setIsCheckIn(1);
                    pic.setpPath(img);
                    pic.setIsFeedback(1);
                    target.addProblem(pic);
                }
            }
            target.setVipId(vipId);
            target.setName((String)data.get("child_name"));
            target.setHomeworkId((String)data.get("homework_id"));
            target.setGrade((String)data.get("grade"));
            int banben = banbenDetailService.findBanben((String)data.get("subject"), (String)data.get("school"), (String)data.get("grade"));
            target.setVersion(banben);
            list.add(target);
        }
        return target;
    }

    /**
     * 查询图片数据
     * @return
     */
    @Override
    public Map<String, Object> findPictureData(String pid) {
        Map<String, Object> data = new HashMap<String, Object>();
        ProblemPicture pp = this.getById(pid);
        ProblemDetailDto result = new ProblemDetailDto();

        if (pp != null){
            result.setPictureId(pid);
            result.setProblemImage(pp.getFileKey());
            result.setSubject(pp.getSubject());
            result.setCreateTime(DateUtil.format_yyyyMMddHHmmss(pp.getCreateTime()));
            LibVip vip = null;
            if (StringUtils.isNotEmpty(pp.getVipId())){
                vip = libVipService.getById(pp.getVipId());
                if (vip != null){
                    result.setStudentName(vip.getChildName());
                    result.setGrade(vip.getGrade());
                } else {
                    data.put("msg", "查不到该学生的记录");
                }
            } else {
                data.put("msg", "错题记录中不存在学生id");
            }
            this.injectImageList(result, pid);
        } else {
            data.put("msg", "不存在该错题");
        }

        data.put("data", result);
        return data;
    }

    @Override
    public Map<String, Object> findPictureData4PC(String pid) {
        Map<String, Object> data = new HashMap<String, Object>();
        ProblemDetailDto result = new ProblemDetailDto();
        if (StringUtils.isNotEmpty(pid)){
            result.setPictureId(pid);
            this.injectTextList(result, pid);
            this.injectImageList(result, pid);
            this.injectKnowList(result, pid);
            this.injectVoiceData(result, pid);
        } else {
            data.put("msg", "pid不能为空");
        }
        data.put("data", result);

        return data;
    }

    /**
     * 往result中添加反馈图片
     * @param result
     * @param pid
     */
    public void injectImageList (ProblemDetailDto result, String pid) {
        if (StringUtils.isNotEmpty(pid)){
            Feedback fd = feedbackService.getFeedback(pid);
            List<SconPhotoFeedbackDetail> list = sconPhotoFeedbackDetailService.findByFeedbackIdOrderByNumAsc(fd.getId());
            for (SconPhotoFeedbackDetail photo : list){
                result.addImg(Integer.parseInt(photo.getType()), photo.getFileKey());
            }
        }
    }

    /**
     * 往result中添加反馈文字
     * @param result
     * @param pid
     */
    public void injectTextList (ProblemDetailDto result, String pid) {
        if (StringUtils.isNotEmpty(pid)){
            Feedback fd = feedbackService.getFeedback(pid);
            List<SconTextFeedbackDetail> list = sconTextFeedbackDetailService.findByFeedbackId(fd.getId());
            for (SconTextFeedbackDetail text : list){
                result.addText(Integer.parseInt(text.getType()), text.getContent());
            }
        }
    }

    /**
     * 添加关联知识点
     * @param result
     * @param pid
     */
    public void injectKnowList (ProblemDetailDto result, String pid){
        if (StringUtils.isNotEmpty(pid)) {
            List<Map<String, Object>> list = sconKnowFeedbackDetailService.findKnowledgeFeedbakList(pid);
            if (list != null){
                for (Map<String, Object> map : list){
                    if (StringUtils.isNotEmpty(map.get("id") + "")){
                        result.addKnowledge(map);
                    }
                }
            }
        }
    }

    /**
     * 添加语音数据
     * @param result
     * @param pid
     */
    public void injectVoiceData (ProblemDetailDto result, String pid){
        if (StringUtils.isNotEmpty(pid)){
            Feedback fd = feedbackService.getFeedback(pid);
            SconSynthVoiceFeedbackDetail detail = sconSynthVoiceFeedbackDetailService.findByFeedbackId(fd.getId());
            if (detail != null){
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("voiceKey", detail.getFileKey());
                data.put("voiceDuration", detail.getDuration());
                result.setVoiceData(data);
            }
        }
    }

    public void injectVoices (ProblemDetailDto result, String pid){
        if (StringUtils.isNotEmpty(pid)) {
            Feedback fd = feedbackService.getFeedback(pid);
            List<SconVoiceFeedbackDetail> detailList = sconVoiceFeedbackDetailService.findByFeedbackId(fd.getId());
            if (detailList != null){
                for (SconVoiceFeedbackDetail detail : detailList){
                    result.addVoice(detail.getFileKey(), detail.getDuration(), Integer.parseInt(detail.getType()));
                }
            }
        }
    }


    @Override
    public String saveAnswerPhoto(String pid, String data) {
        String msg = null;
        JSONArray dataArray = null;
        if (StringUtils.isEmpty(pid) || StringUtils.isEmpty(data)){
            msg = "图片ID或答疑的图片列表不能为空";
            return msg;
        }

        try{
            dataArray = JSONArray.parseArray(data);
        }catch (Exception e){
            msg = "图片列表传递的格式错误";
        }
        Feedback fb = feedbackService.getFeedback(pid);
        List<SconPhotoFeedbackDetail> list = sconPhotoFeedbackDetailService.findByFeedbackIdOrderByNumAsc(fb.getId());
        SconPhotoFeedbackDetail temp = null;
        //循环入参列表，按类型顺序排列
        this.removeFeedbackPhoto(list, dataArray);
        list = sconPhotoFeedbackDetailService.findByFeedbackIdOrderByNumAsc(fb.getId());
        this.reSortPhotoNum(list);
        this.addFeedbackPhoto(list, dataArray, fb.getId());
        return msg;
    }

    /**
     * 删除库里有传参没有的图片
     * @param pfdList
     * @param dataArray
     */
    public void removeFeedbackPhoto (List<SconPhotoFeedbackDetail> pfdList, JSONArray dataArray) {
        JSONArray temp = null;
        for (SconPhotoFeedbackDetail  pfd : pfdList){
            temp  = dataArray.getJSONArray(Integer.parseInt(pfd.getType()) - 1);
            boolean rmFlag = true;
            for (Object photo : temp){
                if (pfd.getFileKey().equals(photo.toString())){
                    rmFlag = false;
                }
            }
            if (rmFlag){
                sconPhotoFeedbackDetailService.delete(pfd);
            }
        }
    }

    /**
     * num重排序
     * @param pfdList
     */
    public void reSortPhotoNum (List<SconPhotoFeedbackDetail> pfdList){
        int num = 1;
        int type = 1;
        SconPhotoFeedbackDetail temp = null;
        if (pfdList != null){
            for (int i = 0; i < pfdList.size(); i++){
                temp = pfdList.get(i);
                if (!temp.getType().equals(type + "")){
                    num = 1;
                    type++;
                }
                if (temp.getNum() != num){
                    temp.setNum(num);
                    sconPhotoFeedbackDetailService.save(temp);
                }
            }
        }
    }

    /**
     * 找出需要添加的图片反馈
     */
    public void addFeedbackPhoto (List<SconPhotoFeedbackDetail> pfdList, JSONArray dataArray, String feedbackId) {
        JSONArray temp = null;
        SconPhotoFeedbackDetail fdTmp = null;
        if (dataArray != null){
            for (int i = 0; i < dataArray.size(); i++){
                temp = dataArray.getJSONArray(i);
                if (temp != null){
                    for (Object photo : temp){
                        if (!hasInDb(pfdList, photo.toString(), (i + 1) + "")){
                            fdTmp = new SconPhotoFeedbackDetail();
                            fdTmp.setFeedbackId(feedbackId);
                            fdTmp.setFileKey(photo.toString());
                            fdTmp.setType((i + 1) + "");
                            fdTmp.setNum(getTypeMaxNum(pfdList, (i + 1) + ""));
                            fdTmp.setCreateTime(new Date());
                            sconPhotoFeedbackDetailService.save(fdTmp);
                        }
                    }
                }
            }
        }
    }

    /**
     * 是否存在库里
     * @param pfdList
     * @param url
     * @param type
     * @return
     */
    public boolean hasInDb (List<SconPhotoFeedbackDetail> pfdList, String url, String type) {
        boolean result = false;
        if (pfdList != null){
            for (SconPhotoFeedbackDetail pfd : pfdList){
                if (pfd.getType().equals(type) && pfd.getFileKey().equals(url)){
                    result = true;
                }
            }
        }
        return result;
    }

    /**
     * 获取某个类别的最大num
     * @param pfdList
     * @param type
     * @return
     */
    public int getTypeMaxNum (List<SconPhotoFeedbackDetail> pfdList, String type) {
        int result = 0;
        if (pfdList != null){
            for (SconPhotoFeedbackDetail pfd : pfdList){
                if (pfd.getType().equals(type) && result < pfd.getNum()){
                    result = pfd.getNum();
                }
            }
        }
        return (result + 1);
    }


    @Override
    public void saveAnswerSubmit(String pid, String imgs, String texts, String knows) {
        this.saveAnswerPhoto(pid, imgs);
        this.saveAnswerText(pid, texts);
        this.saveAnswerKnowledge(pid, knows);
        this.setFeedbakcAndPush(pid);
        feedbackService.feedback2Conch(pid);
    }

    @Override
    public void minuteSave(String pid, String imgs, String texts, String knows) {
        this.saveAnswerPhoto(pid, imgs);
        this.saveAnswerText(pid, texts);
        this.saveAnswerKnowledge(pid, knows);
    }

    /**
     * 如果是未答疑的，设置为已答疑
     * @param pid
     */
    public void setFeedbakcAndPush (String pid) {
        ProblemPicture pp = getById(pid);
        //User parent = userService.getById(pp.getParentId());
        LibVip libVip = libVipService.getById(pp.getVipId());
        TbLibManager teacher = managerService.findByUserId(pp.getTeacherId(), Constant.ORG_TEACHER_TYPE);
        String teacherName = ParseUtil.getName(teacher.getName(), pp.getTeacherId());
        //推送文本
        String first = "尊敬的" + libVip.getChildName() + "家长，您孩子的难题老师已经解答完毕，快来看看吧";
        if (pp.getIsFeedback() == 1){
            //first = "尊敬的" + parent.getName() + "家长，已收到" + teacherName + "老师修改您孩子的难题解答，请您及时地反馈给孩子并督促学习";
        } else {
            pp.setIsFeedback(1);
            this.save(pp);
            zuoybDayService.saveToday(pp.getVipId(), 2, DateUtil.format_yyyyMMdd(pp.getCreateTime()));
            //first = "尊敬的" + parent.getName() + "家长，已收到" + teacherName + "老师完成您孩子的难题解答，请您及时地反馈给孩子并督促学习";
        }

        Feedback fd = feedbackService.findByBizId(pid);
        List<SconTextFeedbackDetail> tfdList = sconTextFeedbackDetailService.findByFeedbackId(fd.getId());
        String content = null;
        for (SconTextFeedbackDetail tfd : tfdList){
            if (tfd.getType().equals("4")){
                content = tfd.getContent();
            }
        }
        //推送ipad学生端
        sconXingeService.asynPushThreadTask(libVip.getChildUserId(),null, 3 , libVip.getChildName()+"同学，老师已经解答了你的"+pp.getSubject()+"难题，赶快来看看吧！",PushConstants.PUSH_PROBLEM);
        //推送家长端APP
        sconXingeService.asynPushThreadTask(pp.getParentId(), null,2 , first,PushConstants.PUSH_PROBLEM);
        //推送家长微信公众号
        pushJzShortTemplate(first, teacherName, content, pp.getParentId(),pid);
    }

    /**
     * 推送接口
     * @param first
     * @param key1
     * @param key2
     * @param userId
     */
    public void pushJzShortTemplate (String first, String key1, String key2, String userId,String problemId) {
        String template_id_short="OPENTM412213720";
        User parent = userService.getById(userId);
        try{
            //小程序提醒
            Map<String,String> data =new HashMap<String, String>();
            data.put("first", first +"\n");
            data.put("keyword1", key1);
            data.put("keyword2", key2);
            data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日  HH时mm分"));
            data.put("remark", "\n");
            
			Miniprogram miniprogram =new  Miniprogram();
			miniprogram.setAppid(WxUtil.map.get("jzdAppId"));
			miniprogram.setPagepath("pages/problem_report/problem_report?type=9&problemId="+problemId);
            
            SendTemplateShort sendTemplateShort = new SendTemplateShort(parent.getAccount(), template_id_short, null, data,miniprogram);
            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
            logger.info("推送代码完成");
        } catch (Exception e){
            logger.error("推送小程序异常");
        }
    }


    /**
     * 删除该图片的图片反馈
     * @param pid
     * @param imgs
     */
    public void removeAnswerImg (String pid, String imgs){
        JSONArray imgArray = JSONArray.parseArray(imgs);
        List<SconPhotoFeedbackDetail> list = sconPhotoFeedbackDetailService.findPhotoByPid(pid);
        if (imgArray != null && imgArray.size() > 0){
            for (SconPhotoFeedbackDetail pfd : list){
                for (Object img : imgArray){
                    if (StringUtils.isNotEmpty(pfd.getFileKey()) && pfd.getFileKey().equals(img.toString())){
                        sconPhotoFeedbackDetailService.delete(pfd);
                    }
                }
            }
        }
    }

    /**
     * 保存修改的文字
     */
    public void saveAnswerText (String pid, String texts){
        JSONArray textArray = JSONArray.parseArray(texts);
        Feedback fd = feedbackService.getFeedback(pid);
        List<SconTextFeedbackDetail> list = sconTextFeedbackDetailService.findByFeedbackId(fd.getId());

        if (textArray != null && textArray.size() > 0){
             for (int i = 0; i < textArray.size(); i++){
                 boolean has = false;
                 for (SconTextFeedbackDetail tfd : list){
                    if (tfd.getType().equals((i + 1) + "")){
                        has = true;
                        tfd.setContent(textArray.getString(i));
                        sconTextFeedbackDetailService.save(tfd);
                    }
                 }

                 if (!has && StringUtils.isNotEmpty(textArray.getString(i))){
                     SconTextFeedbackDetail tfd = new SconTextFeedbackDetail();
                     tfd.setContent(textArray.getString(i));
                     tfd.setType((i + 1) + "");
                     tfd.setCreateTime(new Date());
                     tfd.setFeedbackId(fd.getId());
                     sconTextFeedbackDetailService.save(tfd);
                 }
             }
        }
    }

    /**
     * 保存关联的知识点
     */
    public void saveAnswerKnowledge (String pid, String knows) {
        JSONArray knowArray = JSONArray.parseArray(knows);
        Feedback fd = feedbackService.getFeedback(pid);
        ProblemPicture pp = this.getById(pid);
        List<SconKnowFeedbackDetail> kfdList = sconKnowFeedbackDetailService.findByFeedbackId(fd.getId());
        this.removeKnowFeedbackDetail(kfdList, knowArray);
        List<String> insertDetailIds = findInsertDetailIds(kfdList, knowArray);
        if (insertDetailIds != null && insertDetailIds.size() > 0){
            List<ZuoybKnowHowDetails> zkhd = zuoybKnowHowDetailsService.findByIds(insertDetailIds);
            SconKnowFeedbackDetail temp = null;
            for (ZuoybKnowHowDetails details : zkhd){
                temp = new SconKnowFeedbackDetail();
                temp.setKnowHowId(details.getHowId());
                temp.setKnowHowDetailsId(details.getId());
                temp.setDerver(pp.getDerver());
                temp.setCreateTime(new Date());
                temp.setSubject(pp.getSubject());
                temp.setFeedbackId(fd.getId());
                temp.setProblemId(pid);
                sconKnowFeedbackDetailService.save(temp);
            }
        }
    }

    /**
     * 找到需要插入的知识点id
     * @param kfdList
     * @return
     */
    public List<String> findInsertDetailIds (List<SconKnowFeedbackDetail> kfdList, JSONArray array){
        List<String> result = new ArrayList<String>();
        if (array != null && array.size() > 0){
            for (Object detailId : array){
                if (StringUtils.isEmpty(detailId.toString())) continue;
                boolean has = false;
                for (SconKnowFeedbackDetail kfd : kfdList){
                    if (kfd.getKnowHowDetailsId().equals(detailId.toString())){
                        has =  true;
                    }
                }
                if (!has){
                    result.add(detailId.toString());
                }
            }
        }
        return result;
    }

    /**
     * 删除前端去除的知识点
     * @param kfdList
     * @param array
     */
    public void  removeKnowFeedbackDetail (List<SconKnowFeedbackDetail> kfdList, JSONArray array){
        if (kfdList != null && kfdList.size() > 0){
            for (SconKnowFeedbackDetail kfd : kfdList) {
                boolean rmFlag = true;
                for (Object detailId : array) {
                    if (kfd.getKnowHowDetailsId().equals(detailId.toString())){
                        rmFlag = false;
                    }
                }
                if (rmFlag){
                    sconKnowFeedbackDetailService.delete(kfd);
                }
            }
        }
    }

	@Override
	public List<ProblemPicture> findByisDeleteAndTeacherIdAndIsFeedbackAndCreateTimeAfterAndVipIdOrderByCreateTimeAsc(
			int i, String teacherUserId, int isFeedback, Date todatDate, String vipId) {

		return problemPictureDao.findByisDeleteAndTeacherIdAndIsFeedbackAndCreateTimeAfterAndVipIdOrderByCreateTimeAsc(i,teacherUserId,isFeedback,todatDate,vipId);
	}

	@Override
    public void sendPictureMsg2KmtTeacher (String pid, String teacherId) {
        JSONObject data = new JSONObject();
        data.put("type", 3);
        data.put("pid", pid);
        data.put("msg", "");

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

    @Override
    public void sendMsg2KmtTeacher (String vipId, String teacherId) {
        int notCorrectCount = problemPictureDao.countByTeacherIdNotFeedback(teacherId);
        LibVip vip = libVipService.getById(vipId);
        JSONObject data = new JSONObject();
        data.put("type", 2);
        data.put("problemCount", notCorrectCount);
        data.put("msg", vip.getChildName() + "同学提交难题了,快点帮他答疑！");

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

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

	@Override
	public int countHitstoryNotFeedback (String teacherId){
        //今天凌晨作为结束时间
        Date endTime = DateUtil.getTodatDate();
        return problemPictureDao.countByIsFeedbackAndCreateTimeBeforeAndTeacherId(0, endTime, teacherId);
    }

    @Override
    public Page<ProblemPicture> findByPage(Map<String, Object> params, Pageable sp) {
        Map<String, SearchFilter> filters = SearchFilter.parse(params);
        Specification<ProblemPicture> specification = DynamicSpecifications.bySearchFilter(filters.values(), ProblemPicture.class);
        return  problemPictureDao.findAll(specification,sp);
    }

    @Override
    public  List<ProblemPictureListDto> findProblemPictureList(ClassIdPageRequest pageReq, String subjectStr,String libId) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(pageReq.getPageNo(), pageReq.getPageSize());
        List<String> subjects = CourseConstant.MAIN_SUBJECT_LIST;
        if (StringUtils.isNotBlank(subjectStr)){
            subjects = Arrays.asList(subjectStr.split(","));
        }
        List<ProblemPictureListDto> result =  problemMapper.findProblemListByTeacherId(pageReq.getClassId(), subjects, libId,DateUtil.format_yyyyMMdd(DateUtil.addDays(new Date(), -3)), page);
        return result;
    }

    @Override
    public Map<String, Object> findProblemPictureList(AnsweredProblemReq req) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(req.getPageNo(), req.getPageSize());
        List<String> subjects = CourseConstant.MAIN_SUBJECT_LIST;
        if (StringUtils.isNotBlank(req.getSubject())) {
            subjects = Arrays.asList(req.getSubject().split(","));
        }
        List<ProblemPictureListDto> result = null;
        LibVip vip = libVipService.getById(req.getVipId());
        if (vip != null) {
            result = problemMapper.findProblemListByVipIdAndSubject(req.getVipId(), subjects, page);
            result.stream().forEach(problemPictureListDto -> {
                problemPictureListDto.setChildImg(vip.getImgUrl());
                problemPictureListDto.setChildName(vip.getChildName());
                //家长端此值需要修改
                if (req.getPort() == 1) {
                    //解答状态，0待解答，1已解答
                    problemPictureListDto.setResolutionStatus(problemPictureListDto.getIsFeedback());
                }
            });
        }

        Map<String, Object> data = new HashMap<>();
        data.put("pageNo", req.getPageNo());
        data.put("pageSize", req.getPageSize());
        data.put("pages", page.getTotal());
        data.put("maxCreateTime", req.getMaxCreateTime());
        data.put("list", result);
        return data;
    }

    @Override
    public ResponseEntity saveTeacherMessage(TeacherMessaggeRequest request, String userId) {
        ResponseEntity responseEntity = new ResponseEntity();
        ProblemPicture problemPicture = problemPictureDao.findByIdAndIsDelete(request.getProblemPictureId(), 0);
        if (problemPicture != null){
            LibVip libVip = libVipService.getById(problemPicture.getVipId());
            if (libVip == null || StringUtil.isBlank(libVip.getUserId())) {
                return responseEntity.failure("此学⽣已被删除，无法提交");
            }
            if (StringUtil.isNotBlank(request.getTeacherMessage()) || CollectionUtils.isNotEmpty(request.getFileKeys()) || CollectionUtils.isNotEmpty(request.getVoiceKeyList())) {
                problemPicture.setManualEditType(1);
            } else {
                return responseEntity.failure("请编辑解答内容");
            }
            Date now = new Date();
            problemPicture.setTeacherMessage(request.getTeacherMessage());
            problemPicture.setMessageSubmitTime(now);
            problemPicture.setTeacherId(userId);
            problemPicture.setIsFeedback(1);
            this.save(problemPicture);
            //每次提交，删除老的反馈，新增新的反馈记录
            Feedback feedback = feedbackService.findByBizId(request.getProblemPictureId());
            if (feedback == null) {
                feedback = new Feedback();
                feedback.setBizId(request.getProblemPictureId());
                feedback.setBizType("PROBLEM");
                feedback.setCreateTime(now);
                feedback.setParentId(problemPicture.getParentId());
                feedback.setUserId(problemPicture.getTeacherId());
                feedbackService.save(feedback);
            }
            //保存图片解答
            this.savePhotoListV1(feedback.getId(), request.getFileKeys());
            //保存语音解答
            this.saveVoiceListV1(feedback.getId(), request.getVoiceKeyList());
            //推送小塾
            Map<String, Object> result = new HashMap<>();
            result.put("type", "PROBLEM_SIMILAR_FEEDBACK");
            result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
            result.put("data", this.getProblemFeedbackData(problemPicture.getId()));
            sconXingeService.asynPushThreadTask(problemPicture.getDerver(),problemPicture.getVipId(),1, JSON.toJSONString(result), PushConstants.PUSH_PROBLEM);
            this.problemPictureFeedback2Pad(problemPicture);
        }else{
            return responseEntity.failure("该难题已被删除，无法提交");
        }
        return responseEntity.success("保存成功");
    }

    /**
     * 老师解答推送pad
     * @param problemPicture
     */
    private void problemPictureFeedback2Pad (ProblemPicture problemPicture){
        Map<String, Object> result = new HashMap<>();
        result.put("type", "PROBLEM_SIMILAR_FEEDBACK");
        result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
        ProblemPictureListDto problemPictureListDto = new ProblemPictureListDto();
        problemPictureListDto.setProblemPictureId(problemPicture.getId());
        problemPictureListDto.setCreateTime(problemPicture.getCreateTime());
        problemPictureListDto.setSubject(problemPicture.getSubject());
        problemPictureListDto.setProblemPicturePath(problemPicture.getFileKey());
        problemPictureListDto.setWeek(DateUtil.getWeekDateToStr(problemPicture.getCreateTime()));
        problemPictureListDto.setType(org.apache.solr.common.StringUtils.isEmpty(problemPicture.getTeacherMessage()) ? 0 : 1);

        ProblemSimilarPredeal predeal = problemSimilarPreDealService.findPreDealByProblemPictureId(problemPicture.getId());
        if (predeal != null){
            problemPictureListDto.setTaskStatus(predeal.getTaskStatus());
            problemPictureListDto.setDealFlag(predeal.getDealFlag());
        }
        result.put("data", problemPictureListDto);
        sconXingeService.asynPushPadThreadTask(problemPicture.getVipId(), "老师对你的难题进行了解答，快来查看吧！", result);
    }

    @Override
    public com.ssj.bean.conch.conch.dto.ProblemDetailDto getProblemFeedbackData(String problemPictureId) {
        ProblemPicture problemPicture = this.getById(problemPictureId);
        com.ssj.bean.conch.conch.dto.ProblemDetailDto result = new com.ssj.bean.conch.conch.dto.ProblemDetailDto();
        if (problemPicture != null){
            ProblemSimilarPredeal predeal = problemSimilarPreDealService.findPreDealByProblemPictureId(problemPictureId);
            if (predeal == null){
                result = conchDerverService.getProblemFeedbackData(problemPicture, null, false);
            } else {
                boolean showExerciseQuestion = predeal.getDealFlag() == 3 ? true : false;
                result = conchDerverService.getProblemFeedbackData(problemPicture, JSON.parseArray(predeal.getQuestionIds(), String.class), showExerciseQuestion);
            }
            //新加语音和图片的
            Feedback feedback = feedbackService.findByBizId(problemPictureId);
            if (feedback != null) {
                // 获取老师反馈的图片信息
                List<SconPhotoFeedbackDetail> photoList = sconPhotoFeedbackDetailService.findByFeedbackIdOrderByNumAsc(feedback.getId());
                List<Map<String, String>> fileKeys = new ArrayList<>();
                photoList.forEach(e -> {
                    Map<String, String> imageMap = new HashMap<>();
                    imageMap.put("imagekey", e.getFileKey());
                    fileKeys.add(imageMap);
                });
                result.setFileKeys(fileKeys);
                //查找语音列表
                List<SconVoiceFeedbackDetail> voiceList = sconVoiceFeedbackDetailService.findByFeedbackIdOrderByNumAsc(feedback.getId());
                List<Map<String, String>> voiceListMap = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(voiceList)) {
                    for (SconVoiceFeedbackDetail voice : voiceList) {
                        Map<String, String> voiceMap = new HashMap<>();
                        voiceMap.put("voiceKey", voice.getFileKey());
                        voiceMap.put("duration", voice.getDuration());
                        voiceListMap.add(voiceMap);
                    }
                }
                result.setVoiceKeyList(voiceListMap);
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> findAllProblemPictureList(AnsweredProblemReq req) {
        Map<String, Object> data = new HashMap<>();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(req.getPageNo(), req.getPageSize());
        List<ProblemPictureListDto> result = null;
        LibVip vip = libVipService.getById(req.getVipId());
        if (vip != null && StringUtil.isNotBlank(vip.getUserId())){
            result = problemMapper.findAllProblemListByVipIdAndSubject(req.getVipId(), req.getSubject(), page);
        }
        if (CollectionUtils.isNotEmpty(result)){
            int resolutionStatus;
            for (ProblemPictureListDto problemPictureListDto : result) {
                resolutionStatus = problemPictureListDto.getTaskStatus() == 1 && problemPictureListDto.getDealFlag() > 1 ? 1 : 0;
                problemPictureListDto.setResolutionStatus(resolutionStatus);
                problemPictureListDto.setTeacherMessageType(problemPictureListDto.getType());
                problemPictureListDto.setWeek(DateUtil.getWeekDateToStr(DateUtil.parse_yyyyMMddHHmmss(problemPictureListDto.getCreateTime())));
            }
        }
        data.put("pageNo", req.getPageNo());
        data.put("pageSize", req.getPageSize());
        data.put("maxCreateTime", req.getMaxCreateTime());
        data.put("pages", page.getTotal());
        data.put("list", result);
        return data;
    }

    @Override
    public void rephotoProblemPicture(ProblemPictureRephotoRequest request) {
        ProblemPicture problemPicture = this.getById(request.getProblemPictureId());
        if (problemPicture != null){
            problemPicture.setFileKey(request.getFileKeys());
            problemPicture.setCreateTime(new Date());
            this.save(problemPicture);
            problemSimilarPreDealService.asyncPostRequest2AI(problemPicture);
        }
    }

    @Override
    public int countProblemSum (String vipId){
        return problemPictureDao.countProblemSumByVipId(vipId);
    }

}