package org.linlinjava.jz.db.service.hm;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.linlinjava.jz.db.dao.HmButlerTaskParentMapper;
import org.linlinjava.jz.db.dao.HmNoticeMapper;
import org.linlinjava.jz.db.dao.HmNoticeUserMapper;
import org.linlinjava.jz.db.dao.HmNoticeUserMappers;
import org.linlinjava.jz.db.domain.HmButlerTaskParent;
import org.linlinjava.jz.db.domain.HmComment;
import org.linlinjava.jz.db.domain.HmEmployRelation;
import org.linlinjava.jz.db.domain.HmNotice;
import org.linlinjava.jz.db.domain.HmNoticeExample;
import org.linlinjava.jz.db.domain.HmNoticeExample.Criteria;
import org.linlinjava.jz.db.domain.HmNoticeUser;
import org.linlinjava.jz.db.domain.HmNoticeUserExample;
import org.linlinjava.jz.db.domain.JzTicket;
import org.linlinjava.jz.db.dto.hm.HmNoticeDataDto;
import org.linlinjava.jz.db.service.JzTicketService;
import org.linlinjava.jz.db.util.HmResponseUtil;
import org.linlinjava.jz.db.util.hm.CalendarUtil;
import org.linlinjava.jz.db.util.hm.HmCommentEnum;
import org.linlinjava.jz.db.util.hm.HmNoticeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import javax.annotation.Resource;

/**
 * 
 * @author 36952 通知
 */
@Service
public class HmNoticeService {

	@Resource
	HmNoticeMapper hmNoticeMapper;

	@Resource
	HmNoticeUserMapper hmNoticeUserMapper;

	@Autowired
	HmEmployRelationService employRelationService;

	@Autowired
	HmNoticeUserService hmNoticeUserService;

	@Autowired
	HmNoticeUserMappers hmNoticeUserMappers;

	@Autowired
	HmButlerTaskParentService hmButlerTaskParentService;

	@Autowired
	JzTicketService jzTicketService;

	@Autowired
	HmCommentService commentService;

	private final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	/**
	 * 发送通知
	 * 
	 * @param dto
	 */
	public int insertNotice(HmNotice dto) {
		dto.setCreateTime(LocalDateTime.now());
		hmNoticeMapper.insertSelective(dto);
		return dto.getId().intValue();
	}

	/**
	 * 获取用户未读通知,最新5条
	 * 
	 * @param userId
	 * @return
	 */
	public List<HmNoticeDataDto> getUnReadNotice(Long userId, Integer type) {

		List<String> userNoticeType = HmNoticeEnum.getUserNoticeType(type);
		PageHelper.startPage(1, 5, false);
		LocalDateTime sevenDay = LocalDateTime.now().plusDays(-7);
		List<HmNoticeDataDto> list = hmNoticeUserMappers.getUserNoticeList(userId,
				StringUtils.join(userNoticeType, ","), sevenDay);
		list.forEach(e -> {
			//9, 11是拜访的任务
			if (e.getRType().equals(HmNoticeEnum.NOTICE_NUM_9.getType().toString())
					|| e.getRType().equals(HmNoticeEnum.NOTICE_NUM_11.getType().toString())) {
				e.setNoticeInfoId(e.getRId());
				e.setNoticeInfoType(1);
			} else {
				// 跟进
				e.setNoticeInfoId(e.getRId());
				e.setNoticeInfoType(2);
			}
		});
		return list;
		//		HmNoticeUserExample example = new HmNoticeUserExample();
		//		example.or().andIsReadEqualTo(0).andAppUserIdEqualTo(userId).andRTypeIn(userNoticeType);
		//		example.setOrderByClause(HmNoticeUser.Column.id.name() + " desc ");// 0未读，1已读

		//		return hmNoticeUserMapper.selectByExample(example);
	}

	/**
	 * 根据关系id和类型拿通知id
	 * 
	 * @param rId
	 * @param rType
	 * @return
	 */
	public HmNotice getNoticeByRidRtype(String rId, String rType) {
		HmNoticeExample example = new HmNoticeExample();
		example.or().andRIdEqualTo(rId).andRTypeEqualTo(rType);
		return hmNoticeMapper.selectOneByExample(example);
	}

