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"
)

// BusinessTactics 业务 策略 告警
var BusinessTactics = new(businessTacticsCtl)

type businessTacticsCtl struct{}

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

func (c businessTacticsCtl) SaveOrUpdate(ctx *gin.Context) {
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)
	var submitData model.RequestBusinessSubmit
	ctx.ShouldBindJSON(&submitData)
	err := service.BusinessTacticsService.SaveOrUpdate(claims.TenantId, submitData)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}

func (c businessTacticsCtl) Detail(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}

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

func (c businessTacticsCtl) Enable(ctx *gin.Context) {
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)
	var submitData model.RequestBusinessSubmit
	ctx.ShouldBind(&submitData)
	err := service.BusinessTacticsService.SaveOrUpdate(claims.TenantId, submitData)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}
