86133 | aaa3f5d | 2025-04-20 21:33:29 +0800 | [diff] [blame] | 1 | import { DataNode } from 'antd/es/tree'; |
| 2 | import { parse } from 'querystring'; |
| 3 | |
| 4 | /** |
| 5 | * 构造树型结构数据 |
| 6 | * @param {*} data 数据源 |
| 7 | * @param {*} id id字段 默认 'id' |
| 8 | * @param {*} parentId 父节点字段 默认 'parentId' |
| 9 | * @param {*} children 孩子节点字段 默认 'children' |
| 10 | */ |
| 11 | export function buildTreeData( |
| 12 | data: any[], |
| 13 | id: string, |
| 14 | name: string, |
| 15 | parentId: string, |
| 16 | parentName: string, |
| 17 | children: string, |
| 18 | ) { |
| 19 | const config = { |
| 20 | id: id || 'id', |
| 21 | name: name || 'name', |
| 22 | parentId: parentId || 'parentId', |
| 23 | parentName: parentName || 'parentName', |
| 24 | childrenList: children || 'children', |
| 25 | }; |
| 26 | |
| 27 | const childrenListMap: any[] = []; |
| 28 | const nodeIds: any[] = []; |
| 29 | const tree: any[] = []; |
| 30 | data.forEach((item) => { |
| 31 | const d = item; |
| 32 | const pId = d[config.parentId]; |
| 33 | if (!childrenListMap[pId]) { |
| 34 | childrenListMap[pId] = []; |
| 35 | } |
| 36 | d.key = d[config.id]; |
| 37 | d.title = d[config.name]; |
| 38 | d.value = d[config.id]; |
| 39 | d[config.childrenList] = null; |
| 40 | nodeIds[d[config.id]] = d; |
| 41 | childrenListMap[pId].push(d); |
| 42 | }); |
| 43 | |
| 44 | data.forEach((item: any) => { |
| 45 | const d = item; |
| 46 | const pId = d[config.parentId]; |
| 47 | if (!nodeIds[pId]) { |
| 48 | d[config.parentName] = ''; |
| 49 | tree.push(d); |
| 50 | } |
| 51 | }); |
| 52 | |
| 53 | function adaptToChildrenList(item: any) { |
| 54 | const o = item; |
| 55 | if (childrenListMap[o[config.id]]) { |
| 56 | if (!o[config.childrenList]) { |
| 57 | o[config.childrenList] = []; |
| 58 | } |
| 59 | o[config.childrenList] = childrenListMap[o[config.id]]; |
| 60 | } |
| 61 | if (o[config.childrenList]) { |
| 62 | o[config.childrenList].forEach((child: any) => { |
| 63 | const c = child; |
| 64 | c[config.parentName] = o[config.name]; |
| 65 | adaptToChildrenList(c); |
| 66 | }); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | tree.forEach((t: any) => { |
| 71 | adaptToChildrenList(t); |
| 72 | }); |
| 73 | |
| 74 | return tree; |
| 75 | } |
| 76 | |
| 77 | export const getPageQuery = () => parse(window.location.href.split('?')[1]); |
| 78 | |
| 79 | export function formatTreeData(arrayList: any): DataNode[] { |
| 80 | const treeSelectData: DataNode[] = arrayList.map((item: any) => { |
| 81 | const node: DataNode = { |
| 82 | id: item.id, |
| 83 | title: item.label, |
| 84 | key: `${item.id}`, |
| 85 | value: item.id, |
| 86 | } as DataNode; |
| 87 | if (item.children) { |
| 88 | node.children = formatTreeData(item.children); |
| 89 | } |
| 90 | return node; |
| 91 | }); |
| 92 | return treeSelectData; |
| 93 | } |