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.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.ruoyi.common.exception.ServiceException;

/**
 * 第三方生产管理系统 HTTP 调用共用工具。
 * <p>
 * 封装 RestTemplate 创建、OpenAPI 鉴权头（X-App-Key / X-App-Secret）、URL 拼接及 JSON 反序列化配置。
 * 所有 {@code ThirdParty*ClientImpl} 均依赖本类，配置来源 {@link ThirdPartyFarmingProperties}。
 * </p>
 */
public final class ThirdPartyFarmingHttpSupport
{
    private ThirdPartyFarmingHttpSupport()
    {
    }

    /** 校验 base-url 已配置，否则抛出业务异常 */
    public static void requireBaseUrl(ThirdPartyFarmingProperties properties, String hint)
    {
        if (!StringUtils.hasText(properties.getBaseUrl()))
        {
            throw new ServiceException(hint);
        }
    }

    /** 按配置创建 RestTemplate，含连接/读取超时 */
    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;
    }

    /** baseUrl + path，baseUrl 末尾斜杠自动去除 */
    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;
    }

    /**
     * 创建 JSON 反序列化器。
     * <p>
     * 注册 {@link FlexibleLongDeserializer}：第三方部分 int64 字段以字符串返回（如 {@code "2061327199252615170"}），
     * 需兼容解析为 {@link Long}。
     * </p>
     */
    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);
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Long.class, new FlexibleLongDeserializer());
        module.addDeserializer(long.class, new FlexibleLongDeserializer());
        mapper.registerModule(module);
        mapper.findAndRegisterModules();
        return mapper;
    }

    /** 兼容 JSON 数字与字符串形式的 Long 字段 */
    private static final class FlexibleLongDeserializer extends JsonDeserializer<Long>
    {
        @Override
        public Long deserialize(JsonParser parser, DeserializationContext context) throws java.io.IOException
        {
            JsonToken token = parser.currentToken();
            if (token == JsonToken.VALUE_NULL)
            {
                return null;
            }
            if (token == JsonToken.VALUE_NUMBER_INT)
            {
                return parser.getLongValue();
            }
            if (token == JsonToken.VALUE_STRING)
            {
                String text = parser.getText();
                if (!StringUtils.hasText(text))
                {
                    return null;
                }
                return Long.parseLong(text.trim());
            }
            return null;
        }
    }
}
