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

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
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.CollectionUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
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.OpenFarmDto;

/**
 * 第三方养殖场客户端：stub 读取 classpath JSON；http 分页调用开放接口。
 */
@Component
public class ThirdPartyFarmClientImpl implements ThirdPartyFarmClient
{
    private static final String STUB_RESOURCE = "thirdparty/stub-farms.json";

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

    private final ObjectMapper objectMapper = ThirdPartyFarmingHttpSupport.createObjectMapper();

    @Autowired
    private ThirdPartyFarmingProperties properties;

    @Override
    public List<OpenFarmDto> fetchAllFarms()
    {
        if (!properties.isEnabled())
        {
            throw new ServiceException("第三方养殖场同步未启用");
        }
        if ("http".equalsIgnoreCase(properties.getMode()))
        {
            return fetchFromHttp();
        }
        return fetchFromStub();
    }

    private List<OpenFarmDto> 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<OpenFarmDto>>()
                {
                });
            }
        }
        catch (ServiceException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new ServiceException("读取第三方养殖场样例失败：" + e.getMessage());
        }
    }

    private List<OpenFarmDto> fetchFromHttp()
    {
        ThirdPartyFarmingHttpSupport.requireBaseUrl(properties, "第三方生产管理系统 base-url 未配置");
        RestTemplate restTemplate = ThirdPartyFarmingHttpSupport.createRestTemplate(properties);
        HttpHeaders headers = ThirdPartyFarmingHttpSupport.buildOpenApiHeaders(properties);
        List<OpenFarmDto> all = new ArrayList<>();
        int pageNum = 1;
        int pageSize = Math.min(Math.max(properties.getPageSize(), 1), 200);
        Long total = null;
        while (true)
        {
            String url = UriComponentsBuilder.fromHttpUrl(ThirdPartyFarmingHttpSupport.resolveUrl(properties, LIST_PATH))
                    .queryParam("pageNum", pageNum)
                    .queryParam("pageSize", pageSize)
                    .toUriString();
            try
            {
                ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET,
                        new HttpEntity<>(headers), String.class);
                if (!response.getStatusCode().is2xxSuccessful() || response.getBody() == null)
                {
                    throw new ServiceException("第三方养殖场接口返回异常");
                }
                OpenApiResponse<OpenApiPageResult<OpenFarmDto>> body = objectMapper.readValue(response.getBody(),
                        new TypeReference<OpenApiResponse<OpenApiPageResult<OpenFarmDto>>>()
                        {
                        });
                if (body == null || body.getCode() == null || body.getCode() != 0)
                {
                    String msg = body != null && StringUtils.hasText(body.getMessage()) ? body.getMessage() : "业务失败";
                    throw new ServiceException("第三方养殖场接口：" + msg);
                }
                OpenApiPageResult<OpenFarmDto> page = body.getData();
                if (page == null || CollectionUtils.isEmpty(page.getRecords()))
                {
                    break;
                }
                all.addAll(page.getRecords());
                if (total == null && page.getTotal() != null)
                {
                    total = page.getTotal();
                }
                if (page.getRecords().size() < pageSize)
                {
                    break;
                }
                if (total != null && all.size() >= total)
                {
                    break;
                }
                pageNum++;
            }
            catch (ServiceException e)
            {
                throw e;
            }
            catch (RestClientException e)
            {
                throw new ServiceException("第三方服务不可用：" + e.getMessage());
            }
            catch (Exception e)
            {
                throw new ServiceException("解析第三方养殖场数据失败：" + e.getMessage());
            }
        }
        return all;
    }

}
