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.mapper.Tw5gSyncDao;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.validate.*;
import org.apache.commons.lang.StringUtils;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 拓维5g查询服务类
 *
 * @author zhengrong.yan
 * @date 20201114
 */
@Component
public class Tw5gSyncService {

    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private MobValidate mobValidate;

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private SignValidate signValidate;

    @Autowired
    private ParamValidate paramValidate;

    @Autowired
    private CommConfDao commConfDao;

    @Autowired
    private CommonService commonService;

    @Autowired
    private Tw5gSyncDao tw5gSyncDao;

    @Autowired
    private ChannelDao channelDao;

    private static Logger logger = Logger.getLogger(Tw5gSyncService.class);

    private static Logger log = Logger.getLogger("tw5gsync");

    public void busiCheck(OrderInfo orderInfo) throws Exception {

        paramValidate(orderInfo);

        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        ipValidate.volidate(orderInfo,"1");
        //签名验证
        signValidate(orderInfo);
        //手机号码验证
        mobValidate(orderInfo);
        //并发访问控制
        //vistVali(orderInfo);
    }

    /**
     * 业务处理
     *
     * @param orderInfo
     */
    public void busiOper(OrderInfo orderInfo) throws Exception {
        String errorcode = "0";
        String errorinfo = "";
        try {
            commonService.setOperTime(orderInfo);
            commonService.setAreaInfo(orderInfo);
            String userid = orderInfo.getUserid();
            //查询是否有订购同步的产品（只需要满足一个即可）
            String syncproduct = tw5gSyncDao.getSyncproduc(orderInfo.getSpid());
            int flag = 0;
            if(syncproduct!=null && !"".equals(syncproduct)) {
                String[] syncproductarr = syncproduct.split(",");//分割

                for (String s : syncproductarr) {
                    s = s.replace(" ", "");
                    OrderInfo order = new OrderInfo();
                    order.setSpid(s);
                    order.setUserid(userid);
                    HashMap<String, Object> remap = commonService.getOrderStatus(order.getUserid(), order.getSpid());//查看订购关系表是否有
                    System.out.println("---------------------" + remap.size());
                    if (remap != null && remap.size() > 0) {
                        String relid = (String) remap.get("RELID"); //订购关系表ID
                        String orderStatus = (String)remap.get("ORDERSTATUS");
                        log.info("orderstatus====>"+orderStatus);
                        log.info("userid====>"+userid);
                        System.out.println("relid========================>" + relid);
                        if (relid != null && !"".equals(relid) && ("1".equals(orderStatus) || "0".equals(orderStatus))) {
                            return;
                        }
                    }
                    flag++;
                }
                if (flag == syncproductarr.length) {
                    throw new BussinessException("8003", "未订购相关产品，无法订购5G加油包");
                }
            }else {
                throw new BussinessException("8003", "未订购相关产品，无法订购5G加油包");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                errorcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
            } else {
                errorcode = "8000";
                errorinfo = "出现异常，" + e.getMessage();
            }
            throw e;
        }
    }

    /**
     * 验证访问限制，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, "tw5gsync")) {
            throw new BussinessException("8001", "指定时间内重复请求");
        }
    }

    private void paramValidate(OrderInfo orderInfo) throws Exception {
        if (orderInfo != null) {
            if (orderInfo.getUserid() == null || orderInfo.getSpid() == null ||
                    orderInfo.getCpid() == null || orderInfo.getChannel() == null ||
                    orderInfo.getSignature() == null){
                throw new BussinessException("80015", "参数异常");
            }
        }
    }


    /**
     * 拼接签名信息 orderid+channel+timestamp
     *
     * @param
     * @return
     */
    public String getSign(OrderInfo orderInfo) throws Exception {
        StringBuilder strb = new StringBuilder();
        String userid = orderInfo.getUserid();
        strb.append(userid);
        strb.append(orderInfo.getChannel());
        strb.append(orderInfo.getSpid());
        strb.append(orderInfo.getCpid());
        strb.append(orderInfo.getTimestamp());
        return strb.toString();
    }
    /**
     * 签名验证
     *
     * @param
     * @throws Exception
     */
    public void signValidate(OrderInfo orderInfo) throws Exception {
        String lcalsign = getSign(orderInfo);
        String channel = orderInfo.getChannel();
        lcalsign += channelDao.queryChannel(channel).getPassword();
        System.out.println("local-->" + lcalsign);
        lcalsign = MD5.MD5Encode(lcalsign);
        System.out.println("orderinfo==>" + orderInfo.getSignature());
        System.out.println("lcalsign===>" + lcalsign);
        if (!lcalsign.equals(orderInfo.getSignature())) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }


    /**
     * 手机号码验证
     *
     * @param usermob
     * @throws Exception
     */
    private void mobValidate(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 static void main(String[] args) {
        //{"timestamp":"1605086621","spid":"242","userid":"fnn7XhinY498ugTFPGXhvQ==","cpid":"prmInfo","channel":"TX20_twpc_qry","signature":"79c14acbf347f3eaca877836af89477b"}

    }
}
