package com.chinacreator.process.job;


import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
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.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.BackBusiOrderRec;
import com.chinacreator.process.bean.BackShareOrderBean;
import com.chinacreator.process.bean.OrderLog;
import com.chinacreator.process.bean.PointShopOrderBean;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.PointShopDao;
import com.chinacreator.process.dao.VipRetryDao;
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 20190622
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class VipRetryMQJob {

	private Logger logger = Logger.getLogger(VipRetryMQJob.class);
	
	private Logger log = Logger.getLogger("vipretry");

	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	private VipRetryDao vipRetryDao;
	
	@Autowired
	private PointShopDao pointShopDao;

	@Autowired
	private MessageService messageService;

	public void doProcess() throws Exception {
		logger.info("接收vipretry队列JOB启动");
		if (dictionaryDao.getValue("recivemq").equals("0")) {
			long beginTime = System.currentTimeMillis();
			List<MessagePipe> list = messageService.reciveBatchMessage("vipretry", 500);
			logger.info("接收vipretry队列花费时间：" + (System.currentTimeMillis() - beginTime));
			List<Map> dataList = new ArrayList<Map>();
			for (MessagePipe messagePipe : list) {
				Map reqBean = transBean(messagePipe.getBody());
				dataList.add(reqBean);
			}
			
			//{id=201907181120199638342, userid=18673197465, orderid=bd84d022-5bd6-4e71-b8ef-52a347fe4994, type=vipretry}
//			List<Map> dataList = new ArrayList<Map>();
//			Map<String, Object> body = new HashMap<String, Object>();
//			body.put("userid", "18673197465");
//			body.put("orderid", "bd84d022-5bd6-4e71-b8ef-52a347fe4994");
//			body.put("id", "201907181120199638342");
//			dataList.add(body);

			//去重复数据
			List<Map> notrepeatList = getNotRepeatData(dataList);
			if(notrepeatList != null && notrepeatList.size()>0){
				for (Map reqBean : notrepeatList) {
					 this.handleOrder(reqBean);
			     }
			}
		} else {
			logger.info("停止接收vipretry队列消息");
		}
	}
	
	
	public void handleOrder(Map reqBean){
		try {
			PointShopOrderBean orderBean = vipRetryDao.getPSOrderRec(reqBean.get("id")+"");
			if(orderBean != null){
				log.info(reqBean.get("id")+"=>积分商城会员重试");
				handleOrderPointShop(reqBean); //积分商城业务
			}else{
				log.info(reqBean.get("id")+"=>后向专属会员重试");
				handleOrderBack(reqBean); //后向专属业务
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 积分商城业务处理
	 * @param psqBean
	 */
	public void handleOrderPointShop(Map reqBean){
		Map logMap = new HashMap();
		logMap.put("data", reqBean);
		BackBusiOrderRec orderBean = null;
		PointShopOrderBean psoBean = null;
		String resultCode = "-1";
		String resultInfo = "";
		String huchiSpid = ""; //互斥业务ID，如果不为空，则业务互斥
		try {
			//获取订单信息
			orderBean = vipRetryDao.getOrderRec(reqBean.get("id")+"");
			if(orderBean == null 
					|| !orderBean.getOrderid().equals(reqBean.get("orderid")) 
					|| !orderBean.getUserid().equals(reqBean.get("userid"))){
				throw new BusinessException("9071", "无对应订单信息，"+reqBean.get("id"));
			}
			psoBean = pointShopDao.getOrderRec(reqBean.get("id")+"");

			//5代表赠送会员超时
			if(!"5".equals(orderBean.getVipstatus())){
				//throw new BusinessException("9072", "vip处理状态异常，"+orderBean.getVipstatus());
			}
			
			//判断重试时间是否大于订购记录时间2分钟以上，防止并发请求
			if(!vipRetryDao.getMinNum(orderBean.getInserttime(),2)){
				throw new BusinessException("9073", "重试时间与订购时间相差小于2分钟");
			}
			
			//判断业务互斥
			huchiSpid = checkMutual(orderBean); //判断业务互斥
			if(!"".equals(huchiSpid)){
				orderBean.setVipstatus("4"); //设置为不赠送
				throw new BusinessException("9003","已办理互斥业务");
			}
			
			//获取业务结束时间
			String newEndtime = this.getEndTime(orderBean);
			
			//VIPSTATUS IS '赠送会员状态，0成功，1待赠送，2赠送中，3失败，4不赠送，5返回9070，，7重试失败
			orderBean.setVipstatus("2");
			orderBean.setResultcode("2");
			orderBean.setResultinfo("重试中");
			vipRetryDao.updBusiStatus(orderBean,"TD_BACKBUSI_ORDER_REC");
			vipRetryDao.updBusiStatus(orderBean,"TD_POINTS_ORDER_REC");
			String sendVipRes = sendVip(orderBean); //赠送会员
			if("9070".equals(sendVipRes)){
				orderBean.setVipstatus("5"); //赠送超时
				throw new BusinessException("9070","赠送会员超时", new String[0]);
			}
			//小毛会更新vipstatus值，不以接口返回的为准
			if(!"0".equals(sendVipRes)){ //赠送失败，再查记录表状态，（成功后小毛会改为0）
				sendVipRes = vipRetryDao.getVipstatus(orderBean.getId());
			}
			//赠送成功
			if("0".equals(sendVipRes)){
				orderBean.setVipstatus("0");
				if("3".equals(orderBean.getBusitype())){//会员+免流，入订购关系
//					String newEndtime = vipRetryDao.curr31Day();	
//					//查询本地订购关系表当前是否有已生效的订购关系
//					Map reMap = this.hasEffect(orderBean);
//					if((Boolean)reMap.get("hasEffect")){ //存在有效订购关系
//						Map currOrderInfo = (Map)reMap.get("currOrderInfo");
//						newEndtime = vipRetryDao.endtime31Day(currOrderInfo.get("ENDTIME").toString());
//					}
					orderBean.setEndtime(newEndtime);
					vipRetryDao.order(orderBean); //新增或更新订购关系
				}
			}else{
				orderBean.setVipstatus("7");
				throw new BusinessException("9002","赠送会员未成功", new String[0]);
			}

			resultCode = "0";
			resultInfo = "重试成功";
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof BusinessException) {
				resultInfo =  ((BusinessException) e).getMessage();
				resultCode = ((BusinessException) e).getCode();
			}else{
				resultCode = "8000";
				resultInfo = "系统错误，"+e.getMessage();
			}
		} finally{
			String bcstatus = "";
			//存在有效订购记录，更新订购操作表信息:9071无订购信息，9072vip处理状态异常，9073时间不合法
			if(orderBean != null && !"9071".equals(resultCode) && !"9072".equals(resultCode) && !"9073".equals(resultCode)){
				orderBean.setResultcode(resultCode);
				orderBean.setResultinfo(resultInfo);
				orderBean.setRetrychannel("0");
				orderBean.setRetrycount(Integer.parseInt(orderBean.getRetrycount())+1+"");
				vipRetryDao.updOrderRecByVipRetry(orderBean); //更新订购记录表数据
				psoBean.setVipstatus(orderBean.getVipstatus());
				psoBean.setResultCode(orderBean.getResultcode());
				psoBean.setResultInfo(orderBean.getResultinfo());
				pointShopDao.updBusiStatus(psoBean, "TD_POINTS_ORDER_REC");
				//回调通知
				bcstatus = this.callBackPointShop(psoBean.getId(),psoBean.getRequestId());			
				//记录订购日志
				saveOrderLog(orderBean);
			}
		
			//充值成功发送短信
			if("0".equals(orderBean.getResultcode())){
				inserSmstMq(orderBean); //成功发短信
			}
			
			//发送业务互斥短信
			if("9003".equals(resultCode)){
				//this.inserSmstMqHuChi(orderBean,huchiSpid); //发送业务互斥短信
			}
			
			//重试时间不合法，重新掖入到队列
			if("9073".equals(resultCode)){
				inserVipRetryMq(orderBean);
			}
			logMap.put("data2", orderBean);
			logMap.put("reusltCode", resultCode);
			logMap.put("resultInfo", resultInfo);
			logMap.put("bcstatus", bcstatus);
			log.info(JsonUtil.objectToJson(logMap));
		}
	}
	
	/**
	 * 业务处理
	 * @param psqBean
	 */
	public void handleOrderBack(Map reqBean){
		Map logMap = new HashMap();
		logMap.put("data", reqBean);
		BackBusiOrderRec orderBean = null;
		String resultCode = "-1";
		String resultInfo = "";
		String huchiSpid = ""; //互斥业务ID，如果不为空，则业务互斥
		try {
			//获取订单信息
			orderBean = vipRetryDao.getOrderRec(reqBean.get("id").toString());
			if(orderBean == null 
					|| !orderBean.getOrderid().equals(reqBean.get("orderid")) 
					|| !orderBean.getUserid().equals(reqBean.get("userid"))){
				throw new BusinessException("9071", "无对应订单信息，"+reqBean.get("id"));
			}
			//5代表赠送会员超时
			if(!"5".equals(orderBean.getVipstatus())){
				//throw new BusinessException("9072", "vip处理状态异常，"+orderBean.getVipstatus());
			}
			
			//判断重试时间是否大于订购记录时间2分钟以上，防止并发请求
			if(!vipRetryDao.getMinNum(orderBean.getInserttime(),2)){
				throw new BusinessException("9073", "重试时间与订购时间相差小于2分钟");
			}
			
			//判断业务互斥
			huchiSpid = checkMutual(orderBean); //判断业务互斥
			if(!"".equals(huchiSpid)){
				orderBean.setVipstatus("4"); //设置为不赠送
				throw new BusinessException("9003","已办理互斥业务");
			}
			
			List<HashMap> confList = vipRetryDao.getBackBusiConf(orderBean.getCpid(), orderBean.getSpid());
			HashMap confHm = confList.get(0);
			//是否为复合产品，0是，为空或为1时不是
			String hasfh = confHm.get("HASFH") == null ? "": confHm.get("HASFH")+"";
			//调能力平台标识：0调能力平台并以结果落订购关系，1调能力平台其结果不影响订购关系，为空时不调能力平台
			String hasshare = confHm.get("HASSHARE") == null ? "": confHm.get("HASSHARE")+"";
			
			//获取业务结束时间
			String newEndtime = this.getEndTime(orderBean);
			
			//VIPSTATUS IS '赠送会员状态，0成功，1待赠送，2赠送中，3失败，4不赠送，5返回9070，，7重试失败
			orderBean.setVipstatus("2");
			orderBean.setResultcode("2");
			orderBean.setResultinfo("重试中");
			vipRetryDao.updBusiStatus(orderBean,"TD_BACKBUSI_ORDER_REC");
			String sendVipRes = sendVip(orderBean); //赠送会员
			if("9070".equals(sendVipRes)){
				orderBean.setVipstatus("5"); //赠送超时
				throw new BusinessException("9070","赠送会员超时", new String[0]);
			}
			//小毛会更新vipstatus值，不以接口返回的为准
			if(!"0".equals(sendVipRes)){ //赠送失败，再查记录表状态，（成功后小毛会改为0）
				if("0".equals(hasfh)){//是复合产品
					//0：成功, -1：部分成功 , 1：失败, 其他可以作为超时处理。
					if("-1".equals(sendVipRes)){//部分成功
						sendVipRes = "0";
						orderBean.setResultinfo("部分成功");
					}
				}else{
					sendVipRes = vipRetryDao.getVipstatus(orderBean.getId());
				}
			}
			//赠送成功
			if("0".equals(sendVipRes)){
				orderBean.setVipstatus("0");
				if("3".equals(orderBean.getBusitype())){//会员+免流，入订购关系
//					String newEndtime = vipRetryDao.curr31Day();	
//					//查询本地订购关系表当前是否有已生效的订购关系
//					Map reMap = this.hasEffect(orderBean);
//					if((Boolean)reMap.get("hasEffect")){ //存在有效订购关系
//						Map currOrderInfo = (Map)reMap.get("currOrderInfo");
//						newEndtime = vipRetryDao.endtime31Day(currOrderInfo.get("ENDTIME").toString());
//					}
					orderBean.setEndtime(newEndtime);
					orderBean.setOrderchannle(orderBean.getChannel());
					orderBean.setChannel("");
					//调能力平台
					this.shareOrder(orderBean, hasshare);
					vipRetryDao.order(orderBean); //新增或更新订购关系
				}
			}else{
				orderBean.setVipstatus("7");
				throw new BusinessException("9002","赠送会员未成功", new String[0]);
			}

			resultCode = "0";
			resultInfo = "重试成功";
			
			if("部分成功".equals(orderBean.getResultinfo())){
				resultInfo = "部分成功";
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof BusinessException) {
				resultInfo = e.getMessage();
				resultCode = ((BusinessException) e).getCode();
			}else{
				resultCode = "8000";
				resultInfo = "系统错误，"+e.getMessage();
			}
		} finally{
			String bcstatus = "";
			//存在有效订购记录，更新订购操作表信息
			if(!"9071".equals(resultCode) && !"9072".equals(resultCode) && !"9073".equals(resultCode)){
				orderBean.setResultcode(resultCode);
				orderBean.setResultinfo(resultInfo);
				orderBean.setRetrychannel("0");
				orderBean.setRetrycount(Integer.parseInt(orderBean.getRetrycount())+1+"");
				vipRetryDao.updOrderRecByVipRetry(orderBean); //更新订购记录表数据
				//回调通知
				bcstatus = this.callBack(orderBean);
				
				//记录订购日志
				saveOrderLog(orderBean);
			}
		
			//充值成功发送短信
			if("0".equals(orderBean.getResultcode())){
				inserSmstMq(orderBean); //成功发短信
			}
			
			//重试时间不合法，重新掖入到队列
			if("9073".equals(resultCode)){
				inserVipRetryMq(orderBean); 
			}
			logMap.put("data2", orderBean);
			logMap.put("reusltCode", resultCode);
			logMap.put("resultInfo", resultInfo);
			logMap.put("bcstatus", bcstatus);
			log.info(JsonUtil.objectToJson(logMap));
		}
	}
	
	/**
	 * 写订购日志
	 * @param orderInfo
	 * @param errorcode
	 * @param errorinfo
	 */
	private void saveOrderLog(BackBusiOrderRec orderBean){
		try {
			OrderLog orderLog = new OrderLog();
			orderLog.setApptype("2");
			orderLog.setArea(orderBean.getArea());
			orderLog.setChannel(orderBean.getChannel());
			orderLog.setOrderstatus(0);
			orderLog.setStatus(0);
			orderLog.setCpid(orderBean.getCpid());
			orderLog.setIsexperience(0);
			orderLog.setOrdertype("0");
			orderLog.setProvince(orderBean.getProvince());
			orderLog.setSpid(orderBean.getSpid());
			orderLog.setErrorcode(orderBean.getResultcode());
			orderLog.setErrorinfo(orderBean.getResultinfo());				
			orderLog.setUserid(orderBean.getUserid().trim());	
			this.vipRetryDao.addOrderLog(orderLog);
		} catch (Exception e) {
			log.error("orderId: "+orderBean.getId()+", 添加日志出现异常，"+e.getMessage());
			e.printStackTrace();
		}	
	}
	
	/**
	 * 查询本地订购关系表当前是否有已生效的订购关系
	 * @param orderInfo
	 * @return
	 * @throws Exception
	 */
	private Map hasEffect(BackBusiOrderRec orderBean) throws Exception{
		Map reMap = new HashMap();
		boolean hasEffect = false;
		Map currOrderInfo = null;
		String currentTime = vipRetryDao.currTime();
	    //查询用户本地订购关系表未失效的订购数据
		currOrderInfo = vipRetryDao.findByUserAndSpid(orderBean.getUserid(),orderBean.getCpid(),orderBean.getSpid());
		if(currOrderInfo != null){//本地有订购关系
			if(Long.parseLong(currOrderInfo.get("ENDTIME").toString()) >= Long.parseLong(currentTime)){ //结束时间大于或等于当前时间，订购关系有效
				hasEffect = true; 
			}
		}
		reMap.put("hasEffect", hasEffect);
		reMap.put("currOrderInfo", currOrderInfo);
		return reMap;
	}
	

	/**
	 * 判断业务是否互斥
	 * @param orderInfo
	 * @throws Exception
	 */
	private String checkMutual(BackBusiOrderRec orderBean) throws Exception{
		String huchiSpid = "";
		boolean result = false;
		String spid = orderBean.getSpid();
		List<HashMap> spList = vipRetryDao.findSpInfo(spid);
		if(spList != null && spList.size()>0){
			if (spList.get(0).get("MUTEX") != null && !StringUtils.isEmpty(spList.get(0).get("MUTEX").toString())) {
				String[] mutexSpids = spList.get(0).get("MUTEX").toString().trim().split(",");					
				//[{ORDERIDA=2019052, AREA=长沙, SPID=1167, PROVINCE=湖南, ID=201905241107578658666, ORDERCHANNEL=t, STATUS=1, ORDERTIME=20190524104129, USERID=18673197465, CPID=youtu}]
			    //查询用户本地订购关系表未失效的订购数据
			 	List<HashMap> list = vipRetryDao.findOrderRelaAll(orderBean.getUserid());	
				if (list != null && list.size() > 0) {
					for (String mutexSpid : mutexSpids) {
						for (HashMap hm : list) {
							if (hm.get("SPID") != null && !hm.get("SPID").equals(spid) && hm.get("SPID").equals(mutexSpid)
									&& !"2".equals(hm.get("STATUS"))) {
								huchiSpid = hm.get("SPID")+"";
								result = true;
								break;
							}
						}
					}
				}
			}
		}
		return huchiSpid;
	}
	
	/**
	 * 调接口送会员
	 * @param orderInfo
	 * @return
	 * @throws Exception 
	 */
	private String sendVip(BackBusiOrderRec orderBean) throws Exception{
		String resultcode = "3";
		try {
			//http://114.255.201.228:86/activity/youkuHX
			String vipurl = this.dictionaryDao.getValue("backBusiVipUrl");
			String timestamp = (System.currentTimeMillis() / 1000) + "";
			String userid = orderBean.getUserid();
			String orderid = orderBean.getOrderid();
			String channel = orderBean.getChannel();
			String cpid = orderBean.getCpid();
			String spid = orderBean.getSpid();
			String pwd = "";
			List<HashMap> confList = vipRetryDao.getBackBusiConf(cpid, spid);
			pwd = confList.get(0).get("PWD").toString();
			if("0".equals(confList.get(0).get("HASFH"))){ //是复合产品
				vipurl = this.dictionaryDao.getValue("backBusiGroupVipUrl");
			}
			userid = DESUtil.encode(userid, pwd);
			//MD5(orderid+userid+goodscode+pwd+timestamp)转换为十六进制ASCII 码字符串，共32 个字符，全小写 userid= Des(手机号码，pwd)
			//MD5(orderid+userid+timestamp+pwd)转换为十六进制ASCII 码字符串，共32 个字符，全小写
			String signature = MD5.MD5Encode(orderid + userid + timestamp + pwd);
			signature = signature.toLowerCase();
			vipurl = vipurl + "?userid=" + URLEncoder.encode(userid, "utf-8")+ "&orderid="+ orderid + "&cpid=" + cpid + "&spid=" + spid + "&timestamp="
					+ timestamp + "&signature=" + signature+ "&apptype=2";
			logger.info("vipurl: "+vipurl);
			//http://114.255.201.228:86/activity/eshop/vip?userid=iafPbU9aRLghY%2FEVMXFeag%3D%3D&orderid=201906231206498662914&goodscode=pointshop130&timestamp=1561445765&signature=47fe0e3900b29ef88fd0889b7c0e4cc6&apptype=5
			String result = URLUtil.get(vipurl,30*1000); //调赠送会员接口，超时时间设置为10秒
			log.info("赠送会员重试结果=> userid: " +userid+", orderid: "+orderBean.getOrderid()+" , result: "+result);
			Map<?,?> map = JsonUtil.jsonToMap(result);
			resultcode = (String)map.get("resultcode");
			if(resultcode.equals("0")){
				logger.info("赠送成功");
			}		
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("userid: "+orderBean.getUserid()+"赠送会员失败，"+e);
			if(e.getMessage() != null && e.getMessage().indexOf("TimeoutException") != -1){//超时异常
				orderBean.setVipstatus("5"); //赠送超时
				throw new BusinessException("9070","赠送会员超时", new String[0]);
			}else{
				orderBean.setVipstatus("7");
				throw new BusinessException("9002","赠送会员未成功", new String[0]);
			}
		}
		
		return resultcode;
	}
	
    /**
     *  回调通知
     * @param orderBean
     * @return 0成功，1未回调，2出现异常
     */
    private String callBack(BackBusiOrderRec orderBean){
    	String resultcode = "1"; 
    	try {
    		String userid = orderBean.getUserid();
    		HashMap channelInfo = vipRetryDao.getChannelPwdByChannel(orderBean.getChannel());
    		if(channelInfo == null || channelInfo.size() == 0){
    			channelInfo = vipRetryDao.getChannelPwdByChannel(orderBean.getOrderchannle());
    		}
    		String pwd = channelInfo.get("PASSWORD")+"";
    		userid = DESUtil.encode(userid, pwd);
    		userid =  URLEncoder.encode(userid, "utf-8");
			String vipRetryCallBackUrl = this.dictionaryDao.getValue("vipRetryCallBackUrl");//回调接口地址
			vipRetryCallBackUrl += "?orderid="+orderBean.getOrderid()+"&resultcode="+orderBean.getResultcode()+"&resultinfo="+URLEncoder.encode(orderBean.getResultinfo(),"utf-8")+"&userid="+userid;	
			log.info("===========回调地址："+vipRetryCallBackUrl);
			String result = URLUtil.get(vipRetryCallBackUrl,60*1000); //调赠送会员接口，超时时间设置为10秒
			log.info("回调通知接口返回信息=>userid: " +userid+", orderid: "+orderBean.getOrderid()+", result: "+result);
			Map<?,?> map = JsonUtil.jsonToMap(result);
			resultcode = (String)map.get("result");
		} catch (Exception e) {
			resultcode = "2";
			e.printStackTrace();
			log.error("orderId=>"+orderBean.getId()+"，回调接口出现异常，"+e.getMessage());
		} 
    	return resultcode;
    }
	
	/**
	 * 去重复数据
	 * @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("id"))){
				  //insertvacMq(bean);
			  }else{
				  map.put(reqBean.get("id").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;
	  }

	public Map transBean(Map<String, Object> body) {
		String jsonStr = JsonUtil.objectToJson(body);
		return (Map) JsonUtil.jsonToBean(jsonStr, Map.class);
	}
	
	/**
	 * 推送办理成功的短信到队列
	 * @param orderInfo
	 */
	public void inserSmstMq(BackBusiOrderRec orderBean){
		try{
			Map<String, String> map = new HashMap<String, String>();
			map.put("userid", orderBean.getUserid());
			map.put("cpid", orderBean.getCpid());
			map.put("spid", orderBean.getSpid());
			map.put("result", "0");
			map.put("channel", "");
			map.put("style","0000");
			map.put("times", "");
			map.put("orderType", "");
			map.put("type", "cssms");	
			map.put("busiType", "tran_succ");	//订购成功短信
			//logger.info("++++++map:"+map);
			String  mqReciveUrl = dictionaryDao.getValue("mqReciveUrl");
			URLUtil.post(mqReciveUrl, JsonUtil.objectToJson(map));	
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	 /**
     * 获取请求属性性
     * @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(BackBusiOrderRec bean){
		try{
			Map<String, String> map = new HashMap<String, String>();
			map.put("userid", bean.getUserid());
			map.put("id", bean.getId());
			map.put("orderid", bean.getOrderid());
			map.put("type", "vipretry");	
			//System.out.println("==============赠送会员失败，"+map);
			String  mqReciveUrl = dictionaryDao.getValue("mqReciveUrl");
			URLUtil.post(mqReciveUrl, JsonUtil.objectToJson(map));	
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送业务互斥短信
	 * @param inputObj
	 * @param huchiSpid 
	 */
//	public void inserSmstMqHuChi(BackBusiOrderRec psoBean, String huchiSpid){
//		try{
//			String huchiSpName = "";
//			List<HashMap> spList2 = pointShopDao.findSpInfo(huchiSpid);
//			if(spList2 != null && spList2.size()>0 && spList2.get(0).get("SPNAME") != null){
//				huchiSpName = spList2.get(0).get("SPNAME").toString();
//			}
//			String bt = psoBean.getBusitype();
//			//免流，或者免流+会员，业务互斥要发短信
//			if(("2".equals(bt) || "3".equals(bt)) && !"".equals(huchiSpName)){
//				String succFlag = "fail";
//				String busiType = "tran_cdn_fail"; //免流业务互斥短信
//				if("3".equals(bt)){
//					busiType = "tran_vipcdn_cdnfail"; //免流+会员业务互斥短信
//				}
//
//				Map<String, String> map = new HashMap<String, String>();
//				map.put("userid", psoBean.getUserid());
//				map.put("cpid", psoBean.getCpid());
//				map.put("spid", psoBean.getSpid());
//				map.put("result", "0");
//				map.put("channel", "");
//				map.put("param1", huchiSpName);
//				map.put("style","0000");
//				map.put("times", "");
//				map.put("orderType", "");
//				map.put("type", "cssms");
//				map.put("busiType", busiType);
//				logger.info(JsonUtil.objectToJson(map));
//				String  mqReciveUrl = dictionaryDao.getValue("mqReciveUrl");
//				//开发环境
//				//URLUtil.post("http://172.16.33.16:8082/mq-service/recive.do", JsonUtil.objectToJson(map));
//				//测试环境
//				//URLUtil.post("http://10.199.99.177:86/mq-service/recive.do", JsonUtil.objectToJson(map));
//				//生产环境				
//				//URLUtil.post("http://10.199.99.144:8090/mq-service/recive.do", JsonUtil.objectToJson(map));
//				
//				URLUtil.post(mqReciveUrl,  JsonUtil.objectToJson(map));
//			}
//		}catch (Exception e){
//			e.printStackTrace();
//		}
//	}
	
    /**
     * 回调积分商城
     * @param outputObj
     * @param id 我方生成的订单流水号
     * @param requestId 我方生成的请求ID
     */
    private String callBackPointShop(String id,String requestId){
    	String bcstatus = "1"; //回调状态，1未回调，0回调完成，2回调异常
    	String cbReqParams = ""; //回调请求报文
    	String cbRspParams = ""; //回调响应报文
    	try {
    		PointShopOrderBean bean = pointShopDao.getOrderRec(id);
    		TreeMap<String, String > orderOutObj = null;
    		if(bean != null){
    			orderOutObj = new TreeMap<String, String>();
    			orderOutObj.put("account",bean.getUserid());
    			orderOutObj.put("orderId",bean.getId());
    			orderOutObj.put("finishTime",bean.getFinishTime());
    			orderOutObj.put("goodsCode",bean.getSpid());
    			orderOutObj.put("orderNo",bean.getOrderNo());
    			orderOutObj.put("orderTime",bean.getOrderTime());
    			String orderStatus = "3"; //充值状态：1充值中 2充值成功3充值失败
    			String reusltCode = bean.getResultCode(); //办理结果编码，0成功，1待处理，2处理中，其他为异常
    			if("1".equals(reusltCode) || "2".equals(reusltCode)){
    				orderStatus = "1";
    			}else if("0".equals(reusltCode)){
    				orderStatus = "2";
    			}else{ //充值失败，设置失败原因
        			orderOutObj.put("failDesc",bean.getResultInfo());
    			}
    			orderOutObj.put("orderStatus",orderStatus);
    		}
    		
    		if(orderOutObj != null){
    			String callBackUrl = this.dictionaryDao.getValue("pointShopCallBackUrl");//"http://demo.mall.10010.com:8104/jf-service/zcvcard/notify";
    			cbReqParams = JsonUtil.objectToJson(orderOutObj);
    			logger.info("===========回调地址："+callBackUrl);
    			logger.info("===========回调请求参数："+cbReqParams);
    			cbRspParams  = HttpInvoke.sendHttpByPost("POST", callBackUrl, cbReqParams, getProperty());
    			logger.info("============回调响应参数:"+cbRspParams);
    			if("0000".equals(cbRspParams)){
    				bcstatus = "0";
    			}    			
/*    			Map json = JsonUtil.jsonToMap(cbRspParams);
    			if(json != null){
        			String result = json.get("result")+"";
        			if("0000".equals(result)){
        				bcstatus = "0";
        			}
    			}*/
    		}else{
    			cbRspParams = "回调接口时未找到订购信息";
    			log.error("订单流水号=>"+id+"=>requestId=>"+requestId+"，回调接口时未找到订购信息");
    		}
		} catch (Exception e) {
			bcstatus = "2";
			e.printStackTrace();
			log.error("订单流水号=>"+id+"=>requestId=>"+requestId+"，回调接口出现异常，"+e.getMessage());
			cbRspParams = "返回报文: "+cbRspParams+"，回调异常，"+e.getMessage();
		} finally{
			log.info("订单流水号=>"+id+"=>requestId=>"+requestId+"=>cbReqParams: "+cbReqParams+", cbRspParams=>"+cbRspParams);
			addParamsByCb(cbReqParams, cbRspParams, requestId);
		}
    	return bcstatus;
    }
    
    /**
     * 添加回调报文
     * @param cbReqParams
     * @param cbRspParams
     * @param requestId
     */
    private void addParamsByCb(String cbReqParams,String cbRspParams, String requestId){
		try {
			//System.out.println(cbRspParams);
			//System.out.println(cbRspParams.length());
			//一个中文占两个 字节
			if(cbRspParams != null && cbRspParams.length()> 250){
				cbRspParams = cbRspParams.substring(0,250);
			}
			pointShopDao.updParamsByCb(cbReqParams, cbRspParams, requestId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("requestId: "+requestId+", 更新callBack状态出现异常，"+e.getMessage());
		}
    }
    
	/**
	 * 获取endtime
	 * @param bean BackBusiOrderRec
	 * @return
	 */
	private String getEndTime(BackBusiOrderRec bean)throws Exception{
		String endtime = pointShopDao.getBackEndtime(bean.getId());
		if(endtime == null || "null".equals(endtime) || endtime.length() != 14){
			endtime = "";
		}
		if("".equals(endtime)){
			String currEndtime = "";
			Map reMap = this.hasEffect(bean);
			if((Boolean)reMap.get("hasEffect")){ //存在有效订购关系
				Map currOrderInfo = (Map)reMap.get("currOrderInfo");
				currEndtime = (String)currOrderInfo.get("ENDTIME");
			}
			//[{PWD=kijkfds, NETDAYS=31, CHANNEL=test_01, NETDAYS=2, SPID=1168, BUSITYPE=3, CPID=youtu}]
			HashMap confHm = pointShopDao.getBackBusiConf(bean.getCpid(), bean.getSpid()).get(0);
			//String busiType = confHm.get("BUSITYPE")+"";
			if("2".equals(confHm.get("BUSITYPE")) || "3".equals(confHm.get("BUSITYPE"))){ 
				if(currEndtime != null && !"".equals(currEndtime)){			
					endtime = pointShopDao.endtimeParamDay(confHm.get("NETDAYS")+"", currEndtime);
				}else{
					endtime = pointShopDao.currParamDay(confHm.get("NETDAYS")+"");
				}
			}
		}
		return endtime;
	}
	
	
	/**
	 * 调能力平台
	 * @param orderInfo
	 * @param hasshare //调能力平台标识：0调能力平台并以结果落订购关系，1调能力平台其结果不影响订购关系，为空时不调能力平台，
	 * @throws Exception
	 */
	private void shareOrder(BackBusiOrderRec orderBean, String hasshare) throws Exception{
		if("0".equals(hasshare) || "1".equals(hasshare)){
			String shareErcode = "0";
			String shareErnfo = "成功";
			if("0".equals(hasshare)){//以能力平台调用结果落订购关系的要设置渠道为SHARE，此渠道记录在订购关系表和订购日志表中
				orderBean.setChannel("SHARE");
			}
			try {
				shareOrder(orderBean.getUserid(),orderBean.getCpid(),orderBean.getSpid());
			} catch (BusinessException e) {
				e.printStackTrace();
				shareErcode = e.getCode();
				shareErnfo = e.getMessage();
				if("0".equals(hasshare)){
					throw new BusinessException("8888","调用能力共享平台订购接口失败");
				}
			} finally {
				saveBackShareLog(orderBean,shareErcode,shareErnfo);
			}
		}
	}
	
	/**
	 * 写后向订购能力平台日志
	 * @param orderInfo
	 * @param errorcode
	 * @param errorinfo
	 */
	public void saveBackShareLog(BackBusiOrderRec orderBean,String errorcode,String errorinfo){
		try {
			BackShareOrderBean bso = new BackShareOrderBean();
			bso.setUserid(orderBean.getUserid());
			bso.setErrorcode(errorcode);
			bso.setErrorinfo(errorinfo);
			bso.setCpid(orderBean.getCpid());
			bso.setSpid(orderBean.getSpid());
			vipRetryDao.addShareOrderLog(bso);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("userid："+orderBean.getUserid()+"，写后向订购能力平台日志出现异常，"+e.getMessage());
		}

	}
	
	/**
	 * 订购
	 * @param userid
	 * @param cpid
	 * @param spid
	 * @throws BusinessException
	 */
	public void shareOrder(String userid,String cpid,String spid) throws BusinessException{
		String result ="";
		String url = "";
		try{
			url = dictionaryDao.getValue("shareOrderUrl");
			result = URLUtil.get(url+"?cpid="+cpid+"&spid="+spid+"&userid="+userid,15000);
		}catch (Exception e) {
			log.error("****："+userid+cpid+spid+":"+e.getMessage());
			if(e.getMessage().indexOf("connect timed out")!= -1) { //如果连接超时就再重试一次
				try {
					result = URLUtil.get(url+"?cpid="+cpid+"&spid="+spid+"&userid="+userid,15000);
					log.info(userid+cpid+spid+"重试:"+result);
					if(result.indexOf("您已订购，请勿重复")!= -1){ //包含您已订购，请勿重复订购
						result = "{\"resultCode\":0,\"resultInfo\":\"成功！\",\"data\":null}";
					}
				}catch (Exception e1){
					throw new BusinessException("9170", "调用能力共享平台订购接口异常！");
				}
			}else {
				throw new BusinessException("9170", "调用能力共享平台订购接口异常");
			}
		}
		JSONObject obj = JSONObject.fromObject(result);
		if(!obj.getString("resultCode").equals("0")){
			throw new BusinessException(obj.getString("resultCode"), obj.getString("resultInfo"));
		}

	}
}
