package com.ruoyi.logistics.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 税务金额计算工具类（保证精度，适配财务/税务规则）
 */
public class TaxAmountCalculator {
    // 小数位数：中间计算保留6位，最终展示保留2位（符合税务要求）
    private static final int SCALE_DETAIL = 6;
    private static final int SCALE_FINAL = 2;
    // 舍入模式：四舍五入（财务/税务标准）
    private static final RoundingMode ROUND_MODE = RoundingMode.HALF_UP;

    /**
     * 1. 已知含税金额 + 税率 → 计算不含税金额 + 税额
     * @param taxIncludedAmount 含税金额（如113.00元）
     * @param taxRate 税率（如13%则传0.13）
     * @return 结果数组：[0]不含税金额 [1]税额
     */
    public static BigDecimal[] calculateFromTaxIncluded(BigDecimal taxIncludedAmount, BigDecimal taxRate) {
        // 校验参数（非空、非负）
        validateAmount(taxIncludedAmount);
        validateRate(taxRate);

        // 计算不含税金额：含税金额 / (1 + 税率)
        BigDecimal taxExcludedAmount = taxIncludedAmount
                .divide(BigDecimal.ONE.add(taxRate), SCALE_DETAIL, ROUND_MODE)
                .setScale(SCALE_FINAL, ROUND_MODE); // 最终保留2位

        // 计算税额：含税金额 - 不含税金额（避免乘法误差）
        BigDecimal taxAmount = taxIncludedAmount.subtract(taxExcludedAmount)
                .setScale(SCALE_FINAL, ROUND_MODE);

        return new BigDecimal[]{taxExcludedAmount, taxAmount};
    }

    /**
     * 2. 已知不含税金额 + 税率 → 计算含税金额 + 税额
     * @param taxExcludedAmount 不含税金额（如100.00元）
     * @param taxRate 税率（如13%则传0.13）
     * @return 结果数组：[0]含税金额 [1]税额
     */
    public static BigDecimal[] calculateFromTaxExcluded(BigDecimal taxExcludedAmount, BigDecimal taxRate) {
        validateAmount(taxExcludedAmount);
        validateRate(taxRate);

        // 计算税额：不含税金额 × 税率
        BigDecimal taxAmount = taxExcludedAmount.multiply(taxRate)
                .setScale(SCALE_FINAL, ROUND_MODE);

        // 计算含税金额：不含税金额 + 税额
        BigDecimal taxIncludedAmount = taxExcludedAmount.add(taxAmount);

        return new BigDecimal[]{taxIncludedAmount, taxAmount};
    }

    /**
     * 3. 批量金额汇总计算（多笔金额合计，避免逐笔舍入误差）
     * @param taxIncludedAmounts 多笔含税金额数组
     * @param taxRate 税率
     * @return 汇总结果：[0]汇总不含税金额 [1]汇总税额 [2]汇总含税金额
     */
    public static BigDecimal[] calculateBatchTotal(BigDecimal[] taxIncludedAmounts, BigDecimal taxRate) {
        validateRate(taxRate);
        if (taxIncludedAmounts == null || taxIncludedAmounts.length == 0) {
            return new BigDecimal[]{BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO};
        }

        // 先汇总含税金额（避免逐笔计算后舍入导致总额误差）
        BigDecimal totalTaxIncluded = BigDecimal.ZERO;
        for (BigDecimal amount : taxIncludedAmounts) {
            validateAmount(amount);
            totalTaxIncluded = totalTaxIncluded.add(amount);
        }

        // 基于汇总含税金额计算总额
        BigDecimal totalTaxExcluded = totalTaxIncluded
                .divide(BigDecimal.ONE.add(taxRate), SCALE_DETAIL, ROUND_MODE)
                .setScale(SCALE_FINAL, ROUND_MODE);
        BigDecimal totalTax = totalTaxIncluded.subtract(totalTaxExcluded)
                .setScale(SCALE_FINAL, ROUND_MODE);

        return new BigDecimal[]{totalTaxExcluded, totalTax, totalTaxIncluded};
    }

    // 校验金额：非空、非负
    private static void validateAmount(BigDecimal amount) {
        if (amount == null) {
            throw new IllegalArgumentException("金额不能为null");
        }
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("金额不能为负数：" + amount);
        }
    }

    // 校验税率：非空、0-1之间
    private static void validateRate(BigDecimal rate) {
        if (rate == null) {
            throw new IllegalArgumentException("税率不能为null");
        }
        if (rate.compareTo(BigDecimal.ZERO) < 0 || rate.compareTo(BigDecimal.ONE) > 0) {
            throw new IllegalArgumentException("税率需在0-1之间（如13%传0.13）：" + rate);
        }
    }

    // 测试示例
    public static void main(String[] args) {
        // 测试场景1：已知含税金额113元，税率13%
        BigDecimal taxIncluded = new BigDecimal("128900.56");
        BigDecimal taxRate = new BigDecimal("0.06");
        BigDecimal[] result1 = calculateFromTaxIncluded(taxIncluded, taxRate);
        System.out.println("场景1：含税金额113元，税率13%");
        System.out.println("不含税金额：" + result1[0] + " 元"); // 输出100.00
        System.out.println("税额：" + result1[1] + " 元"); // 输出13.00
        System.out.println("------------------------");

        // 测试场景2：已知不含税金额100元，税率13%
        BigDecimal taxExcluded = new BigDecimal("100.00");
        BigDecimal[] result2 = calculateFromTaxExcluded(taxExcluded, taxRate);
        System.out.println("场景2：不含税金额100元，税率13%");
        System.out.println("含税金额：" + result2[0] + " 元"); // 输出113.00
        System.out.println("税额：" + result2[1] + " 元"); // 输出13.00
        System.out.println("------------------------");

        // 测试场景3：批量金额汇总（113元 + 226元）
        BigDecimal[] batchAmounts = {new BigDecimal("113.00"), new BigDecimal("226.00")};
        BigDecimal[] result3 = calculateBatchTotal(batchAmounts, taxRate);
        System.out.println("场景3：批量金额汇总（113+226），税率13%");
        System.out.println("汇总不含税金额：" + result3[0] + " 元"); // 输出300.00
        System.out.println("汇总税额：" + result3[1] + " 元"); // 输出39.00
        System.out.println("汇总含税金额：" + result3[2] + " 元"); // 输出339.00
    }
}
