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.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("commonOrder")
public class CommHandleService 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;
	
	private static final  Logger logger = LoggerFactory.getLogger(CommHandleService.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", "commonOrder");
		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 = "";
			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 {
				e.printStackTrace();
				String errmsg = e.getMessage();
                //不返回videoif相关的错误信息
            	if( errmsg != null && errmsg.indexOf("videoif") != -1){
            		 throw new BussinessException("80003", "系统忙，请稍候再试。");
            	}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 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(); //TB_CP_ACCOUNT_CONFIG表NETPWD字段
			if("0".equals(type)){//订购
				params += "ordertype=0&access="+orderInfo.getAccess()+"&apptype=2&channel="+orderInfo.getChannel()
						+"&subchannel="+subchannel
						+"&cpid="+cpid+"&spid="+spid+"&timestamp="+timestamp+"&token="+orderInfo.getToken()+"&subtype="+subtype;
			}else{//退订
				params += "ordertype=0&access="+orderInfo.getAccess()+"&apptype=2&channel="+orderInfo.getChannel()
						+"&subchannel="+subchannel
						+"&cpid="+cpid+"&spid="+spid+"&timestamp="+timestamp+"&token="+orderInfo.getToken()+"&subtype="+subtype;
			}
			 
			userid = DesUtil.encode(userid, pwd); //手机号码加密
			params += "&userid="+URLEncoder.encode(userid, "utf-8"); //重新编码
			params += seqnumberParams;
		} 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")+"order.do?";
		orderUrl += this.getParams(orderInfo);
		return orderUrl;
	}
	
	public String doHandle(String url) throws Exception {
		return  URLUtil.get(url);
	}
	
	/**
	 * 获取退订url
	 * @param orderInfo
	 * @return
	 * @throws Exception
	 */
	public String cancel(OrderInfo orderInfo) throws Exception {
		String cancelUrl = dictionaryDao.getValue("commonOrderUrl")+"cancelOrder.do?";
		cancelUrl += this.getParams(orderInfo);
		return cancelUrl;
	}

}
