package com.bonus.common.core.utils;

import java.util.regex.Pattern;

/**
 * 身份证工具类
 */
public class IdCardUtil {


    public static String getGenderByIdCard(String idCard) {
        if (idCard == null || (idCard.length() != 18 && idCard.length() != 15)) {
            throw new IllegalArgumentException("身份证号码长度不正确");
        }
        char sexFlag = idCard.charAt(idCard.length() - 2); // 性别标志位
        return (sexFlag % 2 == 0) ? "0" : "1";
    }
    public static boolean isValidChineseID(String id) {
        if (id == null || (id.length() != 18)) {
            return false;
        }

        char[] idArray = id.toCharArray();
        int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] checkCode = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int sum = 0;

        for (int i = 0; i < idArray.length - 1; i++) {
            int num = Integer.parseInt(String.valueOf(idArray[i]));
            if (num < 0 || num > 9) {
                return false;
            }
            sum += num * weight[i];
        }

        sum = sum % 11;
        char lastChar = idArray[17];
        return lastChar == checkCode[sum];
    }

    private static final Pattern CHINA_MOBILE_PATTERN =
            Pattern.compile("^1[3-9]\\d{9}$");

    /**
     * 验证手机号码是否有效。
     * @param number 要验证的手机号码
     * @return 如果手机号码有效，则返回true；否则返回false。
     */
    public static boolean isValidChinaMobileNumber(String number) {
        return CHINA_MOBILE_PATTERN.matcher(number).matches();
    }
}
