package com.ssj.service.weixin.zuoyb.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssj.bean.sys.homework.domain.HomeworkHowDetail;
import com.ssj.bean.sys.homework.domain.HomeworkPicture;
import com.ssj.bean.sys.wrongbook.domain.HomeworkWrongQuestion;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.zyb.domain.*;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybKnowHowDao;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybKnowHowDetailsDao;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.basic.utils.StringUtils;
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.PropertiesUtil;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.service.kmt.dto.KnowHowDTO;
import com.ssj.service.kmt.request.KnowledgeRequest;
import com.ssj.service.sys.homework.enums.WorkDetailTypeEnum;
import com.ssj.service.sys.wrongbook.service.WrongBookService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.zuoyb.service.*;
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.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/** 
 * @author  ZhangCaibao 
 * @version 2017年9月26日 下午2:00:45 
 * 类说明 
 */
@Service
@Transactional
public class ZuoybKnowHowServiceImpl  extends BaseServiceImpl<ZuoybKnowHow, String> implements  ZuoybKnowHowService  {
	private static org.slf4j.Logger logger = LoggerFactory.getLogger(ZuoybKnowHowServiceImpl.class);
	@Autowired
	private  ZuoybKnowHowDao  zuoybKnowHowDao;
	@Autowired
	private  ZuoybQueryDao  zuoybQueryDao;
	@Autowired
	private WrongBookService wrongBookService;

	@Autowired
	private ZuoybKnowHowDetailsDao zuoybKnowHowDetailsDao;
	@Autowired
	private  ZuoybKnowHowDetailsService  zuoybKnowHowDetailsService;

	@Autowired
	private ZuoybStudentWorkHowService zuoybStudentWorkHowService;
	@Autowired
	private ZuoybStudentWorkHowDetailsService  zuoybStudentWorkHowDetailsService;
	@Autowired
	private ZuoybKnowHowDetailsSortService  zuoybKnowHowDetailsSortService;

	@Autowired
	private ILibVipService libVipService;

	  
	@Override
	public PagingAndSortingRepository<ZuoybKnowHow, String> getDao() {
		return zuoybKnowHowDao;
	}
	@Override
	public  List<ZuoybKnowHow> findByCourseNameByGrade(String libId,String courseName,String grade,
			String date,String banben,List<ZuoybStudentWorkHow>  workHowList)throws Exception {
		int weekNum =DateHelper.diffWeeks(date);
		weekNum = weekNum==0?1:weekNum;
		weekNum = weekNum%2==0?weekNum/2:weekNum/2+1;
		String semester= PropertiesUtil.getValue("semester");//下学期
		
		logger.info("date--"+date);
		logger.info("weekNum--"+weekNum);
		logger.info("semester--"+semester);
		if("英语".equals(courseName))banben="2";
		List<ZuoybKnowHow> list = zuoybKnowHowDao.findByCourseNameByGrade(libId, courseName, grade, semester, banben, weekNum);
		
		//logger.info("List<ZuoybKnowHow> list->"+JSON.toJSONString(list));
		for (ZuoybKnowHow zuoybKnowHow : list) {
			 List<ZuoybKnowHowDetails>  howDetailsList=	zuoybKnowHowDetailsService.findByHowIdNotNull(zuoybKnowHow.getId(),libId, courseName, grade, semester, banben,weekNum);
			 List<ZuoybKnowHowDetails>  newDetailsList=  new ArrayList<ZuoybKnowHowDetails>();
			 if(howDetailsList!=null && howDetailsList.size()>0){
				 for (ZuoybKnowHowDetails zuoybKnowHowDetails : howDetailsList) {
                      
					 if("数学".equals(courseName)&&"1".equals(banben)){
							String kdName= zuoybKnowHowDetailsSortService.getZuoybKnowHowDetailsKdName(courseName, grade, banben, semester, zuoybKnowHowDetails.getId());
							if(kdName!=null){
								zuoybKnowHowDetails.setName(zuoybKnowHowDetails.getName()+"("+kdName+")");
							}
						 }
					 
					 for (ZuoybStudentWorkHow zuoybStudentWorkHow : workHowList) {
						 if(zuoybKnowHow.getId().equals(zuoybStudentWorkHow.getHowId())){
									zuoybKnowHow.setHowActive("active");
								 }
						 List<ZuoybStudentWorkHowDetails> workHowDetailsList =zuoybStudentWorkHow.getWorkHowDetailsList();
						 if(workHowDetailsList!=null && workHowDetailsList.size()>0){
							 for (ZuoybStudentWorkHowDetails zuoybStudentWorkHowDetails : workHowDetailsList) {
								 if(zuoybKnowHowDetails.getId().equals(zuoybStudentWorkHowDetails.getHowDetailsId())){
										zuoybKnowHowDetails.setHowName(zuoybStudentWorkHowDetails.getManualName());
										zuoybKnowHowDetails.setHowActive("active");
										zuoybKnowHowDetails.setImgList(zuoybStudentWorkHowDetails.getImgList());
									}
							}
						 }
					 }
					 newDetailsList.add(zuoybKnowHowDetails);
				 }
				 zuoybKnowHow.setHowDetailsList(newDetailsList);
			 }
		
			 
		}
		return list;
	}

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

