package com.nbclass.szxgl.service.impl;

import com.alibaba.fastjson.JSON;
import com.nbclass.szxgl.model.Content;
import com.nbclass.szxgl.service.ElasticSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Map<String, Object> getList(String tagIds,String caseName,Integer pageNum, Integer pageSize) {
        // 封装Map参数返回
        Map<String, Object> result = new HashMap<>();
        try {
            // 选择标签或来源过滤时，从数据库查询记录
			/*if(StringUtils.isNotBlank(tagIds) || StringUtils.isNotBlank(sourceIds)) {
				return getListByMySQL(pageNum, pageSize, type, keyWord, tagIds, sourceIds);
			}*/
            if(StringUtils.isNoneBlank(tagIds) || StringUtils.isNoneBlank(caseName)){
                SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                // 分页采用简单的from + size分页，适用数据量小的，了解更多分页方式可自行查阅资料
                searchSourceBuilder.from((pageNum - 1) * pageSize); // 从0开始
                searchSourceBuilder.size(pageSize);


                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                boolQueryBuilder.must(QueryBuilders.termQuery("release", 2));


//                if(StringUtils.isNoneBlank(tagIds) && StringUtils.isNoneBlank(caseName)){
//                    boolQueryBuilder.must(QueryBuilders.termQuery("release", 2));
//                }

                if (StringUtils.isNoneBlank(tagIds)){
                    List<String> list = Arrays.asList(tagIds.split(","));
                    for(String tagId:list) {
                        boolQueryBuilder.must(QueryBuilders.termQuery("tagList.tid", tagId));
                    }
                }


                if(StringUtils.isNoneBlank(caseName)){
                    BoolQueryBuilder keywordQuery = QueryBuilders.boolQuery();
                    keywordQuery.must(QueryBuilders.matchQuery("title", caseName)).boost(2F);
                    boolQueryBuilder.should(keywordQuery);
                }else {
                    // 排序，根据点赞数倒叙
                    searchSourceBuilder.sort("praiseno", SortOrder.DESC);
                }

                searchSourceBuilder.query(boolQueryBuilder);

                // SearchRequest
                SearchRequest searchRequest = new SearchRequest();
                searchRequest.source(searchSourceBuilder);
                // 查询ES
                SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
                SearchHits hits = searchResponse.getHits();
                // 获取总数
                Long total = hits.getTotalHits().value;
                // 遍历封装列表对象
                List<Content> dataList = new ArrayList<>();
                SearchHit[] searchHits = hits.getHits();
                for (SearchHit searchHit : searchHits) {
                    Content entity = JSON.parseObject(searchHit.getSourceAsString(), Content.class);
                    dataList.add(entity);
                    System.out.println(searchHit.getSourceAsString());
                }
                result.put("total", total); // 总记录数
                result.put("rows", dataList); // 数据体
                int totalPage = (int)(total % pageSize==0 ? total/pageSize : total/pageSize+1);
                result.put("totalPage", totalPage); // 总页数
            }

        }catch (Exception e) {
            log.error("从es查询数据列表异常", e);
        }
        return result;
    }
}
