package com.chinacreator.video.validate;

import com.chinacreator.video.bean.KuaiShouHelpBean;
import com.chinacreator.video.bean.WoInnovateBean;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.exception.WoInnovateException;
import com.chinacreator.video.mapper.CommConfDao;
import com.chinacreator.video.util.IpAddrUtil;
import com.chinacreator.video.util.MD5;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

@Component
public class WoInnovateValidate {
    private static final Logger log = LoggerFactory.getLogger("woInnovate");
    private static final String MOB_KEY = "ac22273abb2f4960";

    @Autowired
    CommConfDao commConfDao;

    /**
     * 验证时间戳
     * @param
     * @throws BussinessException
     */
    public void valiTime(WoInnovateBean bean) throws Exception {
        String timestamp = bean.getUNI_BSS_BODY().get("timeStamp");
        if(StringUtils.isEmpty(timestamp)) {
            bean.getUNI_BSS_BODY().put("respCode","20002");
            bean.getUNI_BSS_BODY().put("respDesc","timeStamp不能为空");
            throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
        }
        /*long localTimestamp = (System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        timestamp = String.valueOf(format.parse(timestamp).getTime());
        try {
            if((localTimestamp - NumberUtils.toLong(timestamp)) >30000 || (localTimestamp - NumberUtils.toLong(timestamp)) <-30000) {
                System.out.println("====================="+(localTimestamp - NumberUtils.toLong(timestamp)));
                bean.getUNI_BSS_BODY().put("respCode","20003");
                bean.getUNI_BSS_BODY().put("respDesc","timeStamp已失效");
                throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
            }
        } catch (Exception e) {
            if(e instanceof WoInnovateException) {
                throw e;
            }else {
                bean.getUNI_BSS_BODY().put("respCode","20003");
                bean.getUNI_BSS_BODY().put("respDesc","timeStamp已失效");
                throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
            }
        }*/
    }

    /**
     * 验证参数
     * @param bean
     * @throws WoInnovateException
     */
    public void validate(WoInnovateBean bean) throws WoInnovateException {
        //手机号验证
        String mobile = bean.getUNI_BSS_BODY().get("mobile");
        if(StringUtils.isEmpty(mobile)) {
            bean.getUNI_BSS_BODY().put("respCode","20002");
            bean.getUNI_BSS_BODY().put("respDesc","手机号不得为空");
            throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
        }
        if(isValid(mobile) && mobile.length() == 11){
            log.info(mobile);
        }else{
            bean.getUNI_BSS_BODY().put("respCode","20003");
            bean.getUNI_BSS_BODY().put("respDesc","手机号错误");
            throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
        }
        //业务类型验证
        String businessNoticeType = bean.getUNI_BSS_BODY().get("businessNoticeType");
        if(StringUtils.isEmpty(businessNoticeType)){
            bean.getUNI_BSS_BODY().put("respCode","20002");
            bean.getUNI_BSS_BODY().put("respDesc","业务类型不得为空");
            throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
        }
        String skuId =  bean.getUNI_BSS_BODY().get("skuId");
        if(StringUtils.isEmpty(skuId)){
            bean.getUNI_BSS_BODY().put("respCode","20002");
            bean.getUNI_BSS_BODY().put("respDesc","商品id型不得为空");
            throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
        }
    }

