package com.liangjian.dataplatform.member.service.impl;

import com.liangjian.dataplatform.member.entity.response.PageResult;
import com.liangjian.dataplatform.member.service.ITagDatabaseService;
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.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author 黄树文
 * @date 2020/4/17 16:43
 */
@Service
public class TagDatabaseService implements ITagDatabaseService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @Override
    public PageResult<Map<String, Object>> queryByCondition(Integer pageIndex, Integer pageSize, String tagTypeName) throws IOException {

        RestHighLevelClient client = elasticsearchTemplate.getClient();

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchPhraseQuery("TagTypeName", tagTypeName))
                .size(pageSize).from((pageIndex - 1) * pageSize);
        SearchResponse searchResponse = client.search(new SearchRequest("mem_tag").source(searchSourceBuilder), RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        List<Map<String, Object>> result = new LinkedList<>();
        hits.forEach(hit ->{
            result.add(hit.getSourceAsMap());
        });

        return PageResult.success(result, hits.getTotalHits());
    }
}
