package com.quantgroup.asset.distribution.service.newrule.common;

import cn.quantgroup.motan.bean.UserAssociationBean;
import com.quantgroup.asset.distribution.model.entity.user.SDKUserInfo;
import com.quantgroup.asset.distribution.model.entity.user.UserAddressInfo;
import com.quantgroup.asset.distribution.service.alarm.IAlarmService;
import com.quantgroup.asset.distribution.service.alarm.impl.MarkdownMessage;
import com.quantgroup.asset.distribution.service.newrule.pojo.enums.AreaEnum;
import com.quantgroup.asset.distribution.service.newrule.pojo.enums.SpecialRuleEnum;
import com.quantgroup.asset.distribution.service.newrule.pojo.funds.RuleParam;
import com.quantgroup.asset.distribution.service.user.IUserCenterService;
import com.quantgroup.asset.distribution.util.IdCardUtil;
import com.quantgroup.asset.distribution.util.JacksonUtil;
import com.quantgroup.asset.distribution.util.PhoneNumberGeo;
import com.quantgroup.asset.distribution.util.PhoneNumberInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author shihuajun
 * @date 2021/9/2 16:28
 * @ describing
 */
@Slf4j
@Component("commonAreaVerifyImpl")
public class AreaVerifyImpl extends AbstractProductRuleVerifyImpl {
    private static final String PROVINCE = "省";
    private static final String SHI = "市";

    private static final String TEL_ALERM_TEXT = "用户的手机号是 %s";

    @Resource
    private IAlarmService alarmService;

    @Resource
    private IUserCenterService userCenterService;

    @Override
    public boolean pass(RuleParam param) {
        if (StringUtils.isBlank(param.getArea()) && !AreaEnum.NO_DEMAND.equals(param.getAreaNum())){
            throw new RuntimeException("区域配置有问题");
        }else if (AreaEnum.NO_DEMAND.equals(param.getAreaNum())){
            log.info("地区校验通过NO_DEMAND");
            return Boolean.TRUE;
        }
        RuleParam.AreaRuleConcrete ruleConcrete = JacksonUtil.deserialize(param.getArea(), RuleParam.AreaRuleConcrete.class);
        if (ruleConcrete == null){
            throw new RuntimeException("反序列化对象AreaRuleConcrete出问题了");
        }
        UserAssociationBean userInfo = param.getUserInfo();
        AtomicInteger hit = new AtomicInteger(0);
        if (StringUtils.isNotBlank(ruleConcrete.getNativeList())){
            String nativeList = ruleConcrete.getNativeList();
            String nativeCode = IdCardUtil.getCityCodeByIdCard(userInfo.getIdNo());
            if (StringUtils.isNotBlank(nativeCode)){
                String[] nativeCodeList = nativeList.replaceAll("\\[", "").replaceAll("]", "").split(",");
                if (ArrayUtils.isNotEmpty(nativeCodeList)) {
                    for (String configCode : nativeCodeList) {
                        String provCode = nativeCode.substring(0, 2);
                        String cityCode = nativeCode.substring(0, 4);
                        if (configCode.endsWith("0000") && configCode.startsWith(provCode)) {
                            log.info("省份匹配");
                            hit.incrementAndGet();
                            break;
                        }
                        if (configCode.endsWith("00") && configCode.startsWith(cityCode)) {
                            log.info("城市匹配");
                            hit.incrementAndGet();
                            break;
                        }
                        if (!configCode.endsWith("00") && configCode.equals(nativeCode)) {
                            log.info("区域匹配");
                            hit.incrementAndGet();
                            break;
                        }
                    }
                }
            }
            if (AreaEnum.CHOOSE_ONE_MORE.equals(param.getAreaNum()) && hit.get() >= AreaEnum.CHOOSE_ONE_MORE.getCode()){
                log.info("地区校验通过CHOOSE_ONE_MORE");
                return true;
            }
        }
        if (StringUtils.isNotBlank(ruleConcrete.getResidenceList())){
            String residenceList = ruleConcrete.getResidenceList();
            SDKUserInfo userExtInfo = userCenterService.getSDKUserExtInfo(userInfo.getPhoneNo(), null);
            List<UserAddressInfo> addressList = userExtInfo.getAddressList();
            if (!CollectionUtils.isEmpty(addressList)){
                UserAddressInfo userAddressInfo = addressList.get(0);
                boolean residenceResult = (userAddressInfo.getDistrictCode() != null && residenceList.contains(String.valueOf(userAddressInfo.getDistrictCode())))
                        || (userAddressInfo.getCityCode() != null && residenceList.contains(String.valueOf(userAddressInfo.getCityCode())))
                        || (userAddressInfo.getProvinceCode() != null && residenceList.contains(String.valueOf(userAddressInfo.getProvinceCode())));
                if (residenceResult){
                    hit.incrementAndGet();
                }
            }
            if ((AreaEnum.TWO_OUT_OF_MANY.equals(param.getAreaNum()) && hit.get() >= AreaEnum.TWO_OUT_OF_MANY.getCode())
                    || (AreaEnum.CHOOSE_ONE_MORE.equals(param.getAreaNum()) && hit.get() >= AreaEnum.CHOOSE_ONE_MORE.getCode())){
                log.info("地区校验通过TWO_OUT_OF_MANY or CHOOSE_ONE_MORE");
                return true;
            }
        }
        if (StringUtils.isNotBlank(ruleConcrete.getTelAreaNameList())){
            String telAreaNameList = ruleConcrete.getTelAreaNameList();
            PhoneNumberGeo phoneNumberGeo = new PhoneNumberGeo();
            PhoneNumberInfo numberInfo = phoneNumberGeo.lookup(userInfo.getPhoneNo());
            if (numberInfo == null){
                log.error("解析手机号出现问题,用户的手机号是 {}",userInfo.getPhoneNo());
                MarkdownMessage markdownMessage = new MarkdownMessage();
                markdownMessage.setTitle("解析手机号出现问题");
                markdownMessage.add(String.format(TEL_ALERM_TEXT,userInfo.getPhoneNo()));
                alarmService.sendMsgWithAlert(markdownMessage);
                log.info("地区校验通过,解析手机号出现问题");
                return Boolean.FALSE;
            }
            String province = numberInfo.getProvince() + PROVINCE;
            String shi = numberInfo.getProvince() + SHI;
            if (telAreaNameList.contains(province) || telAreaNameList.contains(shi) || telAreaNameList.contains(numberInfo.getProvince()) ){
                hit.incrementAndGet();
            }
            if ((AreaEnum.ALL_DEMAND.equals(param.getAreaNum()) && hit.get() >= AreaEnum.ALL_DEMAND.getCode())
                || (AreaEnum.TWO_OUT_OF_MANY.equals(param.getAreaNum()) && hit.get() >= AreaEnum.TWO_OUT_OF_MANY.getCode())
                || (AreaEnum.CHOOSE_ONE_MORE.equals(param.getAreaNum()) && hit.get() >= AreaEnum.CHOOSE_ONE_MORE.getCode())){
                log.info("地区校验通过ALL_DEMAND or TWO_OUT_OF_MANY or CHOOSE_ONE_MORE");
                return true;
            }
        }
        log.info("地区校验未通过");
        return Boolean.FALSE;
    }


    @Override
    public SpecialRuleEnum specialRuleName() {
        return SpecialRuleEnum.AREA_VERIFY;
    }
}
