package department

import (
	"bsm/full/module/base/mgt/internal/impl"
	"bsm/full/module/base/mgt/internal/libs"
	"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"
)

// List 下拉用部门列表，必传 workspace；tree=true 时返回树形
func List(c *gin.Context) {
	var (
		request = types.DptReq{}
		data    = make([]models.MgtDepartment, 0)
	)
	if err := c.ShouldBindJSON(&request); 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
	}

	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 := impl.DBService.Model(&models.MgtDepartment{}).
		Where("app_id = ?", appId).
		Select("id", "identity", "name", "app_id", "parent_id")
	if request.Keyword != "" {
		db = db.Where("name LIKE ?", "%"+request.Keyword+"%")
	}
	if request.Status != 0 {
		db = db.Where("status = ?", request.Status)
	}

	if request.Tree {
		if err := db.Order("parent_id asc").Find(&data).Error; err != nil {
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
		tree := buildDeptTree(data, 0)
		infra.Response.Success(c, types.FetchResp{Data: tree})
		return
	}

	if err := db.Order("parent_id asc").Find(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	infra.Response.Success(c, types.FetchResp{Data: data})
}

// buildDeptTree 将扁平部门列表按 parent_id 建树，parentId 为根节点父ID（0 表示顶层）
func buildDeptTree(list []models.MgtDepartment, parentId uint) []models.MgtDepartment {
	var node []models.MgtDepartment
	for _, d := range list {
		if d.ParentID != parentId {
			continue
		}
		children := buildDeptTree(list, d.ID)
		if len(children) > 0 {
			d.Children = children
		}
		node = append(node, d)
	}
	return node
}
