package logapi

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic"
	"iot_manager_service/util/es"
)

type logService struct {
}

var LogService logService

func (l logService) search(indexName string,
	page, size int,
	query *elastic.BoolQuery) (*res, error) {
	result, err := es.Client.Search(indexName).
		Query(query).
		Size(size).
		From((page-1)*size).
		Sort("t", false).
		Do(context.Background())
	//查询错误
	if err != nil {
		return nil, err
	}
	//处理结果
	var logVOS []logVO
	var a logVO
	var total int64
	if total = result.Hits.TotalHits; total > 0 {
		fmt.Printf("Found a total of %d apilog\n", result.Hits.TotalHits)
		// Iterate through results
		for _, hit := range result.Hits.Hits {
			// hit.Index contains the name of the index
			// Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
			json.Unmarshal(*hit.Source, &a)
			a.Id = hit.Id
			logVOS = append(logVOS, a)
		}
		res := &res{
			Current: page,
			Size:    size,
			Pages:   int(total)/size + 1,
			Total:   total,
			Records: logVOS,
		}
		return res, nil
	} else {
		// No hits
		return nil, nil
	}
}
