package com.ssj.service.kmt.kmt.service.impl;


import com.ssj.bean.kmt.arrange.dto.*;
import com.ssj.bean.kmt.arrange.vo.DutyRequestVO;
import com.ssj.bean.kmt.arrange.vo.DutySysRequestVO;
import com.ssj.bean.kmt.kmt.domain.KmtArrangeAllot;
import com.ssj.bean.kmt.kmt.domain.KmtArrangeDetail;
import com.ssj.bean.weixin.libmy.domain.TbLibLoginInfo;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.dao.kmt.kmt.dao.KmtArrangeAllotDao;
import com.ssj.dao.kmt.kmt.dao.KmtArrangeTemplateDao;
import com.ssj.dao.kmt.kmt.dao.TeacherArrangeQueryDao;
import com.ssj.dao.sys.homework.dao.HomeworkDao;
import com.ssj.dao.weixin.library.dao.IBookManagerDao;
import com.ssj.dao.weixin.library.dao.ILibVipDao;
import com.ssj.dao.weixin.library.dao.TbLibLoginInfoDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.util.MapGetterTool;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.service.kmt.arrange.service.KmtArrangeAllotService;
import com.ssj.service.kmt.arrange.service.KmtArrangeDetailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static java.math.BigDecimal.ROUND_HALF_DOWN;


@Transactional
@Service
public class KmtArrangeAllotServiceImpl extends BaseServiceImpl<KmtArrangeAllot, String> implements KmtArrangeAllotService {

	@Autowired
	private KmtArrangeAllotDao dao;

	@Autowired
	private TeacherArrangeQueryDao queryDao;
	private ResponseEntity responseEntity;

	@Autowired
	private  HomeworkDao homeworkDao;

	@Autowired
	private ILibVipDao libVipDao;

	@Autowired
	private KmtArrangeTemplateDao kmtArrangeTemplateDao;

	@Autowired
	private KmtArrangeDetailService kmtArrangeDetailService;

	@Autowired
	private TbLibLoginInfoDao tbLibLoginInfoDao;

	@Autowired
	private IBookManagerDao managerDao;

	@Override
	public PagingAndSortingRepository<KmtArrangeAllot, String> getDao() {
		return dao;
	}


	@Override
	public TeacherArrangeVO teacherMonthDutyList(String teacherUserId) {
		TeacherArrangeVO vo = new TeacherArrangeVO();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date date = new Date();
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		String thisMonth = sdf.format(date);
		int days = ca.get(Calendar.DAY_OF_MONTH);
		int lastDay = ca.getActualMaximum(Calendar.DAY_OF_MONTH);
		if (days > 24 && days<lastDay) { //将显示下个月排班
			vo.setIsShowNext(1);
			//查询下个月老师有多少排班
			vo.setNextDutyCount(dao.findMonthDutyCount(teacherUserId, getPreMonth()));
		} else {
			vo.setIsShowNext(0);
			vo.setNextDutyCount(0);
		}
		List<Map<String, Object>> list = queryDao.findTeacheDutyList(teacherUserId,thisMonth);

		vo.setMonth(thisMonth.substring(thisMonth.length()-2));
		vo.setYear(thisMonth.substring(0,thisMonth.length()-3));
		//记录出勤 计算出勤率
		int i= 0; //有效出勤数
		int j = 0 ; //总出勤
		Map<String, Object> dayMap = new HashMap<String, Object>();
		List<DutyTimeVO> timeVoList = new ArrayList<DutyTimeVO>();
		TeacherArrangeDayVO dayVO = new TeacherArrangeDayVO();
		List<TeacherArrangeDayVO> dayList = new ArrayList<TeacherArrangeDayVO>();
		if (list != null && list.size() > 0) {
			int x = 0;
			for (Map<String, Object> map : list) {
				int dayCompare = DateHelper.format(new Date(),"yyyy-MM-dd").compareTo(map.get("arrange_date").toString());
				if(map.get("attend_type")!=null && dayCompare>0){ //null则是没有选择时段
					if(map.get("attend_type").toString().equals("1")){ //有效出勤
						i++;
					}
					j++;
				}
				if(dayVO.getDay()!=null){
					if(!dayVO.getDay().equals(map.get("arrange_date").toString().substring(map.get("arrange_date").toString().length()-2))){ //
						dayVO.setTimeVoList(timeVoList);
						dayList.add(dayVO);
						timeVoList=new ArrayList<DutyTimeVO>();
						dayVO = new TeacherArrangeDayVO();
					}
				}
				if(dayCompare<=0){
					dayVO.setIsOutDate(0);
				}else{
					dayVO.setIsOutDate(1);
				}
				dayVO.setIsOpen(Integer.parseInt(map.get("is_open").toString()));
				dayVO.setDay(map.get("arrange_date").toString().substring(map.get("arrange_date").toString().length()-2));
				DutyTimeVO timeVO = new DutyTimeVO();
				timeVO.setId(map.get("id").toString());
				timeVO.setEndInterval(map.get("end_interval").toString());
				timeVO.setStartInterval(map.get("start_interval").toString());
				//先判断是否饱和
				if(dayCompare>0){
					//先判断是否缺勤
					if(map.get("attend_type")==null){
						timeVO.setTimeState(1);
					}else{
						if(map.get("attend_type").toString().equals("0")){
							timeVO.setTimeState(4);
						}else{
							timeVO.setTimeState(2);
						}
					}
				}else{
					if(map.get("attend_type")==null){
						timeVO.setTimeState(1);
					}else{
						timeVO.setTimeState(2);
					}
				}

				timeVoList.add(timeVO);
				x++;
				if(list.size()==x){
					dayVO.setTimeVoList(timeVoList);
					dayList.add(dayVO);
				}
			}
		}
		vo.setDayList(dayList);
		if(j==0 || i==0){
			vo.setDutyRate("0");
		}else{
			DecimalFormat df = new DecimalFormat("#0.00");
			vo.setDutyRate(df.format(new BigDecimal(i).divide(new BigDecimal(j),10,ROUND_HALF_DOWN).multiply(new BigDecimal(100))));
		}
		return vo;
	}

