package com.tofly.loges.controller;

import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.StringUtil;
import com.tofly.loges.config.LogUtil;
import com.tofly.loges.entity.Log;
import com.tofly.loges.service.LogEntityRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author tuonbed
 * @date 2020/4/26  10:54
 */
@RestController
@RequestMapping("/log")
public class LogController {

    @Autowired
    private LogEntityRepository logEntityRepository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @PostMapping("/add")
    public boolean save(@RequestBody Log log) {
        System.out.println("存入es:"+log);
//        long count = logEntityRepository.count();
        log.setCreateTime(Date8Util.getCurrentDate());
        logEntityRepository.save(log);
        return true;
    }

    @GetMapping("/clear")
    public boolean clear() {
        logEntityRepository.deleteAll();
        return true;
    }

    @GetMapping("/pageNew")
    public List newPage(@RequestParam  Map map){
        System.out.println("查询es:page:"+map);

        String[] indexs=getIndex();
        if(indexs==null){
            return null;
        }
        //Map map1=(Map)map.get("logMap");
        BoolQueryBuilder qb = QueryBuilders.boolQuery();
        RangeQueryBuilder rangeQueryBuilder= QueryBuilders.rangeQuery("createTime");
        if(StringUtil.isNotEmpty((String)map.get("type"))){
           qb.filter(QueryBuilders
                    .matchPhraseQuery("type",map.get("type")));
        }
        if(StringUtil.isNotEmpty((String)map.get("startDate"))){
            rangeQueryBuilder.from(Date8Util.parse((String)map.get("startDate"),Date8Util.DATE_TIME).getTime());
        }
        if(StringUtil.isNotEmpty((String)map.get("endDate"))){
            rangeQueryBuilder.to(Date8Util.parse((String)map.get("endDate"),Date8Util.DATE_TIME).getTime());
//            ((BoolQueryBuilder) qb).filter(QueryBuilders.
//                    rangeQuery("createTime").lt(
//                    Date8Util.parse((String)map.get("endDate"),Date8Util.DATE_TIME).getTime()));
        }
        qb.filter(rangeQueryBuilder);
        Sort sort=new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageRequest = PageRequest.of(Integer.parseInt((String)map.get("page"))-1,
                Integer.parseInt((String)map.get("size")),sort);

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withIndices(indexs).withQuery(qb)
                .withPageable(pageRequest);
        List<Log> logList = elasticsearchTemplate.queryForList(nativeSearchQueryBuilder.build(), logEntityRepository.getEntityClass());
//        Page<Log> search = logEntityRepository.search(qb2,pageRequest);
//        List<Log> list = search.getContent();
//        Iterable<Log> search = logEntityRepository.search(qb2);
//        List list=new ArrayList();
//        search.forEach(l->{
//            list.add(l);
//        });
        return logList;
    }


    private String[] getIndex(){
        Class<Log> tClass=logEntityRepository.getEntityClass();
        Document annotation = tClass.getAnnotation(Document.class);
        String[] indexName = annotation.indexName().split("_");
        Set<String> set=new HashSet<>();
        int i=0;
        String minIndex= LogUtil.minIndex;
        if(StringUtil.isEmpty(minIndex)){
            while (true){
                String index=indexName[0]+"_"+ Date8Util.minusMonthstoString(i);
                if(elasticsearchTemplate.indexExists(index)){
                    set.add(index);
                    i++;
                }else{
                    LogUtil.minIndex=index;
                    break;
                }
            }
        }else{
            while (true){
                String index=indexName[0]+"_"+ Date8Util.minusMonthstoString(i);
                if(index.equals(minIndex)){
                    break;
                }
                set.add(index);
                i++;
            }
        }
        String[] indexs=new String[set.size()];
        return set.toArray(indexs);
    }
}
