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

// SetPmn 给角色设置权限
func SetPmn(c *gin.Context) {
	var (
		request = types.AddPmnRequest{}
		pmnData = make([]models.MgtLinkRolePmn, 0)
		Appdta  = models.MgtLinkRoleApp{}
	)
	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
	}
	appModel := models.MgtApplication{Workspace: request.Workspace}
	appId, err := appModel.WorkspaceToId()
	if err != nil {
		printer.Error("未获取到appid: %v", err)
		infra.Response.Error(c, errcode.ErrRecordNotFound)
		return
	}
	for _, v := range request.List {
		if v == 0 {
			printer.Error("权限ID不能为空")
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
		pmnData = append(pmnData, models.MgtLinkRolePmn{AppId: appId, PmnId: v, RoleId: request.Id})
		Appdta = models.MgtLinkRoleApp{AppId: appId, RoleId: request.Id}
	}

	if err := models.DBService.Transaction(func(tx *gorm.DB) error {
		if err := tx.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "app_id"}, {Name: "pmn_id"}, {Name: "role_id"}},
			DoUpdates: clause.AssignmentColumns([]string{"app_id", "pmn_id", "role_id"}),
		}).Create(&pmnData).Error; err != nil {
			printer.Error("创建角色权限关联失败: %v", err)
			return err
		}

		if err := tx.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "app_id"}, {Name: "role_id"}},
			DoUpdates: clause.AssignmentColumns([]string{"app_id", "role_id"}),
		}).Create(&Appdta).Error; err != nil {
			printer.Error("创建角色应用关联失败: %v", err)
			return err
		}
		return nil
	}); err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("角色权限设置成功: roleId=%d", request.Id)
	infra.Response.Success(c, "")
}

// ModifyPmn 给角色修改权限
func ModifyPmn(c *gin.Context) {
	var (
		request = types.AddPmnRequest{}
		pmnData = make([]models.MgtLinkRolePmn, 0)
		Appdta  = models.MgtLinkRoleApp{}
	)
	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
	}
	appModel := models.MgtApplication{Workspace: request.Workspace}
	appId, err := appModel.WorkspaceToId()
	if err != nil {
		printer.Error("未获取到appid: %v", err)
		infra.Response.Error(c, errcode.ErrRecordNotFound)
		return
	}
	for _, v := range request.List {
		if v == 0 {
			printer.Error("权限ID不能为空")
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
		pmnData = append(pmnData, models.MgtLinkRolePmn{AppId: appId, PmnId: v, RoleId: request.Id})
		Appdta = models.MgtLinkRoleApp{AppId: appId, RoleId: request.Id}
	}

	if err := models.DBService.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("app_id = ? and role_id = ?", appId, request.Id).Delete(&models.MgtLinkRolePmn{}).Error; err != nil {
			printer.Error("删除角色权限关联失败: %v", err)
			return err
		}
		if err := tx.Where("app_id = ? and role_id = ?", appId, request.Id).Delete(&models.MgtLinkRoleApp{}).Error; err != nil {
			printer.Error("删除角色应用关联失败: %v", err)
			return err
		}
		if err := tx.Create(&pmnData).Error; err != nil {
			printer.Error("创建角色权限关联失败: %v", err)
			return err
		}
		if err := tx.Create(&Appdta).Error; err != nil {
			printer.Error("创建角色应用关联失败: %v", err)
			return err
		}
		return nil
	}); err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("角色权限修改成功: roleId=%d", request.Id)
	infra.Response.Success(c, "")
}

// DelPmn 角色权限移除
func DelPmn(c *gin.Context) {
	var request = types.AddPmnRequest{}
	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
	}
	appModel := models.MgtApplication{Workspace: request.Workspace}
	appId, err := appModel.WorkspaceToId()
	if err != nil {
		printer.Error("未获取到appid: %v", err)
		infra.Response.Error(c, errcode.ErrRecordNotFound)
		return
	}
	pmnIds := make([]uint, 0, len(request.List))
	for _, v := range request.List {
		if v == 0 {
			printer.Error("权限ID不能为空")
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
		pmnIds = append(pmnIds, v)
	}
	if err := models.DBService.Where("app_id = ? AND role_id = ? AND pmn_id in ?", appId, request.Id, pmnIds).
		Delete(&models.MgtLinkRolePmn{}).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("角色权限删除成功: roleId=%d", request.Id)
	infra.Response.Success(c, "")
}
