package com.chinacreator.video.service.handle;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.CpSpDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.service.IHandleService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.RedisService;
import com.chinacreator.video.util.URLUtil;

@Component("youtuOrder")
public class YoutuHandleService implements IHandleService{
	
	//生产环境
	//private static final String url = "http://10.199.99.147:8092/videoif/";
	//测试环境
	//private static final String url = "http://10.199.99.177:86/videoif/";
	//开发环境
	//private static final String url ="http://172.16.33.16:8082/videoif/"; 
	
	@Autowired
	private CpSpDao CpSpDao;
	
	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	RedisService redisService;
	
	private static final  Logger logger = LoggerFactory.getLogger(YoutuHandleService.class);
	
	private static final  Logger log = LoggerFactory.getLogger("commonOrder");
	
	@Override
	public void handle(OrderInfo orderInfo) throws Exception {
		Map<String,Object> logmap = new HashMap<String,Object>();
		logmap.put("forward", "youtuOrder");
		logmap.put("userInfo", orderInfo);
		this.valiParams(orderInfo);
		String url = order(orderInfo);
		logger.info("userid:"+orderInfo.getUserid());
		logger.info("url:"+url);
		logmap.put("url", url);
		String result = "";
		try {
			this.valiTranLimit(orderInfo);
			result = doHandle(url);
			if(!JSON.parseObject(result).get("resultcode").equals("0")) {
				throw new BussinessException(JSON.parseObject(result).get("resultcode").toString(),JSON.parseObject(result).get("errorinfo").toString());
			}
		}catch(Exception e) {
			e.printStackTrace();
			if(e instanceof BussinessException) {
				throw e;
			}else {
				throw new BussinessException("80003", "出现异常，"+e.getMessage());
			}
		}finally {
			logmap.put("result", result);
			log.info(JSON.toJSONString(logmap));
		}
	}
	
	/**
	 * 参数验证
	 * @param orderInfo
	 * @throws BussinessException
	 */
	private void valiParams(OrderInfo orderInfo) throws BussinessException{
		String type = orderInfo.getType();
		String cpid = orderInfo.getCpid();
		String spid = orderInfo.getSpid();
		String channel = orderInfo.getChannel();
		String userid = orderInfo.getUserid();
		String timestamp = orderInfo.getTimestamp();
		String orderid = orderInfo.getOrderid();
		String reorderid = orderInfo.getReorderid();
		if(StringUtils.isEmpty(orderid) || StringUtils.isEmpty(cpid) || StringUtils.isEmpty(spid) 
				|| StringUtils.isEmpty(userid) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(channel)) {
			throw new BussinessException("80015", "参数不合法");
		}
		if("1".equals(type) && StringUtils.isEmpty(reorderid)){
			throw new BussinessException("80015", "参数不合法");
		}
	}
	
	/**
	 * 拼接转发URL参数
	 * @param orderInfo
	 * @return
	 * @throws BussinessException
	 */
	private String getParams(OrderInfo orderInfo) throws BussinessException{
		String params = "";
		try {
			String cpid = orderInfo.getCpid();
			String spid = orderInfo.getSpid();
			String type = orderInfo.getType();
			String userid = orderInfo.getUserid();
			String timestamp = orderInfo.getTimestamp();
			String orderid = orderInfo.getOrderid();
			String reorderid = orderInfo.getReorderid();
			String pwd = CpSpDao.getCpSp(orderInfo.getCpid(), orderInfo.getSpid()).getPwd(); //TB_CP_ACCOUNT_CONFIG表NETPWD字段
			if("0".equals(type)){
				params += "orderid="+orderid+"&ordertype=0&apptype=2&channel="+orderInfo.getChannel()+"&cpid="+cpid+"&spid="+spid+"&timestamp="+timestamp+"&type="+type;
			}else{
				params += "orderid="+orderid+"&ordertype=0&apptype=2&channel="+orderInfo.getChannel()+"&cpid="+cpid+"&spid="+spid+"&timestamp="+timestamp+"&type="+type+"&reorderid="+reorderid;
			}
			userid = DesUtil.encode(userid, pwd); //手机号码加密
			//数据的签名： Md5(orderid+cpid+spid+userid+type+timestamp+pwd)
			String signature = MD5.MD5Encode(orderid + cpid + spid + userid + timestamp + pwd);
			params += "&userid="+URLEncoder.encode(userid, "utf-8")+"&signature="+signature; //重新编码
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException("80013", "组建调用参数出现异常，"+e.getMessage());
		}
	
		return params;
	}
	
	/**
	 * 获取订购url
	 * @param orderInfo
	 * @return
	 * @throws Exception
	 */
	public String order(OrderInfo orderInfo) throws Exception {
		String orderUrl = dictionaryDao.getValue("commonOrderUrl")+"backorder.do?";
		orderUrl += this.getParams(orderInfo);
		return orderUrl;
	}
	
	public String doHandle(String url) throws Exception {
		return  URLUtil.get(url);
	}
	
	/**
	 * 验证并发控制
	 * @param orderInfo
	 * @throws Exception
	 */
	private void valiTranLimit(OrderInfo orderInfo) throws Exception {
		//按订单ID和订购类型验证并发次数
		Object obj = redisService.get("univideo_tran_"+orderInfo.getOrderid()+"_"+orderInfo.getType());
		if(obj != null ){
			throw new BussinessException("10036", "并发验证限制，请稍候再试");
		}else{
			redisService.incr("univideo_tran_"+orderInfo.getOrderid(),1);
			redisService.expire("univideo_tran_"+orderInfo.getOrderid(), 10); //设置过期 时间10秒
		}
		//按SPID和手机号码和订购类型验证并发次数
		Object obj2 = redisService.get("univideo_tran_"+orderInfo.getSpid()+"_"+orderInfo.getType()+"_"+orderInfo.getUserid());
		if(obj2 != null ){
			throw new BussinessException("10036", "并发验证限制，请稍候再试");
		}else{
			redisService.incr("univideo_tran_"+orderInfo.getSpid()+"_"+orderInfo.getType()+"_"+orderInfo.getUserid(),1);
			redisService.expire("univideo_tran_"+orderInfo.getSpid()+"_"+orderInfo.getType()+"_"+orderInfo.getUserid(), 10); //设置过期 时间10秒
		}
	}
}
