package com.yeejoin.amos.boot.module.statistcs.biz.utils;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.util.Collections;

public class QueryBuilderUtils {
    // 复制BoolQueryBuilder
    public static BoolQueryBuilder copyBoolQuery(BoolQueryBuilder original) {
        if (original == null) {
            return QueryBuilders.boolQuery();
        }

        BoolQueryBuilder copy = QueryBuilders.boolQuery();

        // 复制查询条件
        original.must().forEach(copy::must);
        original.filter().forEach(copy::filter);
        original.should().forEach(copy::should);
        original.mustNot().forEach(copy::mustNot);

        // 复制minimumShouldMatch设置（新版本方式）
        if (original.minimumShouldMatch() != null) {
            copy.minimumShouldMatch(original.minimumShouldMatch());
        }

        // 复制其他属性
        copy.boost(original.boost());
        copy.queryName(original.queryName());

        return copy;
    }

    /**
     * 组装分割符字段的聚合查询
     *
     * @param searchSourceBuilder es查询构造器
     * @param field 需要查询的字段，如：unitType.keyword
     * @param spiltSymbol 分割符号,如：#
     * @param aggName 聚合名称，根据此名称从查询结果获取数据，如：Terms unitTypesTerms = searchResponse.getAggregations().get(aggName)
     */
    public static void buildSplitFieldAggCondition(SearchSourceBuilder searchSourceBuilder, String field, String spiltSymbol, String aggName, String params) {
        // Painless 脚本内容
        String scriptSource = "if (doc['" + field + "'].size() > 0) {" +
                "  String value = doc['" + field + "'].value;" +
                "  if (value != null && !value.isEmpty()) {" +
                "    return value.splitOnToken('" + spiltSymbol + "');" +
                "  }" +
                "}" +
                "return [];";
        Script script = new Script(ScriptType.INLINE, "painless", scriptSource, Collections.emptyMap());
        searchSourceBuilder.aggregation(AggregationBuilders.terms(aggName).script(script).missing(params).size(100));
    }
}