-- =============================================================================
-- 恢复菜单：工作流标准入口 + 考勤（汇总/设置/打卡记录）+ 图片上传审核记录
--
-- 适用场景：把正式库迁到测试后，BASE_MODULE / BASE_AUTHORIZE 与前端路由不一致导致菜单消失。
-- 特点：
-- 1) 尽量自动解析父级与“授权复制来源”，减少手工改 ID
-- 2) 可重复执行：先 DELETE 再 INSERT（固定 F_Id，避免每次 UUID 漂移）
--
-- 执行前建议先备份 BASE_MODULE、BASE_AUTHORIZE。
-- =============================================================================

-- -----------------------------------------------------------------------------
-- 0) 可选：系统管理员角色（当“授权来源模块”在库里找不到任何角色授权时兜底）
--     如你环境不同，请改成你库里的管理员角色 F_Id
-- -----------------------------------------------------------------------------
SET @AdminRoleId = '94e3a9bb0fce4547886972998fddba1c';

-- -----------------------------------------------------------------------------
-- 1) 一级目录：流程中心（固定 F_Id，父级为 -1）
-- -----------------------------------------------------------------------------
SET @FlowCenterRootId = 'lvq-flow-center-root';

-- 清理历史重复「流程中心」目录（同名/同编码但 F_Id 不同）
DELETE a
FROM BASE_AUTHORIZE a
JOIN BASE_MODULE m ON a.F_ItemId = m.F_Id
WHERE m.F_DeleteMark IS NULL
  AND m.F_Type = 1
  AND (
    m.F_FullName = '流程中心'
    OR m.F_EnCode IN ('flowCenter', 'processCenter', 'workflowCenter')
  )
  AND m.F_Id <> @FlowCenterRootId;

DELETE m
FROM BASE_MODULE m
WHERE m.F_DeleteMark IS NULL
  AND m.F_Type = 1
  AND (
    m.F_FullName = '流程中心'
    OR m.F_EnCode IN ('flowCenter', 'processCenter', 'workflowCenter')
  )
  AND m.F_Id <> @FlowCenterRootId;

DELETE FROM BASE_AUTHORIZE WHERE F_ItemId = @FlowCenterRootId;
DELETE FROM BASE_MODULE WHERE F_Id = @FlowCenterRootId;

INSERT INTO BASE_MODULE (
  F_Id, F_ParentId, F_Type, F_FullName, F_EnCode, F_UrlAddress, F_Icon,
  F_SortCode, F_EnabledMark, F_Category, F_DeleteMark, F_LinkTarget,
  F_PropertyJson, F_IsButtonAuthorize, F_IsColumnAuthorize, F_IsDataAuthorize,
  F_IsFormAuthorize, F_CreatorTime
) VALUES (
  @FlowCenterRootId, '-1', 1,
  '流程中心', 'flowCenter', '',
  'icon-ym icon-ym-wf-flowEngine',
  35, 1, 'Web', NULL, '_self',
  '{"moduleId":"","iconBackgroundColor":"","isTree":0}',
  0, 0, 0, 0, NOW()
);

-- -----------------------------------------------------------------------------
-- 2) 解析父级：考勤模块父级（优先取「考勤汇总」菜单行的父级；否则按名称兜底）
-- -----------------------------------------------------------------------------
SELECT F_ParentId INTO @AttParentId
FROM BASE_MODULE
WHERE F_DeleteMark IS NULL
  AND F_Type = 2
  AND (
    F_UrlAddress = 'attendance'
    OR F_FullName LIKE '%考勤汇总%'
    OR F_FullName LIKE '%考勤%汇总%'
  )
ORDER BY (F_UrlAddress = 'attendance') DESC, F_SortCode
LIMIT 1;

-- 若上面没命中，再兜底：找任意考勤相关菜单的父级
SELECT F_ParentId INTO @AttParentId
FROM BASE_MODULE
WHERE F_DeleteMark IS NULL
  AND F_Type = 2
  AND (
    F_UrlAddress IN ('attendance-record', 'attendance-setting')
    OR F_FullName LIKE '%打卡记录%'
    OR F_FullName LIKE '%考勤设置%'
  )
ORDER BY F_SortCode
LIMIT 1;

