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
  next_id,
  (
    SELECT game_manager.id
    FROM (
      SELECT id
      FROM sys_menu
      WHERE alias = 'OperateGameManager'
      LIMIT 1
    ) AS game_manager
  ),
  '热游配置',
  'operate/hotgame-config',
  2,
  'form',
  '0',
  '0',
  4,
  0,
  'hotgame-config',
  'OperateHotgameConfig'
FROM (
  SELECT COALESCE(MAX(id), 1700000000) + 1 AS next_id
  FROM sys_menu
) AS menu_id
WHERE NOT EXISTS (
  SELECT 1 FROM sys_menu WHERE alias = 'OperateHotgameConfig'
);

UPDATE sys_menu
SET
  parent_id = (
    SELECT game_manager.id
    FROM (
      SELECT id
      FROM sys_menu
      WHERE alias = 'OperateGameManager'
      LIMIT 1
    ) AS game_manager
  ),
  menu_name = '热游配置',
  path = 'operate/hotgame-config',
  menu_type = 2,
  icon = 'form',
  create_user = '0',
  update_user = '0',
  sort = 4,
  status = 0,
  router = 'hotgame-config'
WHERE alias = 'OperateHotgameConfig';

INSERT INTO sys_role_menu (role_id, menu_id)
SELECT DISTINCT
  source_role.role_id,
  target_menu.id
FROM sys_role_menu AS source_role
JOIN sys_menu AS source_menu
  ON source_menu.id = source_role.menu_id
JOIN sys_menu AS target_menu
  ON target_menu.alias = 'OperateHotgameConfig'
LEFT JOIN sys_role_menu AS existing_role_menu
  ON existing_role_menu.role_id = source_role.role_id
  AND existing_role_menu.menu_id = target_menu.id
WHERE source_menu.alias IN ('OperateGameManager', 'GameConfig', 'OperateBaishunGameManage', 'OperateLingxianConfig')
  AND existing_role_menu.id IS NULL;
