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

import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
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.YakAssetGrowthChartVo;
import com.ruoyi.web.modules.industryservice.mapper.BizYakGrowthRecordMapper;
import com.ruoyi.web.modules.industryservice.support.ThirdPartyFarmingProperties;
import com.ruoyi.web.modules.industryservice.support.ThirdPartyIotWeighingClient;
import com.ruoyi.web.modules.industryservice.support.YakAssetGrowthSupport;
import com.ruoyi.web.modules.industryservice.support.YakAssetRules;

/**
 * 牦牛档案详情「生长性状」实时数据服务。
 * <p>
 * 体重来自 {@code GET /open-api/v1/iot/weighings}：
 * {@code cattleId} = 档案 {@code external_id}，
 * 称重开始/结束时间默认近一年至当前。
 * 采集时间 = {@code weighingTime}。日龄、体高、胸围、体长暂无接口，保持 null。
 * </p>
 */
@Service
public class YakAssetGrowthLiveService
{
    private static final Logger log = LoggerFactory.getLogger(YakAssetGrowthLiveService.class);

    @Autowired
    private ThirdPartyIotWeighingClient weighingClient;

    @Autowired
    private BizYakGrowthRecordMapper growthRecordMapper;

    @Autowired
    private ThirdPartyFarmingProperties properties;

    /** 详情生长性状列表：近一年称重记录 */
    public List<BizYakGrowthRecord> fetchGrowthRecords(BizYakAsset asset)
    {
        return YakAssetGrowthSupport.toGrowthRecords(
                safeFetchWeighings(asset, YakAssetRules.DEFAULT_GROWTH_LOOKBACK_DAYS));
    }

    /** 生长曲线：体重来自称重 OpenAPI；体高/胸围/体长读本地子表（暂无第三方接口） */
    public YakAssetGrowthChartVo fetchGrowthChart(BizYakAsset asset, String metric)
    {
        if (asset == null || StringUtils.isEmpty(metric))
        {
            return new YakAssetGrowthChartVo();
        }
        String m = metric.trim().toLowerCase();
        List<BizYakGrowthRecord> rows;
        if (YakAssetRules.METRIC_WEIGHT.equals(m))
        {
            rows = YakAssetGrowthSupport.toGrowthRecords(
                    safeFetchWeighings(asset, YakAssetRules.DEFAULT_GROWTH_LOOKBACK_DAYS));
        }
        else
        {
            rows = growthRecordMapper.selectByYakAssetId(asset.getId());
        }
        return YakAssetGrowthSupport.toGrowthChart(rows, m);
    }

    private List<OpenWeighingDto> safeFetchWeighings(BizYakAsset asset, int lookbackDays)
    {
        if (!properties.isEnabled() || asset == null || lookbackDays <= 0)
        {
            return Collections.emptyList();
        }
        Long cattleId = YakAssetGrowthSupport.resolveWeighingCattleIdParam(asset);
        if (cattleId == null)
        {
            return Collections.emptyList();
        }
        Date endTime = new Date();
        Date startTime = new Date(endTime.getTime() - lookbackDays * 24L * 60 * 60 * 1000L);
        try
        {
            return weighingClient.fetchByCattleId(cattleId, startTime, endTime);
        }
        catch (Exception ex)
        {
            log.warn("读取牛只称重数据失败 cattleId={}: {}", cattleId, ex.getMessage());
            return Collections.emptyList();
        }
    }
}
