import { onLoad } from '@dcloudio/uni-app' import { computed, ref } from 'vue' import { fetchRoomList } from '@/api/location' import { getErrorMessage } from '@/utils/api-error' import { parseDeviceId, parseId, sameId } from '@/utils/device-id' import { fetchProductOptions } from '@/pages/add-device/complete/complete.api' import { fetchDeviceList } from '../device.api' import { fetchDeviceRuntime, updateDeviceRuntime } from './device-detail.api' import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types' import { AUTO_FAN_LEVEL_OPTIONS, DEFAULT_FILTER_TOTAL_DAYS, formatConnectionText, formatFilterRemainDays, formatPowerMode, formatTvocLevel, formatTvocValue, isAutoRunMode, isBluetoothConnected, mapRuntimeToView, RUN_MODE_OPTIONS, stabilizePercentReading, } from './device-detail.utils' import { airQualityToLabel, airQualityToTvoc, clampPercent, encodeFanLevelBleCommand, encodeRunModeBleCommand, type Z2AirQuality, Z2_BLE_CMD, } from '@/utils/z2-ble-protocol' import type { BleRuntimePatch } from './device-bluetooth-read' import { useDeviceBluetoothSync } from './use-device-bluetooth-sync' export function useDeviceDetail() { const deviceId = ref('') const deviceNo = ref('') const deviceMac = ref() const deviceName = ref('') const locationName = ref('客厅') const locationId = ref('') const homeId = ref('') const productModel = ref('CZ-Z2023') const deviceStatus = ref() const bluetoothConnected = ref(false) const charging = ref(false) const loading = ref(false) const isOnline = computed(() => bluetoothConnected.value) const runMode = ref('0') const fanLevel = ref('0') const tvoc = ref(null) const airQuality = ref() const powerMode = ref('0') const filterLife = ref(0) const filterTotalDays = ref(DEFAULT_FILTER_TOTAL_DAYS) const filterRemainText = ref('预计还可使用 -- 天') const filterReplaced = ref(false) const filterReplaceDialogVisible = ref(false) const batteryLevel = ref(null) let pendingBatteryReading: number | null = null const syncText = ref('数据实时同步中') const tvocDisplay = computed(() => formatTvocValue(tvoc.value ?? undefined)) const tvocLevel = computed(() => { if (airQuality.value) return airQualityToLabel(airQuality.value) return formatTvocLevel(tvoc.value ?? undefined) }) const powerModeText = computed(() => formatPowerMode(powerMode.value)) const batteryDisplay = computed(() => batteryLevel.value != null ? `${batteryLevel.value}%` : '--', ) const connectionText = computed(() => formatConnectionText({ status: deviceStatus.value, bluetoothConnected: bluetoothConnected.value ? '1' : '0', locationName: locationName.value, }), ) const showFanLevelControl = computed(() => isAutoRunMode(runMode.value)) const fanLevelOptions = computed(() => showFanLevelControl.value ? AUTO_FAN_LEVEL_OPTIONS : [], ) function updateFilterRemainText() { filterRemainText.value = formatFilterRemainDays(filterLife.value, filterTotalDays.value) } function applyBatteryLevel(next: number, smooth = false) { if (!smooth) { batteryLevel.value = clampPercent(next) pendingBatteryReading = null return } const result = stabilizePercentReading( batteryLevel.value, next, pendingBatteryReading, ) batteryLevel.value = result.value pendingBatteryReading = result.pending } async function loadFilterTotalDays() { filterTotalDays.value = DEFAULT_FILTER_TOTAL_DAYS try { const options = await fetchProductOptions() const matched = options.find((item) => item.model === productModel.value) ?? options.find((item) => item.filterEnabled && item.filterTotalDays) ?? options.find((item) => item.filterTotalDays) if (matched?.filterTotalDays && matched.filterTotalDays > 0) { filterTotalDays.value = matched.filterTotalDays if (matched.model) productModel.value = matched.model } } catch { // 产品配置加载失败时使用默认总天数 } updateFilterRemainText() } function applyBleRuntime(patch: BleRuntimePatch) { if (patch.runMode != null) runMode.value = patch.runMode as RunMode if (patch.fanLevel != null) fanLevel.value = patch.fanLevel as FanLevel if (patch.airQuality != null) { airQuality.value = patch.airQuality tvoc.value = airQualityToTvoc(patch.airQuality) ?? tvoc.value } else if (patch.tvoc != null) { tvoc.value = patch.tvoc } if (patch.powerMode != null) powerMode.value = patch.powerMode if (patch.filterLife != null) { filterLife.value = patch.filterLife updateFilterRemainText() } if (patch.deviceBattery != null) applyBatteryLevel(patch.deviceBattery, true) if (patch.charging != null) charging.value = patch.charging === '1' } function applyRuntime(data: AppDeviceRuntimeVo) { const view = mapRuntimeToView(data, deviceName.value, filterTotalDays.value) deviceName.value = view.deviceName runMode.value = view.runMode fanLevel.value = view.fanLevel if (view.tvoc != null) tvoc.value = view.tvoc powerMode.value = view.powerMode filterLife.value = view.filterLife filterRemainText.value = view.filterRemainText filterReplaced.value = view.filterReplaced if (data.deviceBattery != null) applyBatteryLevel(data.deviceBattery, false) if (!bluetoothConnected.value && data.status !== undefined) { deviceStatus.value = data.status } } async function refreshDeviceMeta() { if (!deviceId.value) return const bleConnectedLocally = bluetoothConnected.value try { const list = await fetchDeviceList() const device = list?.find((item) => String(item.deviceId) === deviceId.value) if (!device) return if (device.deviceId != null) deviceId.value = String(device.deviceId) if (device.deviceNo) deviceNo.value = device.deviceNo if (device.mac) deviceMac.value = device.mac const parsedLocationId = parseId(device.locationId) if (parsedLocationId) locationId.value = parsedLocationId const parsedHomeId = parseId(device.homeId) if (parsedHomeId) homeId.value = parsedHomeId if (parsedHomeId && parsedLocationId) { const locations = await fetchRoomList(parsedHomeId) const matched = locations.find((item) => sameId(item.locationId, parsedLocationId)) if (matched) locationName.value = matched.name } charging.value = device.charging === '1' if (!bleConnectedLocally) { bluetoothConnected.value = isBluetoothConnected(device.bluetoothConnected) deviceStatus.value = bluetoothConnected.value ? '1' : (device.status === '0' ? '0' : '2') } } catch { // 列表刷新失败时保留路由参数状态 } } async function loadRuntime() { if (!deviceId.value) return loading.value = true try { const [runtime] = await Promise.all([ fetchDeviceRuntime({ deviceId: deviceId.value }), refreshDeviceMeta(), loadFilterTotalDays(), ]) applyRuntime(runtime) } catch (err) { uni.showToast({ title: getErrorMessage(err, '加载设备数据失败'), icon: 'none' }) } finally { loading.value = false } } async function patchRuntime(patch: { runMode?: RunMode; fanLevel?: FanLevel }) { if (!deviceId.value) return if (patch.runMode != null && runMode.value === patch.runMode) return if (patch.fanLevel != null && fanLevel.value === patch.fanLevel) return const snapshot = { runMode: runMode.value, fanLevel: fanLevel.value } if (patch.runMode != null) runMode.value = patch.runMode if (patch.fanLevel != null) fanLevel.value = patch.fanLevel const bleCmd = patch.runMode != null ? encodeRunModeBleCommand(patch.runMode) : patch.fanLevel != null ? encodeFanLevelBleCommand(patch.fanLevel) : undefined try { const apiTask = updateDeviceRuntime({ deviceId: deviceId.value, ...patch, }) if (bleCmd) { const [bleOk] = await Promise.all([sendBleCommand(bleCmd), apiTask]) if (!bleOk) { throw new Error('蓝牙指令发送失败') } } else { await apiTask } } catch (err) { runMode.value = snapshot.runMode fanLevel.value = snapshot.fanLevel uni.showToast({ title: getErrorMessage(err, '设置失败'), icon: 'none' }) } } function onSelectRunMode(mode: RunMode) { if (runMode.value === mode) return void patchRuntime({ runMode: mode }) } function onSelectFanLevel(level: FanLevel) { if (!isAutoRunMode(runMode.value)) return if (fanLevel.value === level) return void patchRuntime({ fanLevel: level }) } function onSettings() { if (!deviceId.value) { uni.showToast({ title: '设备信息不完整', icon: 'none' }) return } const q = [ `deviceId=${deviceId.value}`, ...(deviceNo.value ? [`deviceNo=${encodeURIComponent(deviceNo.value)}`] : []), `name=${encodeURIComponent(deviceName.value)}`, `locationName=${encodeURIComponent(locationName.value)}`, ...(locationId.value ? [`locationId=${locationId.value}`] : []), ...(homeId.value ? [`homeId=${homeId.value}`] : []), `model=${encodeURIComponent(productModel.value)}`, `bluetoothConnected=${bluetoothConnected.value ? '1' : '0'}`, ].join('&') uni.navigateTo({ url: `/pages/device/settings/index?${q}` }) } function onFilterReplace() { if (filterReplaced.value) return filterReplaceDialogVisible.value = true } async function onConfirmFilterReplace() { await sendBleCommand(Z2_BLE_CMD.FILTER_RESET) filterReplaced.value = true filterLife.value = 100 updateFilterRemainText() uni.showToast({ title: '操作成功', icon: 'success' }) } const { startSyncLoop, sendBleCommand } = useDeviceBluetoothSync({ getDeviceId: () => deviceId.value, getMac: () => deviceMac.value, getDeviceName: () => deviceName.value, getRuntimePatch: () => ({ runMode: runMode.value, fanLevel: fanLevel.value, tvoc: tvoc.value ?? (airQuality.value ? airQualityToTvoc(airQuality.value) : undefined), powerMode: powerMode.value, charging: charging.value ? '1' : '0', }), onBluetoothConnectedChange: (connected) => { bluetoothConnected.value = connected deviceStatus.value = connected ? '1' : '2' }, onSyncTextChange: (text) => { syncText.value = text }, onBleRuntimeRead: (patch) => { applyBleRuntime(patch) }, onSynced: async () => { await refreshDeviceMeta() }, }) onLoad((query?: DeviceDetailRouteQuery) => { deviceId.value = parseDeviceId(query?.deviceId) if (query?.deviceNo) { deviceNo.value = decodeURIComponent(String(query.deviceNo)) } if (query?.name) deviceName.value = decodeURIComponent(String(query.name)) if (query?.locationName) { locationName.value = decodeURIComponent(String(query.locationName)) } const parsedLocationId = parseId(query?.locationId) if (parsedLocationId) locationId.value = parsedLocationId const parsedHomeId = parseId(query?.homeId) if (parsedHomeId) homeId.value = parsedHomeId if (query?.model) productModel.value = decodeURIComponent(String(query.model)) if (query?.mac) deviceMac.value = decodeURIComponent(String(query.mac)) bluetoothConnected.value = false deviceStatus.value = '2' charging.value = query?.charging === '1' void loadRuntime().then(() => { startSyncLoop() }) }) return { deviceName, connectionText, isOnline, tvocDisplay, tvocLevel, syncText, runMode, fanLevel, powerModeText, filterLife, filterRemainText, filterReplaced, filterReplaceDialogVisible, batteryDisplay, batteryLevel, charging, loading, showFanLevelControl, runModeOptions: RUN_MODE_OPTIONS, fanLevelOptions, onSelectRunMode, onSelectFanLevel, onSettings, onFilterReplace, onConfirmFilterReplace, } }