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

import java.math.BigDecimal;
import java.math.RoundingMode;
import com.ruoyi.web.modules.trading.domain.BizSupplier;

/**
 * 结算服务费与实际应付计算（生成时快照）。
 */
public final class SettlementFeeCalculator
{
    private static final int MONEY_SCALE = 2;

    private SettlementFeeCalculator()
    {
    }

    public static BigDecimal calcServiceFee(BizSupplier supplier, int totalHeads, BigDecimal totalAmount)
    {
        if (supplier == null || supplier.getFeeMethod() == null)
        {
            return BigDecimal.ZERO;
        }
        int method = supplier.getFeeMethod();
        if (method == SupplierRules.FEE_METHOD_PER_ACCOUNT)
        {
            return moneyZero();
        }
        if (method == SupplierRules.FEE_METHOD_PER_HEAD)
        {
            BigDecimal standard = nz(supplier.getFeeStandard());
            return money(standard.multiply(BigDecimal.valueOf(totalHeads)));
        }
        if (method == SupplierRules.FEE_METHOD_PER_AMOUNT)
        {
            BigDecimal rateSum = nz(supplier.getTransactionFeeRate()).add(nz(supplier.getManagementFeeRate()));
            return money(nz(totalAmount).multiply(rateSum).divide(BigDecimal.valueOf(100), MONEY_SCALE, RoundingMode.HALF_UP));
        }
        return moneyZero();
    }

    public static BigDecimal calcPayableAmount(BigDecimal totalAmount, BigDecimal serviceFee)
    {
        return money(nz(totalAmount).subtract(nz(serviceFee)));
    }

    private static BigDecimal money(BigDecimal value)
    {
        return nz(value).setScale(MONEY_SCALE, RoundingMode.HALF_UP);
    }

    private static BigDecimal moneyZero()
    {
        return BigDecimal.ZERO.setScale(MONEY_SCALE, RoundingMode.HALF_UP);
    }

    private static BigDecimal nz(BigDecimal value)
    {
        return value == null ? BigDecimal.ZERO : value;
    }
}
