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

import cn.quantgroup.motan.bean.UserAssociationBean;
import cn.quantgroup.motan.retbean.XContactInfo;
import com.alibaba.fastjson.JSON;
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.newrule.common.AbstractProductRuleVerifyImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author shihuajun
 * @date 2021/8/26 19:44
 * @ describing
 */
@Slf4j
@Component
public class ContactsTelErrorVerifyImpl extends AbstractProductRuleVerifyImpl {
    private static final int TEL_LENGTH = 11;

    @Override
    public boolean pass(RuleParam param) {
        if (param == null){
            throw new RuntimeException("联系人手机号校验入参param有问题");
        }
        UserAssociationBean userInfo = param.getUserInfo();
        if (userInfo == null){
            throw new RuntimeException("联系人手机号校验入参userInfo有问题");
        }
        List<XContactInfo> contractResults = userInfo.getContractResults();
        if (CollectionUtils.isEmpty(contractResults)){
            log.warn("联系人手机号校验时发现联系人为空");
            return true;
        }
        for (XContactInfo info : contractResults) {
            if (StringUtils.isBlank(info.getPhoneNo())){
                log.warn("联系人手机号校验时发现联系人手机号为空，联系人信息 {}", JSON.toJSONString(info));
                continue;
            }
            if (this.telVerify(info.getPhoneNo())){
                log.warn("联系人手机号校验时发现当前用户手机号有问题，联系人信息 {}", JSON.toJSONString(info));
                return false;
            }
        }
        return true;
    }

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

    private boolean telVerify(String tel){
        if (tel.length() != TEL_LENGTH){
            return false;
        }
        if (!tel.startsWith("1")){
            return false;
        }
        return !tel.startsWith("170") || !tel.startsWith("171");
    }
}
