package log

import (
	"log"

	"bsm/full/module/base/logs/internal/impl"
	"bsm/full/module/base/logs/internal/models"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	"github.com/gin-gonic/gin"
)

var (
	DefaultPage = 1
	DefaultSize = 50
)

func LogFetch(c *gin.Context) {
	var request map[string]any
	err := c.BindJSON(&request)
	if err != nil {
		log.Printf("解析json异常: %v", err)
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}

	var (
		data  []any
		count int64
		tx    = impl.DBService.Model(&models.LogData{})
	)

	var size int
	var page int
	if request["op_name"] != "" {
		tx.Where("op_name like ?", "%"+request["op_name"].(string)+"%")
	}
	if request["service"] != "" {
		tx.Where("service like ?", "%"+request["service"].(string)+"%")
	}
	if request["op_ip"] != "" {
		tx.Where("op_ip = ?", "%"+request["ip"].(string)+"%")
	}
	if request["level"] != "" {
		tx.Where("level = ?", request["level"].(int))
	}

	if page <= 0 {
		page = DefaultPage
	}
	if size <= 0 {
		size = DefaultSize
	}

	if err := tx.Count(&count).Limit(size).Offset((page - 1) * size).Find(&data).Error; err != nil {
		log.Printf("查询异常: %v", err)
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	infra.Response.Success(c, map[string]any{
		"data":  data,
		"total": count,
	})
}