	@Override
	public void updateKnowHowNum(String id, Integer num) {
		zuoybKnowHowDao.updateKnowHowNum(id, num);
		
	}

	@Override
	public void insertKonwHow(String libId) {
		Integer count=zuoybKnowHowDao.getLibIdCount(libId);
		if(count==0){
			List<ZuoybKnowHow> list =zuoybKnowHowDao.findByLibId("SSJ");
			for (ZuoybKnowHow zuoybKnowHow : list) {
				ZuoybKnowHow  how  = new  ZuoybKnowHow();
				how.setCourseName(zuoybKnowHow.getCourseName());
				how.setCreateTime(new Date());
				//how.setEndTime(zuoybKnowHow.getEndTime());
				//how.setFewWeeks(zuoybKnowHow.getFewWeeks());
				//how.setGrade(zuoybKnowHow.getGrade());
				how.setLibId(libId);
				how.setName(zuoybKnowHow.getName());
				how.setNum(zuoybKnowHow.getNum());
			//	how.setStartTime(zuoybKnowHow.getStartTime());
				this.save(how);
				zuoybKnowHowDao.insertKnowHowDetail(libId, zuoybKnowHow.getId(), how.getId());
			}
		}
		
	}

	@Override
	public List<ZuoybKnowHow> findByCourseNameByGrade(String libId,
			String courseName, String grade,String banben,List<ZuoybStudentWorkHow>  workHowList) {
		String semester= PropertiesUtil.getValue("semester");//下学期
		if("英语".equals(courseName))banben="2";
		List<ZuoybKnowHow> list =zuoybKnowHowDao.findByCourseNameByGrade(courseName, grade, semester, banben);


		for (ZuoybKnowHow zuoybKnowHow : list) {
			List<ZuoybKnowHowDetails>  howDetailsList=	zuoybKnowHowDetailsService.findByHowIdNotNull(zuoybKnowHow.getId(),libId, courseName, grade, semester, banben);
			 List<ZuoybKnowHowDetails>  newDetailsList=  new ArrayList<ZuoybKnowHowDetails>();
			 if(howDetailsList!=null && howDetailsList.size()>0){
				 for (ZuoybKnowHowDetails zuoybKnowHowDetails : howDetailsList) {

					 if("数学".equals(courseName)&&"1".equals(banben)){
						String kdName= zuoybKnowHowDetailsSortService.getZuoybKnowHowDetailsKdName(courseName, grade, banben, semester, zuoybKnowHowDetails.getId());
						if(kdName!=null){
							zuoybKnowHowDetails.setName(zuoybKnowHowDetails.getName()+"("+kdName+")");
						}
					 }
					 for (ZuoybStudentWorkHow zuoybStudentWorkHow : workHowList) {
						 if(zuoybKnowHow.getId().equals(zuoybStudentWorkHow.getHowId())){
									zuoybKnowHow.setHowActive("active");
								 }
						 List<ZuoybStudentWorkHowDetails> workHowDetailsList =zuoybStudentWorkHow.getWorkHowDetailsList();
						 if(workHowDetailsList!=null && workHowDetailsList.size()>0){
							 for (ZuoybStudentWorkHowDetails zuoybStudentWorkHowDetails : workHowDetailsList) {
								 if(zuoybKnowHowDetails.getId().equals(zuoybStudentWorkHowDetails.getHowDetailsId())){
										zuoybKnowHowDetails.setHowName(zuoybStudentWorkHowDetails.getManualName());
										zuoybKnowHowDetails.setHowActive("active");
										zuoybKnowHowDetails.setImgList(zuoybStudentWorkHowDetails.getImgList());
									}
							}
						 }
					 }
					 newDetailsList.add(zuoybKnowHowDetails);
				 }
				 zuoybKnowHow.setHowDetailsList(newDetailsList);
			 }
		}
		
		return list;
	}
	
