package com.chinacreator.process.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.process.bean.ActivityConfigBean;
import com.chinacreator.process.bean.NetOrderBean;
import com.chinacreator.process.bean.OrderBean;
import com.chinacreator.process.dao.ActivityConfigDao;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.YoutuActiveDao;

/**
 * 优酷产品处理类
 * @author xu.zhou
 * @date 20190409
 */
@Component
public class YoutuOrderService {
		
	private Logger log = Logger.getLogger("recivemq");

	@Autowired
	private YoutuActiveDao youtuActiveDao;
	
	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	private ActivityConfigDao activityConfigDao;

	public void handle(OrderBean orderBean) throws Exception {
		OrderBean activityOrderBean = youtuActiveDao.existUser(orderBean.getUserid(), orderBean.getCpid(),
				orderBean.getSpid(),orderBean.getActiveType()+"");
		 if(activityOrderBean == null){//活动表无数据，订购或退订
			 orderBean = getOrderInfo(orderBean);
			 orderBean = setFlowstatus(orderBean,activityOrderBean);
			 String id = youtuActiveDao.getId();
			 orderBean.setId(id);
			// log.info("添加活动数据");
			 youtuActiveDao.insertBeans(orderBean);
		 }else{//活动表有数据，订购或退订
			 orderBean = getOrderInfo(orderBean);
			 OrderBean vipOrderBean = getVipInfo(activityOrderBean);
			 orderBean.setVipstatus(vipOrderBean.getVipstatus());
			 orderBean.setViptime(vipOrderBean.getViptime());
			 orderBean.setId(activityOrderBean.getId());
			 orderBean = setFlowstatus(orderBean,activityOrderBean);
			 //log.info("更新活动数据");
			 youtuActiveDao.update(orderBean);
		 }
		 //赠送流量流程
		 if(hasActivityDate(orderBean)){//当前时间在活动期内			 
			 OrderBean flowBean = youtuActiveDao.existFlowRec(orderBean);
			 /**
			  * 用户订购时如果此表没有数据就新增数据，
				用户退订时如果已有数据且是订购状态更新此表数据为退订，只会更新一次退订操作
			  */
			 if(flowBean == null && "0".equals(orderBean.getOrderstatus())){//记录表为空，此次是订购
				 youtuActiveDao.insertFlowRec(orderBean); 
			 }else if(flowBean == null && "1".equals(orderBean.getFlowstatus())){//记录表为空，此次是要送流量（一分钟内订购又退订的）
				 youtuActiveDao.insertFlowRec(orderBean); 				 
			 }else if(flowBean != null && "0".equals(flowBean.getOrderstatus()) && "1".equals(orderBean.getOrderstatus())){ //记录是的订购状态，此次是退订
				 orderBean.setId(flowBean.getId());
				 youtuActiveDao.updateFlowRec(orderBean);
			 } 
		 }else{
			 updateExpireFlowRec(orderBean);
		 }
	}
	
