package com.goafanti.common.task;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
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 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.model.Notice;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.SendEmailUtil;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.customer.bo.LockingReleaseBo;
import com.goafanti.customer.service.CustomerService;
import com.goafanti.user.service.UserService;

@Component
@Controller
public class ReleaseUserTask {
	@Resource
	private CustomerService customerServiceImpl;
	@Resource
	private UserService userServiceImpl;
	@Autowired
	private NoticeMapper	noticeMapper;
	
	int pointsDataLimit=50;
	
	/**
	 *   每天凌晨一点
	 * @throws InterruptedException
	 */
//	@Scheduled(cron = "0 55 15  * * ?")
	@Scheduled(cron = "0 0 1  * * ?")
	public void startTask()  {
		try {
			pushUserDays();
			Thread.sleep(2000);
			updateUser();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	@RequestMapping(value = "/open/remindUser", method = RequestMethod.GET)
	private void pushUserDays() throws InterruptedException {
		LoggerUtils.debug(getClass(), "==============客户提醒开始============");
		List<User> userList = userServiceImpl.selectUserByRoleName("营销员","营销经理");
		List<userDaysBo> count = new ArrayList<>();
		List<userDaysBo> userTmpList = null;
		for(User u : userList){
			if(StringUtils.isNotBlank(u.getId())) {
				userTmpList = customerServiceImpl.selectUserDays(u.getId());
			}
			if(!userTmpList.isEmpty())count.addAll(userTmpList);
		}
		List<Notice> ln=new ArrayList<>();
		for (userDaysBo ub : count) {
			ln.add(new Notice(UUID.randomUUID().toString(),new Date(),0,
				ub.getAid(),NoticeStatus.CUSTOMER_PRIVATE_REMINDER.getCode(),"您的客户:"+ub.getName()+"，剩余天数不足十五天，请及时跟进或者限时签单！"));
		}
		List<Notice> newList=new ArrayList<>();
		 if (ln!=null&&ln.size()>0) {
			  for(int i=0;i<ln.size();i++){
				  newList.add(ln.get(i));
				  if(pointsDataLimit == newList.size()||i == ln.size()-1){
					  if(newList.size()>0) noticeMapper.insertBatch(newList);
					  newList.clear();
					  Thread.sleep(2000);
				  }  
			  }
		}
		 LoggerUtils.debug(getClass(), "==============客户提醒结束============");
	}


	/**
	 *将客户和业务转为待释放
	 */
	@RequestMapping(value = "/open/updateUser", method = RequestMethod.GET)
	public void updateUser(){
		LoggerUtils.debug(getClass(), "==============客户释放开始============");
		Date releaseTime = new Date();
		try {
			List<User> userList = userServiceImpl.selectUserByRoleName("营销员","营销经理");
			List<LockingReleaseBo> lockUserList = new ArrayList<LockingReleaseBo>();
			List<LockingReleaseBo> userTmpList = null;
			List<LockingReleaseBo> userTmpList2 = null;
			if (userList!=null&&!userList.isEmpty()) {
				for(User u : userList){
					if(StringUtils.isNotBlank(u.getId())) {
						//获取30天释放
						userTmpList = customerServiceImpl.selectWaitReleaseCustomer(u.getId(),0);
						//获取270天释放
						userTmpList2 = customerServiceImpl.selectWaitReleaseCustomer(u.getId(),1);
						customerServiceImpl.pushReleaseLog(userTmpList,0);
						customerServiceImpl.pushReleaseLog(userTmpList2,1);
						if(userTmpList!=null&&!userTmpList.isEmpty())lockUserList.addAll(userTmpList);
						if(userTmpList2!=null&&!userTmpList2.isEmpty())lockUserList.addAll(userTmpList2);
						}
				}
			}
		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) {
							  customerServiceImpl.updatePendingReleaseLock(newList);
						  }
						  newList.clear();
						  Thread.sleep(2000);
					  }  
				  }
			}
			List<LockingReleaseBo> lockList=customerServiceImpl.selectPendinglockUserList();
			if (lockList.size()>0)customerServiceImpl.updateReleaseLock(releaseTime);
		} catch (Exception e) {
			Notice n =new Notice(UUID.randomUUID().toString(),new Date(),0,"1",NoticeStatus.TASK_PATENT_ERROR.getCode(),"==============客户释放失败================");
			 noticeMapper.insert(n);
			EmailBo emailBo = new EmailBo( "释放客户失败",  AFTConstants.ADMIN_EMAIL,  "超管", "平台",  "系统", "释放客户失败");
			try {
				SendEmailUtil.getInstance().send(emailBo);
			} catch (UnsupportedEncodingException | MessagingException e1) {
				e1.printStackTrace();
			}
			LoggerUtils.error(getClass(), "====================客户释放失败=================");
			LoggerUtils.error(getClass(), "客户释放失败", e);
		}
		LoggerUtils.debug(getClass(), "==============客户释放完成============");
	}
	
}
