package controller

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

// NoticeSet 告警设置
var NoticeSet = new(noticeSetCtl)

type noticeSetCtl struct{}

func (c noticeSetCtl) List(ctx *gin.Context) {
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)
	current, _ := strconv.Atoi(ctx.Query("current"))
	size, _ := strconv.Atoi(ctx.Query("size"))
	searchValue := ctx.Query("searchValue")
	if current == 0 {
		current = 1
	}
	if size <= 0 || size > 100 {
		size = 10
	}
	records, err := service.NoticeSetService.GetList(claims.TenantId, searchValue)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, err)
		return
	}
	pages := math.Ceil(float64(len(records)) / float64(size))
	rsp := model.ResposeNoticeSetRecords{
		Current: current,
		Size:    size,
		Total:   len(records),
		Pages:   int(pages),
		Records: records,
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, rsp))
}

func (c noticeSetCtl) GetUserList(ctx *gin.Context) {
	current, _ := strconv.Atoi(ctx.Query("current"))
	size, _ := strconv.Atoi(ctx.Query("size"))
	account := ctx.Query("account")
	realName := ctx.Query("realName")
	if current == 0 {
		current = 1
	}
	if size <= 0 || size > 100 {
		size = 10
	}
	users, err := service.NoticeSetService.UserList(account, realName, current, size)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, users))
}

func (c noticeSetCtl) Detail(ctx *gin.Context) {
	id := ctx.Query("id")
	data, err := service.NoticeSetService.GetById(id)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, data))
}

func (c noticeSetCtl) Update(ctx *gin.Context) {
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)
	post := model.NoticeUpdateData{}
	err := ctx.ShouldBindJSON(&post)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, err)
		return
	}
	err = service.NoticeSetService.Update(post, claims.TenantId)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}

func (c noticeSetCtl) Remove(ctx *gin.Context) {
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)
	id := ctx.Query("ids")
	err := service.NoticeSetService.Remove(id, claims.TenantId)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}
