package com.goafanti.common.task;

import java.util.*;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.goafanti.common.bo.EmailBo;
import com.goafanti.common.bo.userDaysBo;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.NoticeMapper;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.enums.NoticeTypes;
import com.goafanti.common.model.Notice;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.customer.bo.LockingReleaseBo;
import com.goafanti.customer.service.CustomerService;
import com.goafanti.user.service.UserService;
import org.springframework.web.bind.annotation.RestController;


@Component
//@RestController
public class ReleaseUserTask {
	@Resource
	private CustomerService customerService;
	@Resource
	private UserService userService;
	@Autowired
	private NoticeMapper	noticeMapper;
	@Autowired
	private AsyncUtils	asyncUtils;
	@Value(value = "${dev.name}")
	private String devName=null;


	int pointsDataLimit = 50;

	/**
	 * 每天凌晨一点
	 *
	 * @throws InterruptedException
	 */
//	@Scheduled(cron = "0 31 15  * * ?")
	@Scheduled(cron = "0 0 1  * * ?")
	public void startTask() {
		try {
			List<User> userList = userService.selectUserByRoleName("营销员", "营销经理");
			pushUserDays(userList);
			Thread.sleep(2000);
			updateUser(userList);
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	private void pushUserDays(List<User> userList ) throws InterruptedException {
		LoggerUtils.debug(getClass(), "==============客户提醒开始============");
		List<Notice> ln = new ArrayList<>();
		for (User u : userList) {
			if (StringUtils.isNotBlank(u.getId())) {
				List<userDaysBo> userTmpList  = customerService.selectReleaseUserDays(u.getId());
				for (userDaysBo ub : userTmpList) {
					String str=null;
					if (ub.getChannel() == 0) {
						String shareType="";
						if(ub.getNewChannel()==0)shareType="私有";
						else if(ub.getNewChannel()==1)shareType="渠道";
						str = String.format("您的%s客户【%s】剩余天数不足十五天，请及时%s！", shareType, ub.getName(),ub.getType()==0?"跟进":"签单");
					}else {
						str = String.format("您的%s客户【%s】剩余天数不足十五天，请及时签单！", "外联", ub.getName());
					}
					ln.add(new Notice(UUID.randomUUID().toString(), new Date(), 0, ub.getAid(),
							NoticeStatus.CUSTOMER_LOSE_REMINDER.getCode(), str,ub.getUid()));
				}
			}
		}
		//查询15天未跟进，私有跟释放前15天重复，去除
		List<userDaysBo> userChannelList = new ArrayList<userDaysBo>();
		for (User u : userList) {
			if (StringUtils.isNotBlank(u.getId())) {
				userChannelList = customerService.selectChannelNotFollow(u.getId());
			}
			for (userDaysBo ub : userChannelList) {
				String str=null;
				if (ub.getChannel() == 1) {
					str = String.format("您的%s客户【%s】已经十五天未跟进，请及时跟进或者限时签单！", "外联", ub.getName());
				}
				ln.add(new Notice(UUID.randomUUID().toString(), new Date(), 0, ub.getAid(),
						NoticeStatus.CUSTOMER_PRIVATE_REMINDER.getCode(), str,ub.getUid()));
			}
		}
		addNoticeBatch(ln);
		LoggerUtils.debug(getClass(), "==============客户提醒结束============");
	}

	/**
	 * 将客户和业务转为待释放
	 */
	public void updateUser(List<User> userList ) {
		LoggerUtils.debug(getClass(), "==============客户释放开始============");
		Date releaseTime = new Date();
		try {
			List<LockingReleaseBo> lockUserList = new ArrayList<LockingReleaseBo>();
			if (userList != null && !userList.isEmpty()) {
				for (User u : userList) {
					if (StringUtils.isNotBlank(u.getId())) {
						// 获取30天释放
						List<LockingReleaseBo>  userTmpList = customerService.selectWaitReleaseCustomer(u.getId());
						customerService.pushReleaseLog(userTmpList, 0);
						addUserNotice(userTmpList);
						if (userTmpList != null && !userTmpList.isEmpty())
							lockUserList.addAll(userTmpList);
					}
				}
			}
			List<LockingReleaseBo> newList = new ArrayList<LockingReleaseBo>();
			if (lockUserList != null && lockUserList.size() > 0) {
				for (int i = 0; i < lockUserList.size(); i++) {
					newList.add(lockUserList.get(i));
					if (pointsDataLimit == newList.size() || i == lockUserList.size() - 1) {
						if (newList.size() > 0) {
							customerService.updatePendingReleaseLock(newList);
						}
						newList.clear();
						Thread.sleep(2000);
					}
				}
			}
			pushChannel(releaseTime, userList);
		} catch (Exception e) {
			Notice n = new Notice(UUID.randomUUID().toString(), new Date(), 0, "1",
					NoticeStatus.TASK_PATENT_ERROR.getCode(), "==============客户释放失败================",null);
			addNotice(n);
			EmailBo emailBo = new EmailBo("释放客户失败", AFTConstants.ADMIN_EMAIL, "超管", "平台", "系统", devName+"释放客户失败");
			asyncUtils.send(emailBo);
			LoggerUtils.error(getClass(), "====================客户释放失败=================");
			LoggerUtils.error(getClass(), "客户释放失败", e);
		}
		LoggerUtils.debug(getClass(), "==============客户释放完成============");
	}

	/**
	 * 处理外联
	 * @param releaseTime
	 * @param userList
	 * @throws InterruptedException
	 */
	private void pushChannel(Date releaseTime, List<User> userList) throws InterruptedException {
		// 获取超过90天客户，判断是否回收过，未回收则回收，已回收则释放为公共客户
		List<userDaysBo> userChannelList =null;
		List<userDaysBo> count =new ArrayList<userDaysBo>();
		if (userList != null && !userList.isEmpty()) {
			for (User u : userList) {
				userChannelList=customerService.selectChannelUserDays(u.getId());
				if (userChannelList!=null) {
					count.addAll(userChannelList);
				}
			}
		}
		List<userDaysBo> hsList=new ArrayList<>();
		List<userDaysBo> sfList=new ArrayList<>();
		if (count != null && count.size() > 0) {
			for (int i = 0; i < count.size(); i++) {
				//回收
				if (count.get(i).getRecovery()==0) {
					hsList.add(count.get(i));
				}else {
					sfList.add(count.get(i));
				}
				if (pointsDataLimit == (hsList.size()+sfList.size()) || i == count.size() - 1) {
					if(!hsList.isEmpty())userService.pushReleaseUserChannel(hsList,0);
					if(!sfList.isEmpty())userService.pushReleaseUserChannel(sfList,1);
					addChannelNotice(hsList,sfList);
					hsList.clear();
					sfList.clear();
					Thread.sleep(2000);
				}
			}
		}
		List<LockingReleaseBo> lockList = customerService.selectPendinglockUserList();
		if (lockList.size() > 0)
			customerService.updateReleaseLock(releaseTime);
	}

	public void addNotice(Notice n ) {
		n.setType(NoticeTypes.getType(n.getNoticeType()));
		noticeMapper.insertSelective(n);
	}

	public void addNoticeBatch(List<Notice> ln) {
		List<Notice> newList=new ArrayList<Notice>();
		if (ln != null && ln.size() > 0) {
			for (int i = 0; i < ln.size(); i++) {
				ln.get(i).setType(NoticeTypes.getType(ln.get(i).getNoticeType()));
				newList.add(ln.get(i));
				if (50 == newList.size() || i == ln.size() - 1) {
					if (newList.size() > 0) {
						//发送站内信
						noticeMapper.insertBatch(newList);
					}
					newList.clear();
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}


	private void addUserNotice(List<LockingReleaseBo> userTmpList) {
		List<Notice> nl=new ArrayList<Notice>();
		if (!userTmpList.isEmpty()) {
			for (LockingReleaseBo u : userTmpList) {
				String shareType="";
				if(u.getNewChannel()==0)shareType="私有";
				else if(u.getNewChannel()==1)shareType="渠道";
				nl.add(new Notice(UUID.randomUUID().toString(), new Date(), 0, u.getAid(),
						NoticeStatus.CUSTOMER_LOSE30.getCode(),
						String.format("您的%s客户【%s】已经30天未跟进，已经自动释放！", shareType, u.getUserName()),
						u.getUid()));
			}
		}
		if(!nl.isEmpty())addNoticeBatch(nl);
	}





	private void addChannelNotice(List<userDaysBo> hsList, List<userDaysBo> sfList) {
		List<Notice> nl=new ArrayList<Notice>();
		for (userDaysBo hs : hsList) {
			nl.add(new Notice(UUID.randomUUID().toString(), new Date(), 0, hs.getAid(),
					NoticeStatus.CUSTOMER_CHENNEL_RECOVERY.getCode(),
					String.format("您的%s客户【%s】已经90天未跟进，已经自动回收！", "外联", hs.getName()),
					hs.getUid()));
		}

		for (userDaysBo sf : sfList) {
			nl.add(new Notice(UUID.randomUUID().toString(), new Date(), 0, sf.getAid(),
					NoticeStatus.CUSTOMER_CHENNEL_LOSE.getCode(),
					String.format("您的%s客户【%s】已经90天未跟进，已经自动释放！", "外联", sf.getName()),
					sf.getUid()));
		}
		if(!nl.isEmpty())addNoticeBatch(nl);
	}

}