    /**
     * 验证appid
     */
    public void valiAppid(WoInnovateBean bean) throws WoInnovateException{
        String appid = bean.getUNI_WCX_HEAD().get("AppId");
        String businessNoticeType = bean.getUNI_BSS_BODY().get("businessNoticeType");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip = IpAddrUtil.getIpAddr2(request);
        System.out.println("ip地址"+ip +"   接口限制"+    bean.getUNI_BSS_BODY().get("INVOKEFACE"));
        try {
            //busitype 业务类型，1查询，2办理，3退订，4扣费金额结果通知
            List<Map> list = commConfDao.getIpLimitConf(businessNoticeType,appid);

            if(list == null || list.size() == 0){
                bean.getUNI_BSS_BODY().put("respCode","40007");
                bean.getUNI_BSS_BODY().put("respDesc","IP限制无对应业务配置信息");
                throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
            }else{
                boolean result = false;
                boolean hasExists = false;
                boolean hasinvokeface = true; //是否有允许调指定接口
                //[{CHANNEL=TX20_wtqd, SPID=1167, IP=172.16.33.16, CPID=youtu}]
                for(Map map : list){
                    //CPID级别验证
                    if("*".equals(map.get("CPID"))){ //不限CPID
                        hasExists = true;
                    }else if(appid != null && appid.equals(map.get("CPID"))
                            && (appid != null && appid.equals(map.get("SPID")) || "*".equals(map.get("SPID")))){
                        hasExists = true;
                    }

                    if(hasExists){
                        if("*".equals(map.get("IP"))){
                            result = true;
                        }else if(map.get("IP") != null && !"".equals(map.get("IP"))){
                            String [] ips = map.get("IP").toString().split("\\|");
                            for(String str : ips){
                                if(str != null && ip != null && str.contains(ip)){
                                    result = true;
                                }
                                //如果IP地址配置有*号，访问的IP包含*号前面的部分
                                if(!result && str.indexOf("*") != -1 && ip.startsWith(str.split("[*]")[0])){
                                    result = true;
                                }
                            }
                        }

                        //有接口调用限制
                        if(result && map.get("INVOKEFACE") != null && !"".equals(map.get("INVOKEFACE"))
                                && !map.get("INVOKEFACE").equals(bean.getUNI_BSS_BODY().get("INVOKEFACE"))){
                            hasinvokeface = false;
                        }

                        break;
                    }
                }
                if(!hasExists){ //无业务配置
                    bean.getUNI_BSS_BODY().put("respCode","40007");
                    bean.getUNI_BSS_BODY().put("respDesc","IP限制无业务配置信息");
                    throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
                }
                if(!result){//ip验证
                    bean.getUNI_BSS_BODY().put("respCode","40007");
                    bean.getUNI_BSS_BODY().put("respDesc","IP验证失败:"+ip);
                    throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
                }
                /*if(!hasinvokeface){
                    throw new BussinessException("10011", "渠道【"+appid+"】无【"+orderInfo.getInvokeface()+"】接口调用权限");
                }*/
            }
        } catch (Exception e) {
            e.printStackTrace();
            if(e instanceof WoInnovateException) {
                throw e;
            }else {
                if(e.getMessage() != null && e.getMessage().indexOf("SQLException") != 0){
                    bean.getUNI_BSS_BODY().put("respCode","40007");
                    bean.getUNI_BSS_BODY().put("respDesc","IP限制验证出现SQLException异常。");
                    throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
                    //throw new BussinessException("10014", "IP限制验证出现SQLException异常。");
                }else{
                    bean.getUNI_BSS_BODY().put("respCode","40008");
                    bean.getUNI_BSS_BODY().put("respDesc","IP限制验证出现异常，"+e.getMessage());
                    throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());

                }
            }
        }
    }

    /**
     * tocken验证
     * @param bean
     * @throws WoInnovateException
     */
    public void tockenVali(WoInnovateBean bean)throws WoInnovateException{
        String AppId = "WoInnovate";
        String app_secret = "W54261150";
        //String Transid = "Jwi0F9oMAVQI";
        String Transid = "533219958439840507648";
        //沃创新传输的tocken
        String token = bean.getUNI_WCX_HEAD().get("Token");
        if(token == null){
            bean.getUNI_BSS_BODY().put("respCode","20002");
            bean.getUNI_BSS_BODY().put("respDesc","tocken信息不得为空");
            throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
        }
        //拼接参数
        String unCheckTocken = "APP_ID"+AppId+"TRANS_ID"+Transid+app_secret;
        String md5Encode = MD5.MD5Encode(unCheckTocken);
        String s = md5Encode.toLowerCase();
        log.info("沃创新平台传输tocken："+token+",拼接验证的tocken:"+token);
        if(!token.equals(s)){
            bean.getUNI_BSS_BODY().put("respCode","40008");
            bean.getUNI_BSS_BODY().put("respDesc","tocken验签出错");
            throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
        }
    }

    public void checkBusinessNoticeType(WoInnovateBean bean) throws WoInnovateException {
        String businessNoticeType = bean.getUNI_BSS_BODY().get("businessNoticeType");
        if(!businessNoticeType.equals("2")&&!businessNoticeType.equals("3")){
            bean.getUNI_BSS_BODY().put("respCode","20003");
            bean.getUNI_BSS_BODY().put("respDesc","businessNoticeType类型无效");
            throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
        }
    }

    public void checkOrderType(WoInnovateBean bean) throws WoInnovateException{
        String orderType = bean.getUNI_BSS_BODY().get("orderType");
        if(!orderType.equals("1")){
            bean.getUNI_BSS_BODY().put("respCode","20003");
            bean.getUNI_BSS_BODY().put("respDesc","orderType类型无效");
            throw new WoInnovateException(bean.getUNI_WCX_HEAD(),bean.getUNI_BSS_BODY());
        }
    }
}
