package user

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.MgtLinkUserPmn, 0)
		Appdta  = models.MgtLinkUserApp{}
	)
	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.MgtLinkUserPmn{AppId: appId, PmnId: v, UserId: request.Id})
		Appdta = models.MgtLinkUserApp{AppId: appId, UserId: 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: "user_id"}},
			DoUpdates: clause.AssignmentColumns([]string{"app_id", "pmn_id", "user_id"}),
		}).Create(&pmnData).Error; err != nil {
			return err
		}

		if err := tx.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "app_id"}, {Name: "user_id"}},
			DoUpdates: clause.AssignmentColumns([]string{"app_id", "user_id"}),
		}).Create(&Appdta).Error; err != nil {
			return err
		}
		return nil
	}); err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

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

// ModifyPmn 给用户修改权限
func ModifyPmn(c *gin.Context) {
	var (
		request = types.AddPmnRequest{}
		pmnData = make([]models.MgtLinkUserPmn, 0)
		Appdta  = models.MgtLinkUserApp{}
	)
	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.MgtLinkUserPmn{AppId: appId, PmnId: v, UserId: request.Id})
		Appdta = models.MgtLinkUserApp{AppId: appId, UserId: request.Id}
	}

	if err := models.DBService.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("app_id = ? and user_id = ?", appId, request.Id).Delete(&models.MgtLinkUserPmn{}).Error; err != nil {
			printer.Error("删除用户权限关联失败: %v", err)
			return err
		}
		if len(pmnData) == 0 {
			return nil
		}
		if err := tx.Create(&pmnData).Error; err != nil {
			printer.Error("创建用户权限关联失败: %v", err)
			return err
		}
		if err := tx.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "app_id"}, {Name: "user_id"}},
			DoUpdates: clause.AssignmentColumns([]string{"app_id", "user_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("用户权限修改成功: userId=%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 user_id = ? AND pmn_id in ?", appId, request.Id, pmnIds).
		Delete(&models.MgtLinkUserPmn{}).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

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