package com.codvision.basic.util;

import lombok.extern.slf4j.Slf4j;

/**
 * @author KX
 * @date 2023/5/11 10:18
 */
@Slf4j
public class AddressCheckCodeUtil {

    /**
     * 身份证校验方式：https://www.doc88.com/p-9488630368918.html
     * 参考身份证 WI 加权因子计算
     * 身份证为：2^(i-1) % 11
     * <p>
     * 此处计算方式改为 (i*3 + 1) % 10
     */
    private static final String[] WI = {"1", "2", "4", "8", "5", "10", "9", "7", "3", "6",
            "1", "2", "4", "8", "5", "10", "9", "7", "3", "6",
            "1", "2", "4", "8", "5", "10", "9"};

    private static final String[] VERIFY_CODE = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};


    public static String getAddressCode(String addressCode) {
        int sum = 0;
        // a1 + sum(ai*wi) (i=2开始)
        for (int i = 0; i < addressCode.length(); i++) {
            int x;
            if (addressCode.charAt(i) == 'X') {
                x = 10;
            } else {
                x = Integer.parseInt(String.valueOf(addressCode.charAt(i)));
            }
            log.info("x:" + x + "   WI:" + WI[addressCode.length() - i]);
            sum += x * Integer.parseInt(WI[addressCode.length() - i]);
        }
        // 身份证校验码 (sum + 校验码) % 11 = 1
        int num = sum % 11;
        return addressCode + VERIFY_CODE[num];
    }


    public static void main(String[] args) {
        System.out.println("生成身份证号校验位"+getAddressCode("45048119780423443"));
    }
}
