package org.linlinjava.jz.service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

import org.linlinjava.jz.core.util.DateTimeUtil;
import org.linlinjava.jz.db.dao.HmButlerTaskChildMapper;
import org.linlinjava.jz.db.dao.HmButlerTaskDictMapper;
import org.linlinjava.jz.db.dao.HmButlerTaskLogMapper;
import org.linlinjava.jz.db.dao.HmButlerTaskParentMapper;
import org.linlinjava.jz.db.dao.HmButlerTaskParentMappers;
import org.linlinjava.jz.db.dao.HmEmployRelationMapper;
import org.linlinjava.jz.db.domain.HmAppUser;
import org.linlinjava.jz.db.domain.HmButlerTaskChild;
import org.linlinjava.jz.db.domain.HmButlerTaskChildExample;
import org.linlinjava.jz.db.domain.HmButlerTaskDict;
import org.linlinjava.jz.db.domain.HmButlerTaskDictExample;
import org.linlinjava.jz.db.domain.HmButlerTaskLog;
import org.linlinjava.jz.db.domain.HmButlerTaskParent;
import org.linlinjava.jz.db.domain.HmButlerTaskParentExample;
import org.linlinjava.jz.db.domain.HmEmployRelation;
import org.linlinjava.jz.db.domain.HmButlerTaskParentExample.Criteria;
import org.linlinjava.jz.db.service.JzTicketService;
import org.linlinjava.jz.db.service.hm.HmAppUserService;
import org.linlinjava.jz.db.service.hm.HmButlerTaskLogService;
import org.linlinjava.jz.db.service.hm.HmTasktimeConfigService;
import org.linlinjava.jz.db.util.hm.HmButlerTaskContans;
import org.linlinjava.jz.db.util.hm.HmButlerTaskLogContans;
import org.linlinjava.jz.db.util.hm.HmNoticeEnum;
import org.linlinjava.jz.dto.HmNoticeDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

/**
 * 首次拜访任务
 * 
 * @author 36952
 *
 */
@Service
public class HmButlerTaskParentService {

	private static final Logger logger = LoggerFactory.getLogger(HmButlerTaskParentService.class);

	@Autowired
	HmButlerTaskParentMapper hmButlerTaskParentMapper;

	@Autowired
	HmButlerTaskChildMapper hmButlerTaskChildMapper;

	@Autowired
	HmEmployRelationMapper hmEmployRelationMapper;

	@Autowired
	HmAppUserService hmAppUserService;

	@Autowired
	JzTicketService jzTicketService;

	@Autowired
	HmButlerTaskDictMapper hmButlerTaskDictMapper;

	@Autowired
	HmButlerTaskLogService hmButlerTaskLogService;

	@Autowired
	HmTasktimeConfigService hmTasktimeConfigService;

	@Autowired
	HmButlerTaskLogMapper hmButlerTaskLogMapper;

	@Autowired
	HmButlerTaskParentMappers hmButlerTaskParentMappers;

	@Autowired
	private NoticeService noticeService;
	
	@Autowired
	HmButlerTaskLogService butlerTaskLogService;

	/**
	 * 超时任务（已超时任务）
	 * 
	 * @param userId
	 * @return
	 */
	public Integer getTaskTimeout(Integer sysUserId) {
//		
//		HmAppUser butlerUser = hmAppUserService.queryBySysUserId(sysUserId);
//		
//		HmButlerTaskParentExample example=new HmButlerTaskParentExample();
//		example.or().andExpirationTimeLessThanOrEqualTo(LocalDateTime.now());
//		long countExpiration = hmButlerTaskParentMapper.countByExample(example);
		Integer countExpiration = hmEmployRelationMapper.selectTaskTimeOut(sysUserId.toString(), LocalDateTime.now());

		Long countTaskTimeOut = jzTicketService.countTaskTimeOut(sysUserId, LocalDateTime.now());

		return countExpiration + countTaskTimeOut.intValue();
	}

	/**
	 * 未完结的任务 （所有状态未完结任务）；
	 * 
	 * @param userId
	 * @return
	 */
	public Integer getTaskUnfinished(Integer sysUserId) {
		Integer countNeedComplate = hmEmployRelationMapper.selectTaskNeedComplate(sysUserId.toString());
		Long countNoComplete = jzTicketService.countNoComplete(sysUserId);
		return countNeedComplate + countNoComplete.intValue();
	}