-- -----------------------------------------------------------------------------
-- 3) 授权复制来源（Role 维度）
--    考勤：优先复制「考勤汇总」菜单已有授权；否则复制「用户管理」
--    工作流：优先复制「流程设计」菜单已有授权；否则复制「用户管理」
--    图片审核：优先复制考勤汇总；否则复制用户管理
-- -----------------------------------------------------------------------------
SELECT F_Id INTO @SrcAttendanceSummaryId
FROM BASE_MODULE
WHERE F_DeleteMark IS NULL
  AND F_Type = 2
  AND (
    F_UrlAddress = 'attendance'
    OR F_FullName LIKE '%考勤汇总%'
  )
ORDER BY (F_UrlAddress = 'attendance') DESC, F_SortCode
LIMIT 1;

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

SELECT F_Id INTO @SrcFlowEngineId
FROM BASE_MODULE
WHERE F_DeleteMark IS NULL
  AND F_Type = 2
  AND (
    F_EnCode = 'workFlow-flowEngine'
    OR F_UrlAddress = 'workFlow/flowEngine'
    OR F_FullName LIKE '%流程设计%'
  )
ORDER BY (F_EnCode = 'workFlow-flowEngine') DESC, F_SortCode
LIMIT 1;

-- 一级目录「流程中心」授权：复制「流程设计」已有角色；没有则复制「用户管理」；再没有则兜底管理员角色
DELETE FROM BASE_AUTHORIZE
WHERE F_ItemType = 'module'
  AND F_ObjectType = 'Role'
  AND F_ItemId = @FlowCenterRootId;

INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT REPLACE(UUID(), '-', ''), 'module', @FlowCenterRootId, 'Role', t.F_ObjectId, 1, NOW(), 'admin'
FROM (
  SELECT DISTINCT F_ObjectId
  FROM BASE_AUTHORIZE
  WHERE F_ItemType = 'module'
    AND F_ObjectType = 'Role'
    AND F_ItemId = COALESCE(@SrcFlowEngineId, @SrcUserManageId)
) t
WHERE COALESCE(@SrcFlowEngineId, @SrcUserManageId) IS NOT NULL;

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

-- -----------------------------------------------------------------------------
-- 4) 基础校验（父级必须存在）
-- -----------------------------------------------------------------------------
SELECT
  @FlowCenterRootId AS flow_center_root_id,
  @AttParentId AS attendance_parent_id,
  @SrcAttendanceSummaryId AS src_attendance_summary_id,
  @SrcFlowEngineId AS src_flow_engine_id,
  @SrcUserManageId AS src_user_manage_id;

-- 若关键父级为空，请先手工确认 BASE_MODULE 是否被清空/迁移不完整
-- MySQL 下可用 SIGNAL（5.5+）提前失败：
-- IF @AttParentId IS NULL THEN ... END IF;  （此处保持脚本兼容：仅 SELECT 提示）

-- =============================================================================
-- A) 工作流：标准子菜单（与 antis-ncc-admin 语言包/页面 name 一致）
-- =============================================================================

SET @wf_engine   = 'lvq-wf-flow-engine';
SET @wf_launch   = 'lvq-wf-flow-launch';
SET @wf_todo     = 'lvq-wf-flow-todo';
SET @wf_done     = 'lvq-wf-flow-done';
SET @wf_circ     = 'lvq-wf-flow-circulate';
SET @wf_entrust  = 'lvq-wf-entrust';
SET @wf_monitor  = 'lvq-wf-flow-monitor';

-- 清理历史重复行（同 EnCode / UrlAddress 但 F_Id 不同），避免迁移后出现两条同名菜单
DELETE a
FROM BASE_AUTHORIZE a
JOIN BASE_MODULE m ON a.F_ItemId = m.F_Id
WHERE m.F_DeleteMark IS NULL
  AND m.F_Type = 2
  AND (
    m.F_EnCode IN (
      'workFlow-flowEngine','workFlow-flowLaunch','workFlow-flowTodo','workFlow-flowDone',
      'workFlow-flowCirculate','workFlow-entrust','workFlow-flowMonitor'
    )
    OR m.F_UrlAddress IN (
      'workFlow/flowEngine','workFlow/flowLaunch','workFlow/flowTodo','workFlow/flowDone',
      'workFlow/flowCirculate','workFlow/entrust','workFlow/flowMonitor'
    )
  )
  AND m.F_Id NOT IN (
    @wf_engine, @wf_launch, @wf_todo, @wf_done, @wf_circ, @wf_entrust, @wf_monitor
  );

