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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizGrassLivestockImbalanceWarning;
import com.ruoyi.web.modules.industryservice.mapper.BizGrassLivestockImbalanceWarningMapper;

/**
 * 草畜失衡预警写入/清除（独立表）。
 */
@Component
public class GrassLivestockImbalanceWarningSyncSupport
{
    @Autowired
    private BizGrassLivestockImbalanceWarningMapper mapper;

    /**
     * 失衡则 upsert；已平衡则按 sourceKey 删除。
     */
    public void sync(boolean imbalanced, BizGrassLivestockImbalanceWarning payload)
    {
        if (payload == null || StringUtils.isEmpty(payload.getSourceKey()))
        {
            return;
        }
        if (!imbalanced)
        {
            mapper.deleteBySourceKey(payload.getSourceKey());
            return;
        }
        Date now = new Date();
        payload.setAlertTime(now);
        payload.setUpdateTime(now);
        BizGrassLivestockImbalanceWarning existing = mapper.selectBySourceKey(payload.getSourceKey());
        if (existing == null)
        {
            payload.setCreateTime(now);
            mapper.insert(payload);
        }
        else
        {
            payload.setId(existing.getId());
            mapper.updateContent(payload);
        }
    }

    public void deleteBySourceKeys(List<String> sourceKeys)
    {
        if (sourceKeys == null || sourceKeys.isEmpty())
        {
            return;
        }
        List<String> cleaned = new ArrayList<>();
        for (String key : sourceKeys)
        {
            if (StringUtils.isNotEmpty(key))
            {
                cleaned.add(key);
            }
        }
        if (!cleaned.isEmpty())
        {
            mapper.deleteBySourceKeys(cleaned);
        }
    }

    public static String buildMessage(Integer statYear, Integer statMonth, String townName, String villageName,
            String subjectName, BigDecimal approvedCarryingCapacity, BigDecimal yearEndStockSheepUnit)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("草畜失衡预警：");
        if (statYear != null)
        {
            sb.append(statYear).append("年");
        }
        if (statMonth != null)
        {
            sb.append(statMonth).append("月");
        }
        if (StringUtils.isNotEmpty(townName) || StringUtils.isNotEmpty(villageName))
        {
            sb.append(" ");
            if (StringUtils.isNotEmpty(townName))
            {
                sb.append(townName);
            }
            if (StringUtils.isNotEmpty(villageName))
            {
                sb.append(villageName);
            }
        }
        if (StringUtils.isNotEmpty(subjectName))
        {
            sb.append(" ").append(subjectName);
        }
        sb.append("：核定年末草畜平衡载畜量(")
                .append(approvedCarryingCapacity == null ? "-"
                        : approvedCarryingCapacity.stripTrailingZeros().toPlainString())
                .append(")小于年底牲畜存栏绵羊单位(")
                .append(yearEndStockSheepUnit == null ? "-"
                        : yearEndStockSheepUnit.stripTrailingZeros().toPlainString())
                .append(")");
        return sb.toString();
    }
}
