package com.bcxin.autodownloadupload.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.UUID;

/**
 * description: http 请求工具类
 * author: linchunpeng
 * date:  2023-04-18 9:54
 */
public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * description: http post请求
     * author: linchunpeng
     * date:  2023-04-18 9:54
     */
    public static String post(String url, String bodyJson) {
        String postId = UUID.randomUUID().toString();
        logger.info("=====================http post 请求=====================");
        logger.info("postId：" + postId);
        logger.info("请求地址：" + url);
        JSONObject jsonObject = JSONObject.parseObject(bodyJson);
        if (jsonObject.containsKey("img_base64")) {
            jsonObject.keySet().removeIf("img_base64"::equals);
            logger.info("请求参数：" + JSONObject.toJSONString(jsonObject));
        } else {
            logger.info("请求参数：" + bodyJson);
        }
        logger.info("=======================================================");
        String result = "";
        // 创建一个httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个post对象
        HttpPost post = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            // 设置请求的内容
            post.setEntity(new StringEntity(bodyJson, "utf-8"));
            // 设置请求的报文头部的编码
            post.addHeader("Content-Type", "application/json;charset=utf-8");
            post.addHeader("skip_validation", "noitadilav_piks");
            // 执行post请求
            response = client.execute(post);
            // 获取响应码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取数据
                result = EntityUtils.toString(response.getEntity());
            } else {
                result = "fail";
                logger.error("调用接口请求失败,错误码为：" + statusCode);
                post.abort();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("调用接口请求失败：" + e.getMessage(), e);
            result = "fail";
            post.abort();
        } finally {
            if (response != null) {
                try {
                    response.close();
                    post.abort();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("关闭接口response出错：" + e.getMessage(), e);
                }
            }
            try {
                client.close();
                post.abort();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("关闭http接口client出错：" + e.getMessage(), e);
            }
        }
        logger.info("=====================http post 请求结果=====================");
        logger.info("postId：" + postId);
        logger.info("请求结果：" + result);
        logger.info("=======================================================");
        return result;
    }

    /**
     * description: http get请求
     * author: linchunpeng
     * date:  2023-04-18 9:55
     */
    public static String get(String url) {
        String getId = UUID.randomUUID().toString();
        logger.info("=====================http get 请求=====================");
        logger.info("getId：" + getId);
        logger.info("请求地址：" + url);
        logger.info("=======================================================");
        String result = "";
        // 创建一个httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个post对象
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            // 设置请求的报文头部的编码
            get.addHeader("Content-Type", "application/json;charset=utf-8");
            // 执行post请求
            response = client.execute(get);
            // 获取响应码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取数据
                result = EntityUtils.toString(response.getEntity());
            } else {
                result = "fail";
                logger.error("调用接口请求失败,错误码为：" + statusCode);
                get.abort();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("调用接口请求失败：" + e.getMessage(), e);
            result = "fail";
            get.abort();
        } finally {
            if (response != null) {
                try {
                    response.close();
                    get.abort();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("关闭接口response出错：" + e.getMessage(), e);
                }
            }
            try {
                client.close();
                get.abort();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("关闭http接口client出错：" + e.getMessage(), e);
            }
        }
        logger.info("=====================http get 请求结果=====================");
        logger.info("getId：" + getId);
        logger.info("请求结果：" + result);
        logger.info("=======================================================");
        return result;
    }

}