DELETE m
FROM BASE_MODULE m
WHERE m.F_DeleteMark IS NULL
  AND m.F_Type = 2
  AND (
    m.F_EnCode IN (
      'workFlow-flowEngine','workFlow-flowLaunch','workFlow-flowTodo','workFlow-flowDone',
      'workFlow-flowCirculate','workFlow-entrust','workFlow-flowMonitor'
    )
    OR m.F_UrlAddress IN (
      'workFlow/flowEngine','workFlow/flowLaunch','workFlow/flowTodo','workFlow/flowDone',
      'workFlow/flowCirculate','workFlow/entrust','workFlow/flowMonitor'
    )
  )
  AND m.F_Id NOT IN (
    @wf_engine, @wf_launch, @wf_todo, @wf_done, @wf_circ, @wf_entrust, @wf_monitor
  );

DELETE FROM BASE_AUTHORIZE WHERE F_ItemId IN (
  @wf_engine, @wf_launch, @wf_todo, @wf_done, @wf_circ, @wf_entrust, @wf_monitor
);
DELETE FROM BASE_MODULE WHERE F_Id IN (
  @wf_engine, @wf_launch, @wf_todo, @wf_done, @wf_circ, @wf_entrust, @wf_monitor
);

INSERT INTO BASE_MODULE (
  F_Id, F_ParentId, F_Type, F_FullName, F_EnCode, F_UrlAddress, F_Icon,
  F_SortCode, F_EnabledMark, F_Category, F_DeleteMark, F_LinkTarget,
  F_PropertyJson, F_IsButtonAuthorize, F_IsColumnAuthorize, F_IsDataAuthorize,
  F_IsFormAuthorize, F_CreatorTime
) VALUES
(@wf_engine,  @FlowCenterRootId, 2, '流程设计', 'workFlow-flowEngine', 'workFlow/flowEngine', 'icon-ym icon-ym-generator-menu', 10, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW()),
(@wf_launch,  @FlowCenterRootId, 2, '我发起的', 'workFlow-flowLaunch', 'workFlow/flowLaunch', 'icon-ym icon-ym-btn-open', 20, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW()),
(@wf_todo,    @FlowCenterRootId, 2, '待办事宜', 'workFlow-flowTodo', 'workFlow/flowTodo', 'icon-ym icon-ym-generator-menu', 30, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW()),
(@wf_done,    @FlowCenterRootId, 2, '已办事宜', 'workFlow-flowDone', 'workFlow/flowDone', 'icon-ym icon-ym-generator-menu', 40, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW()),
(@wf_circ,    @FlowCenterRootId, 2, '抄送事宜', 'workFlow-flowCirculate', 'workFlow/flowCirculate', 'icon-ym icon-ym-generator-menu', 50, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW()),
(@wf_entrust, @FlowCenterRootId, 2, '流程委托', 'workFlow-entrust', 'workFlow/entrust', 'icon-ym icon-ym-generator-menu', 60, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW()),
(@wf_monitor, @FlowCenterRootId, 2, '流程监控', 'workFlow-flowMonitor', 'workFlow/flowMonitor', 'icon-ym icon-ym-generator-menu', 70, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW());

-- 工作流菜单授权：复制「流程设计」已有角色；没有则复制「用户管理」；再没有则兜底管理员角色
INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT REPLACE(UUID(), '-', ''), 'module', m.F_Id, 'Role', t.F_ObjectId, 1, NOW(), 'admin'
FROM (
  SELECT F_Id FROM (
    SELECT @wf_engine AS F_Id UNION ALL SELECT @wf_launch UNION ALL SELECT @wf_todo UNION ALL SELECT @wf_done
    UNION ALL SELECT @wf_circ UNION ALL SELECT @wf_entrust UNION ALL SELECT @wf_monitor
  ) x
) m
JOIN (
  SELECT DISTINCT F_ObjectId
  FROM BASE_AUTHORIZE
  WHERE F_ItemType = 'module'
    AND F_ObjectType = 'Role'
    AND F_ItemId = COALESCE(@SrcFlowEngineId, @SrcUserManageId)
) t ON 1=1
WHERE COALESCE(@SrcFlowEngineId, @SrcUserManageId) IS NOT NULL;

INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT REPLACE(UUID(), '-', ''), 'module', m.F_Id, 'Role', @AdminRoleId, 1, NOW(), 'admin'
FROM (
  SELECT F_Id FROM (
    SELECT @wf_engine AS F_Id UNION ALL SELECT @wf_launch UNION ALL SELECT @wf_todo UNION ALL SELECT @wf_done
    UNION ALL SELECT @wf_circ UNION ALL SELECT @wf_entrust UNION ALL SELECT @wf_monitor
  ) x
) m
WHERE NOT EXISTS (
  SELECT 1 FROM BASE_AUTHORIZE b
  WHERE b.F_ItemType='module' AND b.F_ObjectType='Role' AND b.F_ItemId = m.F_Id
);

