package com.lemon.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
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.util.Arrays;
import java.util.HashMap;
import java.util.Set;

/**
 * @program: Lemon
 * @description:
 * @author: ray
 * @create: 2022-11-03 13:11
 **/
public class HttpUtils {
    /*
     * static 修饰方法和变量
     * 静态特点：
     *   0、直接用类名点击调用
     *   1、被所有的对象共享（环境变量）
     *   2、所有类加载而加载
     */

    /**
     * call :方法 发起请求
     *
     * @param url:URL
     * @param type：Post请求、get请求
     * @param params：请求参数
     * @param contentType：请求类型，JSON或from
     * @param isAuthorization            ：请求接口是否需要传递token值
     */
    public static String call(String url, String type, String params, String contentType, boolean isAuthorization) {
        try {
            // 如果说JSON类型请求方式
            if ("json".equalsIgnoreCase(contentType)) {
                //如果是Post请求
                if ("post".equalsIgnoreCase(type)) {
                    return HttpUtils.jsonPost(url, params, isAuthorization);
                } else if ("get".equalsIgnoreCase(type)) {
                    //如果是get请求
                    return HttpUtils.jsonGet(url, isAuthorization);
                } else if ("patch".equalsIgnoreCase(type)) {
                    //如果是patch请求
                    return HttpUtils.jsonPatch(url, params, isAuthorization);
                }
            } else if ("from".equalsIgnoreCase(contentType)) {
                if ("post".equalsIgnoreCase(type)) {
                    // JSON类型参数转换为from类型参数
                    params = HttpUtils.json2from(params);
                    return HttpUtils.fromPost(url, params, isAuthorization);
                } else if ("get".equalsIgnoreCase(type)) {
                    return HttpUtils.fromGet(url, params, isAuthorization);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String json2from(String json) {
        // 1、JSON转换成map
        HashMap<String, String> map = JSONObject.parseObject(json, HashMap.class);
        // 2、获取所有的key
        Set<String> keySet = map.keySet();
        // 3、定义返回结果字符串
        String result = "";
        // 4、循环遍历所有key和value
        for (String key : keySet) {
            // 5、通过键key找值value
            String value = map.get(key);
            if (result.length() > 0) {
                result += "&";
            }
            //拼接
            result += key + "=" + value;
        }
        return result;
    }


    public static String jsonGet(String url, Boolean isAuthorization) throws Exception {
        // login?username=15500110011&password=123456
        HttpGet httpGet = new HttpGet(url);
//        httpGet.addHeader(Constants.HEADER_MEDIA_TYPE_NAME, Constants.HEADER_MEDIA_TYPE_VALUE);
        httpGet.setHeader("Content-Type", "application/json, text/plain, */*");
        // 添加鉴权头
        if (isAuthorization) {
            AuthorizationUtils.setTokenInRequest(httpGet);
        }
        CloseableHttpClient client = HttpClients.createDefault();
        long startTime = System.currentTimeMillis();
        CloseableHttpResponse response = client.execute(httpGet);
        long endTime = System.currentTimeMillis();
        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        Header[] headers = response.getAllHeaders();

        String body = EntityUtils.toString(entity);
        System.out.println(url);
        System.out.println(body);
        System.out.println(statusCode);
        System.out.println(Arrays.toString(headers));
        System.out.println("接口响应时间(毫秒):" + (endTime - startTime));
        return body;
    }

    public static String jsonPost(String url, String params, Boolean isAuthorization) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        // 有参传参、有头加头
//        httpPost.setHeader(Constants.HEADER_MEDIA_TYPE_NAME, Constants.HEADER_MEDIA_TYPE_VALUE);
        // Post请求必须添加content-type
        httpPost.setHeader("Content-Type", "application/json");
        // 添加鉴权头
        if (isAuthorization) {
            AuthorizationUtils.setTokenInRequest(httpPost);
        }
        // 传参
        httpPost.setEntity(new StringEntity(params, "UTF-8"));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        Header[] headers = response.getAllHeaders();

        String body = EntityUtils.toString(entity);
        System.out.println(url);
        System.out.println(params);
        System.out.println(body);
        System.out.println(statusCode);
        System.out.println(Arrays.toString(headers));
        return body;
    }

    public static String fromPost(String url, String params, Boolean isAuthorization) throws Exception {
        HttpPost httpPost = new HttpPost(url);
//        httpPost.setHeader(Constants.HEADER_MEDIA_TYPE_NAME, Constants.HEADER_MEDIA_TYPE_VALUE);
        // post请求必须添加Content-Type请求方式
        httpPost.setHeader("Content-Type", "application/x-www-from-urlencoded;charset=UTF-8");
        // 添加鉴权头
        if (isAuthorization) {
            AuthorizationUtils.setTokenInRequest(httpPost);
        }
        httpPost.setEntity(new StringEntity(params, "UTF-8"));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        Header[] headers = response.getAllHeaders();

        String body = EntityUtils.toString(entity);
        System.out.println(url);
        System.out.println(params);
        System.out.println(body);
        System.out.println(statusCode);
        System.out.println(Arrays.toString(headers));
        return body;
    }


    public static String fromGet(String url, String params, Boolean isAuthorization) throws Exception {
        // login?username=15500110011&password=123456
        HttpGet httpGet = new HttpGet(url + "？" + params);
        System.out.println("httpGet请求" + httpGet);
        // 添加鉴权头
        if (isAuthorization) {
            AuthorizationUtils.setTokenInRequest(httpGet);
        }
        CloseableHttpClient client = HttpClients.createDefault();
        long startTime = System.currentTimeMillis();
        CloseableHttpResponse response = client.execute(httpGet);
        long endTime = System.currentTimeMillis();
        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        Header[] headers = response.getAllHeaders();

        String body = EntityUtils.toString(entity);
        System.out.println(url);
        System.out.println(params);
        System.out.println(body);
        System.out.println(statusCode);
        System.out.println(Arrays.toString(headers));
        System.out.println("接口响应时间(毫秒):" + (endTime - startTime));
        return body;
    }

    public static String jsonPatch(String url, String params, Boolean isAuthorization) throws Exception {
        HttpPatch patch = new HttpPatch(url);
//        patch.setHeader(Constants.HEADER_MEDIA_TYPE_NAME, Constants.HEADER_MEDIA_TYPE_VALUE);
        patch.setHeader("Content-Type", "application/json");
        // 添加鉴权头
        if (isAuthorization) {
            AuthorizationUtils.setTokenInRequest(patch);
        }
        patch.setEntity(new StringEntity(params, "UTF-8"));
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(patch);

        String body = EntityUtils.toString(response.getEntity());
        System.out.println(url);
        System.out.println(params);
        System.out.println(body);
        System.out.println(response.getStatusLine().getStatusCode());
        System.out.println(Arrays.toString(response.getAllHeaders()));
        return body;
    }

    public static void main(String[] args) {

    }


}