	@Override
	public TeacherNextArrangeVO teacherNextMonthDutyList(String teacherUserId) {
		TeacherNextArrangeVO vo = new TeacherNextArrangeVO();
		String thisMonth = getPreMonth();

		List<Map<String, Object>> list = queryDao.findTeacheDutyList(teacherUserId,thisMonth);
		vo.setMonth(thisMonth.substring(thisMonth.length()-2));
		vo.setYear(thisMonth.substring(0,thisMonth.length()-3));
		vo.setNextDutyCount(dao.findCountByTeacherId(thisMonth,teacherUserId));
		Map<String, Object> dayMap = new HashMap<String, Object>();
		List<DutyTimeVO> timeVoList = new ArrayList<DutyTimeVO>();
		TeacherArrangeDayVO dayVO = new TeacherArrangeDayVO();
		List<TeacherArrangeDayVO> dayList = new ArrayList<TeacherArrangeDayVO>();
		if (list != null && list.size() > 0) {
			int x = 0;
			for (Map<String, Object> map : list) {
				if(dayVO.getDay()!=null){
					if(!dayVO.getDay().equals(map.get("arrange_date").toString().substring(map.get("arrange_date").toString().length()-2))){
						dayVO.setTimeVoList(timeVoList);
						dayList.add(dayVO);
						timeVoList=new ArrayList<DutyTimeVO>();
						dayVO = new TeacherArrangeDayVO();
					}
				}
				dayVO.setIsOpen(Integer.parseInt(map.get("is_open").toString()));
				dayVO.setDay(map.get("arrange_date").toString().substring(map.get("arrange_date").toString().length()-2));
				DutyTimeVO timeVO = new DutyTimeVO();
				timeVO.setId(map.get("id").toString());
				timeVO.setEndInterval(map.get("end_interval").toString());
				timeVO.setStartInterval(map.get("start_interval").toString());
				//先判断是否饱和
				if(map.get("attend_type")==null){
					if(Integer.parseInt(map.get("max_num").toString())<=Integer.parseInt(map.get("have_num").toString())){
						timeVO.setTimeState(3);
					}else {
						timeVO.setTimeState(1);
					}
				}else{
					timeVO.setTimeState(2);
				}
				timeVoList.add(timeVO);

				x++;
				if(list.size()==x){
					dayVO.setTimeVoList(timeVoList);
					dayList.add(dayVO);
				}
			}
			vo.setDayList(dayList);
		}
		return vo;
	}