	/**
	 * 即将超时任务（距离任务完结时间小于24小时）；
	 * 
	 * @param userId
	 * @return
	 */
	public Integer getTaskTwentyFourBefore(Integer userId) {
		LocalDateTime time = LocalDateTime.now().plusDays(-1);// 减去一天**
//		 
		int count = hmEmployRelationMapper.selectGtTwentyFour(userId.longValue(), time);
		// crm ticket任务的

		HmAppUser user = hmAppUserService.queryById(userId.longValue());
		if (user != null) {
			Long ct = jzTicketService.countTwentyFourTicket(userId.intValue(), time);
			count = count + ct.intValue();
		}

		return count;
	}

	/**
	 * 管家我的任务大于24小时的 userId 管家id
	 * 
	 * @return
	 */
	public Integer getTaskTwentyFourSize(Long userId) {
		// #距离当前时间大于24小时，找hm_employ_relation的first_service_time大于当前时间+24小时的
		LocalDateTime time = LocalDateTime.now().plusDays(1);// 加一天
//		 
		int count = hmEmployRelationMapper.selectGtTwentyFour(userId, time);
		// crm ticket任务的

		HmAppUser user = hmAppUserService.queryById(userId);
		if (user != null) {
			Long ct = jzTicketService.countTwentyFourTicket(userId.intValue(), time);
			count = count + ct.intValue();
		}

		return count;
	}

	/**
	 * 管家 我的任务，今日需完成的
	 * 
	 * @param userId 管家id
	 * @return
	 */
	public Integer getTaskcurrentDaySize(Long userId) {
		// #今日需完成，找hm_employ_relation的first_service_time为今天，拿到关系编号
		// #找hm_butler_task_parent状态 未完成的

		LocalDateTime start = LocalDateTime.now().with(LocalTime.MIN);
		LocalDateTime end = LocalDateTime.now().with(LocalTime.MAX);

		int count = hmEmployRelationMapper.selectCurrentDay(userId, start, end);

		// 查ticket_type为2，且handler为user.getSysUserid()，和status是TicketStatusConstant.STATUS_PROCESSING
		// crm ticket任务的
		HmAppUser user = hmAppUserService.queryById(userId);
		if (user != null) {
			Long ct = jzTicketService.countCurrentDayTicket(userId.intValue(), start, end);
			count = count + ct.intValue();
		}

		return count;
	}

	/**
	 * 管家首次任务生成
	 * 
	 * @param orderNo          保姆订单编号
	 * @param employRelationId 三者关系id
	 *
	 */
	@Async
	public void butlerFirstTask(String orderNo, Long employRelationId) {
		Integer vistTaskTime = hmTasktimeConfigService.getVistTaskTime();
		LocalDateTime expirationTime = LocalDateTime.now().plusDays(vistTaskTime);

		HmButlerTaskParent record = new HmButlerTaskParent();
		record.setOrderNo(orderNo);
		record.setEmployRelationId(employRelationId);

		record.setExpirationTime(expirationTime);
		record.setTaskType(HmButlerTaskContans.BUTLER_TASK_TYPE_1);
		record.setTaskTypeName(HmButlerTaskContans.BUTLER_TASK_TYPENAME_1);
		record.setStatus(HmButlerTaskContans.BUTLER_TASK_PARENT_STATUS_0);

		hmButlerTaskParentMapper.insertSelective(record);

		HmButlerTaskDictExample example = new HmButlerTaskDictExample();
		example.or().andIsFirstEqualTo(1);
		List<HmButlerTaskDict> taskList = hmButlerTaskDictMapper.selectByExample(example);

		insertButlerTaskChild(orderNo, employRelationId, record, taskList, expirationTime);

	}

