Files
ndm-web-client/src/composables/device/use-device-selection.ts
2025-09-30 15:09:12 +08:00

74 lines
2.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { NdmDeviceResultVO } from '@/apis/models';
import { DeviceType, tryGetDeviceTypeVal, type DeviceTypeVal } from '@/enums/device-type';
import { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { LineDevices } from '../query';
export function useDeviceSelection() {
const route = useRoute();
const router = useRouter();
const selectedStationCode = ref<string>();
const selectedDeviceType = ref<DeviceTypeVal>(DeviceType.Camera);
const selectedDevice = ref<NdmDeviceResultVO>();
const initFromRoute = (lineDevices: LineDevices) => {
const { stationCode, deviceType, deviceDBId } = route.query;
if (stationCode) {
selectedStationCode.value = stationCode as string;
}
if (deviceType) {
selectedDeviceType.value = deviceType as DeviceTypeVal;
}
// 如果有设备ID参数尝试找到对应设备
if (deviceDBId && selectedStationCode.value && selectedDeviceType.value) {
const deviceId = deviceDBId as string;
const stationDevices = lineDevices[selectedStationCode.value];
if (stationDevices) {
const typedDevices = stationDevices[selectedDeviceType.value];
if (typedDevices) {
const device = typedDevices.find((device) => device.id === deviceId);
if (device) {
selectedDevice.value = device;
}
}
}
}
};
const selectDevice = (device: NdmDeviceResultVO, stationCode: string) => {
selectedDevice.value = device;
selectedStationCode.value = stationCode;
const deviceTypeVal = tryGetDeviceTypeVal(device.deviceType);
if (!!deviceTypeVal) {
selectedDeviceType.value = deviceTypeVal;
}
};
const syncToRoute = () => {
const query = { ...route.query };
if (selectedStationCode.value) {
query['stationCode'] = selectedStationCode.value;
}
if (selectedDeviceType.value) {
query['deviceType'] = selectedDeviceType.value;
}
if (selectedDevice.value?.id) {
query['deviceDBId'] = selectedDevice.value.id;
}
router.replace({ query });
};
watch([selectedStationCode, selectedDevice], () => syncToRoute());
return {
selectedStationCode,
selectedDeviceType,
selectedDevice,
initFromRoute,
selectDevice,
syncToRoute,
};
}