package cn.sikey.hmd.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.sikey.framework.common.exception.ServiceException;
// import cn.sikey.hmd.api.hmd.tuling.ApiResponse;
// import cn.sikey.hmd.api.hmd.tuling.QueryUpgradeResponse;
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表单请求
     */
    public String doPostForm(String url, Map<String, String> formData) {
        FormBody.Builder builder = new FormBody.Builder();
        if (formData != null) {
            formData.forEach(builder::add);
        }

        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .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;
    }

    /**
     * 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;
    }

    /**
     * 请求图灵API
     *
     * @param url  地址
     * @param json
     * @return
     */
    /*public ApiResponse<QueryUpgradeResponse> postRequest(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())) {
                JSONObject jsonObject = new JSONObject(response.body().string());

                int code = Integer.parseInt(String.valueOf(jsonObject.get("code")));
                String message = String.valueOf(jsonObject.get("message"));

                ApiResponse<QueryUpgradeResponse> apiResponse = new ApiResponse<>();
                if (code == HttpStatus.SC_OK) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    QueryUpgradeResponse queryUpgradeResponse = JSONUtil.toBean(data, QueryUpgradeResponse.class);
                    apiResponse.setData(queryUpgradeResponse);
                    apiResponse.setRequestId(String.valueOf(jsonObject.get("requestId")));
                } else {
                    String dialog = String.valueOf(jsonObject.get("dialog"));
                    apiResponse.setDialog(dialog);
                }

                apiResponse.setMessage(message);
                apiResponse.setCode(code);
                log.info("[请求图灵API]返回数据：{}", jsonObject);
                return apiResponse;
            }
        } catch (IOException e) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "post请求失败");
        }

        return null;
    }*/

}
