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


import com.ssj.bean.weixin.zyb.domain.ZuoybStudentPush;
import com.ssj.bean.weixin.zyb.domain.ZuoybStudentWork;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybQueryDao;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybStudentPushDao;
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.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.mapper.ZybStudentWorkMapper;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.service.weixin.zuoyb.service.ZuoybDayService;
import com.ssj.service.weixin.zuoyb.service.ZuoybStudentPushSerivce;
import com.ssj.service.weixin.zuoyb.service.ZuoybStudentWorkService;
import org.apache.commons.lang3.StringUtils;
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.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/** 
 * @author  ZhangCaibao 
 * @version 2017年7月21日 上午11:27:33 
 * 类说明 
 */
@Service
@Transactional
public class ZuoybStudentPushSerivceImpl extends BaseServiceImpl<ZuoybStudentPush, String> implements ZuoybStudentPushSerivce{

	@Autowired
	private ZuoybStudentPushDao  zuoybStudentPushDao;
	@Autowired
	private ZuoybStudentWorkService  zuoybStudentWorkService;
	@Autowired
	 private ZuoybDayService  zuoybDayService;
	@Autowired
	 private  UserService   userService;
	
	 @Autowired
	private  ZuoybQueryDao  zuoybQueryDao;
	 @Autowired
	 private ZybStudentWorkMapper zybStudentWorkMapper;
	 
	@Override
	public PagingAndSortingRepository<ZuoybStudentPush, String> getDao() {
		return zuoybStudentPushDao;
	}
	@Override
	public Page<ZuoybStudentPush> findByPage(Map<String, Object> params,
			Pageable sp) {
		Map<String, SearchFilter> filters = SearchFilter.parse(params);
		Specification<ZuoybStudentPush> specification = DynamicSpecifications.bySearchFilter(filters.values(), ZuoybStudentPush.class);    
		return  zuoybStudentPushDao.findAll(specification, sp);
	}
	@Override
	public ZuoybStudentPush findByLibIdAndVipIdAndCourseHour(String libId,
			String vipId, String courseHour,String date) {
		return zuoybStudentPushDao.findByLibIdAndVipIdAndCourseHour(libId, vipId, courseHour, date);
	}
	@Override
	public ZuoybStudentPush findByVipIdAndDate(
			String vipId, String date) {
		Date dateTime = null;
		try {
			dateTime = DateUtil.parse_yyyyMMddHHmmss(date);
		} catch (Exception e){
			dateTime = DateUtil.parse_yyyyMMdd(date);
		}

		String beginTime = DateUtil.format_yyyyMMdd(dateTime);
		String endTime = beginTime + " 23:59:59";
		return zuoybStudentPushDao.findByVipIdAndDate(beginTime, endTime, vipId);
	}
	@Override
	public ZuoybStudentPush  findByVipIdToDay(String vipId) {
		Date dateTime = new Date();
		String beginTime = DateUtil.format_yyyyMMdd(dateTime);
		String endTime = beginTime + " 23:59:59";
		return zuoybStudentPushDao.findByVipIdAndDate(beginTime, endTime, vipId);
	}

	@Override
	public List<ZuoybStudentPush> findByVipId(String vipId){
		return zuoybStudentPushDao.findByVipId(vipId);
	}
	@Override
	public Page<Map<String, Object>> zuoybStudentPushList(
			Map<String, Object> searchParams, Pageable pageable) {
		return zuoybQueryDao.zuoybStudentPushList(searchParams, pageable);
	}
	@Override
	public List<ZuoybStudentPush> yesterdayLibIdpush(String libId,
			String date) {
		return zuoybStudentPushDao.yesterdayLibIdpush(libId, date);
	}
	@Override
	public long getXqLearningTime(String vipId) {
		return zuoybStudentPushDao.getXqLearningTime(vipId);
	}
	@Override
	public Map<String, Object> getXqTopicCount(String vipId) {
		return zuoybQueryDao.getXqTopicCount(vipId);
	}
	@Override
	public List<Map<String, Object>> getXqWeekReport(String vipId) {
		Date endDate = new Date();
		Date startDate =DateHelper.getNextDay(endDate, -8);
		return zuoybStudentWorkService.getXqWeekReport(vipId,DateHelper.getDate(startDate),DateHelper.getDate(endDate));
	}
	@Override
	public Integer getToDayAndVipId(String vipId) {
		return zuoybStudentPushDao.getToDayAndVipId(vipId);
	}
	@Override
	public Map<String, Object> getStudentWork(String pushId) {
		List<Map<String, Object>> list=	zuoybQueryDao.getStudentWork(pushId);
		Map<String, Object> mapWork = new  HashMap<String, Object>();
		String desc ="";
		Integer ztTotal  = 0;
		Integer ctTotal  = 0;
		for (Map<String, Object> map : list) {
			Object child_name =map.get("child_name");
			Object num =map.get("num");
			Integer nums = Integer.parseInt(num.toString());
			if(nums==111){
				desc = child_name.toString();
			}
			if(nums==6){
				ztTotal +=Integer.parseInt(child_name.toString());
			}
			if(nums==5){
				ctTotal +=Integer.parseInt(child_name.toString());
			}
		}
		mapWork.put("desc", "".equals(desc)?"暂无学习建议":desc);
		mapWork.put("zqtotal", ztTotal-ctTotal>0? ztTotal-ctTotal :0);
		mapWork.put("cttotal", ctTotal);
		return mapWork;
	}
	@Override
	public Page<Map<String, Object>> getZuoybStudentPushList(
			Map<String, Object> searchParams, Pageable pageable) {
		return zuoybQueryDao.getZuoybStudentPushList(searchParams, pageable);
	}
	@Override
	public Map<String, Object> getTeacherAndPhoto(String vipId) {
		return zuoybQueryDao.getTeacherAndPhoto(vipId);
	}
	@Override
	public String getToDayVipSubscribe(String vipId, String libId) {
		return zuoybStudentPushDao.getToDayVipSubscribe(vipId, libId);
	}