	/**
	 * 保姆获取管家服务记录
	 * 
	 * @param employRelationId
	 * @param yearMonth        yyyy-MM-dd
	 * @param type             1雇主，2保姆，3管家(getNoticeByButler)
	 * @return
	 */
	public Object getNoticeByServant(Long employRelationId, String yearMonth, Integer type) {
		// 通过employRelationId获取管家的id，拿管家的服务记录

		// 保姆获取管家的服务类型
		List<String> servantNoticeType = new ArrayList<String>();

		if (type == 1) {// 雇主
			servantNoticeType = HmNoticeEnum.getCustomerNoticeType();
		}
		if (type == 2) {// 保姆
			servantNoticeType = HmNoticeEnum.getServantNoticeType();
		}

		HmEmployRelation relation = employRelationService.queryById(employRelationId);
		if (relation == null) {
			return HmResponseUtil.fail_null();
		}

		// 通知里的数据
		List<HmNotice> list = selectByReIdRTypeCteateTime(employRelationId, yearMonth, servantNoticeType);
		// 处理成记录
		for (HmNotice h : list) {
			List<HmNoticeUser> templist = new ArrayList<HmNoticeUser>();
			HmNoticeUser hus = hmNoticeUserService.getLastNoticeIduserIdList(h.getId(), type==1?relation.getUserEmployerId():relation.getUserServantId());//relation.getUserButlerId()
			if (null != hus) {
				templist.add(hus);
			}
			h.setNoticeUserList(templist);
		}

		// 拿拜访的数据合并成 List<HmNotice>
		List<HmButlerTaskParent> employeeRelationTask = hmButlerTaskParentService.selectByYeahMonth(employRelationId,
				yearMonth);
		for (HmButlerTaskParent e : employeeRelationTask) {
			HmNotice no = new HmNotice();
			no.setId(e.getId());
			no.setContent(e.getTaskTypeName());
			no.setType(HmCommentEnum.comment_num_1.getType());// 1是拜访数据
			no.setCreateTime(e.getCreateTime());
			//			if (e.getTaskType().equals(1)) {
			//				no.setrType("-1");//首次拜访
			//			}
			//			if (e.getTaskType().equals(2)) {
			//				no.setrType("-2");//周期拜访
			//			}
			//			if (e.getTaskType().equals(3)) {
			//				no.setrType("-3");//月度拜访
			//			}

			List<HmNoticeUser> tempNoticeUser = new ArrayList<HmNoticeUser>();
			e.getButlerTaskLogList().forEach(c -> {
				HmNoticeUser nu = new HmNoticeUser();
				nu.setCreateTime(c.getCreateTime());
				nu.setNoticeContent(c.getOperateContent());
				nu.setTicketStatus(e.getStatus() == 1 ? "2" : "0");
				tempNoticeUser.add(nu);
			});
			no.setNoticeUserList(tempNoticeUser);
			list.add(no);// 添加到后面
		}
		// 排序
		ListSort(list);

		// 处理小程序进度展示,拿第一条数据的最新3个处理记录
		if (list.size() > 0) {
//			HmNotice hmNotice = list.get(0);
			for(HmNotice hmNotice:list) {
				 
				List<HmNoticeUser> noticeUserList = new ArrayList<HmNoticeUser>();
				if (hmNotice.getType().equals(HmCommentEnum.comment_num_2.getType())) {// 2是跟进通知
					noticeUserList = hmNoticeUserService.getNoticeIduserIdList(hmNotice.getId(),
							relation.getUserButlerId());// 拿管家id的处理过程
				}
				if (hmNotice.getType().equals(HmCommentEnum.comment_num_1.getType())) {// 1是拜访
					noticeUserList = hmNotice.getNoticeUserList();
				}
				
				if (noticeUserList.size() > 3) {
					noticeUserList = noticeUserList.subList(0, 3);// 取0,1,2
				}
				
				boolean boo = true;
				for (HmNoticeUser e : noticeUserList) {
					e.setTitle(e.getNoticeContent());
					e.setDescription(df.format(e.getCreateTime()));
					if (boo) {
						e.setSize("14");
						boo = false;
					} else {
						e.setSize("8");
					}
				}
//				list.get(0).setNoticeUserList(noticeUserList);
				hmNotice.setNoticeUserList(noticeUserList);
				
				if(null==noticeUserList||noticeUserList.size()==0) {
					hmNotice.setStatus("0");
				}else {
					hmNotice.setStatus(noticeUserList.get(0).getTicketStatus());
				}
				
			}  
		}

		// 雇主的要处理评价
		if (type == 1) {
			list.forEach(e -> {
				e.setIsComment(false);
				HmComment comment = commentService.queryByRIdAndType(e.getId(), e.getType());
				if (comment != null) {
					e.setIsComment(true);
				}

			});
		}

		return HmResponseUtil.ok(list);
	}

