package com.ruoyi.web.modules.industryservice.support;

import java.math.BigDecimal;
import java.math.RoundingMode;
import com.ruoyi.web.modules.industryservice.domain.BizDisposableIncome;

/**
 * 可支配收入增幅、增速：可选填；未填或口径变更时按公式计算。
 * 增幅 = 本年人均可支配收入 - 上年人均可支配收入；
 * 增速 = (增幅 / 上年人均可支配收入) × 100，保留 2 位小数。
 */
public final class DisposableIncomeGrowthSupport
{
    private static final int RATE_SCALE = 2;

    private DisposableIncomeGrowthSupport()
    {
    }

    /**
     * 按公式强制重算增幅、增速（先清空再填）。
     */
    public static void recalculateGrowth(BizDisposableIncome current, BizDisposableIncome previousYear)
    {
        if (current == null)
        {
            return;
        }
        current.setIncomeIncrease(null);
        current.setIncomeGrowthRate(null);
        fillMissingGrowth(current, previousYear);
    }

    /**
     * 仅对未填写的增幅、增速按上年数据补齐；已填写的保留。
     */
    public static void fillMissingGrowth(BizDisposableIncome current, BizDisposableIncome previousYear)
    {
        if (current == null)
        {
            return;
        }
        if (current.getRuralDisposableIncome() == null || previousYear == null
                || previousYear.getRuralDisposableIncome() == null)
        {
            return;
        }
        BigDecimal prev = previousYear.getRuralDisposableIncome();
        BigDecimal increase = current.getRuralDisposableIncome().subtract(prev);
        if (current.getIncomeIncrease() == null)
        {
            current.setIncomeIncrease(increase);
        }
        if (current.getIncomeGrowthRate() == null)
        {
            BigDecimal usedIncrease = current.getIncomeIncrease() != null ? current.getIncomeIncrease() : increase;
            if (prev.compareTo(BigDecimal.ZERO) != 0)
            {
                current.setIncomeGrowthRate(usedIncrease.multiply(BigDecimal.valueOf(100))
                        .divide(prev, RATE_SCALE, RoundingMode.HALF_UP));
            }
        }
    }

    public static boolean sameDecimal(BigDecimal a, BigDecimal b)
    {
        if (a == null && b == null)
        {
            return true;
        }
        if (a == null || b == null)
        {
            return false;
        }
        return a.compareTo(b) == 0;
    }
}
