package system

import (
	"errors"
	"server/dao"

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

type BaseMenuService struct{}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteBaseMenu
//@description: 删除基础路由
//@param: id float64
//@return: err error

var BaseMenuServiceApp = new(BaseMenuService)

func (baseMenuService *BaseMenuService) DeleteBaseMenu(id int) (err error) {
	err = global.GVA_DB.First(&dao.SysBaseMenu{}, "parent_id = ?", id).Error
	if err != nil {
		return global.GVA_DB.Transaction(func(tx *gorm.DB) error {

			err = tx.Delete(&dao.SysBaseMenu{}, "id = ?", id).Error
			if err != nil {
				return err
			}

			err = tx.Delete(&dao.SysBaseMenuParameter{}, "sys_base_menu_id = ?", id).Error
			if err != nil {
				return err
			}

			err = tx.Delete(&dao.SysBaseMenuBtn{}, "sys_base_menu_id = ?", id).Error
			if err != nil {
				return err
			}
			err = tx.Delete(&dao.SysAuthorityBtn{}, "sys_menu_id = ?", id).Error
			if err != nil {
				return err
			}

			err = tx.Delete(&dao.SysAuthorityMenu{}, "sys_base_menu_id = ?", id).Error
			if err != nil {
				return err
			}
			return nil
		})
	}
	return errors.New("此菜单存在子菜单不可删除")
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UpdateBaseMenu
//@description: 更新路由
//@param: menu model.SysBaseMenu
//@return: err error

func (baseMenuService *BaseMenuService) UpdateBaseMenu(menu dao.SysBaseMenu) (err error) {
	return menu.UpdateBaseMenu()
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetBaseMenuById
//@description: 返回当前选中menu
//@param: id float64
//@return: menu system.SysBaseMenu, err error

func (baseMenuService *BaseMenuService) GetBaseMenuById(id int) (menu dao.SysBaseMenu, err error) {
	return dao.QueryBaseMenuAndMenuBtnAndParameterById(id)
}