-- =============================================================================
-- B) 考勤：汇总 + 设置 + 打卡记录（与前端 views 路径一致）
-- =============================================================================

SET @att_summary = 'lvq-attendance-summary';
SET @att_setting = 'lvq-attendance-setting';
SET @att_record  = 'lvq-attendance-record';

DELETE a
FROM BASE_AUTHORIZE a
JOIN BASE_MODULE m ON a.F_ItemId = m.F_Id
WHERE m.F_DeleteMark IS NULL
  AND m.F_Type = 2
  AND (
    m.F_EnCode IN ('attendanceSummary','attendanceSetting','attendanceRecord')
    OR m.F_UrlAddress IN ('attendance','attendance-setting','attendance-record')
  )
  AND m.F_Id NOT IN (@att_summary, @att_setting, @att_record);

DELETE m
FROM BASE_MODULE m
WHERE m.F_DeleteMark IS NULL
  AND m.F_Type = 2
  AND (
    m.F_EnCode IN ('attendanceSummary','attendanceSetting','attendanceRecord')
    OR m.F_UrlAddress IN ('attendance','attendance-setting','attendance-record')
  )
  AND m.F_Id NOT IN (@att_summary, @att_setting, @att_record);

DELETE FROM BASE_AUTHORIZE WHERE F_ItemId IN (@att_summary, @att_setting, @att_record);
DELETE FROM BASE_MODULE WHERE F_Id IN (@att_summary, @att_setting, @att_record);

INSERT INTO BASE_MODULE (
  F_Id, F_ParentId, F_Type, F_FullName, F_EnCode, F_UrlAddress, F_Icon,
  F_SortCode, F_EnabledMark, F_Category, F_DeleteMark, F_LinkTarget,
  F_PropertyJson, F_IsButtonAuthorize, F_IsColumnAuthorize, F_IsDataAuthorize,
  F_IsFormAuthorize, F_CreatorTime
) VALUES
(@att_summary, @AttParentId, 2, '考勤汇总表', 'attendanceSummary', 'attendance', 'icon-ym icon-ym-clock', 1, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW()),
(@att_setting, @AttParentId, 2, '考勤设置', 'attendanceSetting', 'attendance-setting', 'icon-ym icon-ym-clock', 2, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW()),
(@att_record,  @AttParentId, 2, '打卡记录', 'attendanceRecord', 'attendance-record', 'icon-ym icon-ym-clock', 3, 1, 'Web', NULL, '_self', '{"moduleId":"","iconBackgroundColor":"","isTree":0}', 1, 1, 1, 1, NOW());

-- 考勤菜单授权：复制「考勤汇总来源模块」的角色；没有则复制「用户管理」
INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT REPLACE(UUID(), '-', ''), 'module', m.F_Id, 'Role', t.F_ObjectId, 1, NOW(), 'admin'
FROM (
  SELECT F_Id FROM (
    SELECT @att_summary AS F_Id UNION ALL SELECT @att_setting UNION ALL SELECT @att_record
  ) x
) m
JOIN (
  SELECT DISTINCT F_ObjectId
  FROM BASE_AUTHORIZE
  WHERE F_ItemType = 'module'
    AND F_ObjectType = 'Role'
    AND F_ItemId = COALESCE(@SrcAttendanceSummaryId, @SrcUserManageId)
) t ON 1=1
WHERE COALESCE(@SrcAttendanceSummaryId, @SrcUserManageId) IS NOT NULL;

INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT REPLACE(UUID(), '-', ''), 'module', m.F_Id, 'Role', @AdminRoleId, 1, NOW(), 'admin'
FROM (
  SELECT F_Id FROM (
    SELECT @att_summary AS F_Id UNION ALL SELECT @att_setting UNION ALL SELECT @att_record
  ) x
) m
WHERE NOT EXISTS (
  SELECT 1 FROM BASE_AUTHORIZE b
  WHERE b.F_ItemType='module' AND b.F_ObjectType='Role' AND b.F_ItemId = m.F_Id
);

