-- 检查超级管理员权限的完整脚本
-- 1. 检查超级管理员用户信息
SELECT 
    u.id,
    u.mobile,
    u.name,
    u.role_id,
    r.role_name,
    r.role_code
FROM sys_user u
LEFT JOIN sys_role r ON u.role_id = r.id
WHERE u.mobile = '15900000000';

-- 2. 检查 delivery:edit 权限是否存在
SELECT 
    id,
    name,
    authority,
    parent_id,
    type
FROM sys_menu 
WHERE authority = 'delivery:edit';

-- 3. 检查超级管理员是否有 delivery:edit 权限
SELECT 
    u.mobile,
    u.name,
    r.role_name,
    m.name as menu_name,
    m.authority,
    rm.role_id,
    rm.menu_id
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';

-- 4. 如果权限不存在，添加权限
-- 首先确保 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');

-- 5. 确保超级管理员角色有 delivery:edit 权限
INSERT INTO sys_role_menu (role_id, menu_id)
SELECT 
    (SELECT id FROM sys_role WHERE role_name = '超级管理员' OR id = 1 LIMIT 1),
    (SELECT id FROM sys_menu WHERE authority = 'delivery:edit')
WHERE NOT EXISTS (
    SELECT 1 FROM sys_role_menu rm 
    INNER JOIN sys_role r ON rm.role_id = r.id 
    INNER JOIN sys_menu m ON rm.menu_id = m.id 
    WHERE (r.role_name = '超级管理员' OR r.id = 1) AND m.authority = 'delivery:edit'
);

-- 6. 最终验证
SELECT 
    u.mobile,
    u.name,
    r.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';
