package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONObject;

import java.util.Calendar;

public class IDCard {
    /**
     * 通过身份证号码获取出生日期、性别、年龄
     * @param certificateNo
     * @return 返回的出生日期格式：1990-01-01 性别格式：F-女，M-男
     */
    public static JSONObject getBirAgeSex(String certificateNo) {
        String birthday = "";
        int age = 0;
        String sexCode = "";

        int year = Calendar.getInstance().get(Calendar.YEAR);
        int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
        int day = Calendar.getInstance().get(Calendar.DATE);
        char[] number = certificateNo.toCharArray();
        boolean flag = true;
        if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag)
                    return new JSONObject();
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && number.length == 18) {
            birthday = certificateNo.substring(6, 10) + "-" + certificateNo.substring(10, 12) + "-"
                    + certificateNo.substring(12, 14);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1))
                    % 2 == 0 ? "F" : "M";
            if ((Integer.parseInt(certificateNo.substring(10, 12)) < month) || (Integer.parseInt(certificateNo.substring(10, 12)) == month && (Integer.parseInt(certificateNo.substring(12, 14))<= day) )){
                age = year - Integer.parseInt(certificateNo.substring(6, 10));
            }else {
                age = year - Integer.parseInt(certificateNo.substring(6, 10)) - 1;
            }
        }
        JSONObject map = new JSONObject();
        map.put("birthday", birthday);
        map.put("age", age);
        map.put("sexCode", sexCode);
        return map;
    }
}
