package role

import (
	"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"
	"gorm.io/gorm"
)

func Del(c *gin.Context) {
	var (
		request = types.RoleReq{}
		pmnId   = []uint{}
		userIds = []uint{}
	)

	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.ID == 0 {
		printer.Error("删除角色参数异常: ID不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if err := models.DBService.Model(&models.MgtLinkRolePmn{}).Where("role_id=?", request.ID).Pluck("pmn_id", &pmnId).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	if len(pmnId) > 0 {
		if err := models.DBService.Model(&models.MgtLinkUserRole{}).
			Where("role_id = ?", request.ID).
			Pluck("user_id", &userIds).Error; err != nil {
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
	}

	if err := models.DBService.Transaction(func(tx *gorm.DB) error {
		if len(pmnId) > 0 && len(userIds) > 0 {
			if err := tx.Where("user_id in ? and pmn_id in ?", userIds, pmnId).
				Delete(&models.MgtLinkUserPmn{}).Error; err != nil {
				printer.Error("删除用户对应角色权限异常: %v", err)
				return err
			}
		}

		if err := tx.Delete(&models.MgtRole{}, request.ID).Error; err != nil {
			printer.Error("删除角色异常: %v", err)
			return err
		}

		if err := tx.Where("role_id = ?", request.ID).Delete(&models.MgtLinkRolePmn{}).Error; err != nil {
			printer.Error("删除角色权限关联异常: %v", err)
			return err
		}

		if err := tx.Where("role_id = ?", request.ID).Delete(&models.MgtLinkUserRole{}).Error; err != nil {
			printer.Error("删除角色用户关联异常: %v", err)
			return err
		}

		if err := tx.Where("role_id = ?", request.ID).Delete(&models.MgtLinkRoleApp{}).Error; err != nil {
			printer.Error("删除角色应用关联异常: %v", err)
			return err
		}

		if err := tx.Where("role_id = ?", request.ID).Delete(&models.MgtLinkDptRole{}).Error; err != nil {
			printer.Error("删除部门角色关联异常: %v", err)
			return err
		}

		return nil
	}); err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("角色删除成功: ID=%d", request.ID)
	infra.Response.Success(c, types.IdResp{Id: request.ID})
}