	@Override
	public ResponseEntity saveTeacherDuty(DutyRequestVO requestVO, String teacherUserId) {
		ResponseEntity responseEntity = new ResponseEntity();
		Date date = new Date();
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		int days = ca.get(Calendar.DAY_OF_MONTH);
		int lastDay = ca.getActualMaximum(Calendar.DAY_OF_MONTH);

		if (days > 24 && days< lastDay) { //时间段
			ca.add(Calendar.MONTH,1);
			SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
			String preMonth = dft.format(ca.getTime());
			List<String> resultList= new ArrayList<>();
			if(requestVO.getIds().length>0){
				resultList = new ArrayList<>(Arrays.asList(requestVO.getIds()));
				//判断是否超过饱和人数
				List<Map<String,Object>> list = queryDao.findIsOver(resultList,teacherUserId);
				if(list!=null && list.size()>0) {
					StringBuffer sb = new StringBuffer();
					for (Map<String, Object> map : list) {
						sb.append(map.get("arrange_date")).append(" ").append(map.get("time_interval")).append(" ");
					}
					sb.append("排班人数已经饱和");
					responseEntity.failure(sb.toString());
					return responseEntity;
				}
			}
			//先减去当前老师的对应的时段饱和数
			//dao.updateArrangeDetailHaveNum(-1,preMonth,teacherUserId);

			//查询老师保存前所有的arrange_detail_id id
			List<String> beforeDelList = dao.findTeacherDetailList(preMonth,teacherUserId);
			//删除原来保存的数据
			dao.delOldAllotData(preMonth,teacherUserId);
			//保存新数据

			//dao.insertNewAllotData(resultList,teacherUserId,preMonth);
			/**
			 * @Query(nativeQuery = true,value = "insert into kmt_arrange_allot(id,arrange_detail_id,teacher_id,arrange_date,attend_type,status,create_time)\n" +
			 *             "SELECT UUID(),a.id,?2,a.arrange_date,0,1,NOW()\n" +
			 *             "from kmt_arrange_detail a\n" +
			 *             "INNER JOIN tb_lib_manager b on a.`subject` = b.course_name and a.type=b.type and b.user_id=?2\n" +
			 *             "where a.id in (?1) and DATE_FORMAT(a.arrange_date,'%Y-%m') = ?3")
			 */
			if(resultList!=null && resultList.size()>0){
				List<KmtArrangeAllot> allotList = new ArrayList<>();
				for(String str:resultList){
					KmtArrangeAllot allot = new KmtArrangeAllot();
					KmtArrangeDetail detail = kmtArrangeDetailService.getById(str);
					allot.setStatus(1);
					allot.setAttendType(0);
					allot.setArrangeDate(detail.getArrangeDate());
					allot.setTeacherId(teacherUserId);
					allot.setArrangeDetailId(str);
					allot.setCreateTime(new Date());
					//allot.set
					allotList.add(allot);
				}
				this.save(allotList);
			}

			//再加上当前老师对应的时段饱和数
			//dao.updateArrangeDetailHaveNum(1,preMonth,teacherUserId);

			//将之前删除的数据与新的数据对比 都存在的id，不处理，新增的has_num+1，删除的-1
			if(!resultList.isEmpty() && !beforeDelList.isEmpty()){
				for(int i=beforeDelList.size()-1;i>=0;i--){
					boolean isDel = false;
					String delStr = beforeDelList.get(i);
					for (int j=resultList.size()-1;j>=0;j--){
						String addStr = resultList.get(j);
						if(delStr.equals(addStr)){
							isDel=true;
							resultList.remove(addStr);
							break;
						}
					}
					if(isDel){
						beforeDelList.remove(delStr);
					}
				}
			}
			List<KmtArrangeDetail> list = new ArrayList<>();
			if(!beforeDelList.isEmpty()){
				//have_num -1
				for(String str:beforeDelList){
					KmtArrangeDetail details = kmtArrangeDetailService.getById(str);
					details.setHaveNum(details.getHaveNum()-1);
					list.add(details);
				}
			}

			if(!resultList.isEmpty()){
				//have_num +1
				for(String str:resultList){
					KmtArrangeDetail details = kmtArrangeDetailService.getById(str);
					details.setHaveNum(details.getHaveNum()+1);
					list.add(details);
				}
			}
			if(!list.isEmpty()){
				kmtArrangeDetailService.save(list);
			}
			//更新所有has_num
			//dao.updateDetailData(preMonth);
			responseEntity.success("保存成功");

		}else{
			responseEntity.failure(000,"不在数据保存时间内，无法保存！");
		}
		return responseEntity;
	}

