package cn.sikey.tools.config;

import cn.sikey.framework.common.exception.ServiceException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: qin
 * @Date: 2025/4/16
 * @Description: http工具
 */
@Slf4j
@Component
public class HttpUtil {

    @Resource
    private OkHttpClient okHttpClient;

    /**
     * GET请求
     */
    public String doGet(String url, Map<String, String> params) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if (params != null) {
            params.forEach(urlBuilder::addQueryParameter);
        }
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .get()
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "get请求失败");
            }

            if (Objects.nonNull(response.body())) {
                return response.body().string();
            }
        } catch (IOException e) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "get请求失败");
        }
        return null;
    }

    /**
     * POST表单请求（支持自定义Header）
     *
     * @param url      请求地址
     * @param formData 表单数据
     * @param headers  请求头（可为null）
     * @return
     */
    public String doPostForm(String url, Map<String, String> formData, Map<String, String> headers) {
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (formData != null) {
            formData.forEach(formBuilder::add);
        }

        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(formBuilder.build());

        // 添加Header
        if (headers != null && !headers.isEmpty()) {
            headers.forEach((key, value) -> {
                if (key != null && value != null) {
                    requestBuilder.addHeader(key, value);
                }
            });
        }

        Request request = requestBuilder.build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "POST请求失败");
            }

            if (Objects.nonNull(response.body())) {
                return response.body().string();
            }
        } catch (IOException e) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "POST请求失败: " + e.getMessage());
        }
        return null;
    }


    /**
     * POST JSON请求
     */
    public String doPostJson(String url, String json) {
        RequestBody body = RequestBody.create(
                json, MediaType.parse("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "post请求失败");
            }

            if (Objects.nonNull(response.body())) {
                return response.body().string();
            }
        } catch (IOException e) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "post请求失败");
        }
        return null;
    }

    public String doPostWithQueryParams(String url, Map<String, String> queryParams, Map<String, String> headers) {
        // 构建带查询参数的URL
        HttpUrl httpUrl = HttpUrl.parse(url);
        if (httpUrl == null) {
            throw new IllegalArgumentException("Invalid URL: " + url);
        }

        HttpUrl.Builder urlBuilder = httpUrl.newBuilder();
        if (queryParams != null) {
            queryParams.forEach((key, value) -> {
                if (key != null && value != null) {
                    urlBuilder.addQueryParameter(key, value);
                }
            });
        }
        String finalUrl = urlBuilder.build().toString();

        // 创建空请求体（必须为POST请求提供）
        RequestBody emptyBody = RequestBody.create(new byte[0], null);

        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(finalUrl)
                .post(emptyBody);

        // 添加Header
        if (headers != null) {
            headers.forEach((key, value) -> {
                if (key != null && value != null) {
                    requestBuilder.addHeader(key, value);
                }
            });
        }

        // 执行请求
        try (Response response = okHttpClient.newCall(requestBuilder.build()).execute()) {
            if (!response.isSuccessful()) {
                throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "POST请求失败");
            }
            return response.body() != null ? response.body().string() : null;
        } catch (IOException e) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "POST请求失败: " + e.getMessage());
        }
    }

}
