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

import com.yeejoin.amos.boot.module.common.api.entity.EsEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;


@Component
@RequiredArgsConstructor
@Slf4j
public class EsBulkService {

    private final RestHighLevelClient restHighLevelClient;

    private final ElasticsearchConverter converter; // 依赖注入


    public <T> void bulkUpsert(String index, List<EsEntity<T>> list) {
        BulkRequest request = new BulkRequest();
        list.forEach(item -> {
            Map<String, Object> docData = converter.mapObject(item.getData());
            request.add(new UpdateRequest(index, item.getId())
                    .doc(docData)
                    .upsert(docData));
        });
        try {
            restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("批量写入数据失败:{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
