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

import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.push.domain.Miniprogram;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.bean.weixin.zyb.domain.ZuoybCourse;
import com.ssj.bean.weixin.zyb.domain.ZuoybStudentPush;
import com.ssj.bean.weixin.zyb.domain.ZuoybStudentWork;
import com.ssj.bean.weixin.zyb.domain.ZuoybStudentWorkImg;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybQueryDao;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybStudentWorkDao;
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.PropertiesUtil;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.mapper.ZybStudentWorkMapper;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.LibStaffingService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.service.weixin.zuoyb.service.*;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/** 
 * @author  ZhangCaibao 
 * @version 2017年7月6日 下午2:40:33 
 * 类说明 
 */
@Service
@Transactional
public class ZuoybStudentWorkServiceImpl extends BaseServiceImpl<ZuoybStudentWork, String> implements ZuoybStudentWorkService {

	private   Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private  ZuoybStudentWorkDao  zuoybStudentWorkDao;
	
	 @Autowired
	private  ZuoybQueryDao  zuoybQueryDao;
	 
	@Autowired
	private LibStaffingService libStaffingService;
	@Autowired
	private LibVipServiceService libVipServiceService;
	@Autowired
	private ZuoybStudentPushSerivce zuoybStudentPushSerivce;
	@Autowired
	private  ZuoybStudentWorkImgService   zuoybStudentWorkImgService;
	@Autowired
	private ZuoybCourseService zuoybCourseService;
	 @Autowired
	private PushTemplateService  pushTemplateService;
	@Autowired
	private ZuoybStudentWorkDetailsService  zuoybStudentWorkDetailsService;
	@Autowired
	 private  ZuoybStudentWorkHowService   zuoybStudentWorkHowService;;
	@Autowired
	private ILibJoinService joinService;
	@Autowired
	private IBookManagerService managerService;

	@Autowired
	private UserService userService;


	@Autowired
	private ZybStudentWorkMapper zybStudentWorkMapper;
	
	@Override
	public PagingAndSortingRepository<ZuoybStudentWork, String> getDao() {
		return zuoybStudentWorkDao;
	}
	@Override
	public Page<ZuoybStudentWork> findByPage(Map<String, Object> params,
			Pageable sp) {
		Map<String, SearchFilter> filters = SearchFilter.parse(params);
		Specification<ZuoybStudentWork> specification = DynamicSpecifications.bySearchFilter(filters.values(), ZuoybStudentWork.class);    
		return  zuoybStudentWorkDao.findAll(specification, sp);
	}
	@Override
	public ZuoybStudentWork deleteByLibIdAndVipIdAndCourseId(String libId, String vipId,
			String courseId) {
		ZuoybStudentWork zuoybStudentWork=zuoybStudentWorkDao.getByLibIdAndVipIdAndCourseId(libId, vipId, courseId);
		if(zuoybStudentWork!=null){
			zuoybStudentWorkDao.deleteWorkDetalByStudentWorkId(zuoybStudentWork.getId());
			this.delete(zuoybStudentWork);
			return zuoybStudentWork;
		}
		return null;
	}
	@Override
	public ZuoybStudentWork getByLibIdAndVipIdAndCourseId(String libId,
			String vipId, String courseId) {
		return zuoybStudentWorkDao.getByLibIdAndVipIdAndCourseId(libId, vipId, courseId);
	}

	@Override
	public ZuoybStudentWork getByLibIdAndVipIdAndCourseName(String libId, String vipId, String courseName) {
		return zuoybStudentWorkDao.getByLibIdAndVipIdAndAndCourseName(libId,vipId, courseName);
	}

