package cn.reghao.tnb.search.esapp.service;

import cn.reghao.tnb.search.esapp.es.ElasticService;
import cn.reghao.tnb.search.esapp.model.po.VideoText;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchAllQuery;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @author reghao
 * @date 2025-03-12 10:45:58
 */
@Slf4j
@Service
public class VideoTextDocument {
    private final String indexName = "video_text";
    private final ElasticsearchClient esClient;

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

    public void addOrUpdateVideoText(VideoText videoText) {
        try {
            IndexResponse response = esClient.index(i -> i.index(indexName).id(videoText.getId()).document(videoText));
            Result result = response.result();
            log.info(result.jsonValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void batchAddVideoText(List<VideoText> videoTextList) {
        List<BulkOperation> bulkOperations = new ArrayList<>();
        videoTextList.forEach(p -> bulkOperations.add(BulkOperation.of(b -> b.index(c -> c.id(p.getId()).document(p)))));
        try {
            BulkResponse bulkResponse = esClient.bulk(s -> s.index(indexName).operations(bulkOperations));
            bulkResponse.items().forEach(b -> log.info("bulk response result = {}", b.result()));
            log.error("bulk response.error() = {}", bulkResponse.errors());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteVideoText(String id) {
        try {
            DeleteResponse response = esClient.delete(s -> s.index(indexName).id(id));
            Result result = response.result();
            log.info(result.jsonValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteAllDocument() {
        try {
            DeleteByQueryRequest deleteByQueryRequest = DeleteByQueryRequest.of(s -> s.index(indexName)
                    .query(m -> m.matchAll(new MatchAllQuery.Builder().build()))
            );
            DeleteByQueryResponse deleteByQueryResponse = esClient.deleteByQuery(deleteByQueryRequest);
            log.info("del doc result: {}", deleteByQueryResponse.total());
        } catch (IOException e) {
            log.error("del doc failed, error: ", e);
        }
    }
}
