package com.bonus.boot.manager.manager.utils;




import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class IdCardValidateUtil {
    // 校验身份证号码合法性
    public static boolean checkIdCard(String IdCard) {
        if (checkCode(IdCard)) {
            String date = IdCard.substring(6, 14);
            if (checkDate(date)) {
                if (checkProv(IdCard.substring(0, 2))) {
                    return true;
                }
            }
        }
        return false;
    }

    // 身份证校验省份
    private static boolean checkProv(String val) {
        String reg = "^[1-9][0-9]$";
        // {11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江
        // ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北
        // ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏
        // ",61:"陕西",;62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门"};
        Integer[] arr = {11, 12, 13, 14, 15, 21, 22, 23, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 50, 51, 52,
                53, 54, 61, 62, 63, 64, 65, 71, 81, 82};
        List<Integer> list = Arrays.asList(arr);
        if (Pattern.matches(reg, val) && list.contains(Integer.valueOf(val))) {
            return true;
        }
        return false;
    }

    // 身份证校验出生日期
    private static boolean checkDate(String val) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        sdf.setLenient(false);
        try {
            sdf.parse(val);
        } catch (ParseException e) {
            return false;
        }
        return true;
    }

    // 身份证校验码校验
    private static boolean checkCode(String val) {
        String reg = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9X]$";
        int[] factor = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        String[] parity = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
        String code = val.substring(17);
        if (Pattern.matches(reg, val)) {
            int sum = 0;
            char[] c = val.toCharArray();
            for (int i = 0; i < 17; i++) {
                sum += Integer.valueOf(String.valueOf(c[i])) * factor[i];
            }
            if (code.equalsIgnoreCase(parity[sum % 11])) {
                return true;
            }
        }
        return false;
    }
}
