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

func Fetch(c *gin.Context) {
	var (
		request       = types.PermissionRequest{}
		count   int64 = 0
		data          = make([]types.PermissionRsp, 0)
		db            = models.DBService.Model(&models.MgtPermission{})
	)

	// 解析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 != "" {
		likeStr := "%" + request.Keyword + "%"
		db = db.Where("title like ? or code like ? ", likeStr)
	}
	if request.Status != 0 {
		db = db.Where("status =  ? ", request.Status)
	}
	if request.ID != 0 {
		db = db.Where("id = ?", request.ID)
	}
	if request.Workspace != "" {
		app := models.MgtApplication{Workspace: request.Workspace}
		appId, err := app.WorkspaceToId()
		if err != nil {
			printer.Error("查询应用信息异常: %v", err)
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}
		db = db.Where("app_id = ?", appId)
	}
	// 按 sort_key 排序
	if request.OrderDesc {
		db = db.Order("sort_key desc")
	} else {
		db = db.Order("sort_key asc")
	}
	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})
}
