package yem.wmzh.ii.utils;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

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.util.Map;

/**
 * @Description Http连接
 * @Author: LiuHB
 * @CreateTime: 2025-02-18  17:28
 */
public class InterfaceCallspublicMethods {
    /**
     * @Description: 访问接口GET
     * @param url 接口地址(带请求参数)
     * @param info 入参信息
     * @param accessToken 密钥
     * @return java.lang.String  返回结果json
     */

    public static String sendGetRequest(String url, Map<String,Object> info,String accessToken) {


//        // 构建请求参数
//        StringBuilder params = new StringBuilder();
//        params.append("key=").append(URLEncoder.encode(key, "UTF-8"));
//        params.append("&address=").append(URLEncoder.encode(address, "UTF-8"));
//        if (city != null && !city.isEmpty()) {
//            params.append("&city=").append(URLEncoder.encode(city, "UTF-8"));
//        }
//        params.append("&output=json"); // 请求返回类型为JSON
//
//        // 创建URL对象
//        URL url = new URL(API_URL + "?" + params.toString());


        try {
            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

            // 设置请求方法为 GET
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Authorization", "Bearer " + accessToken); // 添加 accessToken 到 Authorization 头部

            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                return response.toString();
            } else {
                // 处理非 200 的状态码
                return "GET请求失败，响应码: " + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * @Description: 访问接口PUT
     * @param url  接口地址
     * @param parameters 请求体
     * @param accessToken 密钥
     * @return java.lang.String 返回结果json
     */

    public static String sendPutRequest(String url, String parameters, String accessToken) {
        try {
            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

            // 设置请求方法为 PUT
            connection.setRequestMethod("PUT");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Authorization", "Bearer " + accessToken); // 添加 accessToken 到 Authorization 头部
            connection.setDoOutput(true);

            // 写入请求体
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(parameters.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();

            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }


    /**
     * @Description: 访问接口post
     * @param url  接口地址
     * @param requestBody 请求体
     * @param accessToken 密钥
     * @return java.lang.String 返回结果json
     */
    public static String sendPostRequests(String url, String requestBody, String accessToken) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer " + accessToken); // 添加 accessToken 到 Authorization 头部
        con.setDoOutput(true);
        OutputStream os = con.getOutputStream();
        os.write(requestBody.getBytes());
        os.flush();
        os.close();

        BufferedReader in;
        if (con.getResponseCode() >= 400) {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    /**
     * @Description: 访问接口DELETE
     * @param url  接口地址
     * @param accessToken 密钥
     * @return java.lang.String 返回结果json     * @return java.lang.String 返回结果json
     */


    public static String sendDeleteRequest(String url, String accessToken) {
        try {
            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

            // 设置请求方法为 DELETE
            connection.setRequestMethod("DELETE");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Authorization", "Bearer " + accessToken); // 添加 accessToken 到 Authorization 头部

            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { // 成功删除
                return "DELETE请求成功，响应码: " + responseCode;
            } else {
                // 处理非 204 的状态码
                return "DELETE请求失败，响应码: " + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取accessToken
     * @param username
     * @param password
     * @return
     */
    public static String loginAndGetAccessToken(String username, String password) {
        try {
            String url = "http://10.64.111.165/admin-api/system/auth/login";
            String requestBody = "{\"username\": \"" + username + "\", \"password\": \"" + password + "\"}";

            URL endpoint = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                JSONParser parser = new JSONParser();
                JSONObject jsonResponse = (JSONObject) parser.parse(response.toString());
                JSONObject data = (JSONObject) jsonResponse.get("data");
                String accessToken = (String) data.get("accessToken");
                return accessToken;
            } finally {
                connection.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
