package com.yeejoin.equip.utils;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;

/**
 * @author LiuLin
 * @date 2023年08月08日 16:30
 */
@Slf4j
@Component
public class ElasticSearchUtil {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * ES修改数据
     *
     * @param indexName 索引名称
     * @param id        主键
     * @param paramJson 参数JSON
     * @return
     */
    public boolean updateData(String indexName, String id, String paramJson) {
        UpdateRequest updateRequest = new UpdateRequest(indexName, id);
        //如果修改索引中不存在则进行新增
        updateRequest.docAsUpsert(true);
        //立即刷新数据
        updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
        updateRequest.doc(paramJson, XContentType.JSON);
        try {
            UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            //log.info("索引[{}],主键：【{}】操作结果:[{}]", indexName, id, updateResponse.getResult());
            if (DocWriteResponse.Result.CREATED.equals(updateResponse.getResult())) {
                //新增
                log.info("索引：【{}】,主键：【{}】新增成功", indexName, id);
                return true;
            } else if (DocWriteResponse.Result.UPDATED.equals(updateResponse.getResult())) {
                //修改
                //log.info("索引：【{}】，主键：【{}】修改成功", indexName, id);
                return true;
            } else if (DocWriteResponse.Result.NOOP.equals(updateResponse.getResult())) {
                //无变化
                log.info("索引:[{}],主键:[{}]无变化", indexName, id);
                return true;
            }
        } catch (IOException e) {
            log.error("索引：[{}],主键：【{}】，更新异常:[{}]", indexName, id, e);
            return false;
        }
        return false;
    }
}
