package com.ms.biz.paas;

import com.alibaba.fastjson.JSON;
import com.jinritemai.cloud.base.core.service.EsFactory;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * author       hahafeng
 * email        chenzhifeng.777@bytedance.com
 * date         2022/11/23 5:19 PM
 */
@Slf4j
//@Component
public class EsDemoService implements ApplicationListener<ContextRefreshedEvent> {
    public void testEs() {
        try {
            RestHighLevelClient restHighLevelClient = EsFactory.newEsHighLevelClient();

            String index = "test_es_index_yeiv7p";
            String type = "product";

            Item item = Item.builder().id(System.currentTimeMillis()).images("shenmetu").build();
            IndexRequest request = new IndexRequest(index, type);
            request.id(String.valueOf(item.getId()));
            request.source(JSON.toJSONString(item), XContentType.JSON);

            IndexResponse putResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            log.info("EsDemoService put doc resp : {}", JSON.toJSONString(putResponse));

            GetRequest getRequest = new GetRequest(index, type, putResponse.getId());
            GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            log.info("EsDemoService get doc resp : {}", JSON.toJSONString(getResponse.getSourceAsMap()));
        } catch (Exception e) {
            log.error("EsDemoService went wrong!", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent ignored) {
        testEs();
    }
}
