-- 将四个分切业务菜单归并到“分切管理”目录。脚本可重复执行。
START TRANSACTION;

SET @lms_menu_id = (
    SELECT id
      FROM system_menu
     WHERE name = 'LMS管理'
       AND type = 1
       AND deleted = b'0'
     LIMIT 1
);

INSERT INTO system_menu
    (id, name, permission, type, sort, parent_id, path, icon, component,
     component_name, status, visible, keep_alive, always_show,
     creator, create_time, updater, update_time, deleted)
SELECT 6863, '分切管理', '', 1, 5, @lms_menu_id, 'slitting-management',
       'carbon:category', NULL, NULL, 0, b'1', b'1', b'1',
       '1', NOW(), '1', NOW(), b'0'
 WHERE @lms_menu_id IS NOT NULL
   AND NOT EXISTS (
       SELECT 1
         FROM system_menu
        WHERE parent_id = @lms_menu_id
          AND path = 'slitting-management'
          AND type = 1
          AND deleted = b'0'
   );

SET @slitting_menu_id = (
    SELECT id
      FROM system_menu
     WHERE parent_id = @lms_menu_id
       AND path = 'slitting-management'
       AND type = 1
       AND deleted = b'0'
     LIMIT 1
);

-- 为原本拥有任一子菜单的角色补充分切管理父目录权限。
INSERT INTO system_role_menu
    (role_id, menu_id, creator, create_time, updater, update_time, deleted, tenant_id)
SELECT DISTINCT role_menu.role_id, @slitting_menu_id, '1', NOW(), '1', NOW(), b'0', role_menu.tenant_id
  FROM system_role_menu role_menu
 WHERE role_menu.menu_id IN (6826, 6839, 6845, 6851)
   AND role_menu.deleted = b'0'
   AND @slitting_menu_id IS NOT NULL
   AND NOT EXISTS (
       SELECT 1
         FROM system_role_menu parent_role_menu
        WHERE parent_role_menu.role_id = role_menu.role_id
          AND parent_role_menu.menu_id = @slitting_menu_id
          AND parent_role_menu.tenant_id = role_menu.tenant_id
          AND parent_role_menu.deleted = b'0'
   );

UPDATE system_menu
   SET parent_id = @slitting_menu_id,
       sort = CASE name
           WHEN '分切区点位库存管理' THEN 1
           WHEN '穿拔轴区点位库存管理' THEN 2
           WHEN '分切区缓存点位库存管理' THEN 3
           WHEN '分切生产计划管理' THEN 4
       END,
       updater = '1',
       update_time = NOW()
 WHERE type = 2
   AND deleted = b'0'
   AND name IN (
       '分切区点位库存管理',
       '穿拔轴区点位库存管理',
       '分切区缓存点位库存管理',
       '分切生产计划管理'
   )
   AND parent_id IN (@lms_menu_id, @slitting_menu_id)
   AND @slitting_menu_id IS NOT NULL;

COMMIT;
