package system

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type SysMenuButton struct {
	MenuButtonId int `orm:"column(menu_button_id);pk" description:"菜单按钮id"`
	MenuId       int
	ButtonName   int
	CreateTime   time.Time
}

type SysMenuButtonItem struct {
	MenuButtonId int    `description:"菜单按钮id"`
	MenuId       int    `description:"菜单id"`
	ButtonName   string `description:"按钮名称"`
}

func GetSysMenuButtonItems(menuId int) (items []*SysMenuButtonItem, err error) {
	sql := ` SELECT * FROM sys_menu_button  WHERE menu_id=? `
	_, err = orm.NewOrm().Raw(sql, menuId).QueryRows(&items)
	return
}

type MenuButtonsResp struct {
	List      []*ButtonMenu
	CheckList []*int
}

func AddSysMenuButton(item *SysMenuButton) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

type SysRoleButton struct {
	Id           int `orm:"column(id);pk" description:"关联id"`
	RoleId       int
	MenuButtonId int
	CreateTime   time.Time
}

func AddSysRoleButton(item *SysRoleButton) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

func GetRoleButtonCheck(roleId int) (items []*SysRoleButton, err error) {
	sql := `SELECT b.* FROM  sys_menu_button AS a
			INNER JOIN sys_role_button AS b ON a.menu_button_id=b.menu_button_id
			WHERE b.role_id=?`
	o := orm.NewOrm()
	_, err = o.Raw(sql, roleId).QueryRows(&items)
	return
}

type ButtonMenu struct {
	MenuId int    `description:"导航唯一标识"`
	Name   string `json:"name" description:"导航名称"`
	List   []*SysMenuButtonItem
}

func GetButtonMenu() (items []*ButtonMenu, err error) {
	sql := `SELECT b.menu_id,b.name FROM sys_menu_button AS a
			INNER JOIN sys_menu AS b ON a.menu_id=b.menu_id
			GROUP BY  b.menu_id `
	o := orm.NewOrm()
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func DeleteSysRoleButton(roleId int) (err error) {
	o := orm.NewOrm()
	sql := `DELETE FROM sys_role_button WHERE role_id=? `
	_, err = o.Raw(sql, roleId).Exec()
	return
}

func GetSysRoleButtonCount(roleId, buttonId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM sys_role_button WHERE role_id=? AND menu_button_id=? `
	_, err = o.Raw(sql, roleId, buttonId).Exec()
	return
}