-- =============================================================================
-- C) 图片上传审核记录：views/lqUploadRecord/index.vue -> F_UrlAddress = lqUploadRecord
--    父级：优先取「考勤汇总表」同父级；否则取「用户管理」同父级
-- =============================================================================

SET @upload_audit = 'lvq-upload-record-audit';

SELECT COALESCE(
  (SELECT F_ParentId FROM BASE_MODULE WHERE F_DeleteMark IS NULL AND F_Type = 2 AND F_Id = @att_summary LIMIT 1),
  (SELECT F_ParentId FROM BASE_MODULE WHERE F_DeleteMark IS NULL AND F_Type = 2 AND F_FullName = '用户管理' LIMIT 1)
) INTO @UploadParentId;

DELETE a
FROM BASE_AUTHORIZE a
JOIN BASE_MODULE m ON a.F_ItemId = m.F_Id
WHERE m.F_DeleteMark IS NULL
  AND m.F_Type = 2
  AND (m.F_EnCode = 'lqUploadRecordAudit' OR m.F_UrlAddress = 'lqUploadRecord')
  AND m.F_Id <> @upload_audit;

DELETE m
FROM BASE_MODULE m
WHERE m.F_DeleteMark IS NULL
  AND m.F_Type = 2
  AND (m.F_EnCode = 'lqUploadRecordAudit' OR m.F_UrlAddress = 'lqUploadRecord')
  AND m.F_Id <> @upload_audit;

DELETE FROM BASE_AUTHORIZE WHERE F_ItemId = @upload_audit;
DELETE FROM BASE_MODULE WHERE F_Id = @upload_audit;

INSERT INTO BASE_MODULE (
  F_Id, F_ParentId, F_Type, F_FullName, F_EnCode, F_UrlAddress, F_Icon,
  F_SortCode, F_EnabledMark, F_Category, F_DeleteMark, F_LinkTarget,
  F_PropertyJson, F_IsButtonAuthorize, F_IsColumnAuthorize, F_IsDataAuthorize,
  F_IsFormAuthorize, F_CreatorTime
) VALUES (
  @upload_audit, @UploadParentId, 2,
  '图片上传审核', 'lqUploadRecordAudit', 'lqUploadRecord',
  'icon-ym icon-ym-upload',
  80, 1, 'Web', NULL, '_self',
  '{"moduleId":"","iconBackgroundColor":"","isTree":0}',
  1, 1, 1, 1, NOW()
);

INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT REPLACE(UUID(), '-', ''), 'module', @upload_audit, 'Role', t.F_ObjectId, 1, NOW(), 'admin'
FROM (
  SELECT DISTINCT F_ObjectId
  FROM BASE_AUTHORIZE
  WHERE F_ItemType = 'module'
    AND F_ObjectType = 'Role'
    AND F_ItemId = COALESCE(@SrcAttendanceSummaryId, @SrcUserManageId)
) t
WHERE COALESCE(@SrcAttendanceSummaryId, @SrcUserManageId) IS NOT NULL;

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

-- =============================================================================
-- D) 小程序/APP 菜单（App 首页）：补齐「流程申请」「考勤打卡」
-- 说明：uni-app 首页会调用 getAppAuthorize，根节点为 fullName = 'app首页'
-- =============================================================================

SET @app_workflow_apply  = 'lvq-app-workflow-apply';
SET @app_attendance_punch = 'lvq-app-attendance-punch';

-- 解析「app首页」->「其他」分组目录
SELECT m.F_Id INTO @AppHomeRootId
FROM BASE_MODULE m
WHERE m.F_Category = 'App'
  AND m.F_Type = 1
  AND m.F_FullName = 'app首页'
ORDER BY m.F_SortCode
LIMIT 1;

SELECT m.F_Id INTO @AppOtherSectionId
FROM BASE_MODULE m
WHERE m.F_Category = 'App'
  AND m.F_Type = 1
  AND m.F_FullName = '其他'
  AND m.F_ParentId = @AppHomeRootId
ORDER BY m.F_SortCode
LIMIT 1;

-- 授权复制来源：优先复制「门店管理」；没有则复制「AI问答」；再没有则兜底管理员角色
SELECT m.F_Id INTO @SrcAppMenuId
FROM BASE_MODULE m
WHERE m.F_Category = 'App'
  AND m.F_Type = 2
  AND m.F_FullName IN ('门店管理', 'AI问答')
ORDER BY (m.F_FullName = '门店管理') DESC, m.F_SortCode
LIMIT 1;

