/** * 把扁平的 org 节点数组构造为嵌套树(对齐 PC 端 src/utils/organization-tree.js)。 * 节点形状:{ id, name, type, parentId, sort?, children: [] } */ const LEGAL_TYPES = new Set(["10", "20", "group", "company"]); export function buildOrganizationTree(list = []) { const nodeMap = new Map(); const roots = []; list.forEach((item) => { const node = Object.assign({}, item, { children: [] }); nodeMap.set(String(item.id), node); }); nodeMap.forEach((node) => { const parentId = node.parentId == null ? "0" : String(node.parentId); const parent = nodeMap.get(parentId); if (parent && String(node.id) !== parentId) { parent.children.push(node); } else { roots.push(node); } }); const sortNodes = (nodes, level = 0) => { nodes.sort((a, b) => Number(a.sort || 0) - Number(b.sort || 0)); nodes.forEach((node) => { node.treeLevel = level; sortNodes(node.children || [], level + 1); }); }; sortNodes(roots); return roots; } /** * 从全量 org 列表里识别法人节点。 */ export function pickLegalEntities(list = []) { if (!Array.isArray(list) || !list.length) return []; const parents = new Map(list.map((item) => [String(item.id), item])); const isLegalType = (item) => LEGAL_TYPES.has(String(item.type)); const hasNoParent = (item) => { const pid = item.parentId == null ? "0" : String(item.parentId); return pid === "0" || !parents.has(pid); }; return list.filter((item) => isLegalType(item) || hasNoParent(item)).map((item) => ({ id: item.id, name: item.name })); } /** * 从全量 org 列表里取出某个法人节点下(含自身)的所有节点,再构树。 */ export function buildDeptTreeUnderLegal(allList = [], legalId) { if (!legalId) return buildOrganizationTree(allList); const key = String(legalId); const root = allList.find((item) => String(item.id) === key); if (!root) return []; const picked = [root]; const walk = (parentId) => { allList.forEach((item) => { if (String(item.parentId) === String(parentId)) { picked.push(item); walk(item.id); } }); }; walk(legalId); return buildOrganizationTree(picked); } export { LEGAL_TYPES };