-- 简化权限检查和修复
-- 1. 删除可能存在的重复权限
DELETE FROM sys_role_menu WHERE role_id = 1 AND menu_id IN (
    SELECT id FROM sys_menu WHERE authority = 'delivery:edit'
);

-- 2. 确保 delivery:edit 权限存在
INSERT INTO sys_menu (parent_id, type, name, authority, sort, is_delete, create_time)
SELECT 
    (SELECT id FROM sys_menu WHERE route_url LIKE '%delivery%' OR route_url LIKE '%loading%' LIMIT 1),
    2, 
    '运送清单编辑', 
    'delivery:edit', 
    3, 
    0, 
    NOW()
WHERE NOT EXISTS (SELECT 1 FROM sys_menu WHERE authority = 'delivery:edit');

-- 3. 确保超级管理员有 delivery:edit 权限
INSERT INTO sys_role_menu (role_id, menu_id)
SELECT 
    1, -- 超级管理员角色ID
    (SELECT id FROM sys_menu WHERE authority = 'delivery:edit')
WHERE NOT EXISTS (
    SELECT 1 FROM sys_role_menu rm 
    WHERE rm.role_id = 1 AND rm.menu_id = (SELECT id FROM sys_menu WHERE authority = 'delivery:edit')
);

-- 4. 确保超级管理员有通配符权限
INSERT INTO sys_menu (parent_id, type, name, authority, sort, is_delete, create_time)
SELECT 
    0, -- 根菜单
    2, 
    '所有权限', 
    '*:*:*', 
    999, 
    0, 
    NOW()
WHERE NOT EXISTS (SELECT 1 FROM sys_menu WHERE authority = '*:*:*');

-- 5. 确保超级管理员有通配符权限
INSERT INTO sys_role_menu (role_id, menu_id)
SELECT 
    1, -- 超级管理员角色ID
    (SELECT id FROM sys_menu WHERE authority = '*:*:*')
WHERE NOT EXISTS (
    SELECT 1 FROM sys_role_menu rm 
    WHERE rm.role_id = 1 AND rm.menu_id = (SELECT id FROM sys_menu WHERE authority = '*:*:*')
);

-- 6. 验证权限分配
SELECT 
    u.mobile,
    u.name,
    r.name as role_name,
    m.name as menu_name,
    m.authority
FROM sys_user u
LEFT JOIN sys_role r ON u.role_id = r.id
LEFT JOIN sys_role_menu rm ON r.id = rm.role_id
LEFT JOIN sys_menu m ON rm.menu_id = m.id
WHERE u.mobile = '15900000000'
  AND (m.authority = 'delivery:edit' OR m.authority = '*:*:*')
ORDER BY m.authority;