	/**
	 * 管家周期任务生成
	 * 
	 * @param orderNo          保姆订单编号
	 * @param employRelationId 三者关系id
	 * 
	 */
	@Async
	public void butlerWeekTask(String orderNo, Long employRelationId) {
		Integer vistTaskTime = hmTasktimeConfigService.getVistTaskTime();
		LocalDateTime expirationTime = LocalDateTime.now().plusDays(vistTaskTime);
		expirationTime = expirationTime.plusDays(7);// 再加7天

		HmButlerTaskParent record = new HmButlerTaskParent();
		record.setOrderNo(orderNo);
		record.setEmployRelationId(employRelationId);
		record.setExpirationTime(expirationTime);
		record.setTaskType(HmButlerTaskContans.BUTLER_TASK_TYPE_2);
		record.setTaskTypeName(HmButlerTaskContans.BUTLER_TASK_TYPENAME_2);
		record.setStatus(HmButlerTaskContans.BUTLER_TASK_PARENT_STATUS_0);

		hmButlerTaskParentMapper.insertSelective(record);

		HmButlerTaskDictExample example = new HmButlerTaskDictExample();
		example.or().andIsWeekEqualTo(1);
		List<HmButlerTaskDict> taskList = hmButlerTaskDictMapper.selectByExample(example);
		insertButlerTaskChild(orderNo, employRelationId, record, taskList,expirationTime);
	}

	/**
	 * 管家月度任务生成
	 * 
	 * @param orderNo          保姆订单编号
	 * @param employRelationId 三者关系id
	 * @param day              加多少天
	 */
	@Async
	public void butlerMonthTask(String orderNo, Long employRelationId, Integer day) {

		Integer vistTaskTime = hmTasktimeConfigService.getVistTaskTime();
		LocalDateTime expirationTime = LocalDateTime.now().plusDays(vistTaskTime);
		expirationTime = expirationTime.plusDays(day);// 再加30天

		HmButlerTaskParent record = new HmButlerTaskParent();
		record.setOrderNo(orderNo);
		record.setEmployRelationId(employRelationId);
		record.setExpirationTime(expirationTime);
		record.setTaskType(HmButlerTaskContans.BUTLER_TASK_TYPE_3);
		record.setTaskTypeName(HmButlerTaskContans.BUTLER_TASK_TYPENAME_3);
		record.setStatus(HmButlerTaskContans.BUTLER_TASK_PARENT_STATUS_0);

		hmButlerTaskParentMapper.insertSelective(record);

		HmButlerTaskDictExample example = new HmButlerTaskDictExample();
		example.or().andIsMonthEqualTo(1);
		List<HmButlerTaskDict> taskList = hmButlerTaskDictMapper.selectByExample(example);
		insertButlerTaskChild(orderNo, employRelationId, record, taskList,expirationTime);
	}

	/**
	 * 管家拜访类主任务完成
	 * 
	 * @param parentTaskId   主任务id
	 * @param businessId
	 * @param operateContent
	 * @return
	 */
	@Transactional
	public void completeParentTask(Long parentTaskId) {
		// 验证子任务都完成
		HmButlerTaskChildExample childexample = new HmButlerTaskChildExample();
		childexample.or().andTaskParentIdEqualTo(parentTaskId);
		List<HmButlerTaskChild> hmButlerTaskChildList = hmButlerTaskChildMapper.selectByExample(childexample);
		int c = 0;
		for (HmButlerTaskChild t : hmButlerTaskChildList) {
			if (t.getStatus().equals(1)) {// 都是已完成
				c = c + 1;
			}
		}
		if (c != hmButlerTaskChildList.size()) {
//			return HmResponseUtil.fail("请先完成所有子任务");
			throw new RuntimeException("请先完成所有子任务");
		}

		HmButlerTaskParent hp = hmButlerTaskParentMapper.selectByPrimaryKey(parentTaskId);
		if (hp.getStatus() == 1) {
			throw new RuntimeException("你已完成拜访任务，不能重复操作");
		}

		HmButlerTaskParent record = new HmButlerTaskParent();
		record.setId(parentTaskId);
		record.setStatus(1);

		hmButlerTaskParentMapper.updateByPrimaryKeySelective(record);

		// 插入操作日志
		String operateContent = HmButlerTaskLogContans.TASK_LOG_PARENTTASKCOMPLETE;
		hmButlerTaskLogService.insertButlerTaskLogParent(parentTaskId, parentTaskId, operateContent);

		// 邀请评价1111
		HmEmployRelation hmEmployRelation = hmEmployRelationMapper.selectByPrimaryKey(hp.getEmployRelationId());
		HmNoticeDto hmNoticeDto = new HmNoticeDto();
		hmNoticeDto.setAppUserId(Lists.newArrayList(hmEmployRelation.getUserButlerId()));
		hmNoticeDto.setEmployRelationId(hmEmployRelation.getId());
		hmNoticeDto.setrId(hp.getId().toString());
		hmNoticeDto.setCreateUserId(hmEmployRelation.getUserEmployerId());

//		hmNoticeDto.setContent("管家拜访任务完成，快来评价吧");
		hmNoticeDto.setRtype(HmNoticeEnum.NOTICE_NUM_9.getType());
		hmNoticeDto.setNoticeUserType(HmNoticeEnum.NOTICE_NUM_9.getNoticeUserType());
		 
		noticeService.create(hmNoticeDto);
	}

