-- 计费模块菜单 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, 30, 'billingConfig', 'saas/billing/index', 1, 0, 'C', '0', '0', 'fee:billing:config', '#',
  @createBy, @now, '', NULL, 'SaaS计费配置入口（方案、绑定、钱包、事件）'
FROM dual
WHERE NOT EXISTS (
  SELECT 1 FROM sys_menu WHERE component = 'saas/billing/index'
);

-- 菜单ID
SELECT @configMenuId := menu_id
FROM sys_menu
WHERE component = 'saas/billing/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
  '计费配置查询', @configMenuId, 1, '#', '', 1, 0, 'F', '0', '0', 'fee:billing:config:query', '#',
  @createBy, @now, '', NULL, '计费配置查询权限'
FROM dual
WHERE @configMenuId IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM sys_menu WHERE parent_id = @configMenuId AND perms = 'fee:billing:config:query' AND menu_type = 'F'
  );

-- 3) 按钮权限（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
  '计费配置编辑', @configMenuId, 2, '#', '', 1, 0, 'F', '0', '0', 'fee:billing:config:edit', '#',
  @createBy, @now, '', NULL, '计费配置编辑权限'
FROM dual
WHERE @configMenuId IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM sys_menu WHERE parent_id = @configMenuId AND perms = 'fee:billing:config:edit' AND menu_type = 'F'
  );

-- 4) 授权给 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 IN (
    @configMenuId,
    (SELECT menu_id FROM sys_menu WHERE parent_id = @configMenuId AND perms = 'fee:billing:config:query' AND menu_type = 'F' LIMIT 1),
    (SELECT menu_id FROM sys_menu WHERE parent_id = @configMenuId AND perms = 'fee:billing:config:edit' AND menu_type = 'F' LIMIT 1)
  )
  AND NOT EXISTS (
    SELECT 1 FROM sys_role_menu rm WHERE rm.role_id = @adminRoleId AND rm.menu_id = m.menu_id
  );

