import { onShow, onUnload } from '@dcloudio/uni-app' import { computed, ref } from 'vue' import { resolveValidHomeId } from '@/api/home' import { getErrorMessage } from '@/utils/api-error' import { fetchRoomList } from '@/api/location' import type { RoomOption } from '@/types/location' import { fetchAllDeviceList } from '@/pages/device/device.api' import { updateDeviceRuntime } from '@/pages/device/detail/device-detail.api' import { updateDeviceSettings } from '@/pages/device/settings/device-settings.api' import { buildBleDeviceName, isStandardBleDeviceName } from '@/utils/ble-device-name' import { releaseBleDevice } from '@/utils/bluetooth' import { clearZ2BleHandleCache, sendZ2BleRenameCommand } from '@/utils/z2-ble' import { bindDevice } from '../add-device.api' import { parseId, sameId } from '@/utils/device-id' import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home' import { readBindDeviceContext } from '../add-device.types' import { fetchProductOptions } from './complete.api' import type { ProductOption } from './complete.types' export function useCompleteDevice() { const currentStep = 4 const deviceNo = ref('') const deviceName = ref('Z2 空气净化器') /** 配对时读到的 BLE 广播名,与用户可改的云端显示名无关 */ const pairedBleName = ref('') const serialMasked = ref('****A3B2') const productId = ref('') const model = ref('') const productOptions = ref([]) const productOptionsLoading = ref(false) const productIndex = ref(0) const imei = ref() const mac = ref() const homeId = ref('') const roomOptions = ref([]) const roomOptionsLoading = ref(false) const roomName = ref('请选择所在房间') const locationId = ref() const loading = ref(false) const initialized = ref(false) const bluetoothConnected = ref(false) const bleDeviceId = ref('') const roomSelected = computed(() => !!locationId.value && roomName.value !== '请选择所在房间') const productSelected = computed(() => !!productId.value && !!model.value) const productDisplayText = computed(() => { if (productOptionsLoading.value) return '加载中...' if (model.value) return model.value return '请选择产品型号' }) const bluetoothStatusText = computed(() => bluetoothConnected.value ? '蓝牙已连接' : '蓝牙未连接', ) function applyProduct(option: ProductOption) { const parsedProductId = parseId(option.productId) if (parsedProductId) productId.value = parsedProductId if (option.model) model.value = option.model const index = productOptions.value.findIndex((item) => sameId(item.productId, option.productId)) if (index >= 0) productIndex.value = index } function syncProductFromOptions() { const options = productOptions.value if (!options.length) return if (productId.value) { const matched = options.find((item) => sameId(item.productId, productId.value)) if (matched) { applyProduct(matched) return } } if (model.value) { const matched = options.find((item) => item.model === model.value) if (matched) { applyProduct(matched) return } } applyProduct(options[0]) } async function loadProductOptions() { if (productOptionsLoading.value) return productOptionsLoading.value = true try { productOptions.value = await fetchProductOptions() if (productOptions.value.length) { syncProductFromOptions() } else { productId.value = '' model.value = '' productIndex.value = 0 } } catch (err) { uni.showToast({ title: getErrorMessage(err, '加载产品型号失败'), icon: 'none' }) } finally { productOptionsLoading.value = false } } function syncRoomFromOptions() { if (locationId.value) { const matched = roomOptions.value.find((item) => sameId(item.locationId, locationId.value), ) if (matched) { roomName.value = matched.name return } } const first = roomOptions.value[0] if (first && !locationId.value) { roomName.value = first.name locationId.value = String(first.locationId) } } async function loadRoomOptionList() { if (roomOptionsLoading.value) return roomOptionsLoading.value = true try { homeId.value = await resolveValidHomeId(homeId.value) if (!homeId.value) { uni.showToast({ title: '未找到家庭信息', icon: 'none' }) return } roomOptions.value = await fetchRoomList(homeId.value) if (roomOptions.value.length) { syncRoomFromOptions() } else { roomName.value = '请选择所在房间' locationId.value = '' } } catch (err) { uni.showToast({ title: getErrorMessage(err, '加载房间列表失败'), icon: 'none' }) } finally { roomOptionsLoading.value = false } } function applyQuery(query: Record) { const ctx = readBindDeviceContext(query) if (ctx.deviceNo) deviceNo.value = ctx.deviceNo if (ctx.name) { deviceName.value = ctx.name pairedBleName.value = ctx.name } if (ctx.serialMasked) serialMasked.value = ctx.serialMasked const parsedProductId = parseId(ctx.productId) if (parsedProductId) productId.value = parsedProductId if (ctx.model) model.value = ctx.model if (productOptions.value.length) { syncProductFromOptions() } if (ctx.imei) imei.value = ctx.imei if (ctx.mac) mac.value = ctx.mac const parsedHomeId = parseId(ctx.homeId) if (parsedHomeId) homeId.value = parsedHomeId bluetoothConnected.value = ctx.bluetoothConnected === '1' if (ctx.bleDeviceId) bleDeviceId.value = ctx.bleDeviceId if (roomOptions.value.length) { syncRoomFromOptions() } } async function initPage(query: Record) { applyQuery(query) if (!homeId.value) { homeId.value = readStoredHomeId() } await Promise.all([loadRoomOptionList(), loadProductOptions()]) if (homeId.value) { saveSelectedHomeId(homeId.value) } initialized.value = true } function onPickProduct() { if (productOptionsLoading.value) { uni.showToast({ title: '产品型号加载中', icon: 'none' }) return } const options = productOptions.value if (!options.length) { uni.showToast({ title: '暂无产品型号,请稍后重试', icon: 'none' }) void loadProductOptions() return } const labels = options.map((item) => item.model || item.name || '未知型号') uni.showActionSheet({ itemList: labels.slice(0, 6), success: (res) => { const option = options[res.tapIndex] if (option) applyProduct(option) }, }) } function onPickRoom() { if (roomOptionsLoading.value) { uni.showToast({ title: '房间列表加载中', icon: 'none' }) return } if (!homeId.value) { uni.showToast({ title: '未找到家庭信息', icon: 'none' }) return } const params = [ `homeId=${homeId.value}`, ...(locationId.value ? [`locationId=${locationId.value}`] : []), `locationName=${encodeURIComponent(roomName.value)}`, ] uni.navigateTo({ url: `/pages/device/settings/room/index?${params.join('&')}`, events: { roomSelected: (data: { locationId: string | number; name: string }) => { locationId.value = String(data.locationId) roomName.value = data.name }, }, }) } async function onFinishAdd() { const name = deviceName.value.trim() if (!name) { uni.showToast({ title: '请输入设备名称', icon: 'none' }) return } if (!deviceNo.value.trim()) { uni.showToast({ title: '缺少设备编号', icon: 'none' }) return } if (!locationId.value) { uni.showToast({ title: '请选择所在房间', icon: 'none' }) return } if (!bluetoothConnected.value) { uni.showToast({ title: '设备未连接蓝牙,请返回重新配对', icon: 'none' }) return } if (loading.value) return loading.value = true try { if (bleDeviceId.value && bluetoothConnected.value && mac.value) { const bleName = buildBleDeviceName(mac.value) const needRename = pairedBleName.value && !isStandardBleDeviceName(mac.value, pairedBleName.value) if (needRename) { try { await sendZ2BleRenameCommand(bleDeviceId.value, bleName, { timeoutMs: 25000, }) } catch { // 蓝牙名称同步失败不影响云端绑定,静默继续 } } } const validHomeId = await resolveValidHomeId(homeId.value) homeId.value = validHomeId if (validHomeId) saveSelectedHomeId(validHomeId) await bindDevice({ deviceNo: deviceNo.value.trim(), name, productId: productId.value, model: model.value, ...(imei.value ? { imei: imei.value } : {}), ...(mac.value ? { mac: mac.value } : {}), ...(validHomeId ? { homeId: validHomeId } : {}), ...(locationId.value ? { locationId: locationId.value } : {}), }) const list = await fetchAllDeviceList() const bound = list?.find((item) => item.deviceNo === deviceNo.value.trim()) if (bound?.deviceId != null) { const boundName = bound.name?.trim() if (boundName !== name) { await updateDeviceSettings({ deviceId: bound.deviceId, name, }) } await updateDeviceRuntime({ deviceId: bound.deviceId, status: bluetoothConnected.value ? '1' : '2', bluetoothConnected: bluetoothConnected.value ? '1' : '0', }) } uni.showToast({ title: '添加成功', icon: 'success' }) setTimeout(() => { uni.reLaunch({ url: '/pages/device/index' }) }, 400) } catch (err) { uni.showToast({ title: getErrorMessage(err, '绑定失败,请重试'), icon: 'none' }) } finally { loading.value = false } } onShow(() => { uni.hideLoading() if (!initialized.value || !homeId.value) return void loadRoomOptionList() }) onUnload(() => { uni.hideLoading() if (bleDeviceId.value) { clearZ2BleHandleCache(bleDeviceId.value) void releaseBleDevice(bleDeviceId.value) } }) return { currentStep, deviceName, serialMasked, productOptions, productIndex, productDisplayText, productSelected, productOptionsLoading, roomName, roomSelected, roomOptionsLoading, loading, bluetoothConnected, bluetoothStatusText, initPage, onPickProduct, onPickRoom, onFinishAdd, } }