refactor: extract device tree

This commit is contained in:
yangsy
2025-08-27 10:10:38 +08:00
parent c875deb488
commit 9ec22b883b
2 changed files with 263 additions and 257 deletions

View File

@@ -0,0 +1,239 @@
<script setup lang="ts">
import type { Station } from '@/apis/domains';
import type { NdmDeviceResultVO, NdmNvrResultVO } from '@/apis/models';
import type { LineDevices } from '@/composables/query/device/use-line-devices-query';
import { DeviceType, DeviceTypeName, type DeviceTypeKey, type DeviceTypeVal } from '@/enums/device-type';
import destr from 'destr';
import { NButton, NButtonGroup, NFlex, NInput, NRadio, NRadioGroup, NTab, NTabs, NTag, NTree, type TagProps, type TreeInst, type TreeOption, type TreeOverrideNodeClickBehavior } from 'naive-ui';
import { computed, h, ref, toRefs, useTemplateRef } from 'vue';
const deviceTabPanes = Object.keys(DeviceType).map((key) => {
const name = DeviceType[key as DeviceTypeKey];
return {
name,
tab: DeviceTypeName[name],
};
});
const props = defineProps<{
stationList: Station[];
lineDevices: LineDevices;
}>();
// 获取车站和设备数据
const { stationList, lineDevices } = toRefs(props);
// ========== 设备树数据 ==========
const lineDeviceTreeData = computed<Record<string, TreeOption[]>>(() => {
const treeData: Record<string, TreeOption[]> = {};
deviceTabPanes.forEach(({ name: paneName /* , tab: paneTab */ }) => {
treeData[paneName] = stationList.value.map<TreeOption>((station) => {
const { name: stationName, code: stationCode } = station;
const devices = lineDevices.value[stationCode]?.[paneName] ?? ([] as NdmDeviceResultVO[]);
const onlineDevices = devices?.filter((device) => device.deviceStatus === '10');
const offlineDevices = devices?.filter((device) => device.deviceStatus === '20');
// 对于录像机需要根据clusterList字段以分号分隔设备IP进一步形成子树结构
if (paneName === DeviceType.Nvr) {
const nvrs = devices as NdmNvrResultVO[] | undefined;
return {
label: stationName,
key: stationCode,
prefix: () => renderStationNodePrefix(station),
suffix: () => `(${onlineDevices?.length ?? 0}/${offlineDevices?.length ?? 0}/${devices?.length ?? 0})`,
children: nvrs
?.filter((device) => {
const nvr = device as NdmNvrResultVO;
return !!nvr.clusterList?.trim() && nvr.clusterList !== nvr.ipAddress;
})
.map<TreeOption>((nvrCluster) => {
return {
label: `${nvrCluster.name}`,
key: nvrCluster.id,
prefix: () => renderDeviceNodePrefix(nvrCluster, stationCode),
suffix: () => `${nvrCluster.ipAddress}`,
children: nvrs
.filter((nvr) => {
return nvrCluster.clusterList?.includes(nvr.ipAddress ?? '');
})
.map<TreeOption>((nvr) => {
return {
label: `${nvr.name}`,
key: nvr.id,
prefix: () => renderDeviceNodePrefix(nvr, stationCode),
suffix: () => `${nvr.ipAddress}`,
// 当选择设备时,能获取到设备的所有信息,以及设备所属的车站
device: nvr,
stationCode,
};
}),
// 当选择设备时,能获取到设备的所有信息,以及设备所属的车站
device: nvrCluster,
stationCode,
};
}),
};
}
return {
label: stationName,
key: stationCode,
prefix: () => renderStationNodePrefix(station),
suffix: () => `(${onlineDevices?.length ?? 0}/${offlineDevices?.length ?? 0}/${devices?.length ?? 0})`,
children:
lineDevices.value[stationCode]?.[paneName]?.map<TreeOption>((dev) => {
const device = dev as NdmDeviceResultVO;
return {
label: `${device.name}`,
key: device.id,
prefix: () => renderDeviceNodePrefix(device, stationCode),
suffix: () => `${device.ipAddress}`,
// 当选择设备时,能获取到设备的所有信息,以及设备所属的车站
device,
stationCode,
};
}) ?? [],
};
});
});
return treeData;
});
const renderStationNodePrefix = (station: Station) => {
const { online } = station;
const tagType: TagProps['type'] = online ? 'success' : 'error';
const tagText = online ? '在线' : '离线';
return h(NTag, { type: tagType, size: 'tiny' }, () => tagText);
};
const renderDeviceNodePrefix = (device: NdmDeviceResultVO, stationCode: string) => {
const renderDeviceStatusTag = (device: NdmDeviceResultVO) => {
const { deviceStatus } = device;
const tagType: TagProps['type'] = deviceStatus === '10' ? 'success' : deviceStatus === '20' ? 'error' : 'warning';
const tagText = device.deviceStatus === '10' ? '在线' : device.deviceStatus === '20' ? '离线' : '未知';
return h(NTag, { type: tagType, size: 'tiny' }, () => tagText);
};
const renderViewDeviceButton = (device: NdmDeviceResultVO, stationCode: string) => {
return h(
NButton,
{
text: true,
size: 'tiny',
type: 'info',
onClick: () => {
// 更新选中的设备和车站编码
selectedDevice.value = device;
selectedStationCode.value = stationCode;
},
},
() => '选择',
);
};
return h('div', [renderViewDeviceButton(device, stationCode), renderDeviceStatusTag(device)]);
};
// ========== 选中设备 ==========
const selectedTab = defineModel<DeviceTypeVal>('selected-tab', { required: true, default: DeviceType.Camera });
const selectedKeys = defineModel<string[]>('selected-keys');
const selectedDevice = defineModel<NdmDeviceResultVO>('selected-device');
const override: TreeOverrideNodeClickBehavior = ({ option }) => {
if (!option['device']) {
return 'none';
}
return 'default';
};
// ========== 设备树搜索 ==========
const searchInput = ref('');
const statusInput = ref('');
// 设备树将搜索框和单选框的值都交给NTree的pattern属性
// 但是如果一个车站下没有匹配的设备,那么这个车站节点也不会显示
const searchPattern = computed(() => {
const search = searchInput.value;
const status = statusInput.value;
if (!search && !status) return ''; // 如果pattern非空会导致NTree组件认为筛选完成UI上发生全量匹配
return JSON.stringify({ search: searchInput.value, status: statusInput.value });
});
const searchFilter = (pattern: string, node: TreeOption): boolean => {
const { search, status } = destr<{ search: string; status: string }>(pattern);
const device = node['device'] as NdmDeviceResultVO | undefined;
const { name, ipAddress, deviceId, deviceStatus } = device ?? {};
const searchMatched = (name ?? '').includes(search) || (ipAddress ?? '').includes(search) || (deviceId ?? '').includes(search);
const statusMatched = status === '' || status === deviceStatus;
return searchMatched && statusMatched;
};
// ========== 设备树交互 ==========
const selectedStationCode = defineModel<string>('selected-station-code');
const expandedKeys = ref<string[]>();
const deviceTreeInst = useTemplateRef<TreeInst>('deviceTreeInst');
const onClickLocateDeviceTree = () => {
selectedTab.value = (selectedDevice.value?.deviceType ?? selectedTab.value) as DeviceTypeVal;
selectedKeys.value = selectedDevice.value?.id ? [selectedDevice.value.id] : undefined;
let expanded: string[] | undefined = selectedStationCode.value ? [selectedStationCode.value] : undefined;
if (selectedTab.value === DeviceType.Nvr && selectedStationCode.value) {
const nvrs = lineDevices.value[selectedStationCode.value][DeviceType.Nvr];
const clusterKeys = nvrs.filter((nvr) => !!nvr.clusterList?.trim() && nvr.clusterList !== nvr.ipAddress).map((nvr) => String(nvr.id));
expanded = [...(expanded ?? []), ...clusterKeys];
}
expandedKeys.value = expanded;
// 由于数据量大所以开启虚拟滚动,
// 但是无法知晓NTree内部的虚拟列表容器何时创建完成所以使用setTimeout延迟固定时间后执行滚动
scrollDeviceTreeToSelectedDevice();
};
const scrollDeviceTreeToSelectedDevice = (timeout: number = 500) => {
setTimeout(() => {
const inst = deviceTreeInst.value;
inst?.scrollTo({ key: selectedDevice.value?.id, behavior: 'smooth' });
}, timeout);
};
// defineExpose({
// onClickLocateDeviceTree,
// scrollDeviceTreeToSelectedDevice,
// });
</script>
<template>
<div style="height: 100%; display: flex; flex-direction: column">
<div style="flex-shrink: 0; padding: 12px">
<NInput v-model:value="searchInput" placeholder="搜索设备、设备ID或IP地址" clearable />
<NFlex justify="space-between" align="center">
<NRadioGroup v-model:value="statusInput">
<NRadio value="">全部</NRadio>
<NRadio value="10">在线</NRadio>
<NRadio value="20">离线</NRadio>
</NRadioGroup>
<NButtonGroup>
<NButton text size="tiny" type="info" @click="onClickLocateDeviceTree">定位</NButton>
</NButtonGroup>
</NFlex>
</div>
<div style="flex: 1; min-height: 0; display: flex; overflow: hidden">
<div style="flex: 0 0 auto; height: 100%">
<NTabs v-model:value="selectedTab" animated type="line" placement="left" style="height: 100%">
<NTab v-for="pane in deviceTabPanes" :key="pane.name" :name="pane.name" :tab="pane.tab"></NTab>
</NTabs>
</div>
<div style="flex: 1 1 auto; min-width: 0">
<NTree
v-model:selected-keys="selectedKeys"
v-model:expanded-keys="expandedKeys"
:ref="'deviceTreeInst'"
:data="lineDeviceTreeData[selectedTab]"
:show-irrelevant-nodes="false"
:pattern="searchPattern"
:filter="searchFilter"
:override-default-node-click-behavior="override"
default-expand-all
block-line
block-node
show-line
virtual-scroll
style="height: 100%"
/>
</div>
</div>
</div>
</template>
<style scoped></style>