package log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gic.commons.util.DateUtil;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-conf.xml"})
public class KibanaLogDownload {
    static KibanaLogDownload esQueryHelper = new KibanaLogDownload();
    ObjectMapper objectMapper = new ObjectMapper();
    private String indexName = "filebeat-6.7.2*";

    private String ip = "http://10.0.2.11:9200";

    private int skipTime = 1000 * 60 * 60 * 4;

    public static KibanaLogDownload getInstance() {
        return esQueryHelper;
    }

    public KibanaLogDownload setIndexName(String indexName) {
        this.indexName = indexName;
        return this;
    }

    public KibanaLogDownload setIp(String ip) {
        this.ip = ip;
        return this;
    }


    /**
     * 游标查询
     * @param param 参数
     * @param time  失效时间
     * @param consumer 单条回调
     */
    public void postScroll(String param, String time, Consumer<String> consumer) {
        EsResult res = null;
        String htt = ip + "/" + indexName + "/_search?scroll=" + time;
        String s = HttpClientUtil.postJson(htt, param, null);
        String scrollId = null ;
        try {
            res = JSON.parseObject(s, EsResult.class);
            scrollId = res.get_scroll_id();
            for (EsResult.Hits hits2 : res.getHits()) {
                for (EsResult.Source hit : hits2.getHits()) {
                    consumer.accept(hit.get_source());
                }
            }
            boolean empty;
            do {
                empty=true;
                String htt2 = ip + "/_search/scroll";
                Map<String, String> pa = new HashMap<>();
                pa.put("scroll", time);
                pa.put("scroll_id", scrollId);
                String s2 = HttpClientUtil.postJson(htt2, JSON.toJSONString(pa), null);
                res = JSON.parseObject(s2, EsResult.class);
                for (EsResult.Hits hits2 : res.getHits()) {
                    for (EsResult.Source hit : hits2.getHits()) {
                        empty=false;
                        consumer.accept(hit.get_source());
                    }
                }
            } while (!empty);
            Map<String, String> pa = new HashMap<>();
            pa.put("scroll_id", scrollId);
            String clearScrollRes = HttpClientUtil.postDelJson(ip + "/_search/scroll/", JSON.toJSONString(pa), null);
            System.out.println("游标清除1:"+clearScrollRes);
        }catch (Exception e) {
            e.printStackTrace();
            if (null != scrollId) {
                Map<String, String> pa = new HashMap<>();
                pa.put("scroll_id", scrollId);
                String clearScrollRes = HttpClientUtil.postDelJson(ip + "/_search/scroll/", JSON.toJSONString(pa), null);
                System.out.println("游标清除2:"+clearScrollRes);
            }
        }
    }
    static int logCount = 0 ;
    public static void main(String[] args) throws InterruptedException {

        String startTime = "2024-05-08 19:00" ;
        String endTime = "2024-05-08 22:00" ;
        long start = DateUtil.strToDate(startTime,"yyyy-MM-dd HH:mm").getTime() ;
        long end = DateUtil.strToDate(endTime,"yyyy-MM-dd HH:mm").getTime() ;
        //long start = 1714446600000l ;
        //long end = 1714448399999l ;
        int size = 10000 ;
        int batch = 1 ;
        JSONArray arr = new JSONArray() ;
        for(int i=0;i<batch;i++) {
            long per = (end - start) / batch ;
            long s1 = start+ (i)*per ;
            long s2 = start+ (i+1)*per ;
            System.out.println(s1 + " " + s2);
            JSONObject root = JSONObject.parseObject("{}") ;
            root.put("size",size) ;
            JSONObject query = JSONObject.parseObject("{\"bool\":{\"must\":[{\"match_all\":{}},{\"bool\":{\"should\":[{\"match_phrase\":{\"message\":\"创蓝彩信回执=\"}}],\"minimum_should_match\":1}},{\"range\":{\"@timestamp\":{\"gte\":1715166000000,\"lte\":1715176800000,\"format\":\"epoch_millis\"}}}],\"filter\":[],\"should\":[],\"must_not\":[]}}") ;
            root.put("query",query) ;
            KibanaLogDownload.getInstance().postScroll(root.toJSONString(), "15m", source -> {
                try {
                    //System.out.println(source + (logCount++));

                    //
                  //  System.out.println((source.split("创蓝彩信回执=")[1]));
                    Pattern p = Pattern.compile("\\[.*\\]") ;
                    Matcher m = p.matcher(source.split("创蓝彩信回执=")[1]) ;
                    while(m.find()) {
                        String s = m.group() ;
                      //  System.out.println(s);
                        JSONArray xx = JSONArray.parseArray(s.replace("\\",""));
                      //  System.out.println(xx.toJSONString());
                        arr.addAll(xx) ;
                    }


                }catch (Exception e) {
                }
            });
        }
        System.out.println(arr.toJSONString());
    }
}
