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

import java.math.BigDecimal;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizFarmerHousehold;

/**
 * 农牧户派生字段与是/否规范化。
 * <p>
 * 派生：
 * <ul>
 *   <li>草场承包总面积 = 禁牧面积 + 草畜平衡面积</li>
 *   <li>补助奖励总资金 = 禁牧补助 + 草畜平衡奖励</li>
 *   <li>补助合计金额 = 补助奖励总资金 + 封顶保底后享受补助奖励总资金 + 村级草原监督员补助</li>
 * </ul>
 * </p>
 */
public final class FarmerHouseholdDerivedSupport
{
    public static final String YES = "是";

    public static final String NO = "否";

    private FarmerHouseholdDerivedSupport()
    {
    }

    public static void applyDerived(BizFarmerHousehold row)
    {
        if (row == null)
        {
            return;
        }
        row.setPastureContractArea(safeDec(row.getGrazingBanArea()).add(safeDec(row.getGrassBalanceArea())));
        row.setSubsidyRewardSubtotal(safeDec(row.getGrazingBanSubsidy()).add(safeDec(row.getGrassBalanceReward())));
        // 补助合计金额 = 补助奖励总资金 + 封顶保底后享受补助奖励总资金 + 村级草原监督员补助
        row.setSubsidyTotal(safeDec(row.getSubsidyRewardSubtotal())
                .add(safeDec(row.getAfterCapFloorSubsidy()))
                .add(safeDec(row.getVillageSupervisorSubsidy())));
    }

    /**
     * 草畜失衡判定（交接表注 7）：不依赖「草畜平衡计算」模块。
     * <p>核定年末草畜平衡载畜量 &lt; 年底牲畜存栏（绵羊单位）→ 失衡；否则（含等于）→ 已平衡。</p>
     */
    public static boolean isImbalanced(BizFarmerHousehold row)
    {
        if (row == null || row.getApprovedCarryingCapacity() == null || row.getYearEndStockSheepUnit() == null)
        {
            return false;
        }
        return row.getApprovedCarryingCapacity().compareTo(row.getYearEndStockSheepUnit()) < 0;
    }

    public static String normalizeYesNo(String value, String fieldLabel)
    {
        if (StringUtils.isEmpty(value))
        {
            return null;
        }
        String text = value.trim();
        if (YES.equals(text) || NO.equals(text))
        {
            return text;
        }
        throw new ServiceException(fieldLabel + "只能填写「是」或「否」");
    }

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