import type { Region } from "./organization-demo"; import type { TreeSelectNode } from "../components/ui/tree-select"; export const levelNames = ["省", "市", "区县"]; /** 层级只认后端业务投影;缺记录或未知值均为 null,⛔ 按父子深度推断。 */ export function regionLevel(node: { level: string | null | undefined }): number | null { const index = levelNames.indexOf((node.level ?? "").trim()); return index < 0 ? null : index; } export function regionLevelText(level: number | null): string { return level === null ? "未定级" : levelNames[level] || "未定级"; } /** 保留不可选的祖先作为层级上下文,不因此扩大可挂载范围。 */ export function regionTreeNodes(regions: Region[], allowedIds?: string[]): TreeSelectNode[] { const allowed = allowedIds ? new Set(allowedIds) : undefined; function children(parent: string | null): TreeSelectNode[] { return regions.filter((region) => region.parent === parent).flatMap((region) => { const nested = children(region.id), selectable = !allowed || allowed.has(region.id); if (!selectable && !nested.length) return []; return [{ value: region.id, label: region.name, hint: regionLevelText(region.level), disabled: !selectable, children: nested }]; }); } return children(null); } /** 路径作为值,兼容历史档案、筛选 URL,以及已不在当前区域树中的节点。 */ export function regionPathTree(paths: string[]): TreeSelectNode[] { const roots: TreeSelectNode[] = [], nodes = new Map(); for (const path of paths) { const parts = path.split(" / ").map((part) => part.trim()).filter(Boolean); let siblings = roots; for (let index = 0; index < parts.length; index++) { const value = parts.slice(0, index + 1).join(" / "); let node = nodes.get(value); if (!node) { node = { value, label: parts[index], children: [] }; nodes.set(value, node); siblings.push(node); } siblings = node.children!; } } return roots; } export const matchesRegionPath = (path: string, selected: string) => !selected || path === selected || path.startsWith(`${selected} / `);