package com.chinacreator.video.service;

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.util.AESUtil;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.UsermobUtil;
import com.chinacreator.video.validate.ChannelValidate;
import com.chinacreator.video.validate.MobValidate;
import com.chinacreator.video.validate.TimetampValidate;
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.URLDecoder;
import java.net.URLEncoder;

@Component
public class CsCommonOrderService {

    private static final Logger logger = LoggerFactory.getLogger(CsCommonOrderService.class);

    private static final  Logger log = LoggerFactory.getLogger("csCommonOrder");

    @Autowired
    private CpSpDao CpSpDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private MobValidate mobValidate;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private TimetampValidate timetampValidate;
    
    @Autowired
    private CommonService commonService;

    public void busiCheck(OrderInfo orderInfo) throws Exception {

        valiParams(orderInfo);

        //渠道验证
        channelValidate.validate("changshi60");

        //时间戳验证
//        timetampValidate.validate(orderInfo.getTimestamp());

        //签名验证
        signValidate(orderInfo);

        //手机号码验证
        checkUserid(orderInfo);
		//省份办理限制验证
		commonService.valiChannelSpidLimit(orderInfo);
    }


    /**
     * 验证手机号码
     * @param orderInfo
     */
    private void checkUserid(OrderInfo orderInfo) throws Exception {
        String userid = orderInfo.getUserid();
        if(StringUtils.isEmpty(userid)) {
            throw new BussinessException("10007", "手机号不能为空");
        }
        CpSpBean cpSpBean = CpSpDao.getCpSp(orderInfo.getCpid(), orderInfo.getSpid());

        orderInfo.setUserid(DesUtil.decode(userid, cpSpBean.getPwd()));

        if((orderInfo.getUserid() != null) && (orderInfo.getUserid().length() > 11)){
            orderInfo.setUserid(AESUtil.decrypt(orderInfo.getUserid(),"ac22273abb2f4960"));
        }

        if (!UsermobUtil.isValid(orderInfo.getUserid())) {
            throw new BussinessException("10009", "手机号码无效");
        }
    }





    /**
     * 签名验证
     * @param orderInfo
     * @throws Exception
     */
    public void signValidate(OrderInfo orderInfo) throws Exception {
        String lcalsign = getSign(orderInfo);
        lcalsign += CpSpDao.getCpSp(orderInfo.getCpid(), orderInfo.getSpid()).getPwd();
        lcalsign = MD5.MD5Encode(lcalsign);
        if(!lcalsign.equals(orderInfo.getSignature())) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }


    /**
     * 参数校验
     * @param orderInfo
     * @throws Exception
     */
    public void valiParams(OrderInfo orderInfo) throws Exception{

        String cpid = orderInfo.getCpid();
        String spid = orderInfo.getSpid();
        String channel = orderInfo.getChannel();
        String signature = orderInfo.getSignature();
        String timestamp = orderInfo.getTimestamp();
        String userid = URLDecoder.decode(orderInfo.getUserid(),"UTF-8");
        String type = orderInfo.getType();
        if(StringUtils.isEmpty(cpid) || StringUtils.isEmpty(spid) || StringUtils.isEmpty(channel)
                || StringUtils.isEmpty(signature) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(userid)
                || StringUtils.isEmpty(type)){

            throw new BussinessException("80015", "参数不能为空");
        }
    }

    /**
     * 拼接签名串 cpid + spid + userid + type + channel + timestamp
     * @return
     */
    private String getSign(OrderInfo orderInfo) throws Exception {

        if (orderInfo == null) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        sb.append(orderInfo.getCpid());
        sb.append(orderInfo.getSpid());
        sb.append(orderInfo.getUserid());
        sb.append(orderInfo.getType());
        sb.append(orderInfo.getChannel());
        sb.append(orderInfo.getTimestamp());
        return sb.toString();
    }


    /**
     * 拼接转发URL参数
     * @param orderInfo
     * @return
     * @throws BussinessException
     */
    private String getParams(OrderInfo orderInfo) throws BussinessException{
        String params = "";
        try {
            String cpid = orderInfo.getCpid();
            String spid = "1150";
            String type = orderInfo.getType();
            String userid = orderInfo.getUserid();
            String channel = orderInfo.getChannel();
            String timestamp = orderInfo.getTimestamp();
            String pwd = CpSpDao.getCpSp(cpid, spid).getPwd(); //TB_CP_ACCOUNT_CONFIG表NETPWD字段
            params += "&type="+type+"&apptype=2&channel="+channel+"&cpid="+cpid+"&spid="+spid+"&timestamp="+timestamp;
            userid = DesUtil.encode(userid, pwd); //手机号码加密
//            数据的签名： Md5(cpid+spid+userid+type+channel+timestamp+pwd)
            String signature = MD5.MD5Encode( cpid + spid + userid + type + channel + timestamp + pwd);
            params += "&userid="+ URLEncoder.encode(userid, "utf-8")+"&signature="+signature; //重新编码
        } catch (Exception e) {
            e.printStackTrace();
            throw new BussinessException("80013", "组建调用参数出现异常，"+e.getMessage());
        }

        return params;
    }

    /**
     * 获取畅视60元订购url
     * @param orderInfo
     * @return
     * @throws Exception
     */
    public String getOrderUrl(OrderInfo orderInfo) throws Exception {
        String orderUrl = dictionaryDao.getValue("commonOrderUrl")+"csorder.do?";
        //String orderUrl = "http://127.0.0.177:8686/videoif/"+"csorder.do?";
        orderUrl += this.getParams(orderInfo);
        return orderUrl;
    }

    /**
     * 获取畅视20元退订url
     * @param orderInfo
     * @return
     * @throws Exception
     */
    public String getCancerUrl(OrderInfo orderInfo) throws Exception {
        String orderUrl = dictionaryDao.getValue("commonOrderUrl")+"cschannelorder.do?";
        //String orderUrl = "http://127.0.0.177:8686/videoif/"+"cschannelorder.do?";
        orderUrl += "cpid="+orderInfo.getCpid()+"&spid=1150"+"&channel="+
        orderInfo.getChannel()+"&userid="+URLEncoder.encode(DesUtil.encode(orderInfo.getUserid(), CpSpDao.getCpSp(orderInfo.getCpid(), orderInfo.getSpid()).getPwd()).toString(),
                "utf-8")+"&apptype=2";
        return orderUrl;
    }

    /**
     * 获取查询畅视产品资费信息url
     * @param orderInfo
     * @return
     * @throws Exception
     */
    public String getQueryUrl(OrderInfo orderInfo) throws Exception {
        String orderUrl = dictionaryDao.getValue("commonOrderUrl")+"queryproductinfo.do?";
        //String orderUrl = "http://127.0.0.177:8686/videoif/"+"queryproductinfo.do?";
        orderUrl += "cpid="+orderInfo.getCpid()+"&userid="+URLEncoder.encode(DesUtil.encode(orderInfo.getUserid(),
                CpSpDao.getCpSp(orderInfo.getCpid(), orderInfo.getSpid()).getPwd()),"UTF-8")+
                "&channel="+orderInfo.getChannel()+"&type=1"+"&apptype=2";
        return orderUrl;
    }



}
