package com.chinacreator.process.job;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import com.chinacreator.process.bean.KfkChangeNumBean;
import com.chinacreator.process.bean.NetOrderBean;
import com.chinacreator.process.bean.OrderBean;
import com.chinacreator.process.bean.OrderLog;
import com.chinacreator.process.bean.VacOrder;
import com.chinacreator.process.bean.VacOrderItem;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.KfkChangeNumDao;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.process.util.VacUtil;
import com.chinacreator.video.queue.MessageService;
import com.chinacreator.video.queue.bean.MessagePipe;

/**
 * @ClassName: KafkaTransJob
 * @Description: kafka换号处理job
 * @author:liujian
 * @date:2018年8月1日下午2:26:55
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class KafkaTransJob {

	private static Logger logger = Logger.getLogger(KafkaTransJob.class);

	private static Logger log = Logger.getLogger("kfkchange");

	@Autowired
	private DictionaryDao dictionaryDao;

	@Autowired
	private MessageService messageService;

	@Autowired
	private KfkChangeNumDao KfkChangeNumDao;

	public void doProcess() throws Exception {
		if (dictionaryDao.getValue("recivemq").equals("0")) {
			logger.info("接收kafka换号job启动");
			long beginTime = System.currentTimeMillis();
			List<MessagePipe> list = messageService.reciveBatchMessage("kfkchange", 500);
			logger.info("接收kafka换号花费时间：" + (System.currentTimeMillis() - beginTime));
			List<KfkChangeNumBean> listPipe = new ArrayList<KfkChangeNumBean>();
			for (MessagePipe messagePipe : list) {
				KfkChangeNumBean kfkChangeNumBean = transBean(messagePipe.getBody());
				listPipe.add(kfkChangeNumBean);
			}
			handle(listPipe);
		} else {
			logger.info("停止接收kafka换号job");
		}
	}

	public void handle(List<KfkChangeNumBean> listPipe) {
		for (KfkChangeNumBean kfkChangeNumBean : listPipe) {
			Map<String, Object> logMap = new HashMap<String, Object>();
			logMap.put("userid", kfkChangeNumBean.getUserid());
			logMap.put("oldUserid", kfkChangeNumBean.getOldUserid());
			try {
				List<NetOrderBean> oldlist = KfkChangeNumDao.queryByUserid(kfkChangeNumBean.getOldUserid());
				logMap.put("oldlist", oldlist.size() + "");
				if (oldlist != null && oldlist.size() > 0) {
					List<Map<String, Object>> orderlist = order(kfkChangeNumBean, oldlist);
					logMap.put("neworder", orderlist);
					List<Map<String, Object>> cancellist = cancnel(oldlist);
					logMap.put("oldcancel", cancellist);
					for (NetOrderBean netOrderBean : oldlist) {
						if (netOrderBean.getSpid().equals("84")) {
							Map<String, Object> activityMap = handActivity(kfkChangeNumBean);
							logMap.put("activityinfo", activityMap);
							Map<String,Object> vacmap=vacQuery(kfkChangeNumBean.getUserid());
							logMap.put("vacHasOrder", vacmap);
						}
					}
				}
			} catch (Exception e) {
				logger.error("", e);
			}finally {
				log.info(JsonUtil.objectToJson(logMap));
			}
		}
	}
	
	/**
	* @Title: vacQuery 
	* @Description: 查询vac是否有0元的订购关系 
	* @param @param userid
	* @param @return 
	* @return Map<String,Object> 
	* @throws
	 */
	public Map<String,Object> vacQuery(String userid){
		Map<String,Object> logmap = new HashMap<String, Object>();
		try {
			VacOrder vacOrder = VacUtil.query(userid);
			VacOrderItem vacOrderItem = vacOrder.getItem("8000652500");
			if(vacOrderItem != null){
				logmap.put("vac", "0");
			}else{
				logmap.put("vac", "1");
			}
		} catch (Exception e) {
			logger.error("",e);
			logmap.put("vac", "3");
		}
		return logmap;
	}

	/**
	 * @Title: handActivity @Description: 处理和活动有关的产品 @param @param
	 *         kfkChangeNumBean @return void @throws
	 */
	public Map<String, Object> handActivity(KfkChangeNumBean kfkChangeNumBean) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			OrderBean newOrderBean = KfkChangeNumDao.existUser(kfkChangeNumBean.getUserid());
			if(newOrderBean== null ||(NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"))>NumberUtils.toLong(newOrderBean.getEndtime()))){
				copyUsermsg(kfkChangeNumBean);
				map.put("usermsg", "0");
				copyVacMsg(kfkChangeNumBean);
				map.put("vaccontrol", "0");
				copygGiveVipMsg(kfkChangeNumBean);
				map.put("vipcontrol", "0");
				OrderBean orderBean = KfkChangeNumDao.existUser(kfkChangeNumBean.getOldUserid());
				if (orderBean != null) {
					if(newOrderBean == null){
						copyActivityMsg(kfkChangeNumBean,orderBean.getId());
					}else{
						KfkChangeNumDao.updateAcative(orderBean.getId(),newOrderBean.getId());
					}
					map.put("activity", "0");
					if (orderBean.getOrderstatus().equals("0")) {
						cancelActivity(orderBean.getId());
						map.put("cancelActivity", "0");
					}else{
						map.put("cancelActivity", "1");
					}
				} else {
					map.put("activity", "1");// 活动表无数据
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return map;
	}

	/**
	 * @throws SQLException
	 * @Title: cancelActivity @Description: 退订老号码的活动信息 @param @param
	 *         kfkChangeNumBean @return void @throws
	 */
	public void cancelActivity(String id) throws SQLException {
		KfkChangeNumDao.cancelActivity(id);
	}

	/**
	 * @throws Exception
	 * @Title: copyUsermsg @Description: 复制用户信息 @param @param
	 *         kfkChangeNumBean @return void @throws
	 */
	public void copyUsermsg(KfkChangeNumBean kfkChangeNumBean) throws Exception {
		KfkChangeNumDao.copyUserMsg(kfkChangeNumBean.getUserid(), kfkChangeNumBean.getOldUserid());
	}

	/**
	 * @Title: copyVacMsg @Description: 复制用户扣费信息 @param @param
	 *         kfkChangeNumBean @return void @throws
	 */
	public void copyVacMsg(KfkChangeNumBean kfkChangeNumBean) throws Exception {
		KfkChangeNumDao.copyVacMsg(kfkChangeNumBean.getUserid(), kfkChangeNumBean.getOldUserid());
	}

	/**
	 * @Title: copygGiveVipMsg @Description: 复制用户领取会员信息 @param @param
	 *         kfkChangeNumBean @return void @throws
	 */
	public void copygGiveVipMsg(KfkChangeNumBean kfkChangeNumBean) throws Exception {
		KfkChangeNumDao.copyGiveVipMsg(kfkChangeNumBean.getUserid(), kfkChangeNumBean.getOldUserid());
	}

	/**
	 * @Title: copyActivityMsg @Description: 复制用户活动信息 @param @param
	 *         kfkChangeNumBean @return void @throws
	 */
	public void copyActivityMsg(KfkChangeNumBean kfkChangeNumBean,String id) throws Exception {
		KfkChangeNumDao.copyActivityMsg(kfkChangeNumBean.getUserid(), id);
	}

	/**
	 * 退订老号码的wo+15元的订购关系 @Title: cancnelOrder @Description: TODO @param @param
	 * userid @return void @throws
	 * 
	 * @throws Exception
	 */
	public List<Map<String, Object>> cancnel(List<NetOrderBean> oldlist) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (NetOrderBean netOrderBean : oldlist) {
			Map<String, Object> logMap = new HashMap<String, Object>();
			logMap.put("cpid", netOrderBean.getCpid());
			logMap.put("spid", netOrderBean.getSpid());
			try {
				if(netOrderBean.getStatus().equals("0")){
					netOrderBean.setCancelchannel("kfkchange");
					KfkChangeNumDao.cancelOrder(netOrderBean.getId());
					addlog(netOrderBean, "0", "", "1");
					logMap.put("result", "0");//老用户退订
				}else{
					logMap.put("result", "1");//老用户已退订
				}
			} catch (Exception e) {
				logger.error("", e);
				logMap.put("result", "3");
			} finally {
				list.add(logMap);
			}
		}
		return list;
	}

	/**
	 * @throws Exception
	 * @Title: order @Description: 订购老号码所存在的wo+15元订购关系 @param @param
	 *         KfkChangeNumBean @return void @throws
	 */
	public List<Map<String, Object>> order(KfkChangeNumBean kfkChangeNumBean, List<NetOrderBean> oldlist)
			throws Exception {
		List<NetOrderBean> newlist = KfkChangeNumDao.queryByUserid(kfkChangeNumBean.getUserid());
		List<Map<String, Object>> loglist = new ArrayList<Map<String, Object>>();
		for (NetOrderBean netOrderBean : oldlist) {
			Map<String, Object> logMap = new HashMap<String, Object>();
			logMap.put("cpid", netOrderBean.getCpid());
			logMap.put("spid", netOrderBean.getSpid());
			try {
				boolean hasOrder = true;
				if (newlist != null && newlist.size() > 0) {
					for (NetOrderBean newUserNetOrderBean : newlist) {
						if (netOrderBean.getSpid().equals(newUserNetOrderBean.getSpid())) {
							logMap.put("orderresult", "2");// 已有有效订购关系不需要重新
							hasOrder = false;
						}
					}
				}
				if (hasOrder) {
					NetOrderBean newNetOrderBean = new NetOrderBean();
					BeanUtils.copyProperties(newNetOrderBean, netOrderBean);
					newNetOrderBean.setUserid(kfkChangeNumBean.getUserid());
					newNetOrderBean.setOrderchannel("kfkchange");
					newNetOrderBean.setOrderstatus(3);
					logMap.put("orderresult", "0");// 生成订购状态的订购关系
					if (!netOrderBean.getStatus().equals("0")) {
						newNetOrderBean.setCancelchannel("kfkchange");
						newNetOrderBean.setOrderstatus(5);
						logMap.put("orderresult", "1");// 生成退订状态的订购关系
					}
					KfkChangeNumDao.order(newNetOrderBean);
					addlog(newNetOrderBean, "0", "", netOrderBean.getStatus());
				}
			} catch (Exception e) {
				logger.error("", e);
				logMap.put("orderresult", "3");
			} finally {
				loglist.add(logMap);
			}
		}
		return loglist;
	}

	/**
	 * @Title: activity @Description: 生成活动的活动关系 @param @param userid @return
	 *         void @throws
	 * @throws Exception
	 */
	public void activity(List<NetOrderBean> oldlist) throws Exception {
		for (NetOrderBean netOrderBean : oldlist) {
			KfkChangeNumDao.cancelOrder(netOrderBean.getId());
		}
	}

	public KfkChangeNumBean transBean(Map<String, Object> body) {
		String jsonStr = JsonUtil.objectToJson(body);
		return (KfkChangeNumBean) JsonUtil.jsonToBean(jsonStr, KfkChangeNumBean.class);
	}

	public void addlog(NetOrderBean netOrderBean, String resultcode, String errorinfo, String type) throws Exception {
		OrderLog orderLog = new OrderLog();
		orderLog.setUserid(netOrderBean.getUserid());
		orderLog.setArea(netOrderBean.getArea());
		orderLog.setProvince(netOrderBean.getProvince());
		orderLog.setErrorcode(resultcode);
		orderLog.setErrorinfo(errorinfo);
		orderLog.setOrderstatus(type.equals("0") ? 3 : 5);
		orderLog.setChannel(type.equals("0") ? netOrderBean.getOrderchannel() : netOrderBean.getCancelchannel());
		orderLog.setCpid(netOrderBean.getCpid());
		orderLog.setSpid(netOrderBean.getSpid());
		orderLog.setStatus(Integer.valueOf(type));
		KfkChangeNumDao.addOrderLog(orderLog);
	}
}
