package com.winsun.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
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.io.IOException;

@Slf4j
public class AccessStatisticDataSearchUtils {

    public final static String ES_URL = "http://172.18.101.171:9200/";

    public final static String SEARCH = "/_search";

    public final static String HOSTNAME = "ESC-NETWORK";

    public final static String GRAFANA_URL = "http://172.18.101.171:3000/api/datasources/proxy/1/_msearch?max_concurrent_shard_requests=5";

    private final static String AUTHORIZATION = "Bearer eyJrIjoiYUQ3QjlPOFVnejVwTVdHNWJrVDJPa2VUenNmajYyN1MiLCJuIjoieXJ5bSIsImlkIjoxfQ==";

    /**
     * es搜索
     * @param query 查询表达式
     * filter json数组，搜索条件
     * aggs  json对象，聚合搜索
     * @return
     */
    public static String esSearch(String query) {
//		String query = "{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"@timestamp\":{\"gte\":1604795200000,\"lte\":1607895260000,\"format\":\"epoch_millis\"}}},{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"agent.hostname:\\\"ESC-NETWORK\\\" AND request:*.do*\"}}]}},\"aggs\":{\"groupBy\": {\"date_histogram\": {\"field\": \"@timestamp\",\"interval\": \"day\"},\"aggs\":{\"userCount\":{\"cardinality\":{\"field\":\"remote_addr\"}}}}}}";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httppost = new HttpPost(ES_URL + SEARCH);
            // 创建请求内容
            StringEntity entity = new StringEntity(query, ContentType.APPLICATION_JSON);
            httppost.setEntity(entity);

            // 执行http请求
            response = httpClient.execute(httppost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            return resultString;
        } catch (Exception e) {
            log.error("请求es接口异常");
            e.printStackTrace();

        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * grafanaSearch
     * @param query
     * @return
     */
    public static String grafanaSearch(String query) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httppost = new HttpPost(AccessStatisticDataSearchUtils.GRAFANA_URL);
            httppost.setHeader("Authorization", AccessStatisticDataSearchUtils.AUTHORIZATION);
            // 创建请求内容
            StringEntity entity = new StringEntity(query, ContentType.APPLICATION_JSON);
            httppost.setEntity(entity);

            // 执行http请求
            response = httpClient.execute(httppost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            return resultString;
        } catch (Exception e) {
            log.error("请求grafana接口异常");
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}
