Files
estate/src/utils/house.ts
2026-06-01 18:12:58 +08:00

134 lines
3.5 KiB
TypeScript

interface Tree {
label: string;
value: number;
type: string;
children?: Tree[];
}
/**
* 楼栋/单元/房屋 转 Tree 结构(跳过楼层)
* @param buildings 原始楼栋数组
* @returns Tree[]
*/
export function convertBuildingToTree(buildings: any[]): Tree[] {
if (!buildings || !Array.isArray(buildings)) return [];
return buildings.map((building) => {
// 1. 楼栋
const buildingTree: Tree = {
label: building.buildingName || '未知楼栋',
type: 'buildingId',
value: building.buildingId,
children: []
};
// 2. 单元
const units = building.units || [];
const unitTrees = units.map((unit: any) => {
const unitTree: Tree = {
label: unit.unitNoName,
value: unit.unitNoId,
type: 'unitNoId',
children: []
};
// ====================== 关键修改 ======================
// 直接从 floors 里把所有 house 全部抽出来,跳过 floor 层级
const allHouses: any[] = [];
const floors = unit.floors || [];
floors.forEach((floor: any) => {
const houses = floor.houses || [];
allHouses.push(...houses); // 把所有房屋合并到一个数组
});
// 房屋直接挂在单元下
unitTree.children = allHouses.map((house: any) => ({
label: house.houseNo || '未知房屋',
value: house.houseId,
type: 'houseId'
}));
// ======================================================
return unitTree;
});
buildingTree.children = unitTrees;
return buildingTree;
});
}
interface Tree {
label: string;
value: number;
type: string;
children?: Tree[];
}
// 只允许 字符串/数字 类型的 key
type ValidTreeKey = {
[K in keyof Tree]: Tree[K] extends string | number ? K : never;
}[keyof Tree];
/**
* 根据 houseId 查找完整路径(楼栋 > 单元 > 楼层 > 房屋)
* @param treeData 转换后的树形数据
* @param houseId 目标房屋ID
* @returns string[] 路径数组,如 ['1号楼', '1单元', '3层', '301']
*/
export function getHousePathById(treeData: Tree[], houseId: string | number, response: ValidTreeKey = 'value'): (string | number)[] {
const path: (string | number)[] = [];
// 递归查找
function findNode(nodes: Tree[]): boolean {
for (const node of nodes) {
path.push(node[response]); // 把当前节点加入路径
// 找到目标房屋
if (node.type === 'houseId' && node.value === houseId) {
return true;
}
// 递归子节点
if (node.children && node.children.length > 0) {
if (findNode(node.children)) {
return true;
}
}
path.pop(); // 回溯,移除当前节点
}
return false;
}
findNode(treeData);
return path;
}
// 对字符串 图片地址,处理
export function splitStringUrl(str: string, splitLabel: string = ',') {
const list = str.split(splitLabel);
const newlist = list
.map((item) => {
return {
name: item.split('/').pop(),
url: item
};
})
.filter((item) => item.name && item.url);
return newlist;
}
/**
* 判断 FormData 是否有数据
* @param formData 要判断的 FormData 对象
* @returns {boolean} true 有数据 false 没有数据
*/
export function hasFormData(formData: FormData): boolean {
if (!formData || !(formData instanceof FormData)) return false;
// 遍历一次,只要有一个字段就返回 true
for (const entry of formData.entries()) {
return true;
}
return false;
}