package role

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"
	"github.com/gin-gonic/gin"
)

func Fetch(c *gin.Context) {
	var (
		request       = types.RoleReq{}
		count   int64 = 0
		data          = make([]models.MgtRole, 0)
		db            = models.DBService.Model(&models.MgtRole{}).Select("id", "identity", "name", "description")
	)

	// 解析JSON请求
	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.Keyword != "" {
		db = db.Where("name like ?", "%"+request.Keyword+"%")
	}
	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.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})
}
