package department

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.DptReq{}
		count   int64 = 0
		data          = make([]models.MgtDepartment, 0)
		db            = models.DBService.Model(&models.MgtDepartment{}).Select("id", "identity", "name", "app_id", "parent_id")
	)

	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
	}

	// 应用->部门：列表必传 workspace，只查询应用下部门
	if request.Workspace == "" {
		printer.Error("获取部门列表参数异常: workspace 不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}
	appModel := models.MgtApplication{Workspace: request.Workspace}
	appId, err := appModel.WorkspaceToId()
	if err != nil {
		printer.Error("未获取到应用: workspace=%s", request.Workspace)
		infra.Response.Error(c, errcode.ErrRecordNotFound)
		return
	}
	db = db.Where("app_id = ?", appId)

	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)
	}
	if request.ParentID != 0 {
		db = db.Where("parent_id = ?", request.ParentID)
	}

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