-- 清理历史重复行（同 EnCode / UrlAddress 但 F_Id 不同）
DELETE a
FROM BASE_AUTHORIZE a
JOIN BASE_MODULE m ON a.F_ItemId = m.F_Id
WHERE m.F_Category = 'App'
  AND m.F_Type = 2
  AND (
    m.F_EnCode IN ('app-workflow-apply','app-attendance-punch','workflowApply','attendancePunch')
    OR m.F_UrlAddress IN ('/pages/workflow-center/workflow-center','/pages/attendance-punch/attendance-punch')
    OR m.F_FullName IN ('流程申请','考勤打卡')
  )
  AND m.F_Id NOT IN (@app_workflow_apply, @app_attendance_punch);

DELETE m
FROM BASE_MODULE m
WHERE m.F_Category = 'App'
  AND m.F_Type = 2
  AND (
    m.F_EnCode IN ('app-workflow-apply','app-attendance-punch','workflowApply','attendancePunch')
    OR m.F_UrlAddress IN ('/pages/workflow-center/workflow-center','/pages/attendance-punch/attendance-punch')
    OR m.F_FullName IN ('流程申请','考勤打卡')
  )
  AND m.F_Id NOT IN (@app_workflow_apply, @app_attendance_punch);

DELETE FROM BASE_AUTHORIZE WHERE F_ItemId IN (@app_workflow_apply, @app_attendance_punch);
DELETE FROM BASE_MODULE WHERE F_Id IN (@app_workflow_apply, @app_attendance_punch);

INSERT INTO BASE_MODULE (
  F_Id, F_ParentId, F_Type, F_FullName, F_EnCode, F_UrlAddress, F_Icon,
  F_SortCode, F_EnabledMark, F_Category, F_DeleteMark, F_LinkTarget,
  F_Description, F_PropertyJson, F_IsButtonAuthorize, F_IsColumnAuthorize, F_IsDataAuthorize,
  F_IsFormAuthorize, F_CreatorTime
) VALUES
(
  @app_workflow_apply, @AppOtherSectionId, 2,
  '流程申请', 'app-workflow-apply', '/pages/workflow-center/workflow-center',
  'icon-ym icon-ym-generator-steps',
  4, 1, 'App', NULL, '_self',
  '/static/home/order.png,icon-circle-bg-1',
  '{"moduleId":"","iconBackgroundColor":"","isTree":0}',
  0, 0, 0, 0, NOW()
),
(
  @app_attendance_punch, @AppOtherSectionId, 2,
  '考勤打卡', 'app-attendance-punch', '/pages/attendance-punch/attendance-punch',
  'icon-ym icon-ym-generator-steps',
  5, 1, 'App', NULL, '_self',
  '/static/home/usage-record.png,icon-circle-bg-13',
  '{"moduleId":"","iconBackgroundColor":"","isTree":0}',
  0, 0, 0, 0, NOW()
);

-- App 菜单授权：复制来源菜单的已有角色；没有则兜底管理员角色
INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT REPLACE(UUID(), '-', ''), 'module', m.F_Id, 'Role', t.F_ObjectId, 1, NOW(), 'admin'
FROM (
  SELECT F_Id FROM (
    SELECT @app_workflow_apply AS F_Id UNION ALL SELECT @app_attendance_punch
  ) x
) m
JOIN (
  SELECT DISTINCT a.F_ObjectId
  FROM BASE_AUTHORIZE a
  WHERE a.F_ItemType = 'module'
    AND a.F_ObjectType = 'Role'
    AND a.F_ItemId = @SrcAppMenuId
) t ON 1=1
WHERE @SrcAppMenuId IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM BASE_AUTHORIZE b
    WHERE b.F_ItemType='module' AND b.F_ObjectType='Role'
      AND b.F_ItemId = m.F_Id AND b.F_ObjectId = t.F_ObjectId
  );

INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT REPLACE(UUID(), '-', ''), 'module', m.F_Id, 'Role', @AdminRoleId, 1, NOW(), 'admin'
FROM (
  SELECT F_Id FROM (
    SELECT @app_workflow_apply AS F_Id UNION ALL SELECT @app_attendance_punch
  ) x
) m
WHERE NOT EXISTS (
  SELECT 1 FROM BASE_AUTHORIZE b
  WHERE b.F_ItemType='module' AND b.F_ObjectType='Role' AND b.F_ItemId = m.F_Id
);

-- =============================================================================
-- 结束：建议执行后清缓存/重新登录后台验证菜单是否出现
-- =============================================================================