	private List<HmNotice> selectByReIdRTypeCteateTime(Long employRelationId, String yearMonth,
			List<String> servantNoticeType) {
		LocalDateTime st = LocalDateTime.parse(CalendarUtil.getFirstDayOfMonth(yearMonth) + " 00:00:00",
				CalendarUtil.df);
		LocalDateTime ed = LocalDateTime.parse(CalendarUtil.getLastDayOfMonth(yearMonth) + " 23:59:59",
				CalendarUtil.df);

		HmNoticeExample example = new HmNoticeExample();
		example.or().andEmployRelationIdEqualTo(employRelationId).andRTypeIn(servantNoticeType).andCreateTimeBetween(st,
				ed);
		example.setOrderByClause(" id desc ");

		List<HmNotice> list = hmNoticeMapper.selectByExample(example);
		return list;
	}

	/**
	 * 管家工单
	 * 
	 * @param employRelationId
	 * @param page
	 * @param limit
	 * @return
	 */
	public List<HmNotice> getNoticeByButler(String orderNo, Long noticeId, Integer page, Integer limit) {

		List<String> butlerNoticeType = HmNoticeEnum.getButlerNoticeType();

		HmEmployRelation relation = employRelationService.queryByOrderNo(orderNo);
		if (relation == null) {
			throw new RuntimeException("订单关联三者关系错误");
		}

		HmNoticeExample example = new HmNoticeExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEmployRelationIdEqualTo(relation.getId()).andRTypeIn(butlerNoticeType);
		if (null != noticeId) {
			// 关联工单跳转时
			createCriteria.andIdEqualTo(noticeId);
		}
		example.setOrderByClause(" id desc ");

		PageHelper.startPage(page, limit);
		List<HmNotice> list = hmNoticeMapper.selectByExample(example);
		list.forEach(e -> {
			List<HmNoticeUser> noticeUserList = hmNoticeUserService.getNoticeIduserIdList(e.getId(),
					relation.getUserButlerId());// 拿管家id的处理过程
			e.setNoticeUserList(noticeUserList);

			JzTicket ticket = jzTicketService.getTicketByNoticeId(e.getId().intValue());
			e.setJzTicket(ticket);

			Map<String, Object> relationOther = HmNoticeEnum.getRelationTypeValue(e.getrId(), e.getTicketId(),
					Integer.parseInt(e.getrType()));
			e.setRelationOther(relationOther);
		});

		return list;
	}

	/**
	 * 更新通知未读状态
	 * 
	 * @param noticeId
	 */
	public void updateNoticeRead(Long noticeId) {
		HmNoticeUser record = new HmNoticeUser();
		record.setId(noticeId);
		record.setIsRead(1);
		record.setReadTime(LocalDateTime.now());
		hmNoticeUserMapper.updateByPrimaryKeySelective(record);
	}

	public HmNotice findById(Integer id) {
		return hmNoticeMapper.selectByPrimaryKey((long) id);
	}

	/**
	 * 根据通知id获取需要通知的人
	 * 
	 * @param noticeId
	 * @return
	 */
	public List<Long> getPostUserId(int noticeId) {
		HmNotice findById = findById(noticeId);
		if (findById == null) {
			return new ArrayList<Long>();
		}
		return getNoticeUserId(findById.getEmployRelationId(), findById.getNoticeUserType());
	}

	/**
	 * 根据 通知类的noticeUserType和 三者关系 获取要发送的用户
	 * 
	 * @param employRelationId
	 * @param userTypeStr      HmNoticeEnum.noticeUserType
	 * @return
	 */
	public List<Long> getNoticeUserId(Long employRelationId, String userTypeStr) {
		List<Long> templist = new ArrayList<Long>();
		if (null != userTypeStr) {
			String[] userType = userTypeStr.split(",");
			HmEmployRelation relation = employRelationService.queryById(employRelationId);
			// 1雇主，2保姆，3管家
			for (String u : userType) {
				if ("1".equals(u)) {
					templist.add(relation.getUserEmployerId());
					continue;
				}
				if ("2".equals(u)) {
					templist.add(relation.getUserServantId());
					continue;
				}
				if ("3".equals(u)) {
					templist.add(relation.getUserButlerId());
					continue;
				}
			}
		}
		return templist;
	}

	private static void ListSort(List<HmNotice> list) {
		Collections.sort(list, new Comparator<HmNotice>() {
			@Override
			// 定义一个比较器
			public int compare(HmNotice o1, HmNotice o2) {

				try {

					if (o1.getCreateTime().isAfter(o2.getCreateTime())) {
						return -1;
					} else if (o1.getCreateTime().isBefore(o2.getCreateTime())) {
						return 1;
					} else {
						return 0;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
	}

}
