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 AKeyAlarmRecord = new(aKeyAlarmRecordCtl)

type aKeyAlarmRecordCtl struct{}

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

func (c *aKeyAlarmRecordCtl) List(ctx *gin.Context) {
	searchValue := ctx.Query("searchValue")
	start := ctx.Query("queryStartTime")
	end := ctx.Query("queryEndTime")
	serveId := ctx.Query("serveId")
	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 serveId != "" {
		id, _ = strconv.Atoi(serveId)
	}

	records, err := service.AKeyAlarmRecordService.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 := AKeyAlarmRecordRespose{
		Current: current,
		Size:    size,
		Total:   len(records),
		Pages:   int(pages),
		Records: records,
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, rsp))
}

// refresh 同步sos记录
func (c *aKeyAlarmRecordCtl) Refresh(ctx *gin.Context) {
	c.SosRecordSync()
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}

func (c *aKeyAlarmRecordCtl) SosRecordSync() {
	recordService := service.AKeyAlarmRecordService
	go func() {
		recordService.Refresh()
	}()
}

// Detail 查看详情
func (c *aKeyAlarmRecordCtl) Detail(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Query("id"))
	record, err := service.AKeyAlarmRecordService.Detail(id)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, record))
}

// Dispose 添加备注
func (c *aKeyAlarmRecordCtl) Dispose(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Query("id"))
	remark := ctx.Query("remark")
	err := service.AKeyAlarmRecordService.UpdateRemark(id, remark)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}

	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}
