package com.fs.watch.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class MyHttpUtils {
    private static final Logger log = LoggerFactory.getLogger(MyHttpUtils.class);

    public void printHeaders(HttpServletRequest request) {
        StringBuilder headerInfo = new StringBuilder();
        // Get all header names
        java.util.Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headerInfo.append(headerName).append(": ");
            // Get all values for the current header
            java.util.Enumeration<String> headerValues = request.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                headerInfo.append(headerValues.nextElement());
                if (headerValues.hasMoreElements()) {
                    headerInfo.append(", "); // If there are multiple values, separate them with a comma
                }
            }

            headerInfo.append("\n");
        }
        log.info(headerInfo.toString());
    }


    private Map<String,Object> request(URIBuilder builder, HttpClient client) {
        try {
            URI uri = builder.build();
            // 创建GET请求对象
            HttpGet request = new HttpGet(uri);
            // 发送GET请求
            HttpResponse response = client.execute(request);
            // 获取响应代码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应内容
                String content = EntityUtils.toString(response.getEntity());
                return JSONObject.parseObject(content, HashMap.class);
            }
        } catch (IOException | URISyntaxException e) {
            throw new RuntimeException(e);
        }
        return null;

    }

    /**
     * http请求
     * @param host
     * @param path
     * @param params
     * @return
     */
    public Map<String,Object> getRequest(String host, String path, Map<String, Object> params) {
        // 创建HttpClient对象
        HttpClient client = HttpClientBuilder.create().build();

        // 创建URI对象，并添加参数
        URIBuilder builder = new URIBuilder();
        for (String key : params.keySet()) {
            builder.setParameter(key, params.get(key).toString());
        }
        builder.setScheme("https").setHost(host).setPath(path);
        return request(builder, client);

    }


    /**
     * 腕表平台设置
     * @param path
     * @param params
     * @return
     */
    public Map<String,Object> getRequest1(String path, Map<String, Object> params) {
        // 创建HttpClient对象
        HttpClient client = HttpClientBuilder.create().build();
        // 创建URI对象，并添加参数
        URIBuilder builder = new URIBuilder();
        for (String key : params.keySet()) {
            builder.setParameter(key, params.get(key).toString());
        }
        builder.setScheme("https").setHost("search.iwown.com").setPath(path);
        return request(builder, client);
    }

    /**
     * http请求
     *
     * @param host
     * @param path
     * @return
     */
    public Map<String,Object> getRequest2(String host, String path) {
        // 创建HttpClient对象
        HttpClient client = HttpClientBuilder.create().build();

        // 创建URI对象，并添加参数
        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost(host).setPath(path);
        return request(builder, client);
    }

    /**
     * http请求 多个参数
     * @param host
     * @param path
     * @param params
     * @return
     */
    public Map getRequest3(String host, String path, Map<String, Object> params) {
            // 创建HttpClient对象
            HttpClient client = HttpClientBuilder.create().build();

            // 创建URI对象，并添加参数
            URIBuilder builder = new URIBuilder();
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value != null) {
                    builder.setParameter(key, value.toString());
                }
            }
            builder.setScheme("http").setHost(host).setPath(path);

            return request(builder, client);
    }


    private static Map<String, Object> getObjectMap(Map<String, Object> params, HttpPost httpPost, CloseableHttpClient httpClient) throws IOException {
        String result;
        BasicResponseHandler handler = new BasicResponseHandler();
        //设置请求格式
        String jsonData = JSONObject.toJSONString(params);
        StringEntity entity = new StringEntity(jsonData, "utf-8");//解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        //执行POST请求
        result = httpClient.execute(httpPost, handler);
        Map<String, Object> resMap = JSONObject.parseObject(result, HashMap.class);
        return resMap;
    }

    public Map getPost(String path, Map<String, Object> params) {
        String result = "";
        path = "https://search.iwown.com" + path;
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(path);
        //创建httpclient对象
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            Map<String, Object> resMap = getObjectMap(params, httpPost, httpClient);
            if ((int) resMap.get("ReturnCode") == 0) {
                return JSONObject.parseObject(resMap.get("Data").toString(), HashMap.class);
            } else {
                return null;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //释放连接
        return null;
    }


    public Map getPost2(String uri, String path, Map<String, Object> params) {
        String result = "";
        path = uri + path;
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(path);
        //创建httpclient对象
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            Map<String, Object> resMap = getObjectMap(params, httpPost, httpClient);
            if ((int) resMap.get("ReturnCode") == 0) {
                if (resMap.get("Data") == null) {
                    return JSONObject.parseObject(resMap.get("data").toString(), HashMap.class);
                }
                return JSONObject.parseObject(resMap.get("Data").toString(), HashMap.class);
            } else {
                return null;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //释放连接
        return null;
    }

    //    public Map getPost3(String path, Map<String,Object> params) {
    public Map getPost3(String path, Object params) {
        String result = "";
        path = "http://" + path;
        log.debug("=================================4===============================" + path);
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(path);
        //创建httpclient对象
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            BasicResponseHandler handler = new BasicResponseHandler();
            //设置请求格式
            String jsonData = JSONObject.toJSONString(params);
            StringEntity entity = new StringEntity(jsonData, "utf-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            //执行POST请求
            result = httpClient.execute(httpPost, handler);
            Map<String, Object> resMap = JSONObject.parseObject(result, HashMap.class);
            return resMap;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //释放连接
        return null;
    }

    public Map getDel(String path) {
        Map<String, Object> result = new HashMap<>();
        path = "http://" + path;
        //创建post方式请求对象
        HttpDelete httpDelete = new HttpDelete(path);
        // 创建HTTP客户端
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
//            BasicResponseHandler handler = new BasicResponseHandler();
//            //设置请求格式
//            String jsonData = JSONObject.toJSONString(params);
//            StringEntity entity = new StringEntity(jsonData, "utf-8");//解决中文乱码问题
//            entity.setContentEncoding("UTF-8");
//            entity.setContentType("application/json");
//            httpDelete.set(entity);
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpDelete);
            Map responseBody = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"), HashMap.class);
            result.put("code", responseBody.get("code"));
            result.put("message", responseBody.get("msg"));
            return result;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //释放连接
        return null;
    }

}
