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>

View File

@@ -1,37 +1,14 @@
<script setup lang="ts">
import type { Station } from '@/apis/domains';
import type { NdmDeviceResultVO, NdmNvrResultVO } from '@/apis/models';
import type { NdmDeviceResultVO } from '@/apis/models';
import DeviceTree from '@/components/device-tree.vue';
import { useLineDevicesQuery } from '@/composables/query';
import { DeviceType, DeviceTypeName, type DeviceTypeVal, type DeviceTypeKey } from '@/enums/device-type';
import { DeviceType, type DeviceTypeVal } from '@/enums/device-type';
import { useLineDevicesStore } from '@/stores/line-devices';
import { useStationStore } from '@/stores/station';
import { ChevronBack } from '@vicons/ionicons5';
import { destr } from 'destr';
import {
NButton,
NButtonGroup,
NFlex,
NIcon,
NInput,
NLayout,
NLayoutContent,
NLayoutSider,
NPageHeader,
NRadio,
NRadioGroup,
NScrollbar,
NTabs,
NTab,
NTag,
NTree,
type TagProps,
type TreeInst,
type TreeOption,
type TreeOverrideNodeClickBehavior,
} from 'naive-ui';
import { NIcon, NLayout, NLayoutContent, NLayoutSider, NPageHeader } from 'naive-ui';
import { storeToRefs } from 'pinia';
import { h, onMounted, useTemplateRef } from 'vue';
import { computed, ref, watch } from 'vue';
import { ref, watch } from 'vue';
import { useRoute, useRouter, type LocationQuery } from 'vue-router';
const { isFetching: lineDevicesFetching } = useLineDevicesQuery();
@@ -54,157 +31,33 @@ const router = useRouter();
const onClickBack = () => router.push({ path: `${route.query['from']}` });
const deviceTabPanes = Object.keys(DeviceType).map((key) => {
const name = DeviceType[key as DeviceTypeKey];
return {
name,
tab: DeviceTypeName[name],
};
});
// 获取车站和设备数据
const stationStore = useStationStore();
const { stationList } = storeToRefs(stationStore);
const lineDevicesStore = useLineDevicesStore();
const { lineDevices } = storeToRefs(lineDevicesStore);
// ========== 设备树数据 ==========
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; // 更新选中的设备
router.replace({
query: {
...route.query,
stationCode: stationCode,
deviceType: selectedTab.value,
deviceDBId: device.id,
},
});
},
},
() => '查看',
);
};
return h('div', [renderViewDeviceButton(device, stationCode), renderDeviceStatusTag(device)]);
};
// ========== 选中设备 ==========
const selectedTab = ref<DeviceTypeVal>(DeviceType.Camera);
const selectedKeys = ref<string[]>();
const selectedDevice = ref<NdmDeviceResultVO>();
const selectedStationCode = ref<string>();
// 解析路由参数,设置选中的设备
const setSelectedRefsFromRouteQuery = (query: LocationQuery) => {
const { stationCode, deviceType, deviceDBId } = query;
let stnCode = '';
if (stationCode) selectedStationCode.value = stationCode as string;
let devType: DeviceTypeVal = DeviceType.Camera;
let devDBId = '';
if (stationCode) stnCode = stationCode as string;
if (deviceType) devType = deviceType as DeviceTypeVal;
if (deviceDBId) devDBId = deviceDBId as string;
selectedTab.value = devType;
selectedKeys.value = [devDBId];
const stnDevices = lineDevices.value[stnCode];
const stnDevices = lineDevices.value[selectedStationCode.value ?? ''];
const devices = stnDevices?.[devType];
// 如果没找到,那还是赋值为原来选择的设备
selectedDevice.value = devices?.find((device) => device.id === devDBId) ?? selectedDevice.value;
};
// 页面加载时,需要设置选中的设备
onMounted(() => {
// setSelectedRefsFromRouteQuery(route.query);
// scrollDeviceTreeToSelectedDevice();
});
// 页面加载时设备数据可能不存在,因此当设备数据更新时,需要重新设置选中的设备
watch(
lineDevices,
@@ -216,110 +69,29 @@ watch(
immediate: true,
},
);
// 更改选择的设备类型时,更新路由查询参数
watch(selectedTab, (newTab) => {
router.replace({ query: { ...route.query, deviceType: newTab } });
});
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 });
watch(selectedDevice, (newDevice) => {
router.replace({ query: { ...route.query, deviceDBId: newDevice?.id } });
});
watch(selectedStationCode, (newStationCode) => {
router.replace({ query: { ...route.query, stationCode: newStationCode } });
});
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 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;
const stationCode = route.query['stationCode'] as string | undefined;
let expanded: string[] | undefined = stationCode ? [stationCode] : undefined;
if (selectedTab.value === DeviceType.Nvr && stationCode) {
const nvrs = lineDevices.value[stationCode][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);
};
</script>
<template>
<NLayout has-sider style="height: 100%">
<NLayoutSider bordered :width="600" :collapsed-width="0" show-trigger="bar">
<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>
<!-- 左侧为设备类型Tab右侧为设备树 -->
<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" />
</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>
<DeviceTree
v-model:selected-keys="selectedKeys"
v-model:selected-tab="selectedTab"
v-model:selected-device="selectedDevice"
v-model:selected-station-code="selectedStationCode"
:line-devices="lineDevices"
:station-list="stationList"
/>
</NLayoutSider>
<NLayoutContent :content-style="{ 'padding-left': '24px', 'padding-top': '6px' }">
<NPageHeader v-if="route.query['from']" title="" @back="onClickBack">
@@ -330,12 +102,7 @@ const scrollDeviceTreeToSelectedDevice = (timeout: number = 500) => {
<div style="font-size: 15px">返回</div>
</template>
</NPageHeader>
<div>selectedKeys: {{ selectedKeys }}</div>
<div>expandedKeys: {{ expandedKeys }}</div>
<div>selectedDevice: {{ selectedDevice?.deviceId }}</div>
<NScrollbar style="width: 800px; height: 400px; border: solid 1px salmon" x-scrollable>
<pre>{{ selectedDevice }}</pre>
</NScrollbar>
<div>{{ selectedDevice }}</div>
</NLayoutContent>
</NLayout>
</template>