package service

import (
	"iot_manager_service/app/system/dao"
	"iot_manager_service/util/common"
)

// 角色菜单管理服务
var RoleMenuService = new(roleMenuService)

type roleMenuService struct{}

func (s *roleMenuService) UpdateRoleMenus(roleIds, menuIds []int64) error {
	roleMenu := &dao.RoleMenu{}
	err := roleMenu.DeleteRoleIds(roleIds)
	if err != nil {
		return err
	}

	var roleMenus []dao.RoleMenu
	for _, roleId := range roleIds {
		for _, menuId := range menuIds {
			roleMenus = append(roleMenus, dao.RoleMenu{
				MenuId: menuId,
				RoleId: roleId,
			})
		}
	}
	return roleMenu.BatchSave(roleMenus)
}

func (s *roleMenuService) GetMenuByRole(roleId int64) []dao.RoleMenu {
	roleMenu := &dao.RoleMenu{RoleId: roleId}
	if common.IsAdmin(roleId) {
		menus, err := roleMenu.GetAll()
		if err != nil {
			return nil
		}
		return menus
	} else {
		menus, err := roleMenu.GetMenusByRole()
		if err != nil {
			return nil
		}
		return menus
	}
}
func (s *roleMenuService) GetMenuIdByRoleId(roleId int64) []int64 {
	rmDao := &dao.RoleMenu{RoleId: roleId}
	menus, err := rmDao.GetMenusByRole()
	if err != nil {
		return nil
	}
	var ids []int64
	for _, menu := range menus {
		ids = append(ids, menu.MenuId)
	}
	return ids
}
