package com.aiotagro.cattletrade.common.utils.http;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * HTTP工具类
 *
 * @author System
 * @date 2025-01-16
 */
public class HttpUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    
    /**
     * 发送POST请求
     */
    public static String sendPost(String url, Map<String, Object> params) throws Exception {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        
        try {
            // 创建连接
            URL urlObj = new URL(url);
            connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            
            // 发送请求参数
            if (params != null && !params.isEmpty()) {
                ObjectMapper mapper = new ObjectMapper();
                String jsonParams = mapper.writeValueAsString(params);
                
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = jsonParams.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
            }
            
            // 读取响应
            int responseCode = connection.getResponseCode();
            logger.info("HTTP响应状态码: {}", responseCode);
            
            // 读取响应内容
            StringBuilder response = new StringBuilder();
            if (responseCode >= 200 && responseCode < 300) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
            }
            
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            
            return response.toString();
            
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    logger.error("关闭输入流失败", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    
    /**
     * 发送带认证token的POST请求
     */
    public static String sendPostWithToken(String url, Map<String, Object> params, String token) throws Exception {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        
        try {
            // 创建连接
            URL urlObj = new URL(url);
            connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setRequestProperty("Accept", "application/json");
            if (token != null && !token.isEmpty()) {
                // 尝试不同的认证头格式
                connection.setRequestProperty("Authorization", "Bearer " + token);
                // 也尝试其他可能的头
                connection.setRequestProperty("X-Auth-Token", token);
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            
            // 发送请求参数
            if (params != null && !params.isEmpty()) {
                ObjectMapper mapper = new ObjectMapper();
                String jsonParams = mapper.writeValueAsString(params);
                
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = jsonParams.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
            }
            
            // 读取响应
            int responseCode = connection.getResponseCode();
            logger.info("HTTP响应状态码: {}", responseCode);
            
            // 读取响应内容
            StringBuilder response = new StringBuilder();
            if (responseCode >= 200 && responseCode < 300) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
            }
            
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            
            return response.toString();
            
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    logger.error("关闭输入流失败", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    
    /**
     * 发送GET请求
     */
    public static String sendGet(String url) throws Exception {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        
        try {
            // 创建连接
            URL urlObj = new URL(url);
            connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            
            // 读取响应
            int responseCode = connection.getResponseCode();
            logger.info("HTTP响应状态码: {}", responseCode);
            
            // 读取响应内容
            StringBuilder response = new StringBuilder();
            if (responseCode >= 200 && responseCode < 300) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
            }
            
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            
            return response.toString();
            
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    logger.error("关闭输入流失败", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
