package com.haha.sdk.util;

import com.alibaba.fastjson2.JSON;
import okhttp3.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * HTTP工具类
 * 基于OkHttp实现HTTP请求
 * 
 * @author haha-sdk
 * @version 1.0.0
 */
@Slf4j
public class HttpUtils {
    
    private final OkHttpClient client;
    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType FORM_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    
    /**
     * 构造方法，使用默认配置
     */
    public HttpUtils() {
        this(10, 30, 30);
    }
    
    /**
     * 构造方法，自定义超时配置
     * 
     * @param connectTimeout 连接超时时间（秒）
     * @param readTimeout 读取超时时间（秒）
     * @param writeTimeout 写入超时时间（秒）
     */
    public HttpUtils(int connectTimeout, int readTimeout, int writeTimeout) {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }
    
    /**
     * POST请求（form表单方式）
     * 
     * @param url 请求URL
     * @param params 请求参数
     * @return 响应内容
     * @throws IOException IO异常
     */
    public String post(String url, Map<String, String> params) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            params.forEach(builder::add);
        }
        
        Request request = new Request.Builder()
                .url(url)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .post(builder.build())
                .build();
        
        log.debug("POST请求URL: {}", url);
        log.debug("POST请求参数: {}", params);
        
        try (Response response = client.newCall(request).execute()) {
            log.debug("POST响应状态: {}", response.code());
            log.debug("POST响应头: {}", response.headers());
            
            if (!response.isSuccessful()) {
                throw new IOException("HTTP请求失败: " + response.code());
            }
            ResponseBody body = response.body();
            String responseBody = body != null ? body.string() : "";
            log.debug("POST响应体: {}", responseBody);
            return responseBody;
        }
    }
    
    /**
     * POST请求（JSON方式）
     * 
     * @param url 请求URL
     * @param jsonBody JSON请求体
     * @return 响应内容
     * @throws IOException IO异常
     */
    public String postJson(String url, String jsonBody) throws IOException {
        RequestBody body = RequestBody.create(jsonBody, JSON_TYPE);
        Request request = new Request.Builder()
                .url(url)
                .header("Content-Type", "application/json")
                .post(body)
                .build();
        
        log.debug("POST JSON请求URL: {}", url);
        log.debug("POST JSON请求体: {}", jsonBody);
        
        try (Response response = client.newCall(request).execute()) {
            log.debug("POST JSON响应状态: {}", response.code());
            log.debug("POST JSON响应头: {}", response.headers());
            
            if (!response.isSuccessful()) {
                throw new IOException("HTTP请求失败: " + response.code());
            }
            ResponseBody responseBody = response.body();
            String responseBodyStr = responseBody != null ? responseBody.string() : "";
            log.debug("POST JSON响应体: {}", responseBodyStr);
            return responseBodyStr;
        }
    }
    
    /**
     * GET请求
     * 
     * @param url 请求URL
     * @return 响应内容
     * @throws IOException IO异常
     */
    public String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("HTTP请求失败: " + response.code());
            }
            ResponseBody body = response.body();
            return body != null ? body.string() : "";
        }
    }
    
    /**
     * 解析响应JSON
     * 
     * @param response 响应内容
     * @return 解析后的Map对象
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> parseResponse(String response) {
        return JSON.parseObject(response, Map.class);
    }
    
    /**
     * 关闭HTTP客户端
     */
    public void close() {
        if (client != null) {
            client.dispatcher().executorService().shutdown();
            client.connectionPool().evictAll();
        }
    }
}
