package com.xinelu.common.utils;

import com.xinelu.common.exception.ServiceException;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * @author ljh
 * @version 1.0
 * Create by 2023/2/27 11:45
 */
public class AgeUtil {

    /**
     * 根据出生日期计算年龄数值
     *
     * @param date 出生日期
     * @return 年龄数值
     */
    public static Long getAgeMonth(String date) {
        if (StringUtils.isBlank(date)) {
            throw new ServiceException("请输入正确的出生日期！");
        }
        String[] data = StringUtils.split(date, "-");
        if (data.length < 3) {
            throw new ServiceException("请输入正确的出生日期！");
        }
        Calendar birthday = new GregorianCalendar(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2]));
        Calendar now = Calendar.getInstance();
        int day = now.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH);
        //月份从0开始计算，所以需要+1
        int month = now.get(Calendar.MONTH) + 1 - birthday.get(Calendar.MONTH);
        BigDecimal monthFraction;
        int year = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
        //按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
        if (day < 0) {
            month -= 1;
            //得到上一个月，用来得到上个月的天数。
            now.add(Calendar.MONTH, -1);
        }
        if (month < 0) {
            //当前月份加12个月
            monthFraction = BigDecimal.valueOf(month).add(BigDecimal.valueOf(12)).divide(BigDecimal.valueOf(12), 1, RoundingMode.HALF_UP);
            year--;
        } else {
            //当前月份
            monthFraction = BigDecimal.valueOf(month).divide(BigDecimal.valueOf(12), 1, RoundingMode.HALF_UP);
        }
        BigDecimal bigDecimal = BigDecimal.ZERO;
        if (year >= 0) {
            bigDecimal = bigDecimal.add(BigDecimal.valueOf(year));
        }
        if ((monthFraction.compareTo(BigDecimal.ZERO) > 0)) {
            bigDecimal = bigDecimal.add(monthFraction);
        }
        //今天出生
        if (year == 0 && month == 0 && day == 0) {
            return BigDecimal.ZERO.longValue();
        }
        return Math.round(bigDecimal.doubleValue());
    }

}

