-- 员工花名册菜单修复（已执行过旧版 SQL、菜单不显示时用）
-- 原因常见有两类：
-- 1）F_ParentId 仍为占位符 REPLACE_WITH_ORG_PARENT_F_ID，树里挂不上「组织机构」
-- 2）BASE_AUTHORIZE 无记录（@SourceModuleId 未替换导致 INSERT 子查询为空）
--
-- 本脚本：把父级改成与「用户管理」同级，并补全与用户管理相同的角色模块授权。

SET @ModuleId = 'employee-roster-lq';

SELECT F_ParentId INTO @ParentId
FROM BASE_MODULE
WHERE F_FullName = '用户管理' AND F_Type = 2 AND F_DeleteMark IS NULL
LIMIT 1;

SELECT F_Id INTO @SourceModuleId
FROM BASE_MODULE
WHERE F_FullName = '用户管理' AND F_Type = 2 AND F_DeleteMark IS NULL
LIMIT 1;

UPDATE BASE_MODULE
SET F_ParentId = @ParentId
WHERE F_Id = @ModuleId;

INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT REPLACE(UUID(), '-', ''), 'module', @ModuleId, 'Role', t.F_ObjectId, 1, NOW(), 'admin'
FROM (
  SELECT DISTINCT F_ObjectId
  FROM BASE_AUTHORIZE
  WHERE F_ItemId = @SourceModuleId AND F_ItemType = 'module' AND F_ObjectType = 'Role'
) t
WHERE NOT EXISTS (
  SELECT 1 FROM BASE_AUTHORIZE b
  WHERE b.F_ItemId = @ModuleId AND b.F_ItemType = 'module'
    AND b.F_ObjectType = 'Role' AND b.F_ObjectId = t.F_ObjectId
);
