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

/**
 * 第三方 IoT 耳标温度步数客户端实现。
 */
@Component
public class ThirdPartyIotEarTagClientImpl implements ThirdPartyIotEarTagClient
{
    private static final String STUB_RESOURCE = "thirdparty/stub-iot-ear-tags.json";

    private static final String LIST_PATH = "/open-api/v1/iot/ear-tags";

    private final ObjectMapper objectMapper = ThirdPartyFarmingHttpSupport.createObjectMapper();

    @Autowired
    private ThirdPartyFarmingProperties properties;

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

    @Override
    public List<OpenEarTagDto> 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<OpenEarTagDto>>>() { }, "耳标温度步数", params);
        }
        return filterStubRows(ThirdPartyFarmingPageFetcher.fetchFromStub(objectMapper, STUB_RESOURCE,
                new TypeReference<List<OpenEarTagDto>>() { }, "耳标温度步数"), null, startTime, endTime);
    }

    @Override
    public List<OpenEarTagDto> fetchByEarTag(String earTagNumber, Date startTime, Date endTime)
    {
        if (!properties.isEnabled())
        {
            throw new ServiceException("第三方 IoT 耳标数据同步未启用");
        }
        if (com.ruoyi.common.utils.StringUtils.isEmpty(earTagNumber))
        {
            throw new ServiceException("耳标编号不能为空");
        }
        if ("http".equalsIgnoreCase(properties.getMode()))
        {
            Map<String, String> params = IotSyncSupport.buildEarTagQueryParams(earTagNumber, startTime, endTime);
            return ThirdPartyFarmingPageFetcher.fetchAllPages(properties, objectMapper, LIST_PATH,
                    new TypeReference<OpenApiResponse<OpenApiPageResult<OpenEarTagDto>>>() { }, "耳标温度步数", params);
        }
        return filterStubRows(ThirdPartyFarmingPageFetcher.fetchFromStub(objectMapper, STUB_RESOURCE,
                new TypeReference<List<OpenEarTagDto>>() { }, "耳标温度步数"), earTagNumber.trim(), startTime, endTime);
    }

    private static List<OpenEarTagDto> filterStubRows(List<OpenEarTagDto> all, String earTagNumber,
            Date startTime, Date endTime)
    {
        if (startTime == null && endTime == null && earTagNumber == null)
        {
            return all;
        }
        List<OpenEarTagDto> filtered = new ArrayList<>();
        for (OpenEarTagDto row : all)
        {
            if (row == null)
            {
                continue;
            }
            if (earTagNumber != null && !earTagNumber.equalsIgnoreCase(
                    row.getEarTagNumber() != null ? row.getEarTagNumber().trim() : null))
            {
                continue;
            }
            Date eventTime = FarmingSyncSupport.parseThirdPartyTime(row.getReportTime(), null);
            if (IotSyncSupport.withinIncrementalWindow(eventTime, startTime, endTime))
            {
                filtered.add(row);
            }
        }
        return filtered;
    }
}
