package permission

import (
	"bsm/full/module/base/mgt/internal/libs"
	"bsm/full/module/base/mgt/internal/logic/tool"
	"bsm/full/module/base/mgt/internal/models"
	"bsm/full/module/base/mgt/internal/types"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	"git.apinb.com/bsm-sdk/core/printer"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 获取权限用户列表
func UserFetch(c *gin.Context) {
	var (
		request       = types.FetchBase{}
		data          = make([]models.MgtPermission, 0)
		db            = models.DBService.Model(&models.MgtPermission{}).Select("id", "identity", "title")
		count   int64 = 0
	)
	err := c.ShouldBindJSON(&request)
	if err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}

	// 参数验证
	if err := libs.ValidateStruct(&request); err != nil {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if request.Workspace == "" {
		printer.Error("Workspace不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}
	if request.Status != 0 {
		db = db.Where("status = ?", request.Status)
	}
	if request.ID != 0 {
		db = db.Where("id = ?", request.ID)
	}
	page, size := tool.GetSizeAndPage(request.Page, request.Size)
	if err := db.Preload("Users", func(db *gorm.DB) *gorm.DB {
		return db.Select("id", "identity", "name")
	}).Count(&count).Limit(size).Offset((page - 1) * size).Find(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	infra.Response.Success(c, types.FetchResp{Data: data, Page: page, Size: size, Total: count})
}

// 获取权限角色列表
func RoleFetch(c *gin.Context) {
	var (
		request       = types.FetchBase{}
		data          = make([]models.MgtPermission, 0)
		db            = models.DBService.Model(&models.MgtPermission{}).Select("id", "identity", "title")
		count   int64 = 0
	)
	err := c.ShouldBindJSON(&request)
	if err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}

	// 参数验证
	if err := libs.ValidateStruct(&request); err != nil {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if request.Workspace == "" {
		printer.Error("Workspace不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}
	if request.Status != 0 {
		db = db.Where("status = ?", request.Status)
	}
	if request.ID != 0 {
		db = db.Where("id = ?", request.ID)
	}
	page, size := tool.GetSizeAndPage(request.Page, request.Size)
	if err := db.Preload("Roles").Count(&count).Limit(size).Offset((page - 1) * size).Find(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	infra.Response.Success(c, types.FetchResp{Data: data, Page: page, Size: size, Total: count})
}
