package com.tofly.third.common.util;

import com.tofly.common.core.util.StringUtil;
import okhttp3.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class HttpRequestUtil {

    public static String GETRequest(String urlstr, String token) {
        return GETRequest(urlstr, token, "");
    }

    public static String GETRequest(String urlstr, String token, String params) {
        try {
            URL url = null;
            if (!StringUtil.isEmpty(params)) {
                url = new URL(urlstr + "?param=" + params);
            } else {
                url = new URL(urlstr);
            }
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            // 设置头信息
            con.setRequestMethod("GET");
            con.setRequestProperty("Authorization", token);
            con.setRequestProperty("Accept", "application/json, text/plain, */*");
            // 发送请求
            con.connect();

            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // 读取响应
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer content = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();
                con.disconnect();
                return content.toString();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String POSTRequest(String urlstr, String params) {
        return POSTRequest(urlstr, params, "");
    }

    public static String POSTRequest(String urlstr, String params, String token) {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 设置头信息
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", StringUtil.isEmpty(token) ? "null" : token);
            //con.setRequestProperty("Accept", "application/json, text/plain, */*");
            con.setRequestProperty("Content-Type", "application/json");
            //con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            //con.setRequestProperty("X-Sign", "239D943E6EF1E33BDC18BDED629CBE55");
            //con.setRequestProperty("X-Version", "v3");

            // 发送JSON请求体
            con.setDoOutput(true);
//            DataOutputStream out = new DataOutputStream(con.getOutputStream());
//            out.writeBytes(params);
//            out.flush();
//            out.close();
            try (OutputStream out = con.getOutputStream()) {
                if (params != null && !params.isEmpty()) {
                    out.write(params.getBytes());
                    out.flush();
                    out.close();
                }
            }
            // 获取身份标识
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // 读取响应
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer content = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();
                con.disconnect();
                return content.toString();
            }
            return "";

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String POSTRequest3(String urlstr, String params, String token) {

        try {
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .connectTimeout(40, TimeUnit.SECONDS)
                    .readTimeout(40, TimeUnit.SECONDS)
                    .build();
            RequestBody requestBody = RequestBody.create(JSON, params);
            Request request = new Request.Builder()
                    .url(urlstr)
                    .header("Authorization", StringUtil.isEmpty(token) ? "null" : token)
                    .post(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();
            String st = "";
            if (response.body() != null) {
                st = new String(response.body().bytes(), StandardCharsets.UTF_8);
            }
            return st;

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String POSTRequest1(String urlstr, String params, String token) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 创建POST请求，并带上URL参数（注意：这里用的是URIBuilder来构建URI）
            HttpPost httpPost = new HttpPost(urlstr);
            // 设置请求头为JSON格式
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("Authorization", StringUtil.isEmpty(token) ? "null" : token);
            // 设置请求体为JSON数据
            httpPost.setEntity(new StringEntity(params));

            // 执行请求并获取响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                String responseString = EntityUtils.toString(response.getEntity()); // 获取响应内容
                return responseString;
            } finally {
                response.close(); // 关闭响应对象释放资源
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                httpClient.close(); // 关闭HttpClient释放资源
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static String POSTFileRequest(String urlstr, String params, String token) {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 设置头信息
            con.setRequestMethod("POST");
            if (StringUtil.isEmpty(token)) {
                con.setRequestProperty("X-Access-Token", "null");
            } else {
                con.setRequestProperty("X-Access-Token", token);
            }

            con.setRequestProperty("Accept", "multipart/form-data,text/plain, */*");
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
            con.setRequestProperty("X-Sign", "239D943E6EF1E33BDC18BDED629CBE55");
            con.setRequestProperty("X-Version", "v3");

            // 发送请求
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();

            // 读取响应
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine.replace("\"", ""));
            }
            in.close();

            // 获取身份标识
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return content.toString();
            }
            return "";

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String PUTRequest(String urlstr, String params, String token) {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 设置头信息
            con.setRequestMethod("PUT");
            if (StringUtil.isNotEmpty(token)) {
                con.setRequestProperty("Authorization", token);
            }

            con.setRequestProperty("Accept", "application/json, text/plain, */*");
            con.setRequestProperty("Content-Type", "application/json");

            // 发送请求
            if (StringUtil.isNotEmpty(params)) {
                con.setDoOutput(true);
                DataOutputStream out = new DataOutputStream(con.getOutputStream());
                out.writeBytes(params);
                out.flush();
                out.close();
            }

            // 读取响应
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine.replace("\"", ""));
            }
            in.close();

            // 获取身份标识
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return content.toString();
            }
            return "";

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String PUTRequest3(String urlstr, String params, String token) {

        try {
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .connectTimeout(40, TimeUnit.SECONDS)
                    .readTimeout(40, TimeUnit.SECONDS)
                    .build();
            RequestBody requestBody = RequestBody.create(JSON, params);
            Request request = new Request.Builder()
                    .url(urlstr)
                    .header("Authorization", StringUtil.isEmpty(token) ? "null" : token)
                    .put(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();
            String st = "";
            if (response.body() != null) {
                st = new String(response.body().bytes(), StandardCharsets.UTF_8);
            }
            return st;

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
