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

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
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.YakDiseaseWarningDto;

/**
 * 第三方牦牛疾病预警客户端：stub 读取 classpath JSON；http 调用同源开放接口。
 */
@Component
public class ThirdPartyYakAlertClientImpl implements ThirdPartyYakAlertClient
{
    private static final String STUB_RESOURCE = "thirdparty/stub-yak-alerts.json";

    private static final String LIST_PATH = "/open-api/v1/farming/yak-alerts";

    private final ObjectMapper objectMapper = ThirdPartyFarmingHttpSupport.createObjectMapper();

    @Autowired
    private ThirdPartyFarmingProperties properties;

    @Override
    public List<YakDiseaseWarningDto> fetchAlerts()
    {
        if (!properties.isEnabled())
        {
            throw new ServiceException("第三方牦牛疾病预警同步未启用");
        }
        if ("http".equalsIgnoreCase(properties.getMode()))
        {
            return fetchFromHttp();
        }
        return fetchFromStub();
    }

    private List<YakDiseaseWarningDto> fetchFromStub()
    {
        try
        {
            ClassPathResource resource = new ClassPathResource(STUB_RESOURCE);
            if (!resource.exists())
            {
                return Collections.emptyList();
            }
            try (InputStream in = resource.getInputStream())
            {
                String json = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
                return objectMapper.readValue(json, new TypeReference<List<YakDiseaseWarningDto>>()
                {
                });
            }
        }
        catch (ServiceException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new ServiceException("读取第三方预警样例失败：" + e.getMessage());
        }
    }

    private List<YakDiseaseWarningDto> fetchFromHttp()
    {
        ThirdPartyFarmingHttpSupport.requireBaseUrl(properties, "第三方生产管理系统 base-url 未配置");
        RestTemplate restTemplate = ThirdPartyFarmingHttpSupport.createRestTemplate(properties);
        HttpHeaders headers = ThirdPartyFarmingHttpSupport.buildOpenApiHeaders(properties);
        String url = ThirdPartyFarmingHttpSupport.resolveUrl(properties, LIST_PATH);
        try
        {
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET,
                    new HttpEntity<>(headers), String.class);
            if (!response.getStatusCode().is2xxSuccessful() || response.getBody() == null)
            {
                throw new ServiceException("第三方预警接口返回异常");
            }
            return objectMapper.readValue(response.getBody(), new TypeReference<List<YakDiseaseWarningDto>>()
            {
            });
        }
        catch (ServiceException e)
        {
            throw e;
        }
        catch (RestClientException e)
        {
            throw new ServiceException("第三方服务不可用：" + e.getMessage());
        }
        catch (Exception e)
        {
            throw new ServiceException("解析第三方预警数据失败：" + e.getMessage());
        }
    }
}
