package controller

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

var Role = new(role)

type role struct{}

func (c *role) GetDetail(ctx *gin.Context) {
	id := ctx.Query("id")
	iId, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	role, err := service.RoleService.Get(iId)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, role))
}

func (c *role) List(ctx *gin.Context) {
	current, _ := strconv.Atoi(ctx.Query("current"))
	size, _ := strconv.Atoi(ctx.Query("size"))
	roleName := ctx.Query("roleName")
	tenantId := ctx.Query("tenantId")
	roleAlias := ctx.Query("roleAlias")
	if current == 0 {
		current = 1
	}
	if size <= 0 || size > 100 {
		size = 10
	}

	roles, counts, err := service.RoleService.List(roleName, tenantId, roleAlias, current, size)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	rsp := model.RsqRoleList{
		Current: current,
		Size:    size,
		Total:   counts,
		Pages:   int(math.Ceil(float64(counts) / float64(size))),
		Records: roles,
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, rsp))
}

func (c *role) Tree(ctx *gin.Context) {
	roleTree, err := service.RoleService.GetTree()
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}

	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Success, roleTree))
}

func (c *role) Submit(ctx *gin.Context) {
	var req dao.Role
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	err := service.RoleService.Submit(req)
	ctx.JSON(http.StatusOK, err)
}

func (c *role) Remove(ctx *gin.Context) {
	var req *model.ReqRoleRemove
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	err := service.RoleService.Remove(req.IDs)
	if err == nil {
		ctx.JSON(http.StatusOK, common.SuccessResponse(common.Success, nil))
	} else {
		ctx.JSON(http.StatusOK, err)
	}
}

func (c *role) GetList(ctx *gin.Context) {
	roles, err := service.RoleService.GetList()
	if err != nil {
		ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, roles))
}

func (c *role) Grant(ctx *gin.Context) {
	var req *model.ReqRoleGrant
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	err := service.RoleService.Grant(req)
	if err != nil {
		ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}