	@Override
	public List<DutyTemplate> dutyTemplateList(String teacherUserId) {
		String preMonth = getPreMonth();
		List<DutyTemplate> list = new ArrayList<DutyTemplate>();
		List<Map<String,Object>> maplist = queryDao.findTemplateList(preMonth);
		for (Map<String,Object> map:maplist){
			DutyTemplate template = new DutyTemplate();
			template.setDay(map.get("arrange_date").toString());
			template.setIsOpen(map.get("is_open").toString());
			list.add(template);
		}
		return list;
	}

	@Override
	public void saveSysTeacherDuty(DutySysRequestVO vo1) {
		Date date = new Date();
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		int days = ca.get(Calendar.DAY_OF_MONTH);
		int lastDay = ca.getActualMaximum(Calendar.DAY_OF_MONTH);
		if (days > 0 && days<=24) { //时间段
			List<String> strList = Arrays.asList(vo1.getDays());
			dao.updateTemplateisClose(getPreMonth());
			for (String str : strList) {
				//更新
				dao.updateTemplateisOpen(str);
			}
		}
	}

	/**
	 * 描述:获取下一个月.
	 *
	 * @return
	 */
	public static String getPreMonth() {
		Date date = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(cal.MONTH, 1);
		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
		String preMonth = dft.format(cal.getTime());
		return preMonth;

	}

	//获取传入月份天数的map list
	public List<Map<String,Object>> getMonthDayList(Date date){
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		//获取第一天
		Calendar cal = Calendar.getInstance();
		//设置年份
		cal.setTime(date);
		//获取某月最小天数
		int lastDay = cal.getActualMaximum(Calendar.DATE);

		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
		String preMonth = dft.format(cal.getTime());
		for(int i=1;i<=lastDay;i++){
			Map<String,Object> map = new HashMap<String,Object>();
			if(String.valueOf(i).length()==1){
				map.put(preMonth+"-0"+String.valueOf(i),i);
			}else{
				map.put(preMonth+"-"+String.valueOf(i),i);
			}
			mapList.add(map);
		}
		return mapList;
	}

	public static String getMonthFirstDay(Date date){
		Calendar cal = Calendar.getInstance();
		//设置年份
		cal.setTime(date);
		//获取某月最小天数
		int firstDay = cal.getMinimum(Calendar.DATE);
		//设置日历中月份的最小天数
		cal.set(Calendar.DAY_OF_MONTH,firstDay);
		//格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(cal.getTime());
	}

	public static String getMonthLasttDay(Date date){
		Calendar cal = Calendar.getInstance();
		//设置年份
		cal.setTime(date);
		//获取某月最小天数
		int lastDay = cal.getActualMaximum(Calendar.DATE);
		//设置日历中月份的最小天数
		cal.set(Calendar.DAY_OF_MONTH,lastDay);
		//格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(cal.getTime());
	}
	@Override
	public KmtArrangeAllot getKmtArrangeAllotByTeacher(String arrangeDetailId,String teacherId) {
		return dao.getKmtArrangeAllotByTeacher(arrangeDetailId, teacherId);
	}


	@Override
	public void updateKmtArrangeAllotToStatus(String arrangeDetailId,String teacherId, Integer status) {
		dao.updateKmtArrangeAllotToStatus(arrangeDetailId, teacherId, status);
	}


	//统计月活跃数，定时任务的时候先调用再更新
	@Override
	public Integer countArrangeActiveNum(){
		Integer activeCount=libVipDao.findActiveNumByActivateTime();//近 7 天激活用户
		Integer useCount=homeworkDao.findUserCountByCreateTime();//近 7 天使用过作业批改服务的用户
		Integer repetiveCount=homeworkDao.findRepetiveCount();//重复的
		Integer monthActiveCount=activeCount+useCount-repetiveCount;//月活跃数
		return monthActiveCount;
	}