	/**
	 * 活动过期后，用户退订时更新记录数据
	 * @param orderBean
	 * @return
	 */
	private boolean updateExpireFlowRec(OrderBean orderBean){ 
		boolean result = false;
		try {
			//在最后的续送日期内
			if("1".equals(orderBean.getOrderstatus())){//退订
				final Date date = new Date();
				String flowOverTime = getConfTime(orderBean.getSpid(),"3"); //dictionaryDao.getValue(orderBean.getCpid()+orderBean.getSpid()+"FlowOverTime"); //流量续送最后一天（活动结束日期加两月）
				if(flowOverTime != null && !"".equals(flowOverTime.trim()) && NumberUtils.toLong(DateFormatUtils.format(date, "yyyyMMddHHmmss")) - NumberUtils.toLong(flowOverTime.trim()) <= 0){
					//在最后的续送日期内		
					//查询记录是订购状态且当前时间月份减去订购时间月分份小于或等于2的数据
					OrderBean flowBean = youtuActiveDao.existExpireFlowRec(orderBean);
					if(flowBean != null){//
						 orderBean.setId(flowBean.getId());
						 //更新记录表为退订
						 youtuActiveDao.updateFlowRec(orderBean);
					}				
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info(orderBean.getUserid()+": errorinfo=>活动过期后，用户退订时更新记录数据出现异常，"+e.getMessage());
		}
		return result;
	}
	
	/**
	 * 是否在赠送流量活动期内
	 * @return
	 */
	private boolean hasActivityDate(OrderBean orderBean){
		boolean result = false;
		try {
			final Date date = new Date();
			String flowStartTime = getConfTime(orderBean.getSpid(),"1"); //dictionaryDao.getValue(orderBean.getCpid()+orderBean.getSpid()+"FlowStartTime"); //赠送流量开始时间
			String flowEndTime =  getConfTime(orderBean.getSpid(),"2"); //dictionaryDao.getValue(orderBean.getCpid()+orderBean.getSpid()+"FlowEndTime"); //赠送流量结束时间
			if(flowStartTime != null && !"".equals(flowStartTime.trim()) && flowEndTime != null && !"".equals(flowEndTime.trim())){
				flowEndTime = flowEndTime.trim();
				flowStartTime = flowStartTime.trim();
				/*
				//1.活动时间：4月1日00:00:00至6月30日23:59:59
				if (NumberUtils.toLong(DateFormatUtils.format(date, "yyyyMMddHHmmss")) >= Long.parseLong(flowStartTime) 
						&& NumberUtils.toLong(DateFormatUtils.format(date, "yyyyMMddHHmmss")) <= Long.parseLong(flowEndTime)) {
					result = true;
				}
				
				//反向通知的数据可能延迟，当天已超过最后赠送时间，但订购时间在活动期内
				if(result == false && "0".equals(orderBean.getOrderstatus())){
					if (NumberUtils.toLong(orderBean.getOrdertime()) >= Long.parseLong(flowStartTime) 
							&& NumberUtils.toLong(orderBean.getOrdertime()) <= Long.parseLong(flowEndTime)) {
						result = true;
					}
				}
				
				//反向通知的数据可能延迟，订购时间小于活开始时间
				if(result == true && "0".equals(orderBean.getOrderstatus())){
					if (NumberUtils.toLong(orderBean.getOrdertime()) < Long.parseLong(flowStartTime)) {
						result = false;
					}
				}
				*/
				//订购时间在指定范围内
				if (NumberUtils.toLong(orderBean.getOrdertime()) >= Long.parseLong(flowStartTime) 
						&& NumberUtils.toLong(orderBean.getOrdertime()) <= Long.parseLong(flowEndTime)) {
					result = true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info(orderBean.getUserid()+": errorinfo=>判断是否在赠送流量活动期内出现异常，"+e.getMessage());
		}
        return result;
	}
	
	/**
	 * 获取配置时间
	 * @param spid
	 * @param type 1开始时间，2结束时间，3续送最后时间
	 * @return
	 * @throws SQLException
	 */
	private String getConfTime(String spid, String type) throws SQLException{
		String res = "";
		String data = ""; 
		if("1".equals(type)){
			data = dictionaryDao.getValue("flowSendStartTime");		
		}else if("2".equals(type)){
			data = dictionaryDao.getValue("flowSendEndTime");	
		}else if("3".equals(type)){
			data = dictionaryDao.getValue("flowSendOverTime");	
		}
		if(data != null && !"".equals(data)){
			String [] array = data.split("\\|");
			for(String conf : array){
				if(spid.equals(conf.split(",")[0])){
					res = conf.split(",")[1];
					break;
				}
			}
		}
		return res;
	}
	
	/**
	 * 设置赠送流量信息
	 * @param orderBean
	 */
	private OrderBean setFlowstatus(OrderBean orderBean,OrderBean activityOrderBean) throws BusinessException{
		try {
			//初始化数据
			orderBean.setFlowstatus("8"); //不赠送    	
			if(activityOrderBean != null){
				orderBean.setFlowstatus(activityOrderBean.getFlowstatus());
			}
			
			//判断是否在活动期
			if (hasActivityDate(orderBean)) {
				String flowStartTime = getConfTime(orderBean.getSpid(),"1"); //dictionaryDao.getValue(orderBean.getCpid()+orderBean.getSpid()+"FlowStartTime"); //赠送流量开始时间
				String flowEndTime =  getConfTime(orderBean.getSpid(),"2"); //dictionaryDao.getValue(orderBean.getCpid()+orderBean.getSpid()+"FlowEndTime"); //赠送流量结束时间
				if(flowStartTime != null ) flowStartTime = flowStartTime.trim();
				if(flowEndTime != null ) flowEndTime = flowEndTime.trim();
			    //优酷20元赠送流量活动日期
				if(activityOrderBean == null && "0".equals(orderBean.getOrderstatus())){//新用户订购
					orderBean.setFlowstatus("1"); //未赠送
				}else if(activityOrderBean == null && "1".equals(orderBean.getOrderstatus()) 
						&& flowStartTime != null && flowStartTime.length() > 6
						&& flowEndTime != null && flowEndTime.length() > 6
						&& orderBean.getOrdertime() != null && orderBean.getOrdertime().length() > 6
						&& Integer.parseInt(orderBean.getOrdertime().substring(0, 6)) >= Integer.parseInt(flowStartTime.substring(0, 6))
						&& Integer.parseInt(orderBean.getOrdertime().substring(0, 6)) <= Integer.parseInt(flowEndTime.substring(0, 6))){
					//活动表没记录，且是退订操作，订购时间在在活动期内（一分钟内订购又退订的）
					orderBean.setFlowstatus("1"); //未赠送
				}else if(activityOrderBean != null && "8".equals(activityOrderBean.getFlowstatus())  && "1".equals(orderBean.getOrderstatus()) 
						&& flowStartTime != null && flowStartTime.length() > 6
						&& flowEndTime != null && flowEndTime.length() > 6						
						&& activityOrderBean.getOrdertime() != null && activityOrderBean.getOrdertime().length() > 6
						&& Integer.parseInt(activityOrderBean.getOrdertime().substring(0, 6)) < Integer.parseInt(flowStartTime.substring(0, 6))
						&& orderBean.getOrdertime() != null && orderBean.getOrdertime().length() > 6
						&& Integer.parseInt(orderBean.getOrdertime().substring(0, 6)) >= Integer.parseInt(flowStartTime.substring(0, 6))
						&& Integer.parseInt(orderBean.getOrdertime().substring(0, 6)) <= Integer.parseInt(flowEndTime.substring(0, 6))){
					//活动表有记录，且是退订操作，活动表的订购时间在活动开始之前订购的,且此次订购时间在活动期内（在活动期内一分钟内订购又退订的）
					orderBean.setFlowstatus("1"); //未赠送
				}else if(activityOrderBean != null && "8".equals(activityOrderBean.getFlowstatus()) && "0".equals(orderBean.getOrderstatus())){ //老用户活动期间第一次退订后再订购
					orderBean.setFlowstatus("1"); //未赠送
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			//throw new BusinessException("8011", "设置赠送流量信息出现异常，"+e.getMessage());
			log.info(orderBean.getUserid()+": errorinfo=>设置赠送流量信息出现异常，"+e.getMessage());
		}
        return orderBean;
	}
	
	/**
	 * 获取会员赠送信息
	 * @param activityOrderBean
	 * @return
	 * @throws BusinessException
	 */
	private OrderBean getVipInfo(OrderBean activityOrderBean) throws BusinessException{
		 //VIPSTATUS IS '腾讯会员赠送状态 0 成功 1失败 2未赠送 3 会员赠送中 4 暂停赠送 5不送';
		 OrderBean orderBean = new OrderBean();
		 String vipstatus=activityOrderBean.getVipstatus();
		 String viptime = activityOrderBean.getViptime();
		 if(StringUtils.isEmpty(viptime)){
			 vipstatus = activityOrderBean.getVipstatus();
			 viptime = activityOrderBean.getViptime();
		 }else{
			 //领取会员月份是当月
			 if(NumberUtils.toLong(viptime.substring(0, 6)) ==NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMM"))){
				 //续送会员日期是当月
				 if(activityOrderBean.getVipcontime() != null && NumberUtils.toLong(activityOrderBean.getVipcontime().substring(0, 6))  == NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMM"))){
					 vipstatus ="0"; //设置赠送会员成功
					 viptime = activityOrderBean.getVipcontime(); //设置赠送会员时间为续送时间
				 }else{
					 vipstatus = activityOrderBean.getVipstatus();//设置领取会员状态为原数据
					 viptime = activityOrderBean.getViptime();		//设置领取会员时间为原数据
				 }
			 //领取会员日期是往月
			 }else if(NumberUtils.toLong(viptime.substring(0, 6)) < NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMM"))){
				 //续送会员日期是当月
				 if(activityOrderBean.getVipcontime() != null && NumberUtils.toLong(activityOrderBean.getVipcontime().substring(0, 6))  == NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMM"))){
					 vipstatus = activityOrderBean.getVipstatus();	//设置领取会员状态为原数据
					 viptime = activityOrderBean.getViptime();	//设置领取会员时间为原数据
				 }else{
					 vipstatus ="2"; //设置领取会员状态为未赠送
					 viptime =""; //设置领取会员时间为空
				 }
			 }else{
				 throw new BusinessException("8010", "viptime数据异常");
			 }
		 }
		 orderBean.setVipstatus(vipstatus);
		 orderBean.setViptime(viptime);
		return orderBean;
	}
	
	public OrderBean getOrderInfo(OrderBean orderBean) throws Exception{
		 //获取订购关系表中所有数据
		 List<NetOrderBean> list = youtuActiveDao.findOrder(orderBean.getCpid(), orderBean.getUserid(),orderBean.getSpid());
		 List<NetOrderBean> orderlist = new ArrayList<NetOrderBean>();
		 List<NetOrderBean> cancellist = new ArrayList<NetOrderBean>();
		 //获取活动配置表的数据
		 ActivityConfigBean activityConfigBean = activityConfigDao.findByCallerheadtype(orderBean.getCpid(), orderBean.getSpid(), orderBean.getProvince(),orderBean.getActiveType()+"");
		 if(list != null && list.size()>0){
			 for (NetOrderBean netOrderBean : list) {
				 //订购日期大于活动的开始日期且小于活动的结束日期
				 if(NumberUtils.toLong(netOrderBean.getOrdertimestr()) >= NumberUtils.toLong(activityConfigBean.getBegintime()) && NumberUtils.toLong(netOrderBean.getOrdertimestr()) <= NumberUtils.toLong(activityConfigBean.getEndtime())){
					 if(netOrderBean.getStatus().equals("0")){//订购状态
							orderlist.add(netOrderBean);
					 }else if(netOrderBean.getStatus().equals("1")){//退订状态
							cancellist.add(netOrderBean);
					 }
				 }
			}
		 }
		 String ordertime = ""; 		//订购时间
		 String endtime = "";			//结束时间
		 String canceltime = "";		//退订时间
		 String orderstatus = "";		//订购状态 ：0 订购， 1退订， 2失效， 3 老用户退订， 4老用户当月订了又退
		 String orderchannel = "";		//订购渠道
		 String cancelchannel = "";		//退订渠道
		 String effectivetime = ""; 	//生效时间
		 if(orderlist.size()>0 && cancellist.size()==0){//全是订购，取最早订购时间
			 orderstatus = "0";	//订购
			 for (NetOrderBean netOrderBean : orderlist) {
				if(StringUtils.isEmpty(ordertime)){
					ordertime = netOrderBean.getOrdertimestr();
				}
				if(NumberUtils.toLong(netOrderBean.getOrdertimestr()) <= NumberUtils.toLong(ordertime)){
					ordertime = netOrderBean.getOrdertimestr(); 	//取最是订购时间
					orderchannel = netOrderBean.getOrderchannel(); 	//取最是订购渠道
					effectivetime = netOrderBean.getEffecttimestr();//取生效时间
				}
			}
		 }else if(cancellist.size() >0 && orderlist.size()==0){//全是退订
			 orderstatus = "1";	//退订
			 for (NetOrderBean netOrderBean : cancellist) {
					if(StringUtils.isEmpty(ordertime)){
						ordertime = netOrderBean.getOrdertimestr();
						canceltime = netOrderBean.getCanceltimestr();
						cancelchannel = netOrderBean.getCancelchannel();
						orderchannel = netOrderBean.getOrderchannel();
						endtime = netOrderBean.getEndtimestr();
						effectivetime = netOrderBean.getEffecttimestr();//取生效时间
					}
					if(NumberUtils.toLong(netOrderBean.getOrdertimestr()) <= NumberUtils.toLong(ordertime)){
						ordertime = netOrderBean.getOrdertimestr();		//取最早订购时间
						orderchannel = netOrderBean.getOrderchannel();	//取最早订购渠道
						effectivetime = netOrderBean.getEffecttimestr();//取生效时间
					}
					if(NumberUtils.toLong(netOrderBean.getCanceltimestr()) >= NumberUtils.toLong(canceltime)){
						canceltime = netOrderBean.getCanceltimestr();	//取最晚退订时间
						endtime = netOrderBean.getEndtimestr();			//取最晚结束时间
						cancelchannel = netOrderBean.getCancelchannel();	//取最晚退订渠道
					}
				}
		 }else if(cancellist.size() >0 && orderlist.size()>0){ //有退订又有订购
			 orderstatus ="0";
			 orderBean.setCancelchannel(cancelchannel);
			 for (NetOrderBean netOrderBean : list) {
				 if(netOrderBean.getStatus().equals("0") || netOrderBean.getStatus().equals("1")){
					 if(StringUtils.isEmpty(ordertime)){
							ordertime = netOrderBean.getOrdertimestr();
							effectivetime = netOrderBean.getEffecttimestr();//取生效时间
						}
					 if(NumberUtils.toLong(netOrderBean.getOrdertimestr()) <= NumberUtils.toLong(ordertime)){
							ordertime = netOrderBean.getOrdertimestr();		//取最早订购时间
							orderchannel=netOrderBean.getOrderchannel();	//取最早订购渠道
							effectivetime = netOrderBean.getEffecttimestr();//取生效时间
						}
				 }
			 }
		 }else{
			 throw new BusinessException("8010", "order数据异常");
		 }
		 orderBean.setEndtime(endtime);
		 orderBean.setCanceltime(canceltime);
		 orderBean.setOrderstatus(orderstatus);
		 orderBean.setOrdertime(ordertime);
		 orderBean.setOrderchannel(orderchannel);
		 orderBean.setCancelchannel(cancelchannel);
		 orderBean.setEffectivetime(effectivetime);
		 return orderBean;
	} 
}
