package system

import (
	"gorm.io/gorm"
	"server/global"
)

type SysAuthorityBtn struct {
	AuthorityId      uint           `gorm:"comment:角色ID"`
	SysMenuID        uint           `gorm:"comment:菜单ID"`
	SysBaseMenuBtnID uint           `gorm:"comment:菜单按钮ID"`
	SysBaseMenuBtn   SysBaseMenuBtn ` gorm:"comment:按钮详情"`
}

// TODO:按钮查询

// QueryAuthorityBtnAndSysBaseMenuBtnById 查询角色按钮和菜单按钮 按id
func QueryAuthorityBtnAndSysBaseMenuBtnById(authorityId uint) (btns []SysAuthorityBtn, err error) {
	err = global.GVA_DB.Where("authority_id = ?", authorityId).Preload("SysBaseMenuBtn").Find(&btns).Error
	return btns, err
}

// QueryAuthorityBtnByAuthorityIdMenuId 查询角色按钮 按角色id和菜单id
func QueryAuthorityBtnByAuthorityIdMenuId(authorityId, sysMenuId uint) (authorityBtn []SysAuthorityBtn, err error) {
	err = global.GVA_DB.Find(&authorityBtn, "authority_id = ? and sys_menu_id = ?", authorityId, sysMenuId).Error
	return
}

// QueryAuthorityBtn 查询角色按钮 按菜单按钮id global.GVA_DB.First(&dao.SysAuthorityBtn{}, "sys_base_menu_btn_id = ?", ID).Error
func QueryAuthorityBtn(Id string) (sysAuthorityBtn SysAuthorityBtn, err error) {
	err = global.GVA_DB.Model(&SysAuthorityBtn{}).First(sysAuthorityBtn, "sys_base_menu_btn_id =?", Id).Error
	return
}

// TODO:按钮新增
// TODO:按钮修改

func SetAuthorityBtn(menuId, authorityId uint, selected []uint) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var authorityBtn []SysAuthorityBtn
		err = tx.Delete(&[]SysAuthorityBtn{}, "authority_id = ? and sys_menu_id = ?", authorityId, menuId).Error
		if err != nil {
			return err
		}
		for _, v := range selected {
			authorityBtn = append(authorityBtn, SysAuthorityBtn{
				AuthorityId:      authorityId,
				SysMenuID:        menuId,
				SysBaseMenuBtnID: v,
			})
		}
		if len(authorityBtn) > 0 {
			err = tx.Create(&authorityBtn).Error
		}
		if err != nil {
			return err
		}
		return err
	})
}

// TODO:按钮删除
