package com.jojubanking.boot.module.system.util.xytj;

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

public class IDCardParser {
    private String idCardNumber;
    private String birthDate;
    private int gender;

    public IDCardParser(String idCardNumber) {
        this.idCardNumber = idCardNumber;
    }

    public void parse() {
        // 定义身份证号码的正则表达式
        String regex = "^\\d{17}(\\d{1}|[Xx])$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(idCardNumber);

        // 如果身份证号码格式匹配
        if (matcher.matches()) {
            // 提取出生日期和性别信息
            String birthDatePart = idCardNumber.substring(6, 14);
            this.birthDate = formatDate(birthDatePart);
            this.gender = getGender(idCardNumber);
        } else {
            System.out.println("身份证号码格式不正确！");
        }
    }

    private String formatDate(String datePart) {
        // 格式化日期字符串为年月日格式
        String year = datePart.substring(0, 4);
        String month = datePart.substring(4, 6);
        String day = datePart.substring(6, 8);

        return year + "-" + month + "-" + day;
    }

    private int getGender(String idCardNumber) {
        // 获取倒数第二位的数字
        int genderDigit = Integer.parseInt(idCardNumber.substring(16, 17));

        // 判断奇偶性别
        if (genderDigit % 2 == 0) {
            return 2;  //2 女
        } else {
            return 1;   //1 男
        }
    }

    public String getBirthDate() {
        return birthDate;
    }

    public int getGender() {
        return gender;
    }
}