	@Override
	public int countDistinctByTeacherIdAndType(String teacherId, int type) {
		return this.zuoybStudentPushDao.countDistinctByTeacherIdAndType(teacherId, type);
	}

	@Override
	public List<ZuoybStudentPush> findTodayPushByLibIdAndType(int type, List<String> libId) {
		return zuoybStudentPushDao.findByTypeAndLibIdInOrderByPushTimeAsc(type, libId);
	}
	@Override
	public ZuoybStudentPush findSuggestByStudentWorkId(String studentWorkId) {
		return zuoybStudentPushDao.findSuggestByStudentWorkId(studentWorkId);
	}

	@Override
	public ZuoybStudentPush findLastStudentPush(String teacherId, String vipId) {
		return zuoybStudentPushDao.findFirstByTeacherIdAndVipIdOrderByPushTimeDesc(teacherId, vipId);
	}

	@Override
	public ZuoybStudentPush findLastStudentPush(String vipId) {
		return zuoybStudentPushDao.findFirstByVipIdOrderByPushTimeDesc(vipId);
	}

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

	@Override
	public float avgParentPraise(String vipId) {
		Float result = zuoybStudentPushDao.avgParentPraise(vipId);
		if (result == null){
			return 0f;
		}
		return result.floatValue();
	}

	@Override
	public ZuoybStudentPush findLastLess3Suggest(String vipId) {
		return zuoybStudentPushDao.findLastLess3Suggest(vipId);
	}

	@Override
	public ZuoybStudentPush findOneSuggestNotNull(String vipId) {
		return null;
	}

	@Override
	public int findDatesReportCount(String vipId, Date beginTime, Date endTime) {
		return zuoybStudentPushDao.countByTypeAndVipIdAndPushTimeBetween(2, vipId, beginTime, endTime);
	}
	@Override
	public ResponseEntity sendWork(String libId, String vipId, String userId,
			String childName, String pushId) {

		 ResponseEntity responseEntity = new ResponseEntity();
		 try {
			 ZuoybStudentPush  push  = this.getById(pushId);
			 push.setUpdateTime(new Date());
			 push.setType(2);
			 this.save(push);
			 //zuoybStudentWorkService.updatePushTimeAndStat(vipId, libId,  DateHelper.getDate(push.getPushTime()), pushId,push.getCourseHour());
			 List<ZuoybStudentWork> works= zuoybStudentWorkService.getByLibIdAndVipIdAndHour(libId, vipId,push.getCourseHour());
			 for (ZuoybStudentWork zuoybStudentWork : works) {
				 
				 Date endDate=new Date();
				 if(zuoybStudentWork.getNum()<4 &&  !"1".equals(zuoybStudentWork.getHowIds())){
					 String timers=zuoybStudentWork.getTimers();
					 String timeCost="0";
	                if( StringUtils.isNotEmpty(timers)){
	                 	String[] difftimes= timers.split(";");
	                 	String  timesend= difftimes[difftimes.length-1];
	                 	String[] timesend2= timesend.split("-");
	                 	if(timesend2.length==1){
	                 		timers = timers+"-"+DateHelper.format(endDate, "yyyyMMddHHmmss");
	                 	}
	                 	zuoybStudentWork.setTimers(timers);
	                 	String[] difft= timers.split(";");
	                 	long countdiff=0;
	                 	for (String diffstr : difft) {
	     					String[] time2= diffstr.split("-");
	     					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); //记录分钟数 
	                 	if(min>120)min=120;
	     		    	timeCost=Long.toString(min);
	     		    	
	                }else{
	                	timeCost=DateHelper.getCostTime(push.getPushTime(), endDate);
	                	Integer times = Integer.parseInt(timeCost);
	                	if(times>120){
	                		timeCost="120";
	                	}
	                }
	                zuoybStudentWork.setTimeCost(timeCost);
				 }
				
            
               zuoybStudentWork.setStat(3);
               zuoybStudentWork.setPushTime(endDate);
               zuoybStudentWork.setStudentPushId(pushId);
               zuoybStudentWorkService.save(zuoybStudentWork);
			}
			 zuoybDayService.saveToday(vipId, 1);
			 //推送给用户。
			 zuoybStudentWorkService.sendTemplateTeacher(userService.getAccount(userId), childName, pushId);
			 //推送给SD
			 zuoybStudentWorkService.sendTemplateSD(libId, childName, pushId);
			 responseEntity.success();
		 } catch (Exception e) {
			 e.printStackTrace();
			 responseEntity.failure(ResponseConstant.CODE_000, "服务器发生异常，请稍后重试");
		 }
		 return responseEntity;
	 
	}

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

    @Override
    public int updateType() {
		return zybStudentWorkMapper.updateStudentPushType();
    }

	@Override
	public int findCountByVipId(String vipId) {
		return zuoybStudentPushDao.findCountByVipId(vipId);
	}


}