	@Override
	public List<ZuoybKnowHow> findByCourseNameByGrade1(String libId, String courseName, String grade,String banben, String semester) {
		List<ZuoybKnowHow> list = null;
		if("英语".equals(courseName) || "语文".equals(courseName)) {
			Integer isZt = 1;
			list =zuoybKnowHowDao.findKnowByCourseNameByGrade(courseName, grade, semester, banben, isZt);
		} else {
			list =zuoybKnowHowDao.findKnowByCourseNameByGrade(courseName, grade, semester, banben);
		}

		for (ZuoybKnowHow zuoybKnowHow : list) {
			List<ZuoybKnowHowDetails>  howDetailsList=	zuoybKnowHowDetailsService.findByHowIdNotNull(zuoybKnowHow.getId(),libId, courseName, grade, semester, banben);
			 List<ZuoybKnowHowDetails>  newDetailsList=  new ArrayList<ZuoybKnowHowDetails>();
			 if(howDetailsList!=null && howDetailsList.size()>0){
				 for (ZuoybKnowHowDetails zuoybKnowHowDetails : howDetailsList) {
					 if("数学".equals(courseName)&&"1".equals(banben)){
						String kdName= zuoybKnowHowDetailsSortService.getZuoybKnowHowDetailsKdName(courseName, grade, banben, semester, zuoybKnowHowDetails.getId());
						if(kdName!=null){
							zuoybKnowHowDetails.setName(zuoybKnowHowDetails.getName()+"("+kdName+")");
						}
					 }
					 if("英语".equals(courseName)) {
						 //String name = zuoybKnowHowDao.findNameById(zuoybKnowHow.getId());
						 zuoybKnowHowDetails.setTwoModule(zuoybKnowHow.getName());
					 }
					 newDetailsList.add(zuoybKnowHowDetails);
				 }
				 zuoybKnowHow.setHowDetailsList(newDetailsList);
			 }
		}
		
		return list;
	}

    @Override
	public List<Object> findByCourseNameByGradeNew(String libId, String courseName, String grade,Integer banben, String semester) {
		List<Object> list = new ArrayList<Object>();
		//英语语文只取专题
		if("英语".equals(courseName) || "语文".equals(courseName)) {
			Integer isZt = 1;
			list =zuoybKnowHowDao.findKnowByCourseNameByGradeNew(courseName, grade, semester, banben, libId, isZt);
		}else if ("数学".equals(courseName) && "1".equals(banben)) { //数学1版本要取考点
			list = zuoybKnowHowDao.findMathModule(courseName, grade, semester, banben, libId);
		} else {
			list =zuoybKnowHowDao.findKnowByCourseNameByGradeAndBanben(courseName, grade, semester, banben, libId);
		}
		return list;
	}


