SET NAMES utf8mb4;

SET @app_user_manager_id := (
  SELECT id
  FROM sys_menu
  WHERE alias IN ('AppUserManager', 'OperateManager')
  ORDER BY FIELD(alias, 'AppUserManager', 'OperateManager')
  LIMIT 1
);

INSERT INTO sys_menu (
  id,
  parent_id,
  menu_name,
  path,
  menu_type,
  icon,
  create_user,
  update_user,
  sort,
  status,
  router,
  alias
)
SELECT
  menu_id.next_id,
  @app_user_manager_id,
  '工资发放',
  'operate/manual-salary-payment',
  2,
  'form',
  '0',
  '0',
  49,
  0,
  '/manual-salary-payment',
  'ManualSalaryPayment'
FROM (
  SELECT COALESCE(MAX(id), 1700000000) + 1 AS next_id
  FROM sys_menu
) AS menu_id
WHERE @app_user_manager_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM sys_menu WHERE alias = 'ManualSalaryPayment'
  );

UPDATE sys_menu
SET
  parent_id = @app_user_manager_id,
  menu_name = '工资发放',
  path = 'operate/manual-salary-payment',
  menu_type = 2,
  icon = 'form',
  update_user = '0',
  sort = 49,
  status = 0,
  router = '/manual-salary-payment'
WHERE alias = 'ManualSalaryPayment'
  AND @app_user_manager_id IS NOT NULL;

INSERT INTO sys_role_menu (role_id, menu_id)
SELECT DISTINCT
  role_menu.role_id,
  target_menu.id
FROM sys_role_menu AS role_menu
JOIN sys_menu AS source_menu
  ON source_menu.id = role_menu.menu_id
  AND source_menu.alias IN ('AutoSalaryPayRecord', 'AppUserManager', 'OperateManager')
JOIN sys_menu AS target_menu
  ON target_menu.alias = 'ManualSalaryPayment'
WHERE NOT EXISTS (
  SELECT 1
  FROM sys_role_menu AS existing_role_menu
  WHERE existing_role_menu.role_id = role_menu.role_id
    AND existing_role_menu.menu_id = target_menu.id
);