	@Override
	public Integer countKmtArrangeAllotByArrangeDetailId(String arrangeDetailId) {
		return dao.countKmtArrangeAllotByArrangeDetailId(arrangeDetailId);
	}


	@Override
	public List<String> findKmtArrangeAllotByArrangeDetailId(String arrangeDetailId) {
		return dao.findKmtArrangeAllotByArrangeDetailId(arrangeDetailId);
	}


	@Override
	public void updateAttendType(String date) throws Exception{
		//遍历所有的老师
		List<TbLibManager> teacherList=managerDao.findAllTeacher();
		for(TbLibManager tbLibManager:teacherList){
			String userId=tbLibManager.getUserId();
			int type=tbLibManager.getType();
			Map<String, Object> map = new HashMap<>();
			map.put("userId",userId);
			map.put("type", type);
			map.put("date", date);
			List<Map<String, Object>> list = queryDao.findAShouldtendanTime(map);
			try {
				if (list.size() > 0) {
					for (Map<String, Object> map1 : list) {
						MapGetterTool mapGetterTool = new MapGetterTool(map1);
						String beginTime = date + " " + mapGetterTool.getString("start_interval") + ":00";
						LocalDateTime begin = LocalDateTime.parse(beginTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
						String beforeTime = begin.plusMinutes(10).toString().replaceAll("T", " ");
						String endTime = date + " " + mapGetterTool.getString("end_interval") + ":00";
						LocalDateTime end = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
						String afterTime = end.plusMinutes(-5).toString().replaceAll("T", " ");
						String id = mapGetterTool.getString("id");
						//先判断10:10分的状态是在线还是离线
						List<TbLibLoginInfo> minuteList=tbLibLoginInfoDao.findListByTime(userId,type,beforeTime,beforeTime,date);
						if(minuteList.size()!=0){
							//判断10点的状态是在线还是离线
							List<TbLibLoginInfo>  minuteList1=tbLibLoginInfoDao.findListByTime(userId,type,beginTime,beginTime,date);
							List<TbLibLoginInfo> list0;
							if(minuteList1.size()!=0){
								//在线不顺延
								list0=tbLibLoginInfoDao.findCount(userId,type,beginTime,endTime,date);
							}else {
								//不在线顺延,获取第一条记录
								TbLibLoginInfo tb1=tbLibLoginInfoDao.findByTheFirstTime(userId,type,beginTime,date);
								 beginTime=DateHelper.getStandTime(tb1.getLoginTime());
								 endTime=this.getTwoHoursAfter(beginTime);
								list0=tbLibLoginInfoDao.findCount(userId,type,beginTime,endTime,date);
							}
							   if(list0.size()>3){
							   	continue;
							   }else {
							   	if(0==list0.size()){
							   		//肯定出勤了
									dao.updateKmtArrangeAllotByID(id,date);
								}else if(1==list0.size()){
							   		//退出过一次
								  String logout=DateHelper.getStandTime(list0.get(0).getLogoutTime());
								  if(logout.equals(endTime)){
								  	//临界点下线算出勤
									  dao.updateKmtArrangeAllotByID(id,date);
								  }else {
									  String out=this.getFiveMinutesAfter(logout);
									  List<TbLibLoginInfo> list1 = tbLibLoginInfoDao.findAllList(userId, type, logout,endTime,date);
									  if(list1.size()!=0){
										  String intime = DateHelper.getStandTime(list1.get(0).getLoginTime());
										  String otime  =DateHelper.getDateTime(list1.get(0).getLogoutTime());
										  if(out.compareTo(intime)>=0){
											  dao.updateKmtArrangeAllotByID(id,date);
										  }else {
											  continue;
										  }
									  }
								  }

								}else if(list0.size()==2){
									//退出过2次
									String intime = DateHelper.getStandTime(list0.get(1).getLoginTime());
									String outime1  =DateHelper.getDateTime(list0.get(0).getLogoutTime());
									String outime2 =DateHelper.getDateTime(list0.get(1).getLogoutTime());
									String out1 = this.getFiveMinutesAfter(outime1);
									String out2 = this.getFiveMinutesAfter(outime2);
									if(outime2.equals(endTime)){
										//临界点下线算出勤
										dao.updateKmtArrangeAllotByID(id,date);
									}else {
										//判断下一次登录的时间
										List<TbLibLoginInfo> list1 = tbLibLoginInfoDao.findAllList(userId, type, outime2,endTime,date);
										if(list1.size()!=0){
											String intime1 = DateHelper.getStandTime(list1.get(0).getLoginTime());
											if(out1.compareTo(intime)>=0&&out2.compareTo(intime1)>=0){
												dao.updateKmtArrangeAllotByID(id,date);
											}else {
												continue;
											}
										}
									}


								}else {
									//退出过3次
									String otime1  =DateHelper.getDateTime(list0.get(0).getLogoutTime());
									String otime2  =DateHelper.getDateTime(list0.get(1).getLogoutTime());
									String otime3  =DateHelper.getDateTime(list0.get(2).getLogoutTime());
									String out1 = this.getFiveMinutesAfter(otime1);
									String out2 = this.getFiveMinutesAfter(otime2);
									String out3 = this.getFiveMinutesAfter(otime3);
									String lotime1=DateHelper.getDateTime(list0.get(1).getLoginTime());
									String lotime2=DateHelper.getDateTime(list0.get(2).getLoginTime());
									if(otime3.equals(endTime)){
										//临界点下线算出勤
										dao.updateKmtArrangeAllotByID(id,date);
									}else {
										//判断下一次登录的时间
										List<TbLibLoginInfo> list1 = tbLibLoginInfoDao.findAllList(userId, type, otime3,endTime,date);
										if(list1.size()!=0){
											String intime1 = DateHelper.getStandTime(list1.get(0).getLoginTime());
											if(out1.compareTo(lotime1)>=0&&out2.compareTo(lotime2)>=0&&out3.compareTo(intime1)>=0){
												dao.updateKmtArrangeAllotByID(id,date);
											}else {
												continue;
											}
										}
									}

								}

							   }

						}


					}

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	private  String  getFiveMinutesAfter(String time) throws Exception{
		Date date2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
		Calendar cal=Calendar.getInstance();
		cal.setTime(date2);
		cal.add(Calendar.MINUTE,5);
		Date date3=cal.getTime();
		String out1  =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date3);
		return out1;

	}


	private  String getTwoHoursAfter(String time) throws Exception{
		Date date2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
		Calendar cal=Calendar.getInstance();
		cal.setTime(date2);
		cal.add(Calendar.HOUR_OF_DAY,2);
		Date date3=cal.getTime();
		String date1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date3);
		return date1;
	}



	@Override
	public boolean findTeacherArrange(Date createTime, String teacherId) {
		int time = Integer.valueOf(DateHelper.format(createTime, "HH"));
		String startInterval;
		String endInterval;
		if(10 <= time && time < 12) {
			//如果在10-12点之间
			startInterval = "10:00";
			endInterval = "12:00";
		}else if(15 <= time && time < 17) {
			startInterval = "15:00";
			endInterval = "17:00";
		}else if(17 <= time && time < 19) {
			startInterval = "17:00";
			endInterval = "19:00";
		}else if(19 <= time && time < 21) {
			startInterval = "19:00";
			endInterval = "21:00";
		}else {
			//都不在排班时间段则加权重
			return false;
		}
		String userId = dao.findTeacherArrange(startInterval,endInterval,teacherId);
		if(StringUtils.isNotBlank(userId)) {
			return true;
		}
		return false;
	}


	@Override
	public void clearArrangeAllotByTeacherId(String teacherId) {
		List<KmtArrangeAllot> kmtArrangeAllot=dao.findKmtArrangeAllotByNextCurTime(teacherId);
		for (KmtArrangeAllot ka : kmtArrangeAllot) {
			ka.setStatus(0);
			KmtArrangeDetail kmtArrangeDetail=kmtArrangeDetailService.getById(ka.getArrangeDetailId());
			if (kmtArrangeDetail != null && kmtArrangeDetail.getHaveNum() > 0) {
				kmtArrangeDetail.setHaveNum(kmtArrangeDetail.getHaveNum() - 1);
				kmtArrangeDetailService.save(kmtArrangeDetail);
			}
		}
		this.save(kmtArrangeAllot);
	}

}