package com.gree.mall.miniapp.logic.es;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.gree.mall.miniapp.bean.es.CommonListES;
import com.gree.mall.miniapp.utils.CommonUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 操作es
 */

@Service
public class EsLogic {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public boolean createIndexAndMapping(Class<?> classType) {
        if(elasticsearchRestTemplate.indexOps(classType).exists()){
            return true;
        }
        boolean b = elasticsearchRestTemplate.indexOps(classType).create();
        return b;
    }




    public  List<CommonListES>  list(List<String> websitNumbers,String workerNumber,String comId){
        //标题
        BoolQueryBuilder titleQueryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("type", "1"));
        if(StringUtils.isNotEmpty(comId)){
            titleQueryBuilder.must(QueryBuilders.termQuery("comListId", comId));
        }
        //内容
        BoolQueryBuilder must = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("type", "2"));
        if(StringUtils.isNotEmpty(comId)){
            must.must(QueryBuilders.termQuery("comListId", comId));
        }
        if(StringUtils.isNotEmpty(workerNumber)){
            must.must(QueryBuilders.matchPhraseQuery("workerNumber", workerNumber));
        }
        if(CollectionUtils.isNotEmpty(websitNumbers)){
            must.must(QueryBuilders.termsQuery("websitNumber.keyword",websitNumbers));
        }
        NativeSearchQuery titleBuild = new NativeSearchQueryBuilder().withQuery(titleQueryBuilder).build();
        NativeSearchQuery dataBuild = new NativeSearchQueryBuilder().withQuery(must).build();

        List<SearchHit<CommonListES>> searchHits1 = elasticsearchRestTemplate.search(titleBuild, CommonListES.class).getSearchHits();
        List<SearchHit<CommonListES>> searchHits2 = elasticsearchRestTemplate.search(dataBuild, CommonListES.class).getSearchHits();
        List<CommonListES> titles = searchHits1.stream().map(SearchHit<CommonListES>::getContent).collect(Collectors.toList());
        List<CommonListES> datas = searchHits2.stream().map(SearchHit<CommonListES>::getContent).collect(Collectors.toList());
        titles.addAll(datas);

        return titles;
    }



}
