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.restful.dao.AkUserDao;
import com.chinacreator.video.restful.dao.QueryPrmInfoDao;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.validate.ChannelValidate;
import com.chinacreator.video.validate.IpValidate;
import com.chinacreator.video.validate.TimetampValidate;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Service
public class AkUserService {

    @Autowired
    private AkUserDao akUserDao;


    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private CommonService commonService;

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(URLEncoder.encode("tjjx+jN5j5czfVI\\/00wf23bsco2\\/shV9Q5jtvuaft0927295u6FLmg==","UTF-8"));
    }
    public void insertUserInfo(Map<String, Object> params) {
        akUserDao.insertUserInfo(params);
    }
    /***
     * 校验
     * @throws Exception
     */
    public void busiCheck(Map<String, Object> params) throws Exception {
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setTimestamp(String.valueOf(params.get("timestamp")));
        orderInfo.setUserid(String.valueOf(params.get("userid")));
        orderInfo.setChannel(String.valueOf(params.get("channel")));
        orderInfo.setSignature(String.valueOf(params.get("sign")));
        String cid = String.valueOf(params.get("cid"));
        if (StringUtils.isEmpty(cid)){
            throw  new BussinessException("1021","渠道不能为空");
        }
        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        ipValidate.volidate(orderInfo,"1");
        //签名验证
        validate(orderInfo);
        //手机号码验证
        validatePhone(orderInfo);
        params.put("userid",orderInfo.getUserid());
        vistVali(orderInfo,cid);
    }

    /***
     * 校验
     * @throws Exception
     */
    public void busiQueryCheck(Map<String, Object> params) throws Exception {
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setTimestamp(String.valueOf(params.get("timestamp")));
        orderInfo.setUserid(String.valueOf(params.get("userid")));
        orderInfo.setChannel(String.valueOf(params.get("channel")));
        orderInfo.setSignature(String.valueOf(params.get("sign")));


        String cid = String.valueOf(params.get("cid"));
        if (StringUtils.isEmpty(cid)){
            throw  new BussinessException("1021","渠道不能为空");
        }
        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        ipValidate.volidate(orderInfo,"1");
        //签名验证
        validate(orderInfo);
        //手机号码验证
        validatePhone(orderInfo);
        params.put("userid",orderInfo.getUserid());
    }
    /**
     * 验证访问限制，1分钟内同一业务只能办理一次
     * @param orderInfo
     * @throws Exception
     */
    private void vistVali(OrderInfo orderInfo,String cid) throws Exception {
        String [] params = new String [2];
        params[0] = cid;
        params[1] = orderInfo.getUserid();
        if(commonService.vistVali2(params, "akUserInfo")){
            throw new BussinessException("8001", "指定时间内重复请求");
        }
    }

    public void validatePhone(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}).*");
    }


    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());
        strb.append(orderInfo.getChannel());
        strb.append(orderInfo.getTimestamp());
        return strb.toString();
    }


    public Map<String, Object> queryUserInfo(Map<String, Object> params) {
        List<Map<String, Object>> list = akUserDao.queryUserInfo(params);
        if (list!=null && list.size()>0){
            return  list.get(0);
        }else {
            return null;
        }
    }
}
