package com.erp.platformsync.adapter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 平台适配器抽象基类 - 提供通用HTTP调用能力
 */
@Slf4j
public abstract class AbstractPlatformAdapter implements PlatformAdapter {

    protected final RestTemplate restTemplate;

    protected static final DateTimeFormatter DT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

    protected AbstractPlatformAdapter(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 构建API URL（子类实现）
     */
    protected abstract String buildApiUrl(String path);

    /**
     * 获取API密钥（子类实现）
     */
    protected abstract String getAppSecret();

    /**
     * 执行HTTP GET请求
     */
    protected <T> T doGet(String path, Class<T> responseType, Map<String, ?> params) {
        String url = buildApiUrl(path);
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            addAuthHeaders(headers);

            String fullUrl = buildQueryUrl(url, params);
            log.debug("[{}] HTTP GET: {}", getPlatformCode(), fullUrl);

            ResponseEntity<T> response = restTemplate.exchange(
                    fullUrl, HttpMethod.GET, new HttpEntity<>(headers), responseType);
            return response.getBody();
        } catch (RestClientException e) {
            log.error("[{}] HTTP GET失败: url={}, error={}", getPlatformCode(), url, e.getMessage());
            return null;
        }
    }

    /**
     * 执行HTTP POST请求
     */
    protected <T, R> T doPost(String path, R requestBody, Class<T> responseType) {
        String url = buildApiUrl(path);
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            addAuthHeaders(headers);

            log.debug("[{}] HTTP POST: {}", getPlatformCode(), url);
            ResponseEntity<T> response = restTemplate.exchange(
                    url, HttpMethod.POST, new HttpEntity<>(requestBody, headers), responseType);
            return response.getBody();
        } catch (RestClientException e) {
            log.error("[{}] HTTP POST失败: url={}, error={}", getPlatformCode(), url, e.getMessage());
            return null;
        }
    }

    /**
     * 添加平台认证头部（子类可重写）
     */
    protected void addAuthHeaders(HttpHeaders headers) {
        // 默认实现，子类可重写添加token等
    }

    /**
     * 构建带查询参数的URL
     */
    protected String buildQueryUrl(String baseUrl, Map<String, ?> params) {
        if (params == null || params.isEmpty()) {
            return baseUrl;
        }
        StringBuilder sb = new StringBuilder(baseUrl);
        sb.append(baseUrl.contains("?") ? "&" : "?");
        params.forEach((key, value) -> {
            if (value != null) {
                sb.append(key).append("=").append(value.toString()).append("&");
            }
        });
        return sb.toString().replaceAll("&$", "");
    }

    /**
     * 格式化时间
     */
    protected String formatTime(LocalDateTime time) {
        if (time == null) return null;
        return time.format(DT_FORMATTER);
    }
}
