package service

import (
	menuService "nms_nbi/features/sys_menu/service"
	roleService "nms_nbi/features/sys_role/service"
	userService "nms_nbi/features/sys_user/service"
	"nms_nbi/lib/core/utils/parse"
	"nms_nbi/lib/core/vo"
)

// 实例化服务层 ServiceAccount 结构体
var NewServiceAccount = &ServiceAccount{
	sysUserService: userService.NewServiceSysUser,
	sysRoleService: roleService.NewServiceSysRole,
	sysMenuService: menuService.NewServiceSysMenu,
}

// 账号身份操作服务 服务层处理
type ServiceAccount struct {
	// 用户信息服务
	sysUserService *userService.ServiceSysUser
	// 角色服务
	sysRoleService *roleService.ServiceSysRole
	// 菜单服务
	sysMenuService *menuService.ServiceSysMenu
}

// RoleAndMenuPerms 角色和菜单数据权限
func (s *ServiceAccount) RoleAndMenuPerms(userId string, isAdmin bool) ([]string, []string) {
	if isAdmin {
		return []string{"admin"}, []string{"*:*:*"}
	} else {
		// 角色key
		roleGroup := []string{}
		roles := s.sysRoleService.SelectRoleListByUserId(userId)
		for _, role := range roles {
			roleGroup = append(roleGroup, role.RoleKey)
		}
		// 菜单权限key
		perms := s.sysMenuService.SelectMenuPermsByUserId(userId)
		return parse.RemoveDuplicates(roleGroup), parse.RemoveDuplicates(perms)
	}
}

// RouteMenus 前端路由所需要的菜单
func (s *ServiceAccount) RouteMenus(userId string, isAdmin bool) []vo.Router {
	var buildMenus []vo.Router
	if isAdmin {
		menus := s.sysMenuService.SelectMenuTreeByUserId("*")
		buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
	} else {
		menus := s.sysMenuService.SelectMenuTreeByUserId(userId)
		buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
	}
	return buildMenus
}
