package com.zhongshu.card.server.core.util;

import com.zhongshu.card.server.core.dataConfig.PasswordCheckConf;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 验证工具类
 *
 * @author TRX
 * @date 2024/6/4
 */
public class ValidateUtils {

    //身份证前17位数字依次乘以对应的权重因子
    public static final Integer[] idCardWeight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    //身份证最后一位对应的校验码
    public static final String[] idCardCheck = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};

    /**
     * 验证是否是手机号码
     *
     * @param phoneNumber
     * @return
     */
    public static boolean isPhoneNumber(String phoneNumber) {
        Pattern pattern = Pattern.compile("^1[0-9]{10}$");
        // 使用模式匹配手机号码
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }

    /**
     * 判断是否是身份证号码
     *
     * @param idCard
     * @return
     */
    public static boolean isIDCard(String idCard) {
        if (StringUtils.isEmpty(idCard) || idCard.trim().length() != 18) {
            return false;
        }

        idCard = idCard.trim().toUpperCase();
        //获取身份证最后一位进行验证
        String lastStr = idCard.substring(idCard.length() - 1);
        //获取身份证前17位
        String firstStr = idCard.substring(0, 17);
        //验证身份证前17位是否为数字
        boolean isDigits = Pattern.matches("^\\d{17}", firstStr);
        if (!isDigits) {
            return false;
        }
        // 组装根据余数，对应一个指定的校验码
        Map<Integer, String> idCardMap = new HashMap<>();
        // 全局变量
        if (idCardMap.isEmpty()) {
            for (int i = 0; i < 10; i++) {
                idCardMap.put(i, idCardCheck[i]);
            }
        }

        char[] idCardCharNumber = idCard.toCharArray();
        Integer resultSum = 0;
        for (int i = 0; i < idCardCharNumber.length - 1; i++) {
            resultSum += Character.getNumericValue(idCardCharNumber[i]) * idCardWeight[i];
        }
        // 将相加的前17位数字依次乘以对应的权重因子相加，相加的结果除以11，得到余数
        Integer lastResult = resultSum % 11;
        // 根据余数，对应一个指定的校验码。最终得到的校验码就是身份证号码的最后一位数字。通过这个校验码，可以验证前面17位数字是否正确，从而提高身份证号码的准确性
        if (idCardMap.containsKey(lastResult)) {
            return idCardMap.get(lastResult).equals(lastStr);
        }
        return false;
    }

    /**
     * 验证是否有特殊支付 (有一个就是true)
     *
     * @param str
     * @return
     */
    public static ValidateResult isContainsSpecial(String str) {
        ValidateResult result = new ValidateResult();
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？\\s]";
        Pattern pattern = Pattern.compile(validPattern);
        Matcher matcher = pattern.matcher(str);
        StringBuilder specialChars = new StringBuilder();
        while (matcher.find()) {
            result.setSuccess(true);
            specialChars.append(matcher.group());
        }
        result.setMsg(specialChars.toString());
        return result;
    }

    /**
     * 是否包含汉字 (有一个就是true)
     *
     * @param str
     * @return
     */
    public static ValidateResult isContainsChinese(String str) {
        ValidateResult result = new ValidateResult();
        Pattern pattern = Pattern.compile("[\u4E00-\u9FA5]");
        Matcher matcher = pattern.matcher(str);
        StringBuilder specialChars = new StringBuilder();
        while (matcher.find()) {
            result.setSuccess(true);
            specialChars.append(matcher.group());
        }
        result.setMsg(specialChars.toString());
        return result;
    }

    /**
     * 验证密码是否符合要求
     *
     * @param passWord
     * @return
     */
    public static ValidateResult validatePassWord(String passWord) {
        ValidateResult result = new ValidateResult();
        result.setSuccess(true);
        if (StringUtils.isEmpty(passWord)) {
            result.setSuccess(false);
            result.setMsg("密码不能为空");
        } else {
            if (passWord.length() < Integer.parseInt(PasswordCheckConf.MIN_LENGTH)
                    || passWord.length() > Integer.parseInt(PasswordCheckConf.MAX_LENGTH)) {
                result.setSuccess(false);
                result.setMsg(String.format("密码长度必须大于%s位，小于%s位", PasswordCheckConf.MIN_LENGTH, PasswordCheckConf.MAX_LENGTH));
            }
            if (result.isSuccess()) {
                // 是否包含汉字
                ValidateResult validateResult = isContainsChinese(passWord);
                if (validateResult.isSuccess()) {
                    result.setSuccess(false);
                    result.setMsg(String.format("密码不能包含汉字：%s", validateResult.getMsg()));
                }
            }
        }
        return result;
    }

}
