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.URLUtil;

@Component("tcpreOrder")
public class TcPreOrderHandleService 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(TcPreOrderHandleService.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", "tcpreOrder");
		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 {
			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) {
			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));
		}
	}
	
	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();
		String orderid = orderInfo.getOrderid();
		if(StringUtils.isEmpty(cpid) || StringUtils.isEmpty(spid) || StringUtils.isEmpty(type) || StringUtils.isEmpty(userid) || StringUtils.isEmpty(timestamp) 
				|| StringUtils.isEmpty(orderid) || (!"0".equals(type) && !"1".equals(type) && !"2".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 pwd = CpSpDao.getCpSp(orderInfo.getCpid(), orderInfo.getSpid()).getPwd(); //TB_CP_ACCOUNT_CONFIG表NETPWD字段			
			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; //重新编码
		} 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("tcpreOrderUrl")+"tcpreOrder.do?";
		orderUrl += this.getParams(orderInfo);
		return orderUrl;
	}
	
	public String doHandle(String url) throws Exception {
		return  URLUtil.get(url);
	}

}