	@Override
	public Integer getByVipIdAndLibIdCount(String vipId, String libId,String zybCourseId) {
		return zuoybStudentWorkDao.getByVipIdAndLibIdCount(vipId, libId,zybCourseId);
	}
	@Override
	public List<ZuoybStudentWork> getByLibIdAndVipIdAndHour(String libId,String vipId,String courseHour) {
		return zuoybStudentWorkDao.getByLibIdAndVipIdAndHour(libId, vipId, courseHour);
	}
	@Override
	public String  getHtml(String vipId,String libId,String date,String childName,Integer count) {
		StringBuffer div  =new  StringBuffer();
		div.append("今天").append(childName).append("的学习状态");
		if(count==1){
			div.append("好极了");
		}else if(count==2){
			div.append("很好");
		}else if(count==3){
			div.append("不错");
		}else if(count==4){
			div.append("一般");
		}else{
			div.append("欠佳");
		}
		div.append(",");
		List<Map<String,Object>> list =zuoybQueryDao.getWorkList(libId, vipId, date);
		if(list!=null && list.size()>0){
			for (Map<String, Object> map : list) {
				Object  matching = map.get("matching");
				Object child_name =map.get("child_name");
				if(matching !=null && child_name !=null){
					div.append(matching.toString().replace("{变量}", child_name.toString()));
				}
			}
		}
		return div.toString();
	}
	@Override
	public Map<String,String>  getHtmlMap(String vipId,String libId,String date,String childName,Integer count,String courseHour) {
		Map<String,String> mapHtml  =new  HashMap<String,String>();
		StringBuffer div  =new  StringBuffer();
		div.append("今天").append(childName).append("的学习状态");
		if(count==1){
			div.append("好极了");
		}else if(count==2){
			div.append("很好");
		}else if(count==3){
			div.append("不错");
		}else if(count==4){
			div.append("一般");
		}else{
			div.append("欠佳");
		}
		div.append("。");
		List<Map<String,Object>> list =zuoybQueryDao.getWorkList(libId, vipId, date,courseHour);
		
		/*StringBuffer divHml  =new  StringBuffer("<p>");
		StringBuffer divHmlend  =new  StringBuffer("<p>");
		StringBuffer cttips  =new  StringBuffer();
		cttips.append("<div class=\"cttips\">");*/
		StringBuffer jianyi  =new  StringBuffer();
		//StringBuffer jcqk = new StringBuffer();
		if(list!=null && list.size()>0){
			for (Map<String, Object> map : list) {
				Object  matching = map.get("matching");
				Object child_name =map.get("child_name");
				Object num =map.get("num");
				if(matching !=null && child_name !=null){
					Integer nums = Integer.parseInt(num.toString());
					if(nums ==102 || nums == 103){
						div.append(matching.toString().replace("{变量}", child_name.toString()));
					}else if(nums == 5){
						//cttips.append("<span>").append(map.get("course_name").toString()).append("错题<i>").append(map.get("child_name")).append("道</i></span>");
					}else if(nums == 111){
						jianyi.append(child_name.toString());
					}else if(nums == 104){
					//	jcqk.append(matching.toString().replace("{变量}", child_name.toString()).replace(",", "、"));
					}else{
					/*	if(nums<126){
							divHml.append(matching.toString().replace("{变量}", child_name.toString()).replace("{孩子}", childName));
						}else{
							divHmlend.append(matching.toString().replace("{变量}", child_name.toString()).replace("{孩子}", childName));
						}*/
					}
				}
			}
		}
		/*cttips.append("</div>");
		divHmlend.append("</p>");
		divHml.append("</p>");
		if(!"<p></p>".equals(divHmlend.toString())){
			divHml.append(divHmlend);
		}
		if(!"<div class=\"cttips\"></div>".equals(cttips.toString())){
			divHml.insert(0, cttips);
		}
		divHml.insert(0, jcqk);
		mapHtml.put("subhtml", div.toString());
		mapHtml.put("html", divHml.toString());*/
		mapHtml.put("subhtml", div.toString());
		mapHtml.put("suggest", jianyi.toString());
		return mapHtml;
	}
	@Override
	public Map<String,String>  workPercentage(String vipId,String libId,String date,String courseHour){
		Map<String,String> mapHtml  =new  HashMap<String,String>();
		
		List<Map<String,Object>> agelist =zuoybQueryDao.workPercentage(libId, vipId, date,courseHour);
		BigDecimal zongpingTotal = new BigDecimal(0);
		BigDecimal yuwen = new BigDecimal(0);
		BigDecimal yuwencuotiTotal = new BigDecimal(0);
		BigDecimal yuwenTotal = new BigDecimal(0);
		BigDecimal shuxue = new BigDecimal(0);
		BigDecimal shuxuecuotiTotal = new BigDecimal(0);
		BigDecimal shuxueTotal = new BigDecimal(0);
		BigDecimal yingyu = new BigDecimal(0);
		BigDecimal yingyucuotiTotal = new BigDecimal(0);
		BigDecimal yingyuTotal = new BigDecimal(0);
		Integer qinfen =0;
		for (Map<String, Object> map : agelist) {
			Object course_name = map.get("course_name");
			Object child_name =map.get("child_name");
			Object child_stat =map.get("child_stat");
			Object num =map.get("num");
			Integer nums = Integer.parseInt(num.toString());
			if("语文".equals(course_name)){
				if(nums==4){
					yuwen=yuwen.add(getFraction(child_stat.toString(), 1));
				}
				if(nums==7||nums==8){
					yuwen=yuwen.add(getFraction(child_stat.toString(), 2));
				}
				if(nums==5){
					yuwencuotiTotal=yuwencuotiTotal.add(new BigDecimal(child_name.toString()));
				}
				if(nums==6){
					yuwenTotal=yuwenTotal.add(new BigDecimal(child_name.toString()));
				}
			}
			if("数学".equals(course_name)){
				if(nums==4){
					shuxue=shuxue.add(getFraction(child_stat.toString(), 1));
				}
				if(nums==7||nums==8){
					shuxue=shuxue.add(getFraction(child_stat.toString(), 2));
				}
				if(nums==5){
					shuxuecuotiTotal=shuxuecuotiTotal.add(new BigDecimal(child_name.toString()));
				}
				if(nums==6){
					shuxueTotal=shuxueTotal.add(new BigDecimal(child_name.toString()));
				}
			}
			if("英语".equals(course_name)){
				if(nums==4){
					yingyu=yingyu.add(getFraction(child_stat.toString(), 1));
				}
				if(nums==7||nums==8){
					yingyu=yingyu.add(getFraction(child_stat.toString(), 2));
				}
				if(nums==5){
					yingyucuotiTotal=yingyucuotiTotal.add(new BigDecimal(child_name.toString()));
				}
				if(nums==6){
					yingyuTotal=yingyuTotal.add(new BigDecimal(child_name.toString()));
				}
			}
			if(nums==102){
				BigDecimal zongping =getFraction(child_stat.toString(), 2);
				zongping=zongping.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);	
				zongping=zongping.multiply(new BigDecimal("10")).setScale(2,BigDecimal.ROUND_HALF_UP);
				zongpingTotal=zongpingTotal.add(zongping);
			}
			if(nums==1){
				if("2".equals(child_stat)){
					qinfen +=1;
				}
			}
			
		}
		
