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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizYakAsset;
import com.ruoyi.web.modules.industryservice.domain.BizYakGrowthRecord;
import com.ruoyi.web.modules.industryservice.domain.dto.OpenWeighingDto;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetGrowthChartPointVo;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetGrowthChartVo;

/**
 * 牦牛生长性状 OpenAPI 称重数据解析与曲线组装。
 * <p>
 * 当前仅体重有第三方来源（{@code /open-api/v1/iot/weighings}）；
 * 日龄、体高、胸围、体长暂无接口，保持 null。
 * </p>
 */
public final class YakAssetGrowthSupport
{
    private YakAssetGrowthSupport()
    {
    }

    /**
     * 称重接口 cattleId 查询参数：档案 {@code external_id}。
     */
    public static Long resolveWeighingCattleIdParam(BizYakAsset asset)
    {
        return asset == null ? null : asset.getExternalId();
    }

    public static Date parseWeighingTime(OpenWeighingDto dto)
    {
        return dto == null ? null : FarmingSyncSupport.parseThirdPartyTime(dto.getWeighingTime(), null);
    }

    /**
     * 将称重记录转为生长性状列表行：仅填充体重与采集时间，其余维度暂空。
     */
    public static List<BizYakGrowthRecord> toGrowthRecords(List<OpenWeighingDto> weighings)
    {
        if (weighings == null || weighings.isEmpty())
        {
            return new ArrayList<>();
        }
        List<BizYakGrowthRecord> rows = new ArrayList<>(weighings.size());
        for (OpenWeighingDto dto : weighings)
        {
            Date collectTime = parseWeighingTime(dto);
            BigDecimal weightKg = FarmingSyncSupport.parseDecimal(dto != null ? dto.getWeight() : null);
            if (collectTime == null && weightKg == null)
            {
                continue;
            }
            BizYakGrowthRecord row = new BizYakGrowthRecord();
            row.setWeightKg(weightKg);
            row.setCollectTime(collectTime);
            row.setDataKind(YakAssetRules.DATA_KIND_ACTUAL);
            rows.add(row);
        }
        rows.sort(Comparator.comparing(BizYakGrowthRecord::getCollectTime,
                Comparator.nullsLast(Comparator.naturalOrder())));
        return rows;
    }

    /**
     * 组装生长曲线：按 metric 取对应字段；实测/预测按 dataKind 分组。
     */
    public static YakAssetGrowthChartVo toGrowthChart(List<BizYakGrowthRecord> rows, String metric)
    {
        YakAssetGrowthChartVo chart = new YakAssetGrowthChartVo();
        if (rows == null || StringUtils.isEmpty(metric))
        {
            return chart;
        }
        String m = metric.trim().toLowerCase();
        for (BizYakGrowthRecord row : rows)
        {
            if (row == null)
            {
                continue;
            }
            BigDecimal value = resolveGrowthValue(row, m);
            if (value == null)
            {
                continue;
            }
            YakAssetGrowthChartPointVo point = new YakAssetGrowthChartPointVo();
            point.setDayAge(row.getDayAge());
            point.setValue(value);
            point.setCollectTime(row.getCollectTime());
            if (row.getDataKind() != null && row.getDataKind() == YakAssetRules.DATA_KIND_FORECAST)
            {
                chart.getForecast().add(point);
            }
            else
            {
                chart.getActual().add(point);
            }
        }
        return chart;
    }

    public static BigDecimal resolveGrowthValue(BizYakGrowthRecord row, String metric)
    {
        if (row == null || StringUtils.isEmpty(metric))
        {
            return null;
        }
        switch (metric.trim().toLowerCase())
        {
            case YakAssetRules.METRIC_HEIGHT:
                return row.getHeightCm();
            case YakAssetRules.METRIC_CHEST:
                return row.getChestCm();
            case YakAssetRules.METRIC_LENGTH:
                return row.getLengthCm();
            case YakAssetRules.METRIC_WEIGHT:
            default:
                return row.getWeightKg();
        }
    }
}
