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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.industryservice.domain.dto.OpenApiPageResult;
import com.ruoyi.web.modules.industryservice.domain.dto.OpenApiResponse;
import com.ruoyi.web.modules.industryservice.domain.dto.OpenWeighingDto;

/**
 * 第三方 IoT 牛只称重客户端实现。
 * <p>
 * {@code mode=http} 时调用 {@link ThirdPartyFarmingPageFetcher} 分页拉取；
 * {@code mode=stub} 时读取 {@value #STUB_RESOURCE}。
 * </p>
 */
@Component
public class ThirdPartyIotWeighingClientImpl implements ThirdPartyIotWeighingClient
{
    /** Stub 样例：classpath:thirdparty/stub-iot-weighings.json */
    private static final String STUB_RESOURCE = "thirdparty/stub-iot-weighings.json";

    /** 查询牛只称重数据（Apifox 开放接口） */
    private static final String LIST_PATH = "/open-api/v1/iot/weighings";

    private final ObjectMapper objectMapper = ThirdPartyFarmingHttpSupport.createObjectMapper();

    @Autowired
    private ThirdPartyFarmingProperties properties;

    @Override
    public List<OpenWeighingDto> fetchAll()
    {
        return fetchIncremental(null, null, null);
    }

    @Override
    public List<OpenWeighingDto> fetchIncremental(Date startTime, Date endTime, Date updatedAfter)
    {
        if (!properties.isEnabled())
        {
            throw new ServiceException("第三方 IoT 称重同步未启用");
        }
        if ("http".equalsIgnoreCase(properties.getMode()))
        {
            Map<String, String> params = IotSyncSupport.buildIncrementalQueryParams(startTime, endTime, updatedAfter);
            return ThirdPartyFarmingPageFetcher.fetchAllPages(properties, objectMapper, LIST_PATH,
                    new TypeReference<OpenApiResponse<OpenApiPageResult<OpenWeighingDto>>>() { }, "牛只称重", params);
        }
        return filterStubRows(ThirdPartyFarmingPageFetcher.fetchFromStub(objectMapper, STUB_RESOURCE,
                new TypeReference<List<OpenWeighingDto>>() { }, "牛只称重"), null, startTime, endTime);
    }

    @Override
    public List<OpenWeighingDto> fetchByCattleId(Long cattleId, Date startTime, Date endTime)
    {
        if (!properties.isEnabled())
        {
            throw new ServiceException("第三方 IoT 称重同步未启用");
        }
        if (cattleId == null)
        {
            throw new ServiceException("牛只 ID 不能为空");
        }
        if ("http".equalsIgnoreCase(properties.getMode()))
        {
            Map<String, String> params = IotSyncSupport.buildWeighingQueryParams(cattleId, startTime, endTime);
            return ThirdPartyFarmingPageFetcher.fetchAllPages(properties, objectMapper, LIST_PATH,
                    new TypeReference<OpenApiResponse<OpenApiPageResult<OpenWeighingDto>>>() { }, "牛只称重", params);
        }
        return filterStubRows(ThirdPartyFarmingPageFetcher.fetchFromStub(objectMapper, STUB_RESOURCE,
                new TypeReference<List<OpenWeighingDto>>() { }, "牛只称重"), cattleId, startTime, endTime);
    }

    private static List<OpenWeighingDto> filterStubRows(List<OpenWeighingDto> all, Long cattleId,
            Date startTime, Date endTime)
    {
        if (startTime == null && endTime == null && cattleId == null)
        {
            return all;
        }
        List<OpenWeighingDto> filtered = new ArrayList<>();
        for (OpenWeighingDto row : all)
        {
            if (row == null)
            {
                continue;
            }
            if (cattleId != null && !cattleId.equals(row.getCattleId()))
            {
                continue;
            }
            Date eventTime = FarmingSyncSupport.parseThirdPartyTime(row.getWeighingTime(), null);
            if (IotSyncSupport.withinIncrementalWindow(eventTime, startTime, endTime))
            {
                filtered.add(row);
            }
        }
        return filtered;
    }
}
