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

import com.alibaba.fastjson.JSON;
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.support.WriteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
@RequiredArgsConstructor
@Slf4j
public class EsBulkService {

    private final RestHighLevelClient restHighLevelClient;

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