package com.chinacreator.video.validate;

import com.chinacreator.video.bean.CPInfo;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.CPDao;
import com.chinacreator.video.util.AESUtil;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.chinacreator.video.util.UsermobUtil.isValid;

@Component
public class OrderValidate {

    private static final String MOB_KEY = "ac22273abb2f4960";
    @Autowired
    private CPDao cpSpDao;



    public void validate(OrderInfo orderInfo) throws Exception {
        String userid = orderInfo.getUserid();
        if(StringUtils.isEmpty(userid)) {
            throw new BussinessException("10007", "手机号不能为空");
        }
        CPInfo cpSpBean = cpSpDao.findById(orderInfo.getCpid());
        if(cpSpBean == null) {
            throw new BussinessException("10010", "cpid/spid错误");
        }
        int mobType = cpSpBean.getMobtype();
       try {
               if(mobType==0) {
                   userid = DesUtil.decode(userid, cpSpBean.getNetpwd());
               }else {
                   userid = DesUtil.decode(userid, cpSpBean.getNetpwd());
                   if(userid.length() > 11) {
                       userid = AESUtil.decrypt(userid, MOB_KEY);
                   }
               }
            orderInfo.setUserid(userid);
            if(isValid(userid) && userid.length() == 11){
                orderInfo.setUserid(userid);
            }else{
                throw new BussinessException("10009", "手机号错误");
            }
        } catch (Exception e) {
            if(e instanceof BussinessException) {
                throw e;
            }else {
                throw new BussinessException("10008", "手机号加密错误");
            }
        }
    }

    public void checkqueryOrderSign(OrderInfo orderInfo) throws BussinessException {
        String sign = orderInfo.getSignature();
        if (org.springframework.util.StringUtils.isEmpty(sign)) {
            throw new BussinessException("9054", "signature不能为空");
        }
        CPInfo cpSpBean = cpSpDao.findById(orderInfo.getCpid());
        String pwd = cpSpBean.getNetpwd();
        String localSign = MD5.MD5Encode(
                orderInfo.getUserid() + orderInfo.getCpid()  +pwd + orderInfo.getTimestamp());
        if (!localSign.equals(orderInfo.getSignature())) {
            throw new BussinessException("9054", "signature校验失败");
        }
    }

    public void timestampvalidte(){

    }



}
