package department

import (
	"errors"

	"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 给部门设置权限（应用->部门->权限，校验部门所属应用与 workspace 一致）
func SetPmn(c *gin.Context) {
	var (
		request = types.AddPmnRequest{}
		pmnData = make([]models.MgtLinkDptPmn, 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
	}

	appModel := models.MgtApplication{Workspace: request.Workspace}
	appId, err := appModel.WorkspaceToId()
	if err != nil {
		printer.Error("未获取到应用: %v", err)
		infra.Response.Error(c, errcode.ErrRecordNotFound)
		return
	}

	var dpt models.MgtDepartment
	if err := models.DBService.Select("id", "app_id").Where("id = ?", request.Id).First(&dpt).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	if dpt.AppID != appId {
		printer.Error("部门不属于当前应用: dpt_id=%d", request.Id)
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	for _, v := range request.List {
		if v == 0 {
			printer.Error("权限ID不能为空")
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
		pmnData = append(pmnData, models.MgtLinkDptPmn{AppId: appId, PmnId: v, DptId: request.Id})
	}

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

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

// ModifyPmn 按应用维度覆盖部门权限
func ModifyPmn(c *gin.Context) {
	var (
		request = types.AddPmnRequest{}
		pmnData = make([]models.MgtLinkDptPmn, 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
	}

	appModel := models.MgtApplication{Workspace: request.Workspace}
	appId, err := appModel.WorkspaceToId()
	if err != nil {
		printer.Error("未获取到应用: %v", err)
		infra.Response.Error(c, errcode.ErrRecordNotFound)
		return
	}

	var dpt models.MgtDepartment
	if err := models.DBService.Select("id", "app_id").Where("id = ?", request.Id).First(&dpt).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	if dpt.AppID != appId {
		printer.Error("部门不属于当前应用: dpt_id=%d", request.Id)
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	for _, v := range request.List {
		if v == 0 {
			printer.Error("权限ID不能为空")
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
		pmnData = append(pmnData, models.MgtLinkDptPmn{AppId: appId, PmnId: v, DptId: request.Id})
	}

	if err := models.DBService.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("dpt_id = ? and app_id = ?", request.Id, appId).Delete(&models.MgtLinkDptPmn{}).Error; err != nil {
			return err
		}
		if len(pmnData) > 0 {
			if err := tx.Create(&pmnData).Error; err != nil {
				return err
			}
		}
		return nil
	}); err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("部门权限修改成功: dptId=%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
	}
	if len(request.List) == 0 {
		printer.Error("移除部门权限参数异常: list 不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	appModel := models.MgtApplication{Workspace: request.Workspace}
	appId, err := appModel.WorkspaceToId()
	if err != nil {
		printer.Error("未获取到应用: %v", err)
		infra.Response.Error(c, errcode.ErrRecordNotFound)
		return
	}

	var dpt models.MgtDepartment
	if err := models.DBService.Select("id", "app_id").Where("id = ?", request.Id).First(&dpt).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	if dpt.AppID != appId {
		printer.Error("部门不属于当前应用: dpt_id=%d", request.Id)
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		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("dpt_id = ? AND app_id = ? AND pmn_id in ?", request.Id, appId, pmnIds).
		Delete(&models.MgtLinkDptPmn{}).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

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