SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- 为 Banner 管理添加权限并分配给超级管理员角色
-- ----------------------------
BEGIN;

-- 1. 确保 Banner 相关权限存在（如果不存在则插入）
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`) VALUES 
(2084, 'Banner创建', 'community:banner:create', 3, 1, 2063, '', '', NULL, NULL, 0, b'0', b'1', b'1', 'admin', NOW(), 'admin', NOW(), b'0'),
(2085, 'Banner更新', 'community:banner:update', 3, 2, 2063, '', '', NULL, NULL, 0, b'0', b'1', b'1', 'admin', NOW(), 'admin', NOW(), b'0'),
(2086, 'Banner删除', 'community:banner:delete', 3, 3, 2063, '', '', NULL, NULL, 0, b'0', b'1', b'1', 'admin', NOW(), 'admin', NOW(), b'0')
ON DUPLICATE KEY UPDATE 
  `name` = VALUES(`name`),
  `permission` = VALUES(`permission`),
  `status` = 0,
  `deleted` = b'0';

-- 2. 将 Banner 权限分配给超级管理员角色（role_id = 1）
-- 先删除可能存在的旧记录，避免重复
DELETE FROM `system_role_menu` 
WHERE `role_id` = 1 
AND `menu_id` IN (2084, 2085, 2086);

-- 插入权限关联（role_id = 1 是超级管理员）
INSERT INTO `system_role_menu` (`role_id`, `menu_id`) 
SELECT 1, `id` 
FROM `system_menu` 
WHERE `id` IN (2084, 2085, 2086)
AND `deleted` = b'0'
AND NOT EXISTS (
  SELECT 1 FROM `system_role_menu` 
  WHERE `role_id` = 1 AND `menu_id` = `system_menu`.`id`
);

-- 3. 如果 Banner 查询权限（2063）还没有分配给超级管理员，也一并分配
INSERT INTO `system_role_menu` (`role_id`, `menu_id`) 
SELECT 1, 2063
WHERE NOT EXISTS (
  SELECT 1 FROM `system_role_menu` 
  WHERE `role_id` = 1 AND `menu_id` = 2063
);

COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

-- 验证：查询超级管理员角色的 Banner 权限
SELECT 
  rm.role_id,
  r.name AS role_name,
  rm.menu_id,
  m.name AS menu_name,
  m.permission
FROM `system_role_menu` rm
INNER JOIN `system_role` r ON rm.role_id = r.id
INNER JOIN `system_menu` m ON rm.menu_id = m.id
WHERE rm.role_id = 1
AND m.permission LIKE 'community:banner:%'
ORDER BY m.sort;

