SET NAMES utf8mb4;

INSERT INTO sys_menu (
  id,
  parent_id,
  menu_name,
  path,
  menu_type,
  icon,
  create_user,
  update_user,
  sort,
  status,
  router,
  alias
)
SELECT
  1700000268,
  parent_menu.id,
  '首页弹窗管理',
  'app-system/home-popup-manager',
  2,
  'form',
  '0',
  '0',
  2,
  0,
  'home-popups',
  'AppSystemHomePopupManager'
FROM (
  SELECT id
  FROM sys_menu
  WHERE alias = 'AppSystemManager'
     OR alias = 'AppSysManager'
     OR path = '/app/sys/mamange'
     OR router = '/app/sys/mamange'
  ORDER BY id
  LIMIT 1
) AS parent_menu
WHERE NOT EXISTS (
  SELECT 1 FROM sys_menu WHERE alias = 'AppSystemHomePopupManager'
);

UPDATE sys_menu
SET
  parent_id = (
    SELECT parent_menu.id
    FROM (
      SELECT id
      FROM sys_menu
      WHERE alias = 'AppSystemManager'
         OR alias = 'AppSysManager'
         OR path = '/app/sys/mamange'
         OR router = '/app/sys/mamange'
      ORDER BY id
      LIMIT 1
    ) AS parent_menu
  ),
  menu_name = '首页弹窗管理',
  path = 'app-system/home-popup-manager',
  menu_type = 2,
  icon = 'form',
  create_user = '0',
  update_user = '0',
  sort = 2,
  status = 0,
  router = 'home-popups'
WHERE alias = 'AppSystemHomePopupManager';

INSERT INTO sys_role_menu (role_id, menu_id)
SELECT DISTINCT
  parent_role.role_id,
  target_menu.id
FROM sys_role_menu AS parent_role
JOIN sys_menu AS target_menu
  ON target_menu.alias = 'AppSystemHomePopupManager'
LEFT JOIN sys_role_menu AS existing_role_menu
  ON existing_role_menu.role_id = parent_role.role_id
  AND existing_role_menu.menu_id = target_menu.id
WHERE parent_role.menu_id = (
    SELECT parent_menu.id
    FROM (
      SELECT id
      FROM sys_menu
      WHERE alias = 'AppSystemManager'
         OR alias = 'AppSysManager'
         OR path = '/app/sys/mamange'
         OR router = '/app/sys/mamange'
      ORDER BY id
      LIMIT 1
    ) AS parent_menu
  )
  AND existing_role_menu.id IS NULL;