	public Map<String, Object> findRelateKnowledge (String vipId, String subject) {
		String date = SystemResourceLocator.getValue("startschool").toString();//开学的时间。。。
		int weekNum = 0;
		try {
			weekNum = DateHelper.diffWeeks(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		weekNum = weekNum % 2 == 0 ? weekNum / 2 : weekNum / 2 + 1;

		LibVip vip = libVipService.getById(vipId);
		if (vip == null) {
			logger.error("不存在该学生,vip_id=" + vipId);
			return null;
		}

		if (StringUtil.isEmpty(vip.getGrade())){
			vip.setGrade("二年级");
		}
		if (vip.getBanben() == null){
			vip.setBanben(2);
		}
		logger.info("查询知识的参数： 学科=" + subject + ",年级=" + vip.getGrade() + ",版本=" + vip.getBanben() + ",周期=" + weekNum);
		List<ZuoybKnowHow> list = this.findByCourseNameByGrade("SSJ", subject, vip.getGrade(), vip.getBanben() + "", weekNum);

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("list", list);
		return result;
	}

	protected List<ZuoybKnowHow> findByCourseNameByGrade(String libId,String courseName,String grade,
														 String banben, int weekNum){
		String semester= PropertiesUtil.getValue("semester");//下学期
		if("英语".equals(courseName)) banben="2";
		List<ZuoybKnowHow> list =zuoybKnowHowDao.findByCourseNameByGrade(libId, courseName, grade, semester, banben, weekNum);
		for (ZuoybKnowHow zuoybKnowHow : list) {
			List<ZuoybKnowHowDetails>  howDetailsList=	zuoybKnowHowDetailsService.findByHowIdNotNull(zuoybKnowHow.getId(),libId, courseName, grade, semester, banben);
			zuoybKnowHow.setHowDetailsList(howDetailsList);
		}
		return list;
	}

	public Map<String, Object>  findAllKnowledge (String vipId, String subject) {
		LibVip vip = libVipService.getById(vipId);
		if (vip == null) {
			logger.error("不存在该学生,vip_id=" + vipId);
			return null;
		}

		if (StringUtil.isEmpty(vip.getGrade())){
			vip.setGrade("二年级");
		}
		if (vip.getBanben() == null){
			vip.setBanben(2);
		}

		List<ZuoybKnowHow> list = this.findByCourseNameByGrade("SSJ", subject, vip.getGrade(), vip.getBanben() + "");
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("list", list);
		return result;
	}

	@Override
	public List<ZuoybKnowHow> findByCourseNameByGrade(String libId, String courseName, String grade,String banben){
		String semester= PropertiesUtil.getValue("semester");//下学期
		if("英语".equals(courseName)) banben="2";
		List<ZuoybKnowHow> list =zuoybKnowHowDao.findByCourseNameByGrade(courseName, grade, semester, banben);
		for (ZuoybKnowHow zuoybKnowHow : list) {
			List<ZuoybKnowHowDetails>  howDetailsList=	zuoybKnowHowDetailsService.findByHowIdNotNull(zuoybKnowHow.getId(),libId, courseName, grade, semester, banben);
			zuoybKnowHow.setHowDetailsList(howDetailsList);
		}
		return list;
	}

	@Override
	public List<ZuoybKnowHow> getChindIdParentName(String howDetialsId) {
		return zuoybKnowHowDao.getChindIdParentName(howDetialsId);
	}

	@Override
	public List<ZuoybKnowHow> getTheMonthKnowHowAndModule(String libId,
			String courseName, String grade, int weekNum, String semester,String type) {
	//两周一单元
		weekNum = weekNum==0?1:weekNum;
		//一个月就是两个单元
		int start =(weekNum-1)*2;
		start =start>0?start-1:start;//前后增加一个单元。
		int end =weekNum*2+1;
		
		
		//算单元
	  List<ZuoybKnowHow> objlist =	zuoybKnowHowDao.getTheMonthKnowHowAndModule(libId, courseName, grade,semester,type,start,end );
	  return objlist;
		
	}
	@Override
	public List<ZuoybKnowModule> getTheMonthModule(String libId,String courseName,String grade,int weekNum,String semester,String type){
		
		/**
		 * 这里是两周一个单元。那么最近30天出现的模块单元
		 */
		
		
		//两周一单元
		weekNum = weekNum==0?1:weekNum;
		weekNum = weekNum%2==0?weekNum/2:weekNum/2+1;
				//一个月就是两个单元
				int start =weekNum;
				int end =weekNum +1;
				
			 List<String>	objlist=zuoybKnowHowDao.getTheMonthModule(libId, courseName, grade, semester, type, start, end);
			 List<ZuoybKnowModule> knowHowList = new ArrayList<ZuoybKnowModule>();
			 for (String objects : objlist) {
				 ZuoybKnowModule mo = new  ZuoybKnowModule();
				 mo.setModule(objects);
				 mo.setCourseName(courseName);
				 knowHowList.add(mo);
			 }
			 return knowHowList;
				/*Map<String ,List<ZuoybKnowHowDetails>> map  =new  HashMap<String, List<ZuoybKnowHowDetails>>();
				  for (Object[] objects : objlist) {
					    String module =objects[1]!=null?objects[1].toString():null;
					    ZuoybKnowHowDetails details = new ZuoybKnowHowDetails();
					    details.setModule(module);
					    details.setId(objects[0]!=null?objects[0].toString():null);
					    details.setName(objects[2]!=null?objects[2].toString():null);
					    details.setNum(objects[2]!=null?Integer.parseInt(objects[2].toString()):null);
					    if(map.containsKey(module)){
					    	List<ZuoybKnowHowDetails> detlist =map.get(module);
					    	detlist.add(details);
					    }else{
					    	List<ZuoybKnowHowDetails> detList = new ArrayList<ZuoybKnowHowDetails>();
					    	detList.add(details);
					    	map.put(module, detList);
					    }
					}
				 
			      for (Map.Entry<String ,List<ZuoybKnowHowDetails>> entry : map.entrySet()) {
			    	  ZuoybKnowHow how = new ZuoybKnowHow();
			    	  how.setModule(entry.getKey());
			    	  how.setCourseName(courseName);
			    	  how.setHowDetailsList(entry.getValue());
			    	  knowHowList.add(how);
				  }
					return knowHowList;		*/
	}

	@Override
	public ZuoybKnowHow findByNameAndLibIdAndCourseName(String name,
			String libId, String courseName, Integer num) {
		return zuoybKnowHowDao.findByNameAndLibIdAndCourseName(name, libId, courseName, num);
	}
	@Override
	public ZuoybKnowHow findByNameAndLibIdAndCourseName(String name,
			String libId, String courseName) {
		return zuoybKnowHowDao.findByNameAndLibIdAndCourseName(name, libId, courseName);
	}
	@Override
	public List<Map<String, Object>> findMasterByVip(String vipId) {
		return zuoybKnowHowDao.findMasterByVip(vipId);
	}
	@Override
	public List<ZuoybKnowHow> getZybKnowHowByHowDetailsId(String howDetailsIds) {
		return zuoybKnowHowDao.getZybKnowHowByHowDetailsId(howDetailsIds);
	}
	@Override
	public List<ZuoybKnowHow> getZybKnowHowByHowDetailsIdIn(List<String> howDetailIds) {
		return zuoybKnowHowDao.getZybKnowHowByHowDetailsIdIn(howDetailIds);
	}

	@Override
	public void saveHomeworkKnowledgeRelate(List<String> ids, String zybWorkId) {
		if (ids != null && ids.size() > 0) {
			List<ZuoybKnowHow> zuoybKnowHows = this.getZybKnowHowByHowDetailsIdIn(ids);
			List<ZuoybKnowHowDetails> zuoybKnowHowDetailsList = zuoybKnowHowDetailsService.getZybKnowHowById(ids);

			ZuoybStudentWorkHow zuoybStudentWorkHow = null;

		//	logger.info("插入关联知识点记录，查询出来的知识信息："  + zuoybKnowHowDetailsList);
			for (ZuoybKnowHow zuoybKnowHow : zuoybKnowHows) {
				zuoybStudentWorkHow = new ZuoybStudentWorkHow();
				zuoybStudentWorkHow.setCreateTime(new Date());
				zuoybStudentWorkHow.setHowId(zuoybKnowHow.getId());
				zuoybStudentWorkHow.setHowName(zuoybKnowHow.getName());
				zuoybStudentWorkHow.setModule(zuoybKnowHow.getModule());
				zuoybStudentWorkHow.setNum(zuoybKnowHow.getNum());
				zuoybStudentWorkHow.setStudentWorkId(zybWorkId);

				zuoybStudentWorkHowService.save(zuoybStudentWorkHow);
		//		logger.info("保存单元信息成功，id:" +zuoybKnowHow.getId());

				List<ZuoybStudentWorkHowDetails> tmpList = new ArrayList<ZuoybStudentWorkHowDetails>();
				for (ZuoybKnowHowDetails zuoybKnowHowDetails : zuoybKnowHowDetailsList) {
					if (zuoybKnowHowDetails.getHowId().equals(zuoybKnowHow.getId())) {
						ZuoybStudentWorkHowDetails tmp = new ZuoybStudentWorkHowDetails();
						tmp.setApply(zuoybKnowHowDetails.getApply());
						tmp.setCreateTime(new Date());
						tmp.setDuration(zuoybKnowHowDetails.getDuration());
						tmp.setHowDetailsId(zuoybKnowHowDetails.getId());
						tmp.setMemorize(zuoybKnowHowDetails.getMemorize());
						tmp.setModule(zuoybKnowHowDetails.getModule());
						tmp.setName(zuoybKnowHowDetails.getName());
						tmp.setNum(zuoybKnowHowDetails.getNum());
						tmp.setStudentWorkId(zybWorkId);
						tmp.setWorkHowId(zuoybStudentWorkHow.getId());
						tmp.setUnderstanding(zuoybKnowHowDetails.getUnderstanding());
						tmpList.add(tmp);
					}
				}
				zuoybStudentWorkHowDetailsService.save(tmpList);
			//	logger.info("保存知识点信息成功，知识点:" + tmpList);
			}
			logger.info("知识点关联zyb_student_work成功");
		}
	}

    @Override
    public List<KnowHowDTO> findListByCondition(KnowledgeRequest request) {
        return zuoybQueryDao.findHowListWithDetailsByCondition(request);
    }

    @Override
    public ZuoybKnowHow findOneByCondition(String gradeNum, String subject, String version, String semester, String knowHowName) {
        return zuoybKnowHowDao.findOneByCondition(gradeNum, subject, version, semester, knowHowName);
    }

    public void saveCorrectResult (String data, HomeworkPicture homeworkPicture) throws JsonProcessingException {
		JSONArray array = JSONArray.parseArray(data);

		List<HomeworkHowDetail> homeworkHowDetailList = new LinkedList<>();
		ObjectMapper objectMapper = new ObjectMapper();

		//保存错题和知识点详情
		for (Object object : array) {
			JSONObject obj = (JSONObject) object;

			//设置错题的属性并存入数据库
			HomeworkWrongQuestion homeworkWrongQuestion = new HomeworkWrongQuestion();
			homeworkWrongQuestion.setHomeworkId(homeworkPicture.getHomeworkId());
			homeworkWrongQuestion.setHomeworkPictureId(homeworkPicture.getId());
			String img = (String) obj.get("img");
			if (StringUtils.isBlank(img)) {
				throw new HttpMessageNotReadableException("错题图片链接为空");
			}
			homeworkWrongQuestion.setImage(img);
			homeworkWrongQuestion.setCreateTime(new Date());
			homeworkWrongQuestion.setWrongTitle(objectMapper.writeValueAsString(obj.get("wrong_title")));
//			homeworkWrongQuestion.setCorrectText();
			String position = String.valueOf(obj.get("position"));
			homeworkWrongQuestion.setListNum(position);
			String lineNum = String.valueOf(obj.get("line_num"));
			String columnNum = String.valueOf(obj.get("column_num"));
			//题号或者行列数必须有一种是正确的
			if (!StringUtils.isNumeric(lineNum)) {
				if (Objects.equals("", position)) {
					throw new HttpMessageNotReadableException("题号为空，且行数错误（不是数字）");
				} else {
					lineNum = "0";
				}
			}
			if (!StringUtils.isNumeric(columnNum)) {
				if (Objects.equals("", position)) {
					throw new HttpMessageNotReadableException("题号为空，且列数错误(不是数字)");
				} else {
					columnNum = "0";
				}
			}
			homeworkWrongQuestion.setLineNum(Integer.valueOf(lineNum));
			homeworkWrongQuestion.setColumnNum(Integer.valueOf(columnNum));
			homeworkWrongQuestion.setStudentId(homeworkPicture.getVipId());
			homeworkWrongQuestion.setDerver(homeworkPicture.getDerver());
			homeworkWrongQuestion = wrongBookService.save(homeworkWrongQuestion);

			JSONArray howDetailsId = obj.getJSONArray("how_details_id");
			if (howDetailsId != null) {
				for (Object howDetailId : howDetailsId) {
					//设置错题知识点的属性，加入需要保存之数据库的list
					HomeworkHowDetail homeworkHowDetail = new HomeworkHowDetail();
					homeworkHowDetail.setWrongQuestionId(homeworkWrongQuestion.getId());
					homeworkHowDetail.setHomeworkId(homeworkPicture.getHomeworkId());
					homeworkHowDetail.setHomeworkPictureId(homeworkPicture.getId());
					homeworkHowDetail.setHowDetailId(howDetailId.toString());
					homeworkHowDetail.setWorkDetailType(WorkDetailTypeEnum.HomeworkWrongQuestionHowDetail.getCode());

					ZuoybKnowHowDetails zuoybKnowHowDetail = zuoybKnowHowDetailsDao.getOne(howDetailId.toString());
					homeworkHowDetail.setModule(zuoybKnowHowDetail.getModule());
					//题目数默认为1
					homeworkHowDetail.setDetailCount(1);
					homeworkHowDetail.setCreateTime(new Date());

					homeworkHowDetailList.add(homeworkHowDetail);
				}
			}

		}

		if (homeworkHowDetailList.size() > 0) {
			//homeworkHowDetailsService.save(homeworkHowDetailList);
		}
	}

	public List<String> parse2List (JSONArray array){
		Set<String> result = new HashSet<String>();
		if (array != null){
			for (Object o : array){
				result.add(o.toString());
			}
		}
		return new ArrayList<String>(result);
	}


	public void saveWorkRelateKnowHow(String data, String zybworkId) {
		JSONObject jobj = JSONObject.parseObject(data);
		JSONArray ja  = jobj.getJSONArray("howDetailIdList");
		saveWorkRelateKnowHowDetail(ja, zybworkId);
	}

	public void saveWorkRelateKnowHowDetail(JSONArray ja, String homeworkId){
		List<HomeworkHowDetail> list = new ArrayList<>();
		if (ja != null && ja.size() > 0){
			for (Object detail : ja){
				JSONObject temp = (JSONObject)detail;
				String detailId = temp.getString("detailId");
				ZuoybKnowHowDetails knowDetail = zuoybKnowHowDetailsService.getById(detailId);
				HomeworkHowDetail hh = new HomeworkHowDetail();
				hh.setHomeworkId(homeworkId);
				hh.setHowDetailId(detailId);
				//作业知识点
				hh.setWorkDetailType(2);
				hh.setDetailCount(temp.getInteger("count"));
				if (knowDetail != null){
					hh.setModule(knowDetail.getModule());
				} else {
					logger.error("保存全部知识点时，知识点为空， homeowrkId={}", homeworkId);
				}
				hh.setCreateTime(new Date());
				list.add(hh);
			}
			//homeworkHowDetailsService.saveAll(list);
		}
	}


	public List<String> saveHowDetail4StudentWork (List<String> detailIds, List<String> howList,  String zybWorkId, int type){
		logger.info("开始插入一张错题的知识点, 知识点id:" + detailIds);
		Set<String> result = new HashSet<String>();
		ZuoybStudentWorkHowDetails workHowDetails = null;

		if (detailIds != null && detailIds.size() > 0){
            List<ZuoybStudentWorkHowDetails> workHowDetailList = zuoybStudentWorkHowDetailsService.findWorkHowDetail4Id(detailIds, type, zybWorkId);
            List<ZuoybStudentWorkHow> workHowList = zuoybStudentWorkHowService.getWorkHow4SaveWorkHow(howList, zybWorkId, type);
            for (String detailId : detailIds) {
                if (workHowDetailList != null && workHowDetailList.size() > 0) {
                    boolean hasWorkDetail = false;
                    for (ZuoybStudentWorkHowDetails d : workHowDetailList){
                        if (d.getHowDetailsId().equals(detailId)){
                            hasWorkDetail = true;
                            workHowDetails = d;
                        }
                    }

                    if (!hasWorkDetail){
                        workHowDetails = saveZybWorkDetail(detailId, workHowList, zybWorkId, type);
                    }
                } else {
                    workHowDetails = saveZybWorkDetail(detailId, workHowList, zybWorkId, type);
                }
                result.add(workHowDetails.getId());
            }
        }

		logger.info("返回的zybworkhowdetailid: " + result);
		return new ArrayList<String>(result);
	}

	private ZuoybStudentWorkHowDetails saveZybWorkDetail (String detailId, List<ZuoybStudentWorkHow> workHowList, String zybWorkId, int type) {

		ZuoybKnowHowDetails detail = zuoybKnowHowDetailsService.getById(detailId);
		ZuoybStudentWorkHowDetails tmp = new ZuoybStudentWorkHowDetails();
		tmp.setApply(detail.getApply());
		tmp.setCreateTime(new Date());
		tmp.setDuration(detail.getDuration());
		tmp.setHowDetailsId(detail.getId());
		tmp.setMemorize(detail.getMemorize());
		tmp.setModule(detail.getModule());
		tmp.setName(detail.getName());
		tmp.setNum(detail.getNum());
		tmp.setType(type);
		tmp.setStudentWorkId(zybWorkId);

		for (ZuoybStudentWorkHow workHow : workHowList){
		    if (workHow.getHowId().equals(detail.getHowId())){
                tmp.setWorkHowId(workHow.getId());
            }
        }
		tmp.setUnderstanding(detail.getUnderstanding());
		return zuoybStudentWorkHowDetailsService.save(tmp);
	}


	@Override
	public void saveWorkHow(List<String> howIds, String zybWorkId, int type) {
		logger.info("保存ZybStudentWorkHow开始, 单元id:" + howIds);
		if (howIds != null && howIds.size() >0){
			List<ZuoybStudentWorkHow> workHowList = zuoybStudentWorkHowService.getWorkHow4SaveWorkHow(howIds, zybWorkId, type);
            List<String> howIdList = getField(workHowList);
			ZuoybStudentWorkHow zuoybStudentWorkHow = null;
			for (String howId : howIds){
				if (howIdList == null || howIdList.size() == 0 || !howIdList.contains(howId)){
					ZuoybKnowHow how = zuoybKnowHowDao.getOne(howId);
					zuoybStudentWorkHow = new ZuoybStudentWorkHow();
					zuoybStudentWorkHow.setCreateTime(new Date());
					zuoybStudentWorkHow.setHowId(how.getId());
					zuoybStudentWorkHow.setHowName(how.getName());
					zuoybStudentWorkHow.setModule(how.getModule());
					zuoybStudentWorkHow.setNum(how.getNum());
					zuoybStudentWorkHow.setType(type);
					zuoybStudentWorkHow.setStudentWorkId(zybWorkId);
					zuoybStudentWorkHowService.save(zuoybStudentWorkHow);
				}
			}
		}
		logger.info("保存ZybStudentWorkHow结束");
	}

	private List<String> getField (List<ZuoybStudentWorkHow>  workHowList) {
        Set<String> result = new HashSet<String>();
        for (ZuoybStudentWorkHow workHow : workHowList){
            result.add(workHow.getHowId());
        }
        return new ArrayList<String>(result);
    }
	@Override
	public List<ZuoybKnowHow> findlatestHow(String libId, String courseName,
			String grade, Integer banben,Integer semester) {
		List<ZuoybKnowHow> howList=	zuoybQueryDao.findlatestHow(libId, courseName, grade, banben, semester,null);
		for (ZuoybKnowHow zuoybKnowHow : howList) {
			zuoybKnowHow.setHowDetailsList(zuoybKnowHowDetailsService.findlatestHowDetails(libId, zuoybKnowHow.getId(), courseName, grade, banben, semester));
		}
		return howList;
	}
	@Override
	public List<ZuoybKnowHow> findlatestHow(String libId, String courseName,
			String grade, Integer banben, Integer semester,String howName) {
		List<ZuoybKnowHow> howList=	zuoybQueryDao.findlatestHow(libId, courseName, grade, banben, semester,howName);
		for (ZuoybKnowHow zuoybKnowHow : howList) {
			zuoybKnowHow.setHowDetailsList(zuoybKnowHowDetailsService.findlatestHowDetails(libId, zuoybKnowHow.getId(), courseName, grade, banben, semester));
		}
		return howList;
	}
	@Override
	public List<ZuoybKnowHow> findlatestHow(String libId, String courseName,
			String grade, Integer banben, Integer semester, String howName,
			String howDetailsName) {
		//先查询符合条件的知识点
				List<ZuoybKnowHowDetails>  howDetailsList =zuoybKnowHowDetailsService.findlatestHowDetails(libId, null, courseName, grade, banben, semester,howDetailsName);
				Map<String ,List<ZuoybKnowHowDetails>> map =new HashMap<String, List<ZuoybKnowHowDetails>>();
				List<String> ids =new ArrayList<String>();
				for (ZuoybKnowHowDetails zuoybKnowHowDetails : howDetailsList) {
					 String howId =zuoybKnowHowDetails.getHowId();
					 List<ZuoybKnowHowDetails> list =new ArrayList<ZuoybKnowHowDetails>();
					 if(map.containsKey(howId)){
						 list.addAll(map.get(howId));
					 }else{
						 ids.add(libId);
					 }
					 list.add(zuoybKnowHowDetails);
					 map.put(howId, list);
				}
				List<ZuoybKnowHow> howList=	zuoybQueryDao.findlatestHowIds(libId, courseName, grade, banben, semester,howName ,ids);
				for (ZuoybKnowHow zuoybKnowHow : howList) {
					 String howId =zuoybKnowHow.getId();
					 zuoybKnowHow.setHowDetailsList(map.get(howId));
				}
				return howList;
	}
}