	private void insertButlerTaskChild(String orderNo, Long employRelationId, HmButlerTaskParent record,
			List<HmButlerTaskDict> taskList,LocalDateTime expirationTime) {
		for (HmButlerTaskDict h : taskList) {

			HmButlerTaskChild taskChild = new HmButlerTaskChild();
			taskChild.setOrderNo(orderNo);
			taskChild.setEmployRelationId(employRelationId);
			taskChild.setTaskParentId(record.getId());
			taskChild.setTaskChildName(h.getTaskName());
			if(h.getId().equals(1L)) {//上门时间
				String ymd=DateTimeUtil.formatToyyyy_MM_dd(expirationTime);
				taskChild.setTaskChildName(taskChild.getTaskChildName()+":"+ymd);
			}
			taskChild.setTaskDictId(h.getId());
			taskChild.setStatus(HmButlerTaskContans.BUTLER_TASK_CHILD_STATUS_0);
			if(h.getId().equals(6L)) {//6服务信息补充,默认已完成
				taskChild.setStatus(HmButlerTaskContans.BUTLER_TASK_CHILD_STATUS_1);
			}

			hmButlerTaskChildMapper.insertSelective(taskChild);
		}
	}

	/**
	 * 查询拜访任务列表
	 * 
	 * @param orderNo
	 * @param parentTaskId
	 * @return
	 */
	public List<HmButlerTaskParent> getButlerTaskParentList(String orderNo, Long parentTaskId) {
		HmButlerTaskParentExample example = new HmButlerTaskParentExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andOrderNoEqualTo(orderNo);
		if (null != parentTaskId) {
			createCriteria.andIdEqualTo(parentTaskId);
		}
		example.setOrderByClause(" id desc ");

		List<HmButlerTaskParent> listData = hmButlerTaskParentMapper.selectByExample(example);
		if (null != listData && listData.size() > 0) {
			listData.forEach(p -> {
				// 子任务
				HmButlerTaskChildExample childexample = new HmButlerTaskChildExample();
				childexample.or().andTaskParentIdEqualTo(p.getId());
				List<HmButlerTaskChild> hmButlerTaskChildList = hmButlerTaskChildMapper.selectByExample(childexample);
				p.setButlerTaskChildList(hmButlerTaskChildList);

				// 任务记录
				List<HmButlerTaskLog> hmButlerTaskLogList = butlerTaskLogService.getTaskLog(p.getId());
				p.setButlerTaskLogList(hmButlerTaskLogList);
			});
		}

		return listData;
	}

	/**
	 * 定时生成月度任务
	 */
	public void timeProcessMonthTask() {

		// 提前三天生成月度任务；
		int day = 3;
		// expiration_time<小于当前时间-30天 的任务
		// contract_end_date>大于当前时间（合同没到期）
		LocalDateTime expirationTime = LocalDateTime.now().plusDays(-30 + day);
		LocalDateTime contractEndDate = LocalDateTime.now().plusDays(day);
		List<HmButlerTaskParent> expireMonthTask = hmButlerTaskParentMappers.expireMonthTask(expirationTime,
				contractEndDate);

		logger.info("提前{}天生成月度任务,需生成月度任务数{}个", day, expireMonthTask.size());

		expireMonthTask.forEach(e -> {
			butlerMonthTask(e.getOrderNo(), e.getEmployRelationId(), day);
		});

	}

}
