package system

import (
	"kra/pkg/response"

	"github.com/gin-gonic/gin"
)

type AuthorityBtnApi struct{}

// AuthorityBtnRequest 权限按钮请求
type AuthorityBtnRequest struct {
	MenuID      uint   `json:"menuID" binding:"required"`
	AuthorityId uint   `json:"authorityId" binding:"required"`
	Selected    []uint `json:"selected"`
}

// GetAuthorityBtn
// @Tags      AuthorityBtn
// @Summary   获取权限按钮
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      AuthorityBtnRequest                                        true  "菜单ID, 角色ID, 选中的按钮ID集合"
// @Success   200   {object}  response.Response{data=map[string]interface{},msg=string}  "获取权限按钮"
// @Router    /authorityBtn/getAuthorityBtn [post]
func (a *AuthorityBtnApi) GetAuthorityBtn(c *gin.Context) {
	var req AuthorityBtnRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	res, err := authorityBtnUsecase.GetAuthorityBtn(c, req.AuthorityId, req.MenuID)
	if err != nil {
		response.FailWithMessage("查询失败", c)
		return
	}

	response.OkWithDetailed(res, "查询成功", c)
}

// SetAuthorityBtn
// @Tags      AuthorityBtn
// @Summary   设置权限按钮
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      AuthorityBtnRequest            true  "菜单ID, 角色ID, 选中的按钮ID集合"
// @Success   200   {object}  response.Response{msg=string}  "设置权限按钮"
// @Router    /authorityBtn/setAuthorityBtn [post]
func (a *AuthorityBtnApi) SetAuthorityBtn(c *gin.Context) {
	var req AuthorityBtnRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if err := authorityBtnUsecase.SetAuthorityBtn(c, req.AuthorityId, req.MenuID, req.Selected); err != nil {
		response.FailWithMessage("分配失败", c)
		return
	}

	response.OkWithMessage("分配成功", c)
}

// CanRemoveAuthorityBtn
// @Tags      AuthorityBtn
// @Summary   检查是否可以删除权限按钮
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     id    query     string                         true  "按钮ID"
// @Success   200   {object}  response.Response{msg=string}  "删除成功"
// @Router    /authorityBtn/canRemoveAuthorityBtn [post]
func (a *AuthorityBtnApi) CanRemoveAuthorityBtn(c *gin.Context) {
	idStr := c.Query("id")
	if idStr == "" {
		response.FailWithMessage("缺少参数: id", c)
		return
	}

	var id uint
	for _, ch := range idStr {
		if ch >= '0' && ch <= '9' {
			id = id*10 + uint(ch-'0')
		}
	}

	if err := authorityBtnUsecase.CanRemoveAuthorityBtn(c, id); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithMessage("删除成功", c)
}
