-- ============================================
-- 重新创建权限管理菜单（彻底解决乱码）
-- 请在 Navicat 中执行
-- ============================================

SET NAMES utf8mb4;
SET CHARACTER SET utf8mb4;

-- 1. 删除旧的乱码数据
DELETE FROM `sys_role_menu` WHERE `menu_id` >= 28;
DELETE FROM `sys_menu` WHERE `id` >= 28;

-- 2. 重新创建权限管理父菜单
INSERT INTO `sys_menu` (`parent_id`, `type`, `name`, `route_url`, `page_url`, `authority`, `icon`, `sort`, `is_delete`, `create_time`)
VALUES (0, 1, '权限管理', '/permission', null, 'permission:view', 'el-icon-lock', 20, 0, NOW());

SET @permission_parent_id = LAST_INSERT_ID();

-- 3. 创建菜单权限管理子菜单
INSERT INTO `sys_menu` (`parent_id`, `type`, `name`, `route_url`, `page_url`, `authority`, `icon`, `sort`, `is_delete`, `create_time`)
VALUES (@permission_parent_id, 1, '菜单权限管理', '/permission/menu', 'permission/menuPermission', 'permission:menu:view', 'el-icon-menu', 1, 0, NOW());

SET @menu_permission_id = LAST_INSERT_ID();

-- 4. 创建菜单权限管理的按钮
INSERT INTO `sys_menu` (`parent_id`, `type`, `name`, `authority`, `sort`, `is_delete`, `create_time`) VALUES
(@menu_permission_id, 2, '菜单查询', 'permission:menu:list', 1, 0, NOW()),
(@menu_permission_id, 2, '菜单新增', 'permission:menu:add', 2, 0, NOW()),
(@menu_permission_id, 2, '菜单编辑', 'permission:menu:edit', 3, 0, NOW()),
(@menu_permission_id, 2, '菜单删除', 'permission:menu:delete', 4, 0, NOW()),
(@menu_permission_id, 2, '角色分配', 'permission:menu:assign', 5, 0, NOW());

-- 5. 创建操作权限管理子菜单
INSERT INTO `sys_menu` (`parent_id`, `type`, `name`, `route_url`, `page_url`, `authority`, `icon`, `sort`, `is_delete`, `create_time`)
VALUES (@permission_parent_id, 1, '操作权限管理', '/permission/operation', 'permission/operationPermission', 'permission:operation:view', 'el-icon-setting', 2, 0, NOW());

SET @operation_permission_id = LAST_INSERT_ID();

-- 6. 创建操作权限管理的按钮
INSERT INTO `sys_menu` (`parent_id`, `type`, `name`, `authority`, `sort`, `is_delete`, `create_time`) VALUES
(@operation_permission_id, 2, '权限查询', 'permission:operation:list', 1, 0, NOW()),
(@operation_permission_id, 2, '权限分配', 'permission:operation:assign', 2, 0, NOW()),
(@operation_permission_id, 2, '角色管理', 'permission:operation:role', 3, 0, NOW());

-- 7. 为超级管理员分配所有权限
DELETE FROM `sys_role_menu` WHERE `role_id` = 1;
INSERT INTO `sys_role_menu` (`role_id`, `menu_id`)
SELECT 1, `id` FROM `sys_menu` WHERE `is_delete` = 0;

-- 8. 验证结果
SELECT '✅ 权限管理菜单创建完成！' as status;

SELECT 
    m.id,
    m.parent_id,
    m.type,
    m.name,
    m.route_url,
    m.authority
FROM sys_menu m
WHERE m.id >= (SELECT MIN(id) FROM sys_menu WHERE name = '权限管理')
ORDER BY m.parent_id, m.sort, m.id;

SELECT CONCAT('超级管理员拥有 ', COUNT(*), ' 个权限') as info
FROM sys_role_menu 
WHERE role_id = 1;

