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

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.TimeZone;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.ServiceException;

/**
 * 第三方生产管理系统 HTTP 调用共用工具。
 */
public final class ThirdPartyFarmingHttpSupport
{
    private ThirdPartyFarmingHttpSupport()
    {
    }

    public static void requireBaseUrl(ThirdPartyFarmingProperties properties, String hint)
    {
        if (!StringUtils.hasText(properties.getBaseUrl()))
        {
            throw new ServiceException(hint);
        }
    }

    public static RestTemplate createRestTemplate(ThirdPartyFarmingProperties properties)
    {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(properties.getConnectTimeoutMs());
        factory.setReadTimeout(properties.getReadTimeoutMs());
        return new RestTemplate(factory);
    }

    public static HttpHeaders buildOpenApiHeaders(ThirdPartyFarmingProperties properties)
    {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        if (StringUtils.hasText(properties.getAppKey()))
        {
            headers.set("X-App-Key", properties.getAppKey());
        }
        if (StringUtils.hasText(properties.getAppSecret()))
        {
            headers.set("X-App-Secret", properties.getAppSecret());
        }
        return headers;
    }

    public static String resolveUrl(ThirdPartyFarmingProperties properties, String path)
    {
        return trimTrailingSlash(properties.getBaseUrl()) + path;
    }

    public static String trimTrailingSlash(String baseUrl)
    {
        String url = baseUrl.trim();
        while (url.endsWith("/"))
        {
            url = url.substring(0, url.length() - 1);
        }
        return url;
    }

    public static ObjectMapper createObjectMapper()
    {
        ObjectMapper mapper = new ObjectMapper();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        mapper.setDateFormat(df);
        mapper.findAndRegisterModules();
        return mapper;
    }
}
