package controller

import (
	"github.com/gin-gonic/gin"
	"iot_manager_service/app/record/dao"
	"iot_manager_service/app/record/service"
	"iot_manager_service/util/common"
	"math"
	"net/http"
	"strconv"
)

var LightRecord = new(lightRecordCtl)

type lightRecordCtl struct{}

type LightRecordRespose struct {
	Records []dao.LightRecord `json:"records"` //记录列表
	Current int               `json:"current"` //当前分页
	Size    int               `json:"size"`    //每页数量
	Total   int               `json:"total"`   //总数
	Pages   int               `json:"pages"`   //总页数
}

func (c *lightRecordCtl) List(ctx *gin.Context) {
	searchValue := ctx.Query("searchValue")
	start := ctx.Query("queryStartTime")
	end := ctx.Query("queryEndTime")
	groupId := ctx.Query("groupId")
	current, _ := strconv.Atoi(ctx.Query("current"))
	size, _ := strconv.Atoi(ctx.Query("size"))
	if current == 0 {
		current = 1
	}
	if size <= 0 || size > 100 {
		size = 10
	}
	id := -1
	if groupId != "" {
		id, _ = strconv.Atoi(groupId)
	}

	records, total, err := service.LightRecordService.List(searchValue, start, end, id, current, size)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	pages := math.Ceil(float64(len(records)) / float64(size))
	rsp := LightRecordRespose{
		Current: current,
		Size:    size,
		Total:   int(total),
		Pages:   int(pages),
		Records: records,
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, rsp))
}

func (c *lightRecordCtl) Detail(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Query("id"))
	record, err := service.LightRecordService.Detail(id)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, record))
}
