package com.chinacreator.process.job;


import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import net.sf.json.JSONObject;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.common.util.DESUtil;
import com.chinacreator.common.util.MD5;
import com.chinacreator.common.util.URLUtil;
import com.chinacreator.process.bean.NetOrderBean;
import com.chinacreator.process.bean.OrderBean;
import com.chinacreator.process.bean.OrderConfigBean;
import com.chinacreator.process.bean.OrderLog;
import com.chinacreator.process.bean.PointShopMqBean;
import com.chinacreator.process.bean.PointShopOrderBean;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.PointShopDao;
import com.chinacreator.process.dao.YoutuActiveDao;
import com.chinacreator.process.util.HttpInvoke;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.video.queue.MessageService;
import com.chinacreator.video.queue.bean.MessagePipe;

/**
 * 优酷第四季度双倍会员-胡丹丹
 * @author xu.zhou
 * @date 20191111
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class YoutuVipMQJob {

	private Logger logger = Logger.getLogger(YoutuVipMQJob.class);
	
	private Logger log = Logger.getLogger("youtuvip");

	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	private YoutuActiveDao youtoActiveDao;

	@Autowired
	private MessageService messageService;

	public void doProcess() throws Exception {
		logger.info("接收优酷赠送会员队列JOB启动");
		if (dictionaryDao.getValue("recivemq").equals("0")) {
			long beginTime = System.currentTimeMillis();
			List<MessagePipe> list = messageService.reciveBatchMessage("youtuvip", 500);
			logger.info("接收优酷赠送会员队列花费时间：" + (System.currentTimeMillis() - beginTime));
			List<Map> dataList = new ArrayList<Map>();
			for (MessagePipe messagePipe : list) {
				Map reqBean = transBean(messagePipe.getBody());
				dataList.add(reqBean);
			}
		    //{"spid":"1167","userid":"18673197465","cpid":"youtu","sendcont":"1"}
			List<Map> notrepeatList = getNotRepeatData(dataList);
			if(notrepeatList != null && notrepeatList.size()>0){
				for (Map reqBean  : notrepeatList) {
					 this.handleOrder(reqBean);
			    }
			}
		} else {
			logger.info("停止接收优酷赠送会员队列消息");
		}
	}
	
	/**
	 * 业务处理
	 * @param mqBean
	 */
	public void handleOrder(Map reqBean){
		Map logMap = new HashMap();
		logMap.put("data", reqBean);
		String resultCode = "-1";
		String resultInfo = "";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 
			String currtime = sdf.format(new Date()); //当前时间		
			String youtuVipEndtime = dictionaryDao.getValue("youtuVipEndtime");
			if(youtuVipEndtime == null || "".equals(youtuVipEndtime)){
				throw new BusinessException("8001", "无结束时间配置");
			}
			
			if(Long.parseLong(currtime) > Long.parseLong(youtuVipEndtime)){
				throw new BusinessException("8002", "活动已结束");
			}
			
			if(!this.hasEffect(reqBean)){
				throw new BusinessException("8003", "无有效订购信息，不赠送会员");
			}
			
			Map<String, String> reMap = sendVip(reqBean);

			if(!"0".equals(reMap.get("resultcode"))){//赠送未成功
				resultCode = reMap.get("resultcode");
				resultInfo = reMap.get("resultinfo");
			}else{
				resultCode = "0";
				resultInfo = "成功";
			}
		} catch (Exception e) {
			if (e instanceof BusinessException) {
				resultInfo = ((BusinessException) e).getMessage();
				resultCode = ((BusinessException) e).getCode();
			}else{
				e.printStackTrace();
				resultCode = "8000";
				resultInfo = "系统错误，"+e.getMessage();
			}
		} finally{
			if(!"0".equals(resultCode)){
				//未成功，重试赠送会员
				inserVipRetryMq(reqBean);
			}
			
			//写日志
			logMap.put("reusltCode", resultCode);
			logMap.put("resultInfo", resultInfo);
			log.info(JsonUtil.objectToJson(logMap));
		}
	}
	
	/**
	 * 查询本地订购关系表当前是否有已生效的订购关系
	 * @param orderInfo
	 * @return
	 * @throws Exception
	 */
	private boolean hasEffect(Map reqBean) throws Exception{
		boolean hasEffect = false;
	    //查询用户本地订购关系表未失效的订购数据
		List<NetOrderBean> orderList = youtoActiveDao.findOrder("youtu",reqBean.get("userid")+"","1167");
		if(orderList != null && orderList.size()>0){//本地有订购关系	
			for(NetOrderBean bean : orderList){
				if("0".equals(bean.getStatus()) || "1".equals(bean.getStatus())){
					hasEffect = true; 
					break;
				}
			}
		}

		return hasEffect;
	}

	
	/**
	 * 赠送会员
	 * @param orderInfo
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> sendVip(Map reqBean){
		Map<String, String> reMap = new HashMap<String,String>();
		String resultcode = "-1"; //失败
		String resultinfo = ""; //失败
		try {
			//测试地址：http://114.255.201.228:86/activity/joinYouku20Vip
			//正式地址：http://114.255.201.238:8090/video-activity/joinYouku20Vip
			String vipurl = this.dictionaryDao.getValue("youtuVipUrlAddr");
			String timestamp = (System.currentTimeMillis() / 1000) + "";
			String userid = (String)reqBean.get("userid");
			String channel = "youtu";
			String activetype = "27";
			String pwd = "ea044e50";
			userid = DESUtil.encode(userid, pwd);
			String signature = MD5.MD5Encode( userid + pwd + timestamp);
			signature = signature.toLowerCase();
			vipurl = vipurl + "?userid=" + URLEncoder.encode(userid, "utf-8")+ "&channel=" + channel + "&activetype=" + activetype + "&timestamp="
					+ timestamp + "&signature=" + signature;
			logger.info("vipurl: "+vipurl);
			String result = URLUtil.get(vipurl,10*1000); //调赠送会员接口，超时时间设置为10秒
			log.info("赠送会员结果=> userid: " +userid+" , result: "+result);
			Map<?,?> map = JsonUtil.jsonToMap(result);
			resultcode = (String)map.get("resultcode");
			resultinfo = (String)map.get("errorinfo");		
		} catch (Exception e) {
			e.printStackTrace();
			log.error("userid: "+reqBean.get("userid")+"赠送会员失败，"+e);
			resultcode = "8000";
			resultinfo = e.getMessage();
		}
		
		reMap.put("resultcode", resultcode);
		reMap.put("resultinfo", resultinfo);
		
		return reMap;
	}
	
		
	/**
	 * 去重复数据
	 * @param oldBeans
	 * @return
	 */
	public List<Map> getNotRepeatData( List<Map> oldBeans){

		  List<Map> newBeans = new ArrayList<Map>();
		  Map<String,Map> map = new HashMap<String, Map>();
		  for (Map reqBean : oldBeans) {
			  if(map.containsKey(reqBean.get("userid"))){
				  //insertvacMq(bean);
			  }else{
				  map.put(reqBean.get("userid").toString(), reqBean);
			  }
		  }
		  Iterator<String> it = map.keySet().iterator();  
	      while (it.hasNext()) {  
	          String key = it.next().toString();  
	          newBeans.add(map.get(key));  
	      }
	      logger.info("优酷赠送会员:old="+oldBeans.size()+"  new:"+newBeans.size());
		  return newBeans;
	  }

	/**
	 * 解析数据
	 * @param body
	 * orderId TD_POINTS_ORDER_REC表ID字段，我方生成的订单流水号
     * orderNo 积分商城订单号
     * requestId 返回给客户的请求ID
	 * @return
	 */
	public Map transBean(Map<String, Object> body) {
		String jsonStr = JsonUtil.objectToJson(body);
		return (Map) JsonUtil.jsonToBean(jsonStr, Map.class);
	}
	
	/**
	 * 发送赠送成功短信队列推送
	 * @param psoBean
	 * @param resultCode
	 */