		if(yuwen.compareTo(new BigDecimal(0))==0){
			zongpingTotal=zongpingTotal.add(new BigDecimal("20"));
		}else{
			yuwen=yuwen.add(yuwenTotal.subtract(yuwencuotiTotal));
			yuwen=yuwen.divide((new BigDecimal("300").add(yuwenTotal)),2, RoundingMode.HALF_UP);
			yuwen=yuwen.multiply(new BigDecimal("20")).setScale(2,BigDecimal.ROUND_HALF_UP);
			zongpingTotal=zongpingTotal.add(yuwen);
		}
		if(shuxue.compareTo(new BigDecimal(0))==0){
			zongpingTotal=zongpingTotal.add(new BigDecimal("20"));
		}else{
			shuxue=shuxue.add(shuxueTotal.subtract(shuxuecuotiTotal));
			shuxue=shuxue.divide((new BigDecimal("300").add(shuxueTotal)),2, RoundingMode.HALF_UP);
			shuxue=shuxue.multiply(new BigDecimal("20")).setScale(2,BigDecimal.ROUND_HALF_UP);
			zongpingTotal=zongpingTotal.add(shuxue);
		}
		if(yingyu.compareTo(new BigDecimal(0))==0){
			zongpingTotal=zongpingTotal.add(new BigDecimal("20"));
		}else{
			yingyu=yingyu.add(yingyuTotal.subtract(yingyucuotiTotal));
			yingyu=yingyu.divide((new BigDecimal("300").add(yingyuTotal)),2, RoundingMode.HALF_UP);
			yingyu=yingyu.multiply(new BigDecimal("20")).setScale(2,BigDecimal.ROUND_HALF_UP);
			zongpingTotal=zongpingTotal.add(yingyu);
		}
		yuwencuotiTotal=yuwencuotiTotal.add(shuxuecuotiTotal);
		yuwencuotiTotal=yuwencuotiTotal.add(yingyucuotiTotal);
		BigDecimal cuoti=getFraction(yuwencuotiTotal.toString(), 3);
		cuoti=cuoti.divide((new BigDecimal("100")),2, RoundingMode.HALF_UP);
		
		zongpingTotal=zongpingTotal.add(cuoti.multiply(new BigDecimal("30")).setScale(2,BigDecimal.ROUND_HALF_UP));
		zongpingTotal= zongpingTotal.setScale(0,BigDecimal.ROUND_HALF_UP);
		mapHtml.put("jrxx", zongpingTotal.toString());//总体
		mapHtml.put("qfzx", getFraction(qinfen.toString(), 4).toString());//勤奋程度
		
		Integer howIds=zuoybStudentWorkDao.getHowDetailsId(vipId, libId, date, courseHour);//已勾选知识点数,如果为空默认100
		Integer imgCount=zuoybStudentWorkDao.workImgCount(vipId, libId, date, courseHour);//有存在的错误知识点
		// （已勾选知识点数-有存在错题知识点）/已勾选知识点数 
		BigDecimal gouxuanCount =  new BigDecimal(howIds>0?howIds:100);//勾选知识点数
		BigDecimal zhengqueCount=gouxuanCount.subtract(new BigDecimal(imgCount));
		zhengqueCount=zhengqueCount.multiply(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_HALF_UP);
		zhengqueCount=zhengqueCount.divide(gouxuanCount,0, RoundingMode.HALF_UP);
		zhengqueCount= zhengqueCount.setScale(0,BigDecimal.ROUND_HALF_UP);
		mapHtml.put("zxzw",  zhengqueCount.toString());//知识点掌握程度
		
		return mapHtml;
	}
	@Override
	public List<Map<String, Object>> getXqWeekReport(String vipId,String startDate ,String endDate) {
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> agelist =zuoybQueryDao.getXqWeekReport(vipId,startDate,endDate);
		String [] course = {"语文","数学","英语"};
		Date endTime=DateHelper.parseDate(endDate, "yyyy/MM/dd");
		for (String str : course) {
			Map<String, Object> mapCouese = new HashMap<String, Object>();
			mapCouese.put("name", str);
			mapCouese.put("type", "line");
			mapCouese.put("smooth", true);
			List<String> strlist = new ArrayList<String>();
			for(int i=1;i<8;i++){
				String beforeDate=DateHelper.format(DateHelper.getNextDay(endTime, -i),"yyyy-MM-dd");
				//BigDecimal yuwen = new BigDecimal(Math.random()*100);
				BigDecimal yuwen = new BigDecimal(0);
				BigDecimal yuwencuotiTotal = new BigDecimal(0);
				BigDecimal yuwenTotal = new BigDecimal(0);
				for (Map<String, Object> map : agelist) {
					Object scoring_time =map.get("scoring_time");
					Object course_name = map.get("course_name");
					if(beforeDate.equals(scoring_time.toString()) && str.equals(course_name.toString()) ){
						Object child_name =map.get("child_name");
						Object child_stat =map.get("child_stat");
						Object num =map.get("num");
						Integer nums = Integer.parseInt(num.toString());
							if(nums==4){
								yuwen=yuwen.add(getFraction(child_stat.toString(), 1));
							}
							if(nums==7||nums==8){
								yuwen=yuwen.add(getFraction(child_stat.toString(), 2));
							}
							if(nums==5){
								yuwencuotiTotal=yuwencuotiTotal.add(new BigDecimal(child_name.toString()));
							}
							if(nums==6){
								yuwenTotal=yuwenTotal.add(new BigDecimal(child_name.toString()));
							}
					}
				}
				if(yuwen.compareTo(new BigDecimal(0))>0){
					if(yuwenTotal.compareTo(yuwencuotiTotal)>0)yuwen=yuwen.add(yuwenTotal.subtract(yuwencuotiTotal));
					yuwen=yuwen.divide((new BigDecimal("300").add(yuwenTotal)),2, RoundingMode.HALF_UP);
					yuwen=yuwen.multiply(new BigDecimal("100")).setScale(1,BigDecimal.ROUND_HALF_UP);
				}
				/*if(yuwen.compareTo(new BigDecimal(20))<=0){
					yuwen = new BigDecimal(20);
				}*/
				
				strlist.add(yuwen.toString());
			}
			mapCouese.put("data",strlist);
			list.add(mapCouese);
			
		}
		return list;
	}
	
	@Override
	public Map<String,String>  rankedYesterday(String vipId,String libId,String date){
		Map<String,String> mapHtml  =new  HashMap<String,String>();
		//排名
				// 先计算馆内有多少作业吧服务，在看有多少人，不打分就过滤。
			Integer peciesCount=libVipServiceService.getByLibIdAndSpeciesCount(libId, "S003");
			if(peciesCount==0){
				mapHtml.put("gnpx", "-1");	
				return mapHtml;
			}
			List<ZuoybStudentPush> yesterdayPush=zuoybStudentPushSerivce.yesterdayLibIdpush(libId, date);
			int i=1;
			int j=0;
		for (ZuoybStudentPush zuoybStudentPush : yesterdayPush) {
					 if(zuoybStudentPush.getVipId().equals(vipId)){
						 j=i;
						 break;
					 }
					  i++;
		}
		if(j==0){
			mapHtml.put("gnpx", "-1");	
			return mapHtml;
		}
			 // 超过百分比： gnpx
		BigDecimal gnpx =  new BigDecimal(peciesCount-j).multiply(new BigDecimal("100")).divide(new BigDecimal(peciesCount),2, RoundingMode.HALF_UP);
		if(gnpx.compareTo(new BigDecimal("50"))<0){
			gnpx = new BigDecimal("50"); 
		}
		gnpx= gnpx.setScale(0,BigDecimal.ROUND_HALF_UP);
		mapHtml.put("gnpx", gnpx.toString());	
		return mapHtml;
	}
	private BigDecimal getFraction(String stat,int type){
		if(type ==1 ){
			switch(stat){
			case "1":
				return new BigDecimal("100");
			case "2":
				return new BigDecimal("85");
			case "3":
				return new BigDecimal("70");
			case "4":
				return new BigDecimal("55");
			default:
				return new BigDecimal("40");
			}
			
		}else if(type==2){
			switch(stat){
			case "1":
				return new BigDecimal("100");
			case "2":
				return new BigDecimal("80");
			case "3":
				return new BigDecimal("60");
			default:
				return new BigDecimal("40");
			}
		}else if(type==3){
			switch(stat){
			case "0":
				return new BigDecimal("100");
			case "1":
				return new BigDecimal("90");
			case "2":
				return new BigDecimal("80");
			default:
				return new BigDecimal("60");
			}
		}else{
			switch(stat){
			case "0":
				return new BigDecimal("100");
			case "1":
				return new BigDecimal("80");
			case "2":
				return new BigDecimal("60");
			default:
				return new BigDecimal("40");
			}
		}

	}
	@Override
	public Integer getByAvgCount(String vipId, String libId, String date) {
		return zuoybStudentWorkDao.getByAvgCount(vipId, libId, date);
	}
	@Override
	public void sendTemplateTeacher(String openId, String name, String id) {
		if(openId!=null){
			Map<String,String> data =new HashMap<String, String>();
			data.put("first", "家长您好，您孩子今日的作业反馈报告更新啦！\n");
			data.put("keyword1",name);
			data.put("keyword2", "作业吧");
			data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日"));
			data.put("remark", "\n快来看看老师对宝贝作业的反馈吧!");
			String template_id=(String) SystemResourceLocator.getValue("sendTemplate55");
			String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/zuoyb/inform_"+id+".html";
			SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id, url, data);
			pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
		}
		
	}  
	@Override
	public void sendTemplateTeacher(String openId, String name, String id,String appId) {
		if(openId!=null){
			Map<String,String> data =new HashMap<String, String>();
			data.put("first", "家长您好，您孩子今日的作业反馈报告更新啦！\n");
			data.put("keyword1",name);
			data.put("keyword2", "作业吧");
			data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日"));
			data.put("remark", "\n快来看看老师对宝贝作业的反馈吧!");
			String template_id=(String) SystemResourceLocator.getValue("sendTemplate55");
			Miniprogram miniprogram =new  Miniprogram();
			miniprogram.setAppid(appId);
			miniprogram.setPagepath("pages/workpaper/workpaper?type=10&push_id="+id);
			SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id, null, data,miniprogram);
			pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
		}
		
	}
	@Override
	public void sendStudyTime(String openId, String name, String timeCost) {
		Map<String,String> data =new HashMap<String, String>();
		StringBuffer bufString = new StringBuffer("尊敬的家长，");
		bufString.append("您的孩子").append(name).append("已经于"+DateHelper.format(new Date(), "HH:mm")+"时间完成作业，");
		bufString.append("总计").append(timeCost);
		bufString.append("，我在努力的整理本次作业反馈报告，稍后会由系统推送给您，请您留意，感谢\n");
		data.put("first", bufString.toString());
		data.put("keyword1",name);
		data.put("keyword2", "作业吧");
		data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日"));
		String template_id="OPENTM406017459";
		SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id, null, data);
		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
	}
	@Override
	public void sendTemplateSD(String libId, String name, String id) {
		TbLibJoin join=joinService.getById(libId);
		if(join!=null){
			List<String> userList= new ArrayList<String>();
			if(join.getLibtype()==1){
				userList.addAll(libStaffingService.findByCDAndOpenId(libId, "s_sd"));
				userList.addAll(libStaffingService.findByCDAndOpenId(libId, "s_cd")); //2018-03-06 陈彦需求作业反馈需发送给cd
			}else{
				userList.addAll(managerService.findManageOpenidList(libId, 1));//共享馆馆长助理
				userList.addAll(managerService.findManageOpenidList(libId, 4));//共享馆馆长
			}
			if(userList !=null && userList.size()>0){
				for (String string : userList) {
					Map<String,String> data =new HashMap<String, String>();
					data.put("first", "老师您好，今日已完成"+name+"的同伴作业督导报告更新并成功发送至家长。\n");
					data.put("keyword1",name);
					data.put("keyword2", "同伴作业督导");
					data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日"));
					data.put("remark", "\n点击详情，即可查看学习导师对"+name+"的同伴作业督导内容吧！");
					String template_id=(String) SystemResourceLocator.getValue("sendTemplate55");
					String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/zuoyb/inform_"+id+".html";
					SendTemplateShort sendTemplateShort=new SendTemplateShort(string,template_id,url,data);
					pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
					
				}
			}
		}
		
	}
	@Override
	public void sendTemplateSD(String libId, String name, String id,String appId) {
		
		TbLibJoin join=joinService.getById(libId);
		if(join!=null){
			List<String> userList= new ArrayList<String>();
			if(join.getLibtype()==1){		
				userList.addAll(libStaffingService.findByCDAndOpenId(libId, "s_sd"));
				userList.addAll(libStaffingService.findByCDAndOpenId(libId, "s_cd")); //2018-03-06 陈彦需求作业反馈需发送给cd
			}else{
				userList.addAll(managerService.findManageOpenidList(libId, 1));//共享馆馆长助理
				userList.addAll(managerService.findManageOpenidList(libId, 4));//共享馆馆长	
			}
			
			if(userList !=null && userList.size()>0){
				for (String string : userList) {
					Map<String,String> data =new HashMap<String, String>();
					data.put("first", "老师您好，今日已完成"+name+"的同伴作业督导报告更新并成功发送至家长。\n");
					data.put("keyword1",name);
					data.put("keyword2", "同伴作业督导");
					data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日"));
					data.put("remark", "\n点击详情，即可查看学习导师对"+name+"的同伴作业督导内容吧！");
					String template_id=(String) SystemResourceLocator.getValue("sendTemplate55");
					Miniprogram miniprogram =new  Miniprogram();
					miniprogram.setAppid(appId);
					miniprogram.setPagepath("pages/workpaper_teacher/workpaper_teacher?type=10&push_id="+id);
					SendTemplateShort sendTemplateShort=new SendTemplateShort(string,template_id,null,data,miniprogram);
					pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				}
			}
		}	
	
		
	}
	@Override
	public void newSendTemplateSD(String libId, String name, String pushId,String appId) {

		TbLibJoin join=joinService.getById(libId);
		if(join!=null){
			List<String> userList= new ArrayList<String>();
			if(join.getLibtype()==1){		
				userList.addAll(libStaffingService.findByCDAndOpenId(libId, "s_sd"));
				userList.addAll(libStaffingService.findByCDAndOpenId(libId, "s_cd")); //2018-03-06 陈彦需求作业反馈需发送给cd
			}else{
				userList.addAll(managerService.findManageOpenidList(libId, 1));//共享馆馆长助理
				userList.addAll(managerService.findManageOpenidList(libId, 4));//共享馆馆长	
			}
			
			if(userList !=null && userList.size()>0){
				for (String string : userList) {
					Map<String,String> data =new HashMap<String, String>();
					data.put("first", "老师您好，今日已完成"+name+"的同伴作业督导报告更新并成功发送至家长。\n");
					data.put("keyword1",name);
					data.put("keyword2", "同伴作业督导");
					data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日"));
					data.put("remark", "\n点击详情，即可查看学习导师对"+name+"的同伴作业督导内容吧！");
					String template_id=(String) SystemResourceLocator.getValue("sendTemplate55");
					Miniprogram miniprogram =new  Miniprogram();
					miniprogram.setAppid(appId);
					miniprogram.setPagepath("pages/homework_report/homework_report?type=10&pushId="+pushId);
					SendTemplateShort sendTemplateShort=new SendTemplateShort(string,template_id,null,data,miniprogram);
					pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				}
			}
		}
	}

	@Override
	public void sendHomeworkReport2LibManager (String libId, String name, String pushId, String appId){
		TbLibJoin join = joinService.getById(libId);
		if(join!=null) {
			List<Map<String, Object>> managers = managerService.findByLibIdAndType(libId, 4);
			if(join.getLibtype()==1) {
				managers.addAll(libStaffingService.findLibMasterByLibIdAndType(libId, "s_cd"));
			}
			for (Map<String, Object> map : managers) {
				Map<String, String> data = new HashMap<String, String>();
				data.put("first", "尊敬的" + map.get("wx_name") + "馆长，您馆内的" + name + "同学，今日的作业反馈报告已生成\n");
				data.put("keyword1", name);
				data.put("keyword2", "作业吧");
				data.put("keyword3", DateHelper.format(new Date(), "yyyy年MM月dd日"));
				data.put("remark", "\n点击详情，即可查看学习导师对" + name + "的同伴作业督导内容吧！");
				String template_id = (String) SystemResourceLocator.getValue("sendTemplate55");
				Miniprogram miniprogram = new Miniprogram();
				miniprogram.setAppid(appId);
				miniprogram.setPagepath("pages/homework_report/homework_report?type=10&pushId=" + pushId);
				SendTemplateShort sendTemplateShort = new SendTemplateShort((String) map.get("wx_account"), template_id, null, data, miniprogram);
				pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
			}
		}
	}


	@Override
	public void sendTemplate2CooperateLibTeacher(String vipId, String name, String pushId, String appId) {
		String[] libIds = {"cdf451d8-4764-4522-a591-64531cef0394", "844abb1c-0599-435d-b125-3a6e65411bf7"};
		String[] vipIds = {vipId};
		String[] specices = {"S003"};
		String userIdStr =  PropertiesUtil.getValue("COOPERATION_PUSH_TEACHERS");
		if (StringUtil.isBlank(userIdStr)){
			return;
		}
		String[] userIds = userIdStr.split(";");

		List<LibVipService> list = libVipServiceService.findByVipIdInAndSpeciesAndLibIdIn(vipIds, libIds, specices);
		if (list != null && list.size() > 0){
            List<User> users = userService.findByIdIn(Arrays.asList(userIds));
            Map<String,String> data =new HashMap<String, String>();
            data.put("first", "老师您好，今日已完成"+name+"的同伴作业督导报告更新并成功发送至家长。\n");
            data.put("keyword1",name);
            data.put("keyword2", "同伴作业督导");
            data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日"));
            data.put("remark", "\n点击详情，即可查看学习导师对"+name+"的同伴作业督导内容吧！");
            String template_id = (String) SystemResourceLocator.getValue("sendTemplate55");
            Miniprogram miniprogram =new  Miniprogram();
            miniprogram.setAppid(appId);
            miniprogram.setPagepath("pages/homework_report/homework_report?type=10&pushId="+pushId);
            if (users != null) {
                users.forEach(user -> {
                    SendTemplateShort sendTemplateShort=new SendTemplateShort(user.getAccount(),template_id,null,data,miniprogram);
                    pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
                });
            }
        }

	}

	@Override
	public void updatePushTimeAndStat(String vipId, String libId, String date,
			String pushId,String courseHour) {
		zuoybStudentWorkDao.updatePushTimeAndStat(vipId, libId, date, pushId,courseHour);
	}
	@Override
	public List<ZuoybStudentWork> findByStudentPushId(String studentPushId) {
		return zuoybStudentWorkDao.findByStudentPushId(studentPushId);
	}
	@Override
	public Integer getByZTCount(String vipId, String libId, String date,
			String courseHour) {
		return zuoybStudentWorkDao.getByZTCount(vipId, libId, date, courseHour);
	}
	@Override
	public List<ZuoybStudentWork> getByLibIdAndVipIdAndTimer(String libId,
			String vipId) {
		return zuoybStudentWorkDao.getByLibIdAndVipIdAndTimer(libId, vipId);
	}
	@Override
	public List<ZuoybStudentWork>   oldDataWorkHow() {
		return zuoybStudentWorkDao.oldDataWorkHow();
	}
	@Override
	public List<ZuoybStudentWork> getByLibIdAndVipIdAndHourAndType(
			String libId, String vipId, String courseHour, Integer type) {
		return zuoybStudentWorkDao.getByLibIdAndVipIdAndHourAndType(libId, vipId, courseHour,type);
	}
	@Override
	public List<ZuoybStudentWork> getByLibIdAndVipId(String libId, String vipId) {
		return zuoybStudentWorkDao.getByLibIdAndVipId(libId, vipId);
	}
	@Override
	public List<ZuoybStudentWork> getByLibIdAndVipIdAndType(String libId,
			String vipId, Integer type) {
		return zuoybStudentWorkDao.getByLibIdAndVipIdAndType(libId, vipId, type);
	}
	@Override
	public List<Map<String, Object>> getRecentWorkBg(String vipId) {
		return zuoybQueryDao.getRecentWorkBg(vipId);
	}
	@Override
	public String learningbyVipId(String vipId) {
		Long learning =zuoybStudentWorkDao.learningbyVipId(vipId);
		if(learning==null){
			return  "0分";
		}
		if(learning>=60){
			return learning/60+"时"+learning%60+"分";
		}
		return learning+"分";
	}
	@Override
	public Long studyReportbyVipId(String vipId) {
		return zuoybStudentWorkDao.studyReportbyVipId(vipId);
	}
	@Override
	public List<Map<String, Object>> Last7days(String vipId) {
		List<Map<String, Object>> list =  zuoybQueryDao.Last7days(vipId);
		return this.parseToFormateList(list);
	}

	@Override
	public List<Map<String, Object>> parseToFormateList (List<Map<String, Object>> list) {
		List<String> listdays = this.get7days();
		Map<String, Object> newMap =new HashMap<String, Object>();
		for (Map<String, Object> map : list) {
			newMap.put(map.get("date_time").toString(), map.get("used_time"));
		}
		List<Map<String, Object>>  newList =new ArrayList<Map<String,Object>>();
		for (String string : listdays) {
			Map<String, Object> omap =new HashMap<String, Object>();
			if(newMap.containsKey(string)){
				omap.put("dateTime", string);
				omap.put("usedTime", newMap.get(string));
			}else{
				omap.put("dateTime", string);
				omap.put("usedTime", 0);
			}
			newList.add(omap);
		}
		return newList;
	}
	private List<String> get7days(){
		Date date =new Date();
		List<String> list =new ArrayList<String>();
		for (int i = -1; i > -8; i--) {
			list.add(DateHelper.format(DateHelper.getNextDay(date, i), "MM.dd"));
		}
		return list;
	}
	@Override
	public List<Map<String, Object>> Lastproblem7days(String vipId) {
		return zuoybQueryDao.Lastproblem7days(vipId);
	}
	@Override
	public int continuousLearning(String vipId, String beginDateTimeStr, String endDateTimeStr) {
		int continuousLearningDays = 0;

		List<String> dateStrList = zybStudentWorkMapper.findLearningDate(vipId, beginDateTimeStr, endDateTimeStr);
		if (CollectionUtils.isNotEmpty(dateStrList)) {
			dateStrList = dateStrList.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
			dateStrList.sort(String::compareTo);
			int temp = 0;
			String beforeDate = dateStrList.get(0);
			for (String dateStr : dateStrList) {
				if (Objects.equals(beforeDate, dateStr)) {
					continue;
				}

				int daysBetween = DateUtil.daysBetween(DateUtil.parse_yyyyMMdd(beforeDate), DateUtil.parse_yyyyMMdd(dateStr));
				if (daysBetween == 1) {
					temp++;
				} else {
					if (temp > continuousLearningDays) {
						continuousLearningDays = temp;
					}
					temp = 0;
				}

				beforeDate = dateStr;
			}

			if (temp > continuousLearningDays) {
				continuousLearningDays = temp;
			}
		}

		return continuousLearningDays;
	}

	@Override
	public void deleteWorkDetalByStudentWorkId(String id) {
		
		zuoybStudentWorkDao.deleteWorkDetalByStudentWorkId(id);
	}

	@Override
	public ZuoybStudentWork saveZuoybWork(String zuoybWorkId, String vipId, String teacherId, String subject) {
		ZuoybStudentWork result = null;
		if (StringUtil.isEmpty(zuoybWorkId)) {
			result = saveZybStudentWork(vipId, teacherId, subject, 2);
		} else {
			result = this.getById(zuoybWorkId);
		}

	//	logger.info("查询出的zyb_student_work记录：" + result);
		return result;
	}

	public ZuoybStudentWork saveZybStudentWork(String vipId, String teacherId, String subject, int stat){
		ZuoybStudentWork result = null;
		LibVipService libVipService = libVipServiceService.getVipIdZXService5days(vipId);
		if (libVipService == null){
			logger.error("关联不出馆, 查询不出zyb_student_work, 程序夭折");
			return result;
		}
		ZuoybCourse zuoybCourse = zuoybCourseService.getCourseNameAndHour(subject,libVipService.getCourseHour(),libVipService.getLibId());
		result = this.getByLibIdAndVipIdAndCourseName(libVipService.getLibId(), vipId, subject);
		if (result == null){
			result = new ZuoybStudentWork();
			if (zuoybCourse != null){
				result.setCourseHour(zuoybCourse.getCourseHour());
				result.setZybCourseId(zuoybCourse.getId());
				result.setNum(zuoybCourse.getNum());
			} else {
				logger.error("查询zuoybCourse失败，查询条件subject={},course_hour={}, lib_id={}", subject, libVipService.getCourseHour(), libVipService.getLibId());
			}
			result.setCourseName(subject);
			result.setLibId(libVipService.getLibId());
			result.setScoringTime(new Date());
			result.setStat(stat);
			result.setVipId(vipId);
			result.setTeacherId(teacherId);
			result.setType(1);
			result = this.save(result);

		}
		return result;
	}

	@Override
	public String getGzd(String libId, String vipId) {
		return zuoybStudentWorkDao.getGzd(libId, vipId);
	}

	@Override
	public int getTheMonthTimeCost(String vipId, String beginTime, String endTime) {
		Integer result = zuoybStudentWorkDao.getTheMonthTimeCost(vipId, beginTime, endTime);
		if (result == null){
			return 0;
		}
		return result.intValue();
	}

	@Override
	public String getStudentWorkId(String vipId, String subject, String date) {
		ZuoybStudentWork work = zuoybStudentWorkDao.findByVipIdAndcAndCourseName(vipId, subject, date + " 00:00:00", date + " 23:59:59");
		if (work != null){
			return work.getId();
		}
		return null;
	}


	@Override
	public List<ZuoybStudentWork> queryDateZybStudentwork (String vipId, Date dateTime){
		String date = DateUtil.format_yyyyMMdd(dateTime);
		return zuoybStudentWorkDao.findByVipIdAndScoringTimeBetween(vipId,
				DateUtil.parse_yyyyMMddHHmmss(date + " 00:00:00"),
				DateUtil.parse_yyyyMMddHHmmss(date + " 23:59:59"));
	}
	@Override
	public ZuoybStudentWork saveCourse(ZuoybStudentWork zuoybStudentWork,String teacherId) {
		//删除旧数据
		 ZuoybStudentWork oldwork=this.deleteByLibIdAndVipIdAndCourseId(zuoybStudentWork.getLibId(), zuoybStudentWork.getVipId(),
				 zuoybStudentWork.getZybCourseId());
		 Date date =new Date();
		 if(oldwork!=null &&  StringUtils.isNotEmpty(oldwork.getTimers())){
			 zuoybStudentWork.setTimers(oldwork.getTimers());
		 }
		 if(zuoybStudentWork.getNum()<4 &&  !"1".equals(zuoybStudentWork.getHowIds())){
			 String timeCost="0";
			 if(oldwork!=null &&  StringUtils.isNotEmpty(oldwork.getTimers())){
				 zuoybStudentWork.setTimers(oldwork.getTimers());
				 String timers=oldwork.getTimers();
				 String[] difftimes= timers.split(";");
				 long countdiff=0;
				 for (String diffstr : difftimes) {
					 String[] time2= diffstr.split("-");
					 Date endDate=new Date();
					 if(time2.length>1 && StringUtils.isNotEmpty(time2[1])){
						 endDate=DateHelper.parseDate(time2[1],"yyyyMMddHHmmss");
					 }
					 long diff1=DateHelper.getDifferenceTimeNum(DateHelper.parseDate(time2[0],"yyyyMMddHHmmss"),endDate);
					 countdiff=countdiff+diff1;
				 }
				 long min =countdiff / (60 * 1000); //记录分钟数 
				 timeCost=Long.toString(min);
			 }else{
				 ZuoybStudentPush push= zuoybStudentPushSerivce.findByLibIdAndVipIdAndCourseHour(zuoybStudentWork.getLibId(), zuoybStudentWork.getVipId(), zuoybStudentWork.getCourseHour(), DateHelper.getDate(date));
				 timeCost=DateHelper.getCostTime(push.getPushTime(), date);
			 }
			 zuoybStudentWork.setTimeCost(timeCost);
		 }
		 zuoybStudentWork.setTeacherId(teacherId);
		 zuoybStudentWork.setScoringTime(date);
		// zuoybStudentWork.setHowNames(howNames);
		 this.save(zuoybStudentWork);
		 //保存打分数据
		 zuoybStudentWorkDetailsService.saveWorkDetails(zuoybStudentWork.getWorkDetailsList(), zuoybStudentWork.getId(), zuoybStudentWork.getLibId());
		 //保存作业大纲
		 zuoybStudentWorkHowService.saveStudentWorkHow(oldwork, zuoybStudentWork.getWorkHowList(), zuoybStudentWork.getId());
		return zuoybStudentWork;
	}
	@Override
	public ZuoybStudentWork saveCourseH5(ZuoybStudentWork zuoybStudentWork,
			String imgids) {
		//删除旧数据
		 ZuoybStudentWork oldwork=this.deleteByLibIdAndVipIdAndCourseId(zuoybStudentWork.getLibId(), zuoybStudentWork.getVipId(),
				 zuoybStudentWork.getZybCourseId());
		 Date date =new Date();
		 if(oldwork!=null &&  StringUtils.isNotEmpty(oldwork.getTimers())){
			 zuoybStudentWork.setTimers(oldwork.getTimers());
		 }
		 if(zuoybStudentWork.getNum()<4 &&  !"1".equals(zuoybStudentWork.getHowIds())){
			 String timeCost="0";
			 if(oldwork!=null &&  StringUtils.isNotEmpty(oldwork.getTimers())){
				
				 String timers=oldwork.getTimers();
				 String[] difftimes= timers.split(";");
				 long countdiff=0;
				 for (String diffstr : difftimes) {
					 String[] time2= diffstr.split("-");
					 Date endDate=new Date();
					 if(time2.length>1 && StringUtils.isNotEmpty(time2[1])){
						 endDate=DateHelper.parseDate(time2[1],"yyyyMMddHHmmss");
					 }
					 long diff1=DateHelper.getDifferenceTimeNum(DateHelper.parseDate(time2[0],"yyyyMMddHHmmss"),endDate);
					 countdiff=countdiff+diff1;
				 }
				 long min =countdiff / (60 * 1000); //记录分钟数 
				 timeCost=Long.toString(min);
			 }else{
				 ZuoybStudentPush push= zuoybStudentPushSerivce.findByLibIdAndVipIdAndCourseHour(zuoybStudentWork.getLibId(), zuoybStudentWork.getVipId(), zuoybStudentWork.getCourseHour(), DateHelper.getDate(date));
				 timeCost=DateHelper.getCostTime(push.getPushTime(), date);
			 }
			 zuoybStudentWork.setTimeCost(timeCost);
		 }
		 zuoybStudentWork.setScoringTime(date);
		 this.save(zuoybStudentWork);
		 //保存打分数据
		 zuoybStudentWorkDetailsService.saveWorkDetails(zuoybStudentWork.getWorkDetailsList(), zuoybStudentWork.getId(), zuoybStudentWork.getLibId());
		 //删除作业图片。
		 final List<ZuoybStudentWorkImg> list =  zuoybStudentWork.getImgList(); 
		// if(list!=null && list.size()>0){
			 final String id = zuoybStudentWork.getId();
			 Thread t1 = new Thread(new Runnable() {
				 public void run() {
					 zuoybStudentWorkImgService.saveWorkImg(list, imgids, id);
				 }
			 });
			 t1.start();
		 //}
		 //保存作业大纲
		 zuoybStudentWorkHowService.saveZuoybStudentWorkHow(oldwork, zuoybStudentWork.getWorkHowList(), zuoybStudentWork.getId());
		return zuoybStudentWork;
	}

}
