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.BizFamilyRanch;

/**
 * 家庭牧场派生字段与是/否规范化
 */
public final class FamilyRanchDerivedSupport
{
    public static final String YES = "是";

    public static final String NO = "否";

    private FamilyRanchDerivedSupport()
    {
    }

    public static void applyDerived(BizFamilyRanch row)
    {
        if (row == null)
        {
            return;
        }
        row.setStockSubtotal(safeInt(row.getCattleYearEndStock()) + safeInt(row.getSheepYearEndStock()));
        row.setGrasslandAreaSubtotal(safeDec(row.getGrassBalanceArea()).add(safeDec(row.getTransferGrassArea())));
        if (row.getIncome() != null && row.getExpense() != null)
        {
            row.setProfit(row.getIncome().subtract(row.getExpense()));
        }
        else
        {
            row.setProfit(null);
        }
        if (row.getApprovedCarryingCapacity() != null && row.getYearEndStockSheepUnit() != null)
        {
            row.setIsGrassBalanced(
                    row.getApprovedCarryingCapacity().compareTo(row.getYearEndStockSheepUnit()) >= 0 ? YES : NO);
        }
        else
        {
            row.setIsGrassBalanced(null);
        }
    }

    /**
     * 草畜失衡判定（交接约定；不依赖「草畜平衡计算」模块）。
     * <p>核定年末草畜平衡载畜量 &lt; 年底牲畜存栏（绵羊单位）→ 失衡；否则（含等于）→ 已平衡。</p>
     */
    public static boolean isImbalanced(BizFamilyRanch 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 + "只能填写「是」或「否」");
    }

    public static boolean isYes(String value)
    {
        return YES.equals(value);
    }

    private static int safeInt(Integer value)
    {
        return value == null ? 0 : value;
    }

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