package com.chinacreator.video.service.handle;

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.URLUtil;
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 java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Component("specifyOrder")
public class TencentHandleService 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("specifyOrder");
	
	private static final  Logger logger = LoggerFactory.getLogger(TencentHandleService.class);
		
	@Autowired
	private CpSpDao CpSpDao;
	
	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Override
	public void handle(OrderInfo orderInfo) throws Exception {
		Map<String,Object> logmap = new HashMap<String,Object>();
		logmap.put("forward", "specifyOrder");
		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) {
			e.printStackTrace();
			if(e instanceof BussinessException) {
				throw e;
			}else {
				throw new BussinessException("80004", "出现异常，"+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("specifyOrderUrl")+"order?";
		orderUrl += this.getParams(orderInfo);
		return orderUrl;
	}
	
	/**
	 * 转对应接口办理业务
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String doHandle(String url) throws Exception {
		String result = URLUtil.get(url);
		return result;
	}
	
	/**
	 * 参数验证
	 * @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 seqnumber = orderInfo.getSeqnumber();
			String subchannel = orderInfo.getSubchannel()==null?"":orderInfo.getSubchannel();
			String subtype = orderInfo.getSubtype() == null ? "" : orderInfo.getSubtype();
			if(StringUtils.isEmpty(seqnumber)){
				seqnumber = "";
			}
			String seqnumberParams = "";
			if(!"".equals(seqnumber)){
				seqnumberParams = "&seqnumber="+seqnumber;
			}
			//获取密码
			String pwd = CpSpDao.getCpSp(orderInfo.getCpid(), orderInfo.getSpid()).getPwd();
			if("0".equals(type)){//订购
				params += "access="+orderInfo.getAccess()+"&apptype=2&channel="+orderInfo.getChannel()
						+"&subchannel="+subchannel
						+"&cpid="+cpid+"&spid="+spid+"&ordertype=1&timestamp="+timestamp+"&token="+orderInfo.getToken()+"&subtype="+subtype;;
			}else{//退订
				String canceltype = "1"; //包月退订
				if("84".equals(orderInfo.getSpid())){
					canceltype = "2"; //单点退订
				}
				params += "access="+orderInfo.getAccess()+"&apptype=2&channel="+orderInfo.getChannel()
						+"&subchannel="+subchannel
						+"&cpid="+cpid+"&spid="+spid+"&canceltype="+canceltype+"&timestamp="+timestamp+"&token="+orderInfo.getToken()+"&subtype="+subtype;;
			}
			 
			userid = DesUtil.encode(userid, pwd); //手机号码加密
			//签名
			String signature = MD5.MD5Encode(cpid + spid + userid + pwd + timestamp);
			params += "&userid="+URLEncoder.encode(userid, "utf-8")+"&signature="+signature;
			params += seqnumberParams;
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException("80014", "组建调用参数出现异常，"+e.getMessage());
		}
	
		return params;
	}
	
	/**
	 * 退订
	 * @param orderInfo
	 * @return
	 * @throws Exception
	 */
	public String cancel(OrderInfo orderInfo) throws Exception {
		String cancelUrl = dictionaryDao.getValue("specifyOrderUrl")+"cancel?";
		cancelUrl += this.getParams(orderInfo);
		return  cancelUrl;
	}
}
