package com.yunhai.cms.service.impl; import com.yunhai.platform.apistd.BizException; import com.yunhai.platform.openapi.client.YschBaseOpenApi; import com.yunhai.platform.utils.exception.ErrorCode; import com.yunhai.platform.utils.model.BoaModule; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * 用户中心代理(Notice UserCenterService 同款逻辑平移): * 模块菜单树来自基础平台 SDK(YschBaseOpenApi.getUserModule),扁平转树对齐前端 layout 契约。 */ @Slf4j @Service public class CmsUserCenterService { /** * 当前用户已授权模块树(左侧菜单)。 */ public List> getUserModuleTree(Integer userId, Integer schId) { if (userId == null) { throw new BizException(ErrorCode.PARAM_ERROR, "用户ID不得为空"); } List modules; try { modules = YschBaseOpenApi.getUserModule(userId, schId); } catch (Exception e) { // 平台不可达时菜单降级为空(登录/站点能力不受影响),避免整页不可用 log.warn("[cms] 获取用户模块失败, schId={}: {}", schId, e.getMessage()); return Collections.emptyList(); } if (modules == null || modules.isEmpty()) { return Collections.emptyList(); } return buildModuleTree(modules); } /** * 扁平 BoaModule → 树结构(modId/page/children),对齐前端 layout 期望。 * 顶层取 parentId=0 或父节点不在列表中的节点,保持 SDK 返回顺序。 */ private List> buildModuleTree(List modules) { Map moduleMap = modules.stream() .collect(Collectors.toMap(BoaModule::getId, m -> m, (a, b) -> a)); Map> nodeMap = new LinkedHashMap<>(); for (BoaModule m : modules) { Map node = new LinkedHashMap<>(); node.put("id", m.getId()); node.put("modId", m.getId()); node.put("name", m.getName()); node.put("parentId", m.getParentId() != null ? m.getParentId() : 0); node.put("page", m.getPath() != null ? m.getPath() : ""); node.put("level", m.getLevel() != null ? m.getLevel() : 0); node.put("icon", m.getIcon() != null ? m.getIcon() : ""); node.put("orderNumber", m.getSortNo() != null ? m.getSortNo() : 0); node.put("usable", true); node.put("children", new ArrayList<>()); nodeMap.put(m.getId(), node); } List> roots = new ArrayList<>(); for (BoaModule m : modules) { Map node = nodeMap.get(m.getId()); int parentId = m.getParentId() != null ? m.getParentId() : 0; if (parentId == 0 || !moduleMap.containsKey(parentId)) { roots.add(node); } else { @SuppressWarnings("unchecked") List> children = (List>) nodeMap.get(parentId).get("children"); children.add(node); } } return roots; } }