package com.yeejoin.amos.boot.module.common.biz.service.impl;

import com.yeejoin.amos.boot.module.common.api.dao.ESEquipmentCategory;
import com.yeejoin.amos.boot.module.common.api.dto.ESEquipmentCategoryDto;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.yeejoin.amos.boot.module.common.api.constant.TZSCommonConstant.ES_INDEX_NAME_JG_ALL;

@Service
@RequiredArgsConstructor
public class EquipmentCategoryService {

    private final ESEquipmentCategory equipmentCategoryDao;

    private final ElasticsearchOperations elasticsearchOperations;

    private final RestHighLevelClient restHighLevelClient;

    public ESEquipmentCategoryDto saveWithImmediateRefresh(ESEquipmentCategoryDto dto) {
        ESEquipmentCategoryDto saved = equipmentCategoryDao.save(dto);
        // 手动触发索引刷新
        elasticsearchOperations.indexOps(ESEquipmentCategoryDto.class).refresh();
        return saved;
    }

    public List<String> findSequenceNbrByIds(List<String> ids) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
                .query(QueryBuilders.termsQuery("SEQUENCE_NBR.keyword", ids))
                .fetchSource(false);
        SearchRequest request = new SearchRequest(ES_INDEX_NAME_JG_ALL)
                .source(sourceBuilder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            return Arrays.stream(response.getHits().getHits())
                    .map(SearchHit::getId)
                    .collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}