-- 添加入口模块管理路由到 sys_routes 表
-- 执行此脚本将在系统菜单中添加"入口模块管理"菜单项

-- 1. 插入父级菜单：入口模块管理
INSERT INTO sys_routes (
  route_path,
  route_name,
  component,
  parent_id,
  route_title,
  icon,
  sort_order,
  is_hidden,
  is_cache,
  meta,
  status,
  created_at,
  updated_at
) VALUES (
  '/entry-modules',
  'EntryModules',
  'views/entry-modules/Index.vue',
  NULL,
  '入口模块管理',
  'ri-apps-2-line',
  8,
  false,
  true,
  '{"requiresAuth": true, "requiresRole": ["admin", "developer", "provincial_admin"]}'::jsonb,
  0,
  NOW(),
  NOW()
)
ON CONFLICT (route_path) DO UPDATE SET
  route_title = EXCLUDED.route_title,
  icon = EXCLUDED.icon,
  sort_order = EXCLUDED.sort_order,
  updated_at = NOW();

-- 2. 插入子菜单：新建入口模块（如果需要在菜单中显示）
-- 注意：获取父级菜单的ID
WITH parent_route AS (
  SELECT id FROM sys_routes WHERE route_path = '/entry-modules'
)
INSERT INTO sys_routes (
  route_path,
  route_name,
  component,
  parent_id,
  route_title,
  icon,
  sort_order,
  is_hidden,
  is_cache,
  meta,
  status,
  created_at,
  updated_at
)
SELECT
  '/entry-modules/new',
  'EntryModulesNew',
  'views/entry-modules/New.vue',
  parent_route.id,
  '新建入口模块',
  'ri-add-circle-line',
  1,
  true,  -- 隐藏，不在菜单中显示
  false,
  '{"requiresAuth": true, "requiresRole": ["admin", "developer", "provincial_admin"]}'::jsonb,
  0,
  NOW(),
  NOW()
FROM parent_route
ON CONFLICT (route_path) DO UPDATE SET
  parent_id = EXCLUDED.parent_id,
  updated_at = NOW();

-- 3. 查询确认插入结果
SELECT
  id,
  route_path,
  route_name,
  route_title,
  parent_id,
  icon,
  sort_order,
  is_hidden
FROM sys_routes
WHERE route_path LIKE '/entry-modules%'
ORDER BY sort_order;

-- 4. 为管理员角色分配权限（假设角色ID为1是admin）
-- 获取新插入的路由ID
WITH entry_routes AS (
  SELECT id FROM sys_routes WHERE route_path LIKE '/entry-modules%'
)
INSERT INTO role_route (role_id, route_id, created_at, updated_at)
SELECT
  1,  -- 假设 role_id = 1 是 admin 角色
  entry_routes.id,
  NOW(),
  NOW()
FROM entry_routes
ON CONFLICT (role_id, route_id) DO NOTHING;

-- 提示信息
SELECT '✅ 入口模块管理路由已成功添加到系统菜单中！' AS message;
SELECT '📌 请确保已为相应角色分配权限，路由才会在菜单中显示。' AS reminder;
