package com.sckw.core.utils;

import com.sckw.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @author PC
 */
@Slf4j
public class HttpUtil {

    // 单例 OkHttpClient（推荐这样做，避免重复创建）
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .build();

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    /**
     * 同步 GET 请求
     */
    public static String get(String url, Map<String, String> headers) {
        Request.Builder builder = new Request.Builder().url(url);
        addHeaders(builder, headers);

        Request request = builder.build();
        try {
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    String result = response.body().string();
                    log.info("同步 GET 响应结果：{}", result);
                    return result;
                } else if (!response.isSuccessful()) {
                    throw new BusinessException("同步 GET 请求请求异常: " + response.code());
                } else {
                    return "";
                }
            }
        } catch (IOException e) {
            log.error("同步 GET 响应异常: {}", e.getMessage());
            return "";
        }
    }

    /**
     * 异步 GET 请求
     */
    public static void getAsync(String url, Map<String, String> headers, Callback callback) {
        Request.Builder builder = new Request.Builder().url(url);
        addHeaders(builder, headers);

        Request request = builder.build();
        try {
            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            throw new BusinessException("异步 GET 请求 异常",e);
        }
    }

    /**
     * 同步 POST - 表单请求
     */
    public static String postForm(String url, Map<String, String> formData, Map<String, String> headers) {
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (formData != null) {
            for (Map.Entry<String, String> entry : formData.entrySet()) {
                formBuilder.add(entry.getKey(), entry.getValue());
            }
        }

        RequestBody body = formBuilder.build();
        Request.Builder builder = new Request.Builder().url(url).post(body);
        addHeaders(builder, headers);

        Request request = builder.build();
        try {
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    String result = response.body().string();
                    log.info("同步 POST - 表单响应结果：{}", result);
                    return result;
                } else if (!response.isSuccessful()) {
                    throw new BusinessException("同步 POST - 表单请求异常: " + response.code());
                } else {
                    return "";
                }
            }
        } catch (Exception e) {
            log.error("同步 POST - 表单异常: {}", e.getMessage());
            return "";
        }
    }

    /**
     * 同步 POST - JSON 请求
     */
    public static String postJson(String url, String json, Map<String, String> headers)  {
        RequestBody body = RequestBody.create(json, JSON);
        Request.Builder builder = new Request.Builder().url(url).post(body);
        addHeaders(builder, headers);

        Request request = builder.build();

        try {
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    String result =  response.body().string();
                    log.info("同步 POST - JSON响应结果：{}",result );
                    return result;
                } else if (!response.isSuccessful()) {
                    throw new BusinessException("同步 POST - JSON 请求异常: " + response.code());
                } else {
                    return "";
                }
            }
        } catch (Exception e) {
            log.error("同步 POST - JSON 异常: {}", e.getMessage());
            return "";
        }
    }

    /**
     * 异步 POST - JSON
     */
    public static void postJsonAsync(String url, String json, Map<String, String> headers, Callback callback) {
        RequestBody body = RequestBody.create(json, JSON);
        Request.Builder builder = new Request.Builder().url(url).post(body);
        addHeaders(builder, headers);

        Request request = builder.build();
        try {
            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            throw new BusinessException("异步 POST - JSON异常：{}", e.getMessage());
        }
    }

    /**
     * 给请求添加 Header
     */
    private static void addHeaders(Request.Builder builder, Map<String, String> headers) {
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }
}