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

/**
 * 第三方 IoT 牦牛定位项圈客户端实现。
 */
@Component
public class ThirdPartyIotCollarLocationClientImpl implements ThirdPartyIotCollarLocationClient
{
    private static final String STUB_RESOURCE = "thirdparty/stub-iot-collar-locations.json";

    private static final String LIST_PATH = "/open-api/v1/iot/collar-locations";

    private final ObjectMapper objectMapper = ThirdPartyFarmingHttpSupport.createObjectMapper();

    @Autowired
    private ThirdPartyFarmingProperties properties;

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

    @Override
    public List<OpenCollarLocationDto> 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<OpenCollarLocationDto>>>() { }, "定位项圈", params);
        }
        List<OpenCollarLocationDto> all = ThirdPartyFarmingPageFetcher.fetchFromStub(objectMapper, STUB_RESOURCE,
                new TypeReference<List<OpenCollarLocationDto>>() { }, "定位项圈");
        if (startTime == null && endTime == null)
        {
            return all;
        }
        List<OpenCollarLocationDto> filtered = new ArrayList<>();
        for (OpenCollarLocationDto row : all)
        {
            Date eventTime = FarmingSyncSupport.parseThirdPartyTime(
                    row != null ? row.getReportTime() : null, null);
            if (IotSyncSupport.withinIncrementalWindow(eventTime, startTime, endTime))
            {
                filtered.add(row);
            }
        }
        return filtered;
    }
}
