package cn.reghao.tnb.search.app.es;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.analysis.Analyzer;
import co.elastic.clients.elasticsearch._types.analysis.StandardAnalyzer;
import co.elastic.clients.elasticsearch._types.mapping.IntegerNumberProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.elasticsearch.indices.get_mapping.IndexMappingRecord;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author reghao
 * @date 2025-03-12 10:45:52
 */
@Slf4j
@Service
public class IndexService {
    private final ElasticsearchClient esClient;

    public IndexService(ElasticService elasticService) {
        this.esClient = elasticService.getElasticsearchClient();
    }

    public void createIndex(String index, Map<String, Property> propertyMap) throws IOException {
        String type = "_doc";
        ExistsRequest existsRequest = new ExistsRequest.Builder()
                .index(index)
                .local(false)
                .build();
        BooleanResponse exists = esClient.indices().exists(existsRequest);
        if(exists.value()) {
            System.out.println("索引 " + index + " 已存在!");
            return;
        }

        // 设置分词
        IndexSettingsAnalysis indexSettingsAnalysis = new IndexSettingsAnalysis.Builder()
                .analyzer("StandardAnalyzer", new Analyzer.Builder().standard(new StandardAnalyzer.Builder().build()).build())
                .build();

        IndexSettings indexSettings = new IndexSettings.Builder()
                //.analysis(indexSettingsAnalysis)
                .numberOfShards("10")
                .numberOfReplicas("10")
                //.refreshInterval(Time.of(t -> 5))
                .build();
        TypeMapping typeMapping = new TypeMapping.Builder()
                .properties(propertyMap)
                .build();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                .index(index)
                .settings(indexSettings)
                .mappings(typeMapping)
                //.aliases("ngxlog", new Alias.Builder().isWriteIndex(true).build())
                .build();
        CreateIndexResponse createIndexResponse = esClient.indices().create(createIndexRequest);
        if (createIndexResponse.acknowledged()) {
            System.out.println("索引 " + index + " 创建成功!");
        }
    }

    public void updateMapping(String index) throws IOException {
        Map<String, Property> propertyMap = new HashMap<>();
        Property intProp = Property.of(builder -> builder.integer(IntegerNumberProperty.of(pro -> pro.index(true))));
        propertyMap.put("member", intProp);

        /*Property keywordProp = Property.of(builder -> builder.keyword(KeywordProperty.of(pro -> pro.index(true))));
        propertyMap.put("requestMethod", keywordProp);*/

        /*Property textProp = Property.of(builder -> builder.text(TextProperty.of(pro -> pro.index(true).analyzer("ik_max_word"))));
        propertyMap.put("requestUri", textProp);*/

        PutMappingRequest putMappingRequest = PutMappingRequest.of(m -> m.index(index).properties(propertyMap));
        PutMappingResponse putMappingResponse = esClient.indices().putMapping(putMappingRequest);
        boolean acknowledged = putMappingResponse.acknowledged();
        log.info("update mappings ack: {}", acknowledged);
    }

    public void deleteIndex(String index) throws IOException {
        ExistsRequest existsRequest = new ExistsRequest.Builder()
                .index(index)
                .local(false)
                .build();
        BooleanResponse exists = esClient.indices().exists(existsRequest);
        if(!exists.value()) {
            System.out.println("索引 " + index + " 不存在!");
            return;
        }

        DeleteIndexResponse response = esClient.indices().delete(i -> i.index(index));
        System.out.println(response.acknowledged());
    }

    public void getMapping(String index) throws IOException {
        GetMappingRequest request = GetMappingRequest.of(builder -> builder.index(index));
        GetMappingResponse response = esClient.indices().getMapping(request);
        Map<String, IndexMappingRecord> result = response.result();
        log.info("{} mapping message: {}", index, result);
    }

    public void getIndex(String index) throws IOException {
        List<String> indexName = new ArrayList<>();
        indexName.add(index);
        GetIndexRequest request = GetIndexRequest.of(builder -> builder.index(indexName));
        GetIndexResponse getIndexResponse = esClient.indices().get(request);
        Map<String, IndexState> result = getIndexResponse.result();
        result.entrySet().forEach(entry -> {
            log.info("key: {}, value: {}", entry.getKey(), entry.getValue());
        });
    }

    public void existIndex() throws IOException {
        List<String> indexName = new ArrayList<>();
        indexName.add("user");
        ExistsRequest request = ExistsRequest.of(builder -> builder.index(indexName));
        BooleanResponse response = esClient.indices().exists(request);
        log.info("exist: {}", response.value());
    }
}
