-- 计费模块菜单 SQL（总账号）
-- 说明：
-- 1) 本脚本用于平台总账号菜单与权限初始化；
-- 2) 幂等执行，不会重复插入；
-- 3) 默认挂在 path='tenant' 的父菜单下，找不到则挂根节点(0)。

SET @now = NOW();
SET @createBy = 'admin';

-- 找父菜单：优先租户管理目录
SELECT @parentId := menu_id
FROM sys_menu
WHERE path = 'tenant'
ORDER BY menu_id DESC
LIMIT 1;

SET @parentId = IFNULL(@parentId, 0);

-- 1) 总账号页面菜单（C）
INSERT INTO sys_menu
(menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
SELECT
  '费用明细（总账号）', @parentId, 31, 'billingAdmin', 'saas/billingAdmin/index', 1, 0, 'C', '0', '0', 'fee:billing:admin:list', '#',
  @createBy, @now, '', NULL, 'SaaS总账号查看全租户费用明细'
FROM dual
WHERE NOT EXISTS (
  SELECT 1 FROM sys_menu WHERE component = 'saas/billingAdmin/index'
);

-- 页面菜单ID
SELECT @adminPageMenuId := menu_id
FROM sys_menu
WHERE component = 'saas/billingAdmin/index'
LIMIT 1;

-- 2) 总账号查询按钮（F）
INSERT INTO sys_menu
(menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
SELECT
  '总账号费用明细查询', @adminPageMenuId, 1, '#', '', 1, 0, 'F', '0', '0', 'fee:billing:admin:list', '#',
  @createBy, @now, '', NULL, '总账号费用明细查询权限'
FROM dual
WHERE @adminPageMenuId IS NOT NULL
  AND NOT EXISTS (
    SELECT 1
    FROM sys_menu
    WHERE parent_id = @adminPageMenuId
      AND perms = 'fee:billing:admin:list'
      AND menu_type = 'F'
  );

-- 3) 绑定 admin 角色
SELECT @adminRoleId := role_id
FROM sys_role
WHERE role_key = 'admin'
LIMIT 1;

INSERT INTO sys_role_menu (role_id, menu_id)
SELECT @adminRoleId, m.menu_id
FROM sys_menu m
WHERE @adminRoleId IS NOT NULL
  AND m.menu_id = @adminPageMenuId
  AND NOT EXISTS (
    SELECT 1 FROM sys_role_menu rm WHERE rm.role_id = @adminRoleId AND rm.menu_id = m.menu_id
  );

