START TRANSACTION;

SET @dashboard_id := (SELECT menu_id FROM sys_menus WHERE menu_code = 'dashboard' LIMIT 1);
SET @desktop_id := (SELECT menu_id FROM sys_menus WHERE menu_code = 'desktop' LIMIT 1);
SET @account_settings_id := (SELECT menu_id FROM sys_menus WHERE menu_code = 'account_settings' LIMIT 1);
SET @logout_id := (SELECT menu_id FROM sys_menus WHERE menu_code = 'logout' LIMIT 1);

UPDATE sys_menus
SET
  menu_code = 'dashboard',
  menu_name = 'Dashboard',
  menu_icon = 'DashboardOutlined',
  menu_url = '/dashboard',
  menu_type = 'link',
  parent_id = NULL,
  sort_order = 1,
  is_active = 1,
  description = '管理员桌面'
WHERE @dashboard_id IS NULL
  AND menu_id = @account_settings_id;

INSERT INTO sys_menus (
  menu_code, menu_name, menu_icon, menu_url, menu_type, parent_id, sort_order, is_active, description
)
SELECT
  'dashboard', 'Dashboard', 'DashboardOutlined', '/dashboard', 'link', NULL, 1, 1, '管理员桌面'
FROM DUAL
WHERE NOT EXISTS (
  SELECT 1 FROM sys_menus WHERE menu_code = 'dashboard'
);

SET @dashboard_id := (SELECT menu_id FROM sys_menus WHERE menu_code = 'dashboard' LIMIT 1);

UPDATE sys_menus
SET
  menu_code = 'desktop',
  menu_name = 'Desktop',
  menu_icon = 'DesktopOutlined',
  menu_url = '/dashboard',
  menu_type = 'link',
  parent_id = NULL,
  sort_order = 1,
  is_active = 1,
  description = '普通用户桌面'
WHERE @desktop_id IS NULL
  AND menu_id = @logout_id;

INSERT INTO sys_menus (
  menu_code, menu_name, menu_icon, menu_url, menu_type, parent_id, sort_order, is_active, description
)
SELECT
  'desktop', 'Desktop', 'DesktopOutlined', '/dashboard', 'link', NULL, 1, 1, '普通用户桌面'
FROM DUAL
WHERE NOT EXISTS (
  SELECT 1 FROM sys_menus WHERE menu_code = 'desktop'
);

SET @desktop_id := (SELECT menu_id FROM sys_menus WHERE menu_code = 'desktop' LIMIT 1);

UPDATE sys_menus
SET sort_order = 2
WHERE menu_code = 'meeting_manage';

DELETE rmp
FROM sys_role_menu_permissions rmp
JOIN sys_menus m ON m.menu_id = rmp.menu_id
WHERE m.menu_code IN ('account_settings', 'logout');

DELETE FROM sys_menus
WHERE menu_code IN ('account_settings', 'logout');

DELETE FROM sys_role_menu_permissions
WHERE role_id = 1 AND menu_id = @desktop_id;

DELETE FROM sys_role_menu_permissions
WHERE role_id = 2 AND menu_id = @dashboard_id;

INSERT IGNORE INTO sys_role_menu_permissions (role_id, menu_id, granted_at)
SELECT 1, @dashboard_id, NOW()
FROM DUAL
WHERE @dashboard_id IS NOT NULL;

INSERT IGNORE INTO sys_role_menu_permissions (role_id, menu_id, granted_at)
SELECT 2, @desktop_id, NOW()
FROM DUAL
WHERE @desktop_id IS NOT NULL;

COMMIT;
