package com.iamberry.wechat.handles.mq;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.core.entity.task.TaskModel;
import com.iamberry.wechat.core.entity.task.WechatTask;
import com.iamberry.wechat.core.entity.task.WechatTaskLogs;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.reback.RebackServices;
import com.iamberry.wechat.face.task.WechatTaskService;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.zk.SpringContextHolder;
/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年11月3日
 * @explain	MQ模拟实现
 */
@Component(value="mqTask")
@Lazy(false)
public class MQTask implements InitializingBean {
	
	@Autowired
	private AdminOrderService adminOrderService;
	
	@Autowired
	private MQServiceProxy mQSerivce;
	
	@Autowired
	private RatFWLogger logger;
	
	@Autowired
	private WechatTaskService wechatTaskService;
	
	@Autowired
	private RebackServices rebackServices;
	
	private Lock lock = new ReentrantLock();

	@SuppressWarnings(value = {"unchecked", "rawtypes"})
	@Scheduled(cron = "0/30 * * * * ?")
	public void sendOrderService() {
		logger.info("------------task start-----------");
		// If the timer has not stopped, then the next time the timer can not start.
		lock.lock();
		
		try {
			// step 1, Gets the message that is not executed in the database.
			List<MQMessage> messages = mQSerivce.selectWaitHandlerMessage();
			if (messages == null || messages.size() <= 0) {
				return;
			}
			
			// step 2, Handle 10 messages at a time.
			for (MQMessage mqMessage : messages) {
				try {
					Object object = SpringContextHolder.getBean(mqMessage.getServiceHandlerObjectName());
					Class classes = object.getClass();
					Method method = classes.getMethod(mqMessage.getServiceHandlerMethodName(), MQMessage.class);
					if (method == null) {
						mqMessage.setServiceErrorMessage("Method is not defined:" + mqMessage.getServiceHandlerMethodName());
						mqMessage.setServiceStatus(2);
						continue;
					}
					// invoke Method.
					Object resultObject = method.invoke(object, mqMessage);
					if (!(resultObject instanceof Boolean)) {
						mqMessage.setServiceStatus(2);
						mqMessage.setServiceErrorMessage(mqMessage.getServiceHandlerObjectName() + "." + mqMessage.getServiceHandlerMethodName() + "()Return value is not type Boolean");
						continue;
					}
					if (!(Boolean) resultObject) {
						mqMessage.setServiceErrorMessage("invoke Method Error");
						mqMessage.setServiceStatus(2);
						continue;
					}
					mqMessage.setServiceStatus(1);
					continue;
				} catch (Exception e) {
					// TODO: handle exception
					mqMessage.setServiceErrorMessage(e.getMessage());
					mqMessage.setServiceStatus(2);
					continue;
				} finally {
					mqMessage.setServiceIsSend(1);
				}
			}
			
			// step 3, update Message status and serviceIsSend.
			mQSerivce.updateBatchMessage(messages);
			
			// step 4, is next ?
			/*if (messages.size() >= 10) {
				StaticCacheMemory.isStartTask = true;
				this.sendOrderService();
			}*/
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e, "MQ Task Error:" + e.getMessage());
		} finally {
			// reset lock
			lock.unlock();
		}
		logger.info("------------task invoke success-----------");
	}
	
	/**
	 * 订阅消息
	 */
	public void subscribeMessageQueue() {
	}
	
	// 强迫线程可见
	private volatile boolean oldState = true;
	
	/**
	 * 微信定期任务奖励-上个月的定时器
	 */
	@SuppressWarnings("deprecation")
	@Scheduled(cron = "0/59 * * * * ?")
	public void oldMonthTask() {
		if (!oldState) {
			logger.info("线程正忙...");
			return;
		}
		oldState = false;
		try {
			// 判断上一个月的数据是否奖励完成
			logger.info("上一个月的定时奖励任务奖励...");
			// 当前时间
			Date nowDate = new Date();
			
			// 回到上一个月
			nowDate.setMonth(nowDate.getMonth() - 1);
			// 上一个月的结束时间  类似 ：2016-02-29 23:59:59
			Date oldMonthLastDay = DateTimeUtil.getLastDayOfYear(nowDate);
			// 上一个月的开始时间  类似 ：2016-02-01 00:00:00
			Date oldMonthFirstDay = DateTimeUtil.getFirstDayOfYear(nowDate);
			
			List<WechatTask> tasks = wechatTaskService.getRunTask(oldMonthFirstDay, oldMonthLastDay);
			if (tasks == null || tasks.size() == 0) {
				logger.info("暂时没有上一个月的任务奖励...");
				oldState = true;
				return;
			}
			// 获取在上一个月销售达到X台的数据
			for (WechatTask wechatTask : tasks) {
				List<TaskModel> models = rebackServices.getByDate(wechatTask.getTaskProductType(), oldMonthFirstDay, oldMonthLastDay, wechatTask.getTaskSalesNum());
				if (models == null || models.size() == 0) {
					logger.info("暂时没有人完成上一个月的任务" + wechatTask.getTaskId() + "奖励...");
					continue;
				}
				// 达到的用户是否已经领取奖励
				for (TaskModel taskModel : models) {
					WechatTaskLogs logs = new WechatTaskLogs();
					logs.setLogsTaskId(wechatTask.getTaskId());
					logs.setLogsUserOpenId(taskModel.getOpenID());
					Integer logsID = wechatTaskService.getByTaskIdAndOpenId(logs);
					if (logsID != null) {
						// 如果当前用户已经领取了奖励，那么跳过
						continue;
					}
					// 若用没有领取，那么奖励
					try {
						wechatTaskService.handlerTask(taskModel.getOpenID(), wechatTask.getTaskMoney(), wechatTask.getTaskId(), wechatTask.getTaskProductType());
					} catch (Exception e) {
						logger.error(this, "对:" + taskModel.getOpenID() + ",奖励失败!error:" + e.getMessage());
					}
				}
			}
		} catch (Exception e) {
			logger.error(this, "发生异常,奖励失败!error:" + e.getMessage());
		} finally {
			// 归还锁
			oldState = true;
		}
	}

	// 强迫线程可见
	private volatile boolean nowState = true;
	/**
	 * 微信定期任务奖励-本月的定时器
	 */
	@Scheduled(cron = "0/59 * * * * ?")
	public void nowMonthTask() {
		if (!nowState) {
			logger.info("线程正忙...");
			return;
		}
		nowState = false;
		
		try {
			// 判断本月是否有奖励数据
			logger.info("本月的定时奖励任务奖励...");
			// 当前时间
			Date nowDate = new Date();
			
			// 上一个月的结束时间  类似 ：2016-02-29 23:59:59
			Date oldMonthLastDay = DateTimeUtil.getLastDayOfYear(nowDate);
			// 上一个月的开始时间  类似 ：2016-02-01 00:00:00
			Date oldMonthFirstDay = DateTimeUtil.getFirstDayOfYear(nowDate);
			
			List<WechatTask> tasks = wechatTaskService.getRunTask(oldMonthFirstDay, oldMonthLastDay);
			if (tasks == null || tasks.size() == 0) {
				logger.info("暂时没有本月的任务奖励...");
				nowState = true;
				return;
			}
			// 获取在上一个月销售达到X台的数据
			for (WechatTask wechatTask : tasks) {
				List<TaskModel> models = rebackServices.getByDate(wechatTask.getTaskProductType(), oldMonthFirstDay, oldMonthLastDay, wechatTask.getTaskSalesNum());
				if (models == null || models.size() == 0) {
					logger.info("暂时没有人完成本月的任务" + wechatTask.getTaskId() + "奖励...");
					continue;
				}
				// 达到的用户是否已经领取奖励
				for (TaskModel taskModel : models) {
					WechatTaskLogs logs = new WechatTaskLogs();
					logs.setLogsTaskId(wechatTask.getTaskId());
					logs.setLogsUserOpenId(taskModel.getOpenID());
					Integer logsID = wechatTaskService.getByTaskIdAndOpenId(logs);
					if (logsID != null) {
						// 如果当前用户已经领取了奖励，那么跳过
						continue;
					}
					// 若用没有领取，那么奖励
					try {
						wechatTaskService.handlerTask(taskModel.getOpenID(), wechatTask.getTaskMoney(), wechatTask.getTaskId(), wechatTask.getTaskProductType());
					} catch (Exception e) {
						logger.error(this, "对:" + taskModel.getOpenID() + ",奖励失败!error:" + e.getMessage());
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(this, "发生异常:" + e.getMessage());
		} finally {
			nowState = true;
		}
	}
	
	public void afterPropertiesSet() throws Exception {
	}
}