//	public void inserSmstMq(Map reqBean){
//		try{
//			if(reqBean != null){
//				Map<String, String> map = new HashMap<String, String>();
//				map.put("userid", (String)reqBean.get("userid"));
//				map.put("cpid", (String)reqBean.get("cpid"));
//				map.put("spid", (String)reqBean.get("spid"));
//				map.put("result", "0");
//				map.put("channel", "");
//				map.put("style","0000");
//				map.put("times", "");
//				map.put("orderType", "");
//				map.put("type", "cssms");
//				map.put("busiType", "vipsend_succ");
//				logger.info(JsonUtil.objectToJson(map));
//				String  mqReciveUrl = dictionaryDao.getValue("mqReciveUrl");
//				URLUtil.post(mqReciveUrl, JsonUtil.objectToJson(map));
//			}
//		}catch (Exception e){
//			e.printStackTrace();
//			log.error("发送赠送成功短信队列推送出现异常，"+e.getMessage());
//		}
//	}
	
	 /**
     * 获取请求属性性
     * @return
     */
    private static Map getProperty(){
    	 Map reqProperty = new HashMap();
    	 reqProperty.put("Content-type", "application/json;charset=UTF-8");
    	 return reqProperty;
    }
    
    /*
	 * 赠送会员超时异步重试队列推送，最多重试三次
	 * @param orderInfo
	 */
	public void inserVipRetryMq(Map reqBean){
		try {
			String sendcont = (String)reqBean.get("sendcont");
			if("3".equals(sendcont)){
				return;
			}
			MessagePipe mpipe = new MessagePipe();
			mpipe.setHeader("youtuvip");
			mpipe.addBody("userid", (String)reqBean.get("userid"));
			mpipe.addBody("cpid",  (String)reqBean.get("cpid"));
			mpipe.addBody("spid",  (String)reqBean.get("spid"));
			mpipe.addBody("sendcont",(Integer.parseInt(sendcont)+1)+"");
			this.messageService.sendMessage(mpipe);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("赠送会员超时异步重试队列推送出现异常，"+e.getMessage());
		}	
	}
}
