package com.chinacreator.video.restful.service;

import com.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.CommConfDao;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.service.QryBusiService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.IpAddrUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.validate.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Service
public class QueryEcbService {

    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private IpValidate ipValidate;


    @Autowired
    private TimetampValidate timetampValidate;



    @Autowired
    private CommConfDao commConfDao;


    @Autowired
    private CommonService commonService;

    @Autowired
    private QryBusiService qryBusiService;

    @Autowired
    private com.chinacreator.video.mapper.CpSpDao CpSpDao;

    @Autowired
    private ChannelDao channelDao;


    public void busiCheck(OrderInfo orderInfo) throws Exception{

        //paramValidate.validate(orderInfo,null);

        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        //ipValidate.volidate(orderInfo,"1");
        valiIp(orderInfo);
        //签名验证
        orderInfo.setCpid("");
        orderInfo.setSpid("");
        this.validate(orderInfo);
        //手机号码验证
        this.validateIphone(orderInfo);
        //渠道访问次数限制
        qryBusiService.valiVisitLimit(orderInfo);
        //插入访问次数
        qryBusiService.setVisitcount(orderInfo);
    }

    public void validate(OrderInfo orderInfo) throws Exception {
        String lcalsign = getSign(orderInfo);
        lcalsign += channelDao.queryChannel(orderInfo.getChannel()).getPassword();
        lcalsign = MD5.MD5Encode(lcalsign);
        if(!lcalsign.equals(orderInfo.getSignature())) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }
    /**
     * 拼接签名信息 cpid+spid+userid+type+channel+timestamp
     * @param orderInfo
     * @return
     */
    private String getSign(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return "";
        }
        StringBuilder strb = new StringBuilder();
        if(orderInfo.getOrderid() != null && !"".equals(orderInfo.getOrderid())){
            strb.append(orderInfo.getOrderid());
        }
        strb.append(orderInfo.getUserid());
        if (StringUtils.isNotEmpty(orderInfo.getCpid())){
            strb.append(orderInfo.getCpid());
        }
        if (StringUtils.isNotEmpty(orderInfo.getSpid())){
            strb.append(orderInfo.getSpid());
        }
        strb.append(orderInfo.getChannel());
        strb.append(orderInfo.getTimestamp());
        return strb.toString();
    }

    public void validateIphone(OrderInfo orderInfo) throws Exception {
        String userid = orderInfo.getUserid();
        if(StringUtils.isEmpty(userid)) {
            throw new BussinessException("10007", "手机号不能为空");
        }
        ChannelBean channelBean = channelDao.queryChannel(orderInfo.getChannel());
        try {
            userid = DesUtil.decode(userid, channelBean.getPassword());
            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", "手机号加密错误");
            }
        }
    }

    private boolean isValid(String usermob){
        if (usermob == null) {
            return false;
        }
        usermob = usermob.replaceAll("[\\s-]", "");

        return usermob.matches(".*(1\\d{10}).*");
    }
    /**
     * 验证访问限制，1分钟内同一业务只能办理一次
     * @param orderInfo
     * @throws Exception
     */
    private void vistVali(OrderInfo orderInfo) throws Exception {
        String [] params = new String [3];
        params[0] = orderInfo.getChannel();
        params[1] = orderInfo.getUserid();
        params[2] = orderInfo.getSpid();
        if(commonService.vistVali2(params, "queryUserInfoEcB")){
            throw new BussinessException("8001", "指定时间内重复请求");
        }
    }
    /**
     * IP限制验证
     * @param orderInfo
     * @param ，qry查询，tran办理
     * @return
     */
    public void valiIp(OrderInfo orderInfo) throws BussinessException{
    	ipValidate.volidate(orderInfo, "1");
    	/*****
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip = IpAddrUtil.getIpAddr2(request, orderInfo);
        try {
            //busitype 业务类型，1查询，0办理
            List<Map> list = commConfDao.getIpLimitConf("1",orderInfo.getChannel());
            //System.out.println(new Date().toLocaleString());
            //System.out.println("list: "+list);
            if(list == null || list.size() == 0){
                throw new BussinessException("10011", "无业务办理配置信息");
            }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(orderInfo.getCpid().equals(map.get("CPID"))
                            && ((orderInfo.getSpid() != null && orderInfo.getSpid().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(orderInfo.getInvokeface())){
                            hasinvokeface = false;
                        }
                        break;
                    }
                }
                if(!hasExists){ //无业务配置
                    throw new BussinessException("10011", "无业务办理配置信息");
                }
                if(!result){
                    throw new BussinessException("10005", "IP验证失败:"+ip);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if(e instanceof BussinessException) {
                throw e;
            }else {
                e.printStackTrace();
                if(e.getMessage() != null && e.getMessage().indexOf("SQLException") != 0){
                    throw new BussinessException("10014", "IP限制验证出现SQLException异常。");
                }else{
                    throw new BussinessException("10015", "IP限制验证出现异常，"+e.getMessage());
                }
            }
        }
        ****/
    }


}
