package permission

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"
	coreTypes "git.apinb.com/bsm-sdk/core/types"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm/clause"
)

func Sort(c *gin.Context) {
	var (
		request = make([]types.SortPmnRequest, 0)
		data    = make([]models.MgtPermission, 0)
	)

	err := c.ShouldBindJSON(&request)
	if err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}

	if len(request) == 0 {
		printer.Error("排序参数不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	for _, v := range request {
		if err := libs.ValidateStruct(&v); err != nil {
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
	}
	for _, v := range request {
		data = append(data, models.MgtPermission{
			Std_IICUDS: coreTypes.Std_IICUDS{ID: v.PmnId},
			SortKey:    int8(v.SortKey),
		})
	}
	if err := impl.DBService.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns([]string{"sort_key"}),
	}).Create(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("权限排序成功: 排序了 %d 个权限", len(request))
	infra.Response.Success(c, "")
}
