package logapi

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic"
	"iot_manager_service/util/common"
	"iot_manager_service/util/es"
	"net/http"
	"strconv"
	"time"
)

var LogController = new(logController)

type logController struct {
}

// List 查询日志
func (l logController) List(ctx *gin.Context) {
	//处理分页参数,索引名
	var indexName, logDate string
	//var logDate date.Date
	var page, size int
	var err1, err2 error
	if logDate = ctx.Query("time"); logDate == "" {
		indexName = defaultIndex()
	} else {
		indexName = logDate
	}
	if page, err1 = strconv.Atoi(ctx.Query("current")); err1 != nil {
		page = 1
	}
	if size, err2 = strconv.Atoi(ctx.Query("size")); err2 != nil {
		size = 10
	}
	//查询条件
	level := ctx.Query("level")
	reqUri := ctx.Query("req_uri")
	query := elastic.NewBoolQuery()
	var q1, q2 *elastic.MatchQuery
	if level != "" {
		q1 = elastic.NewMatchQuery("level", level)
		query.Must(q1)
	}
	if reqUri != "" {
		q2 = elastic.NewMatchQuery("req_uri", reqUri)
		query.Must(q2)
	}
	//调试-打印DSL
	source, _ := query.Source()
	data, _ := json.MarshalIndent(source, "", "  ")
	fmt.Printf("source: \n%+v", string(data))
	//执行并响应
	result, err3 := LogService.search(indexName, page, size, query)
	if err3 != nil {
		ctx.JSON(http.StatusOK, common.SuccessResponse("es错误", nil))
	} else if result != nil {
		ctx.JSON(http.StatusOK, common.SuccessResponse(common.Success, result))
	} else {
		//todo 修改前端代码 data为空时前端一直处于加载页面,前端不会改
		ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, res{
			Current: 0,
			Pages:   0,
			Size:    0,
			Total:   0,
			Records: nil,
		}))
	}
}

// AddDoc 存储日志 DelIndex 删除索引 在util/es下

// Detail 日志详情
func (l logController) Detail(ctx *gin.Context) {
	fmt.Printf("okkk")
	var id, indexName string
	indexName = ctx.Query("indexName")
	id = ctx.Query("id")

	do, err := es.Client.Get().Index(indexName).Type("_doc").Id(id).Do(context.Background())
	if err != nil {
		fmt.Printf("\nerror=%v\n", err)
	} else {
		//响应数据给前端
		ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, do))
	}
}

// 当天日期作为索引名
func defaultIndex() string {
	return time.Now().Format("2006-01-02")
}
