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.CpSpBean;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
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.URLUtil;

@Component("channelOrder")
public class ChannelOrderHandleService implements IHandleService{

	//生产环境
	//private static final String url ="http://10.199.99.144:8090/video-activity/";
	//测试环境
	//private static final String url ="http://10.199.99.171:8081/activity/";
	//开发环境
	//private static final String url = "http://172.16.33.16:8085/video-activity/";
	
	private static final  Logger log = LoggerFactory.getLogger("channelOrder");
	
	private static final  Logger logger = LoggerFactory.getLogger(ChannelOrderHandleService.class);
			
	@Autowired
	private ChannelDao channelDao;
	
	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Override
	public void handle(OrderInfo orderInfo) throws Exception {
		Map<String,Object> logmap = new HashMap<String,Object>();
		logmap.put("forward", "channelOrder");
		logmap.put("userInfo", orderInfo);
		this.valiParams(orderInfo);
		String url = "";
		if(orderInfo.getType().equals("0")) {//订购
			url = order(orderInfo);
		}else {//退订
			url = cancel(orderInfo);
		}
		logger.info("userid:"+orderInfo.getUserid());
		logger.info("url:"+url);
		logmap.put("url", url);
		String result = "";
		try {
			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) {
			if(e instanceof BussinessException) {
				throw e;
			}else {
				throw new BussinessException("80001", "出现异常，"+e.getMessage());
			}
		}finally {
			logmap.put("result", result);
			log.info(JSON.toJSONString(logmap));
		}
	}

	/**
	 * 订购
	 * @param orderInfo
	 * @return
	 * @throws Exception
	 */
	public String order(OrderInfo orderInfo) throws Exception {
		String orderUrl = dictionaryDao.getValue("channelOrderUrl")+"channelOrder?";
		orderUrl += this.getParams(orderInfo);
		logger.info("orderUrl:"+orderUrl);
		return orderUrl;
	}
	
	/**
	 * 参数验证
	 * @param orderInfo
	 * @throws BussinessException
	 */
	private void valiParams(OrderInfo orderInfo) throws BussinessException{
		String cpid = orderInfo.getCpid();
		String spid = orderInfo.getSpid();
		String type = orderInfo.getType();
		String userid = orderInfo.getUserid();
		String timestamp = orderInfo.getTimestamp();
		if(StringUtils.isEmpty(cpid) || StringUtils.isEmpty(spid) || StringUtils.isEmpty(type) || StringUtils.isEmpty(userid) || StringUtils.isEmpty(timestamp) 
				 || (!"0".equals(type) && !"1".equals(type)) ) {
			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 seqnumber = orderInfo.getSeqnumber();
			if(StringUtils.isEmpty(seqnumber)){
				seqnumber = "";
			}
			String seqnumberParams = "";
			if(!"".equals(seqnumber)){
				seqnumberParams = "&seqnumber="+seqnumber;
			}
			String pwd = channelDao.queryChannel(orderInfo.getChannel()).getPassword(); //TB_CHANNEL_ORG表的PASSWORD 渠道表的密码
			//orderid=TX20_dtqd20190118103239&access=1&apptype=2&channel=TX20_dtqd&cpid=tencent
			//&spid=84&type=0&signature=1f90c1725cccf3e967a69290f8e0932b&timestamp=1553846022&token=8383d76ddd120d928dafef49219297dd&userid=wPt1%2BPmQAHXHk6Gf8I6ZPw%3D%3D
			if("0".equals(type)){//订购
				params += "orderid="+orderid+"&type="+type+"&access="+orderInfo.getAccess()+"&apptype=2&channel="+orderInfo.getChannel()+"&cpid="+cpid+"&spid="+spid+"&timestamp="+timestamp+"&token="+orderInfo.getToken();
			}else{//退订
				params += "orderid="+orderid+"&type="+type+"&access="+orderInfo.getAccess()+"&apptype=2&channel="+orderInfo.getChannel()+"&cpid="+cpid+"&spid="+spid+"&timestamp="+timestamp+"&token="+orderInfo.getToken();	
			}
			 
			userid = DesUtil.encode(userid, pwd);
			String signature = MD5.MD5Encode(orderid + type + cpid + spid + userid + pwd + timestamp);
			params += "&userid="+URLEncoder.encode(userid, "utf-8")+"&signature="+signature;
			params += seqnumberParams;
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException("80011", "组建调用参数出现异常，"+e.getMessage());
		}
	
		return params;
	}
	
	
	/**
	 * 转对应接口办理业务
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String doHandle(String url) throws Exception {
		String result = URLUtil.get(url);
		return result;
	}
	
	/**
	 * 退订
	 * @param orderInfo
	 * @return
	 * @throws Exception
	 */
	public String cancel(OrderInfo orderInfo) throws Exception {
		String cancelUrl = dictionaryDao.getValue("channelOrderUrl")+"channelOrder?";
		cancelUrl += this.getParams(orderInfo);
		logger.info("cancelUrl:"+cancelUrl);
		return  cancelUrl;
	}
}
