package com.fs.fastgptApi.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.domain.R;
import com.fs.company.domain.CompanyConfig;
import com.fs.fastgptApi.config.FastGptApiConfig;
import com.fs.qwApi.Result.QwUploadResult;
import com.fs.qwApi.config.QwApiConfig;
import com.fs.qwApi.domain.QWCompanyConfig;
import com.fs.qwApi.domain.QwDeptResult;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Objects;

public class HttpUtil {


    public static String sendAuthPost(Object param, String url) {
        // 使用 CloseableHttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();

            HttpPost httpPost = new HttpPost(uri);
            // 设置请求头参数类型为 utf-8
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

            // 将 param 转换为 JSON 字符串
            String jsonParam = JSON.toJSONString(param);
            httpPost.setEntity(new StringEntity(jsonParam, "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 请求成功，返回响应内容
                String string = EntityUtils.toString(response.getEntity());
                return string;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sendPost(Object param, String url, String key) {
        // 使用 CloseableHttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();

            HttpPost httpPost = new HttpPost(uri);
            // 设置请求头参数类型为 utf-8
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setHeader("Authorization", "Bearer " + key);

            // 将 param 转换为 JSON 字符串
            String jsonParam = JSON.toJSONString(param);
            httpPost.setEntity(new StringEntity(jsonParam, "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    // 请求成功，返回响应内容
                String string = EntityUtils.toString(response.getEntity());
                return string;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sendGet(String value, String url, String key) {
        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameter("id", value);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);

            httpGet.setHeader("Authorization", "Bearer " + key);
            HttpResponse response = httpClient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public static String sendPut(Object param, String url, String key) {
        // 使用 CloseableHttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();

            HttpPut httpPut = new HttpPut(uri);
            // 设置请求头参数类型为 utf-8
            httpPut.setHeader("Content-Type", "application/json");
            httpPut.setHeader("Authorization", "Bearer " + key);

            // 将 param 转换为 JSON 字符串
            String jsonParam = JSON.toJSONString(param);
            httpPut.setEntity(new StringEntity(jsonParam, "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPut)) {
                    // 请求成功，返回响应内容
                String json = EntityUtils.toString(response.getEntity());
                return json;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sendDelete(String value, String url, String key) {
        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameter("id", value);
            URI uri = builder.build();
            HttpDelete httpDelete = new HttpDelete(uri);

            httpDelete.setHeader("Authorization", "Bearer " + key);
            HttpResponse response = httpClient.execute(httpDelete);
            String json = EntityUtils.toString(response.getEntity());
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 封装的post请求
     */
    public static String templateResultPost(Object param, String url, String key){
        HttpClient httpClient = HttpClients.createDefault();
        URIBuilder builder = null;
        try {
            builder = new URIBuilder(url);
            builder.setParameter("data-raw", param.toString());
            URI uri = builder.build();

            HttpPost httpPost  = new HttpPost(uri);
            // 设置请求头参数类型为utf-8
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setHeader("Authorization", "Bearer "+key);

            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());

            return reJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    /**
//    * 上传文件
//    */
//    public static String upload(File file, String url, String key) throws IOException {
//
//        HttpClient httpClient = HttpClients.createDefault();
//
//        try {
//            URIBuilder uriBuilder = new URIBuilder(url);
//            URI uri = uriBuilder.build();
//
//            HttpPost httpPost = new HttpPost(uri);
//
//            // 构造表单数据
//            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//
//            // 添加文件
//            builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());
//
//            // 构建表单实体
//            HttpEntity multipart = builder.build();
//            httpPost.setEntity(multipart);
//
//            // 设置请求头
//            httpPost.setHeader("Content-Type", "multipart/form-data; charset=UTF-8");
//            httpPost.setHeader("Authorization", "Bearer " + key);
//
//            // 发送请求并获取响应
//            HttpResponse response = httpClient.execute(httpPost);
//            String json = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
//
//            return json;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }

    public static String uploadFile(File file,String filaName,Object param, String url, String key) throws IOException {

        // 获取文件的 ContentType
        String fileContentType = Files.probeContentType(file.toPath());
        if (fileContentType == null) {
            fileContentType = "application/octet-stream";  // 如果无法确定类型，设置为默认值
        }

        // 将参数转换为 JSON
        String jsonParam = JSON.toJSONString(param);
        // 处理文件名
        String fileName = null;
        try {
            fileName = URLEncoder.encode(filaName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        // 创建 HttpClient 实例
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // 创建 HttpPost 请求
            HttpPost post = new HttpPost(url);
            // 设置请求头
            post.setHeader("Authorization", "Bearer " + key);
            // 构建 multipart 实体
//            HttpEntity formEntity = MultipartEntityBuilder.create()
//                    .addBinaryBody("file", file, ContentType.parse(Files.probeContentType(file.toPath())), fileName)
//                    .addTextBody("data", jsonParam, ContentType.APPLICATION_JSON)
//                    .build();

            HttpEntity formEntity = MultipartEntityBuilder.create()
                    .addBinaryBody("file", file, ContentType.create(fileContentType), fileName)
                    .addTextBody("data", jsonParam, ContentType.APPLICATION_JSON)
                    .build();

            // 设置实体到请求中
            post.setEntity(formEntity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = client.execute(post)) {
                // 获取响应体并返回 JSON 数据
                String string = EntityUtils.toString(response.getEntity());
                return string;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


//        String bodyJson = "";
//        String jsonParam = JSON.toJSONString(param);
//        //处理数据
//        RequestBody dataBody = RequestBody.create(jsonParam, MediaType.parse("application/json; charset=utf-8"));
//        String fileName = URLEncoder.encode(file.getName());
//        //处理文件
//        RequestBody fileBody = RequestBody.create(
//                Files.readAllBytes(file.toPath()),
//                MediaType.parse(Files.probeContentType(file.toPath()))
//        );
//        //构建组合体
//        MultipartBody formBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addFormDataPart("file", fileName, fileBody)
//                .addFormDataPart("data", "", dataBody)
//                .build();
//        //构建请求
//        Request request = new Request.Builder()
//                .url(url)
//                .post(formBody)
//                .addHeader("Authorization", "Bearer " + key)
//                .build();
//        //发送请求
//        OkHttpClient client = new OkHttpClient();
//        // 发送请求
//        try (Response response = client.newCall(request).execute()) {
//            if (!response.isSuccessful()) {
//                throw new IOException("Unexpected code " + response);
//            }
//            bodyJson = Objects.requireNonNull(response.body()).string();
//        }
//        // 返回结果（正式用需要解析返回结果的值）
//        return bodyJson;
    }

}