SET @post_menu_id = COALESCE(
  (SELECT `id` FROM `la_system_menu` WHERE `perms` = 'community.communityPost/lists' LIMIT 1),
  (SELECT `id` FROM `la_system_menu` WHERE `component` = 'community/post/index' LIMIT 1)
);

SET @old_edit_menu_id = (
  SELECT `id` FROM `la_system_menu`
  WHERE `perms` = 'community.communityPost/editContent'
  LIMIT 1
);

SET @edit_menu_id = (
  SELECT `id` FROM `la_system_menu`
  WHERE `perms` = 'community.communityPost/edit'
  LIMIT 1
);

UPDATE `la_system_menu`
SET `name` = '编辑帖子',
    `perms` = 'community.communityPost/edit',
    `update_time` = UNIX_TIMESTAMP()
WHERE `id` = @old_edit_menu_id
  AND @edit_menu_id IS NULL;

INSERT INTO `la_system_menu`
  (`pid`, `type`, `name`, `icon`, `sort`, `perms`, `paths`, `component`, `selected`, `params`, `is_cache`, `is_show`, `is_disable`, `create_time`, `update_time`)
SELECT
  @post_menu_id, 'A', '编辑帖子', '', 0, 'community.communityPost/edit', '', '', '', '', 0, 0, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()
WHERE @post_menu_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM `la_system_menu` WHERE `perms` = 'community.communityPost/edit'
  );

SET @edit_menu_id = (
  SELECT `id` FROM `la_system_menu`
  WHERE `perms` = 'community.communityPost/edit'
  LIMIT 1
);

INSERT INTO `la_system_role_menu` (`role_id`, `menu_id`)
SELECT 1, @edit_menu_id
WHERE @edit_menu_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1
    FROM `la_system_role_menu`
    WHERE `role_id` = 1
      AND `menu_id` = @edit_menu_id
  );

INSERT INTO `la_system_role_menu` (`role_id`, `menu_id`)
SELECT old_role_menu.`role_id`, @edit_menu_id
FROM `la_system_role_menu` old_role_menu
WHERE old_role_menu.`menu_id` = @old_edit_menu_id
  AND @old_edit_menu_id IS NOT NULL
  AND @old_edit_menu_id <> @edit_menu_id
  AND NOT EXISTS (
    SELECT 1
    FROM `la_system_role_menu` current_role_menu
    WHERE current_role_menu.`role_id` = old_role_menu.`role_id`
      AND current_role_menu.`menu_id` = @edit_menu_id
  );

DELETE FROM `la_system_role_menu`
WHERE `menu_id` = @old_edit_menu_id
  AND @old_edit_menu_id IS NOT NULL
  AND @old_edit_menu_id <> @edit_menu_id;

DELETE FROM `la_system_menu`
WHERE `id` = @old_edit_menu_id
  AND @old_edit_menu_id IS NOT NULL
  AND @old_edit_menu_id <> @edit_menu_id;
