package com.jay.monitor.data.server.utils;

import cn.hutool.core.bean.BeanUtil;
import com.jay.monitor.data.server.anno.ESSearch;
import com.jay.monitor.data.server.enums.ESQuerySyntax;
import com.jay.monitor.data.server.models.entity.es.JayMonitorMQIndex;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.elasticsearch.index.query.*;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class ESUtils {

    private static List<Class> typeList =
        Arrays.asList(Integer.class, String.class, Date.class, Double.class, Long.class);

    public static QueryBuilder beanToQueryBuilder(Object t) throws Exception {
        if (t == null) {
            return null;
        }
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        Field[] declaredFields = FieldUtils.getAllFields(t.getClass());
        for (int i = 0; i < declaredFields.length; i++) {
            Field declaredField = declaredFields[i];
            String name = declaredField.getName();
            Object value = BeanUtil.getProperty(t, name);
            if (value != null && !ObjectUtils.isEmpty(value) && typeList.contains(value.getClass())) {
                ESSearch esSearch = AnnotationUtils.findAnnotation(declaredField, ESSearch.class);
                QueryBuilder queryBuilder = null;
                if (esSearch == null || esSearch.value() == ESQuerySyntax.eq) {
                    name = name + ".keyword";
                    queryBuilder = QueryBuilders.matchQuery(name, value);
                } else if (esSearch.value() == ESQuerySyntax.gt) {
                    queryBuilder = QueryBuilders.rangeQuery(name).gt(value);
                } else if (esSearch.value() == ESQuerySyntax.lt) {
                    queryBuilder = QueryBuilders.rangeQuery(name).lt(value);
                } else if (esSearch.value() == ESQuerySyntax.like) {
                    queryBuilder = QueryBuilders.matchPhraseQuery(name, value);
                }
                boolQueryBuilder.must(queryBuilder);
            }
        }
        return boolQueryBuilder;
    }

    public static void main(String[] args) throws Exception {
        JayMonitorMQIndex index = new JayMonitorMQIndex();
        index.setRequestTime(11111L);
        QueryBuilder queryBuilder = beanToQueryBuilder(index);
        System.out.println(queryBuilder);
    }
}
