fix:最新

This commit is contained in:
李伊帆
2026-10-23 10:26:54 +08:00
parent e4276b0853
commit 28531c8120
104 changed files with 3248 additions and 722 deletions

View File

@@ -45,7 +45,7 @@
border-radius: 24rpx;
display: flex;
align-items: center;
justify-content: space-between;
justify-content: center;
padding: 0 40rpx;
background: linear-gradient(98deg, #45d685 0%, #21c25e 100%);
box-shadow: 0 8rpx 28rpx rgba(33, 194, 94, 0.28);
@@ -61,6 +61,8 @@
font-size: 32rpx;
font-weight: 500;
color: #fff;
text-align: center;
line-height: 1;
}
.add-device-page__btn-badge {

View File

@@ -31,7 +31,9 @@ export interface BindDeviceContext {
model?: string
imei?: string
mac?: string
homeId?: string | number
bluetoothConnected?: string
bleDeviceId?: string
}
export function buildBindDeviceQuery(ctx: BindDeviceContext): string {
@@ -44,9 +46,13 @@ export function buildBindDeviceQuery(ctx: BindDeviceContext): string {
if (ctx.model) parts.push(`model=${encodeURIComponent(ctx.model)}`)
if (ctx.imei) parts.push(`imei=${encodeURIComponent(ctx.imei)}`)
if (ctx.mac) parts.push(`mac=${encodeURIComponent(ctx.mac)}`)
if (ctx.homeId != null) parts.push(`homeId=${ctx.homeId}`)
if (ctx.bluetoothConnected) {
parts.push(`bluetoothConnected=${ctx.bluetoothConnected}`)
}
if (ctx.bleDeviceId) {
parts.push(`bleId=${encodeURIComponent(ctx.bleDeviceId)}`)
}
return parts.join('&')
}
@@ -68,8 +74,10 @@ export function readBindDeviceContext(
if (query.model) ctx.model = decodeURIComponent(String(query.model))
if (query.imei) ctx.imei = decodeURIComponent(String(query.imei))
if (query.mac) ctx.mac = decodeURIComponent(String(query.mac))
if (query.homeId) ctx.homeId = String(query.homeId)
if (query.bluetoothConnected) {
ctx.bluetoothConnected = String(query.bluetoothConnected)
}
if (query.bleId) ctx.bleDeviceId = decodeURIComponent(String(query.bleId))
return ctx
}

View File

@@ -1,12 +1,21 @@
.complete-page {
min-height: 100vh;
height: 100vh;
overflow: hidden;
background: $color-bg-page;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.complete-page__top {
flex-shrink: 0;
z-index: 10;
background: $color-bg-page;
}
.complete-page__scroll {
flex: 1;
min-height: 0;
width: 100%;
}
@@ -217,6 +226,7 @@
}
.complete-page__footer {
flex-shrink: 0;
padding: 16rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
background: $color-bg-page;
}

View File

@@ -1,7 +1,9 @@
<template>
<view class="complete-page">
<app-navbar title="设备配置" />
<page-scroll-view class="complete-page__scroll">
<view class="complete-page__top">
<app-navbar title="设备配置" />
</view>
<page-scroll-view class="complete-page__scroll" :scroll-style="scrollStyle">
<view class="complete-page__body">
<bind-steps :steps="BIND_STEPS" :current="currentStep" />
<complete-success-hero />
@@ -124,7 +126,15 @@
<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
import { staticAssets } from '@/utils/static-assets'
const sys = uni.getSystemInfoSync()
const footerExtraPx = uni.upx2px(136) + (sys.safeAreaInsets?.bottom ?? 0)
const { scrollStyle } = usePageScrollHeight({
topSelector: '.complete-page__top',
extraBottomPx: footerExtraPx,
})
import BindSteps from '../components/bind-steps/index.vue'
import { BIND_STEPS } from '../use-add-device'
import CompleteSuccessHero from './components/complete-success-hero/index.vue'

View File

@@ -1,4 +1,4 @@
import { onShow } from '@dcloudio/uni-app'
import { onShow, onUnload } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { resolveValidHomeId } from '@/api/home'
import { getErrorMessage } from '@/utils/api-error'
@@ -6,8 +6,17 @@ import { fetchRoomList } from '@/api/location'
import type { RoomOption } from '@/types/location'
import { fetchDeviceList } 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 {
getZ2RenameProgressLabel,
isZ2RenameSuccessful,
} from '@/utils/z2-ble-protocol'
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'
@@ -32,6 +41,7 @@ export function useCompleteDevice() {
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)
@@ -145,7 +155,10 @@ export function useCompleteDevice() {
}
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()
}
@@ -153,7 +166,13 @@ export function useCompleteDevice() {
async function initPage(query: Record<string, string | undefined>) {
applyQuery(query)
if (!homeId.value) {
homeId.value = readStoredHomeId()
}
await Promise.all([loadRoomOptionList(), loadProductOptions()])
if (homeId.value) {
saveSelectedHomeId(homeId.value)
}
initialized.value = true
}
@@ -228,8 +247,41 @@ export function useCompleteDevice() {
loading.value = true
try {
if (bleDeviceId.value && bluetoothConnected.value && mac.value) {
const bleName = buildBleDeviceName(mac.value)
const needRename = !isStandardBleDeviceName(mac.value, deviceName.value)
if (needRename) {
uni.showLoading({ title: '正在同步蓝牙名称…', mask: true })
try {
const renameProgress = await sendZ2BleRenameCommand(bleDeviceId.value, bleName, {
timeoutMs: 25000,
onProgress: (progress) => {
uni.showLoading({
title: getZ2RenameProgressLabel(progress) || '正在同步蓝牙名称…',
mask: true,
})
},
})
if (!isZ2RenameSuccessful(renameProgress)) {
uni.showToast({
title: '蓝牙名称同步未完成,将继续添加设备',
icon: 'none',
})
}
} catch {
uni.showToast({
title: '蓝牙名称同步失败,将继续添加设备',
icon: 'none',
})
} finally {
uni.hideLoading()
}
}
}
const validHomeId = await resolveValidHomeId(homeId.value)
homeId.value = validHomeId
if (validHomeId) saveSelectedHomeId(validHomeId)
await bindDevice({
deviceNo: deviceNo.value.trim(),
name,
@@ -244,6 +296,13 @@ export function useCompleteDevice() {
const list = await fetchDeviceList()
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',
@@ -263,10 +322,19 @@ export function useCompleteDevice() {
}
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,

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="add-device-page">
<app-navbar title="添加设备" />
<page-scroll-view class="add-device-page__scroll">
@@ -30,12 +30,17 @@
</template>
<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import BindBluetoothHero from './components/bind-bluetooth-hero/index.vue'
import BindFeatureList from './components/bind-feature-list/index.vue'
import BindSteps from './components/bind-steps/index.vue'
import { BIND_FEATURES, BIND_STEPS, useAddDevice } from './use-add-device'
const { currentStep, opening, onOpenBluetooth, onBindLater } = useAddDevice()
const { currentStep, opening, applyBindHomeId, onOpenBluetooth, onBindLater } = useAddDevice()
onLoad((query) => {
applyBindHomeId(query?.homeId)
})
</script>
<style lang="scss" scoped>

View File

@@ -1,7 +1,9 @@
<template>
<template>
<view class="pair-page">
<app-navbar title="设备配置" />
<page-scroll-view class="pair-page__scroll">
<view class="pair-page__top">
<app-navbar title="设备配置" />
</view>
<page-scroll-view class="pair-page__scroll" :scroll-style="scrollStyle">
<view class="pair-page__body">
<bind-steps :steps="BIND_STEPS" :current="currentStep" />
<pair-hero />
@@ -32,28 +34,29 @@
<pair-check-list :items="checkItems" />
<pair-device-summary :device="device" :connect-status="connectStatus" />
<view class="pair-page__footer">
<view
v-if="connectStatus === 'failed'"
class="pair-page__retry"
@tap="onRetryPair"
>
<text class="pair-page__retry-text">重新连接</text>
</view>
<view class="pair-page__cancel" @tap="onFooterCancel">
<text class="pair-page__cancel-text">
{{ connectStatus === 'failed' ? '返回' : '取消配对' }}
</text>
</view>
</view>
</view>
</page-scroll-view>
<view class="pair-page__footer">
<view
v-if="connectStatus === 'failed'"
class="pair-page__retry"
@tap="onRetryPair"
>
<text class="pair-page__retry-text">重新连接</text>
</view>
<view class="pair-page__cancel" @tap="onFooterCancel">
<text class="pair-page__cancel-text">
{{ connectStatus === 'failed' ? '返回' : '取消配对' }}
</text>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
import BindSteps from '../components/bind-steps/index.vue'
import { BIND_STEPS } from '../use-add-device'
import { readBindDeviceContext } from '../add-device.types'
@@ -62,6 +65,8 @@ import PairDeviceSummary from './components/pair-device-summary/index.vue'
import PairHero from './components/pair-hero/index.vue'
import { usePairDevice } from './use-pair-device'
const { scrollStyle } = usePageScrollHeight({ topSelector: '.pair-page__top' })
const {
currentStep,
device,
@@ -69,6 +74,7 @@ const {
progress,
errorMessage,
checkItems,
applyBindHomeId,
applyDevice,
startPairing,
onCancelPair,
@@ -108,6 +114,7 @@ function onFooterCancel() {
onLoad((query) => {
const ctx = readBindDeviceContext(query ?? {})
applyBindHomeId(ctx.homeId)
applyDevice({
name: ctx.name ?? '',
serialMasked: ctx.serialMasked ?? '',

View File

@@ -1,17 +1,26 @@
.pair-page {
min-height: 100vh;
height: 100vh;
overflow: hidden;
background: $color-bg-page;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.pair-page__top {
flex-shrink: 0;
z-index: 10;
background: $color-bg-page;
}
.pair-page__scroll {
flex: 1;
min-height: 0;
width: 100%;
}
.pair-page__body {
padding-bottom: 24rpx;
padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
}
.pair-page__status {
@@ -117,8 +126,8 @@
}
.pair-page__footer {
padding: 16rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
background: $color-bg-page;
margin-top: 40rpx;
padding: 0 32rpx;
}
.pair-page__cancel {

View File

@@ -1,12 +1,17 @@
import { onUnmounted, ref } from 'vue'
import {
closeAllBleConnections,
ensureBleConnection,
ensureBluetoothReady,
getBluetoothErrorMessage,
isBluetoothApiSupported,
releaseBleDevice,
scanForBleDeviceByMac,
stopBluetoothDiscovery,
} from '@/utils/bluetooth'
import { queryZ2BleState } from '@/utils/z2-ble'
import { clearZ2BleHandleCache, queryZ2BleState } from '@/utils/z2-ble'
import { parseId } from '@/utils/device-id'
import { readStoredHomeId } from '@/utils/selected-home'
import { buildBindDeviceQuery } from '../add-device.types'
import type { PairCheckItem, PairConnectStatus, PairDeviceInfo } from './pair.types'
@@ -20,6 +25,7 @@ const SCAN_TIMEOUT_MS = 15000
export function usePairDevice() {
const currentStep = 3
const bindHomeId = ref('')
const device = ref<PairDeviceInfo>({ ...DEFAULT_DEVICE })
const connectStatus = ref<PairConnectStatus>('connecting')
const progress = ref(0)
@@ -73,6 +79,13 @@ export function usePairDevice() {
}
await ensureBluetoothReady()
await stopBluetoothDiscovery().catch(() => {})
if (bleDeviceId) {
clearZ2BleHandleCache(bleDeviceId)
await releaseBleDevice(bleDeviceId)
bleDeviceId = undefined
}
await closeAllBleConnections()
updateCheck('signal', 'done', '良好')
progress.value = 30
@@ -98,6 +111,13 @@ export function usePairDevice() {
progress.value = 70
updateCheck('network', 'syncing', '连接中')
if (bleDeviceId && bleDeviceId !== found.deviceId) {
clearZ2BleHandleCache(bleDeviceId)
await releaseBleDevice(bleDeviceId)
}
clearZ2BleHandleCache(found.deviceId)
await releaseBleDevice(found.deviceId)
await new Promise((resolve) => setTimeout(resolve, 400))
await ensureBleConnection(found.deviceId)
bleDeviceId = found.deviceId
@@ -120,7 +140,9 @@ export function usePairDevice() {
model: d.model,
imei: d.imei,
mac: d.mac,
...(bindHomeId.value ? { homeId: bindHomeId.value } : {}),
bluetoothConnected: '1',
bleDeviceId: bleDeviceId,
})
setTimeout(() => {
@@ -140,11 +162,26 @@ export function usePairDevice() {
}
}
function applyBindHomeId(homeId?: string | number) {
const parsed = parseId(homeId)
if (parsed) {
bindHomeId.value = parsed
return
}
if (!bindHomeId.value) {
bindHomeId.value = readStoredHomeId()
}
}
function applyDevice(partial?: Partial<PairDeviceInfo>) {
device.value = { ...device.value, ...partial }
}
onUnmounted(() => {
if (bleDeviceId) {
clearZ2BleHandleCache(bleDeviceId)
void releaseBleDevice(bleDeviceId)
}
bleDeviceId = undefined
})
@@ -171,6 +208,7 @@ export function usePairDevice() {
progress,
errorMessage,
checkItems,
applyBindHomeId,
applyDevice,
startPairing,
onCancelPair,

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="scan-page">
<app-navbar title="扫描设备" />
<page-scroll-view class="scan-page__scroll">
@@ -6,8 +6,8 @@
<bind-steps :steps="BIND_STEPS" :current="currentStep" />
<scan-hero />
<view class="scan-page__status">
<text class="scan-page__title">正在扫描附近设备...</text>
<view class="scan-page__hint">
<text class="scan-page__title">{{ pageTitle }}</text>
<view v-if="!bluetoothDisabled" class="scan-page__hint">
<view class="scan-page__hint-dot" />
<text class="scan-page__hint-text">{{ statusHint }}</text>
</view>
@@ -20,7 +20,18 @@
</text>
</view>
<view v-if="scanError" class="scan-page__empty">
<view v-if="bluetoothDisabled" class="scan-page__empty scan-page__empty--bt">
<text class="scan-page__empty-text">{{ scanError }}</text>
<view class="scan-page__bt-actions">
<view class="scan-page__bt-btn scan-page__bt-btn--primary" @tap="onOpenBluetoothSettings">
<text class="scan-page__bt-btn-text">去开启蓝牙</text>
</view>
<view class="scan-page__bt-btn" @tap="onRetryScan">
<text class="scan-page__bt-btn-text scan-page__bt-btn-text--muted">已开启,重试扫描</text>
</view>
</view>
</view>
<view v-else-if="scanError" class="scan-page__empty">
<text class="scan-page__empty-text">{{ scanError }}</text>
</view>
<view v-else-if="devices.length === 0" class="scan-page__empty">
@@ -47,6 +58,7 @@
<script setup lang="ts">
import { computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import BindSteps from '../components/bind-steps/index.vue'
import { BIND_STEPS } from '../use-add-device'
import ScanDeviceItem from './components/scan-device-item/index.vue'
@@ -61,10 +73,22 @@ const {
secondsLeft,
scanning,
scanError,
bluetoothDisabled,
applyBindHomeId,
onRetryScan,
onOpenBluetoothSettings,
onSelectDevice,
onDeviceAction,
} = useScanDevice()
onLoad((query) => {
applyBindHomeId(query?.homeId)
})
const pageTitle = computed(() =>
bluetoothDisabled.value ? '蓝牙未开启' : '正在扫描附近设备...',
)
const statusHint = computed(() => {
const count = devices.value.length
if (scanning.value) {

View File

@@ -91,3 +91,41 @@
line-height: 1.65;
text-align: center;
}
.scan-page__empty--bt {
display: flex;
flex-direction: column;
align-items: center;
gap: 32rpx;
}
.scan-page__bt-actions {
width: 100%;
display: flex;
flex-direction: column;
gap: 16rpx;
}
.scan-page__bt-btn {
height: 88rpx;
border-radius: 16rpx;
background: #f5f6f8;
display: flex;
align-items: center;
justify-content: center;
}
.scan-page__bt-btn--primary {
background: linear-gradient(98deg, #45d685 0%, #21c25e 100%);
}
.scan-page__bt-btn-text {
font-size: 30rpx;
font-weight: 600;
color: #fff;
}
.scan-page__bt-btn-text--muted {
color: $color-text;
font-weight: 500;
}

View File

@@ -1,37 +1,38 @@
import {
isBrandBleDevice,
resolveBleDeviceDisplayName,
resolveBleDeviceMac,
} from '@/utils/ble-device-name'
import { normalizeMacAddress } from '@/utils/bluetooth'
import type { ScannedDeviceItem } from './scan.types'
function normalizeMac(deviceId: string): string | undefined {
const macPattern = /^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/
if (macPattern.test(deviceId)) return deviceId.toUpperCase()
return undefined
function formatDeviceSerial(deviceId: string, mac?: string): string {
if (mac) return mac
const normalized = normalizeMacAddress(deviceId)
return normalized ?? deviceId
}
/** 扫描列表展示用:优先 MAC,否则完整 deviceId */
function formatDeviceSerial(deviceId: string): string {
return normalizeMac(deviceId) ?? deviceId
function buildDeviceNo(mac?: string, deviceId?: string): string {
if (mac) return mac
const normalized = deviceId ? normalizeMacAddress(deviceId) : undefined
if (normalized) return normalized.replace(/:/g, '')
const compact = (deviceId || '').replace(/[^a-zA-Z0-9]/g, '').toUpperCase()
return compact || deviceId || ''
}
function buildDeviceNo(deviceId: string): string {
const mac = normalizeMac(deviceId)
if (mac) return mac.replace(/:/g, '')
const compact = deviceId.replace(/[^a-zA-Z0-9]/g, '').toUpperCase()
return compact || deviceId
}
/** 将蓝牙广播设备映射为扫描列表项(仅本品牌:Z2_A_<12位MAC>) */
export function mapBluetoothDevice(device: UniApp.BluetoothDeviceInfo): ScannedDeviceItem | null {
if (!isBrandBleDevice(device)) return null
function resolveDisplayName(device: UniApp.BluetoothDeviceInfo): string {
return (device.name || device.localName || '').trim() || '未命名设备'
}
/** 将蓝牙广播设备映射为扫描列表项(使用真实广播数据) */
export function mapBluetoothDevice(device: UniApp.BluetoothDeviceInfo): ScannedDeviceItem {
const serial = formatDeviceSerial(device.deviceId)
const mac = resolveBleDeviceMac(device)
const serial = formatDeviceSerial(device.deviceId, mac)
return {
id: device.deviceId,
name: resolveDisplayName(device),
name: resolveBleDeviceDisplayName(device),
serialMasked: serial,
deviceNo: buildDeviceNo(device.deviceId),
mac: normalizeMac(device.deviceId),
deviceNo: buildDeviceNo(mac, device.deviceId),
mac: mac ? normalizeMacAddress(mac) : normalizeMacAddress(device.deviceId),
canAdd: true,
}
}

View File

@@ -1,13 +1,19 @@
import { onShow } from '@dcloudio/uni-app'
import { onMounted, onUnmounted, ref } from 'vue'
import {
ensureBluetoothReady,
assertBluetoothEnabledForScan,
BLUETOOTH_DISABLED_MESSAGE,
getBluetoothErrorMessage,
getDiscoveredBluetoothDevices,
isBluetoothApiSupported,
isBluetoothDisabledError,
promptEnableBluetooth,
startBluetoothDiscovery,
stopBluetoothDiscovery,
subscribeBluetoothDevicesFound,
} from '@/utils/bluetooth'
import { parseId } from '@/utils/device-id'
import { readStoredHomeId } from '@/utils/selected-home'
import { buildBindDeviceQuery } from '../add-device.types'
import type { ScannedDeviceItem } from './scan.types'
import { mapBluetoothDevice } from './scan.utils'
@@ -16,13 +22,33 @@ const SCAN_SECONDS = 20
export function useScanDevice() {
const currentStep = 2
const bindHomeId = ref('')
const devices = ref<ScannedDeviceItem[]>([])
const selectedId = ref('')
const secondsLeft = ref(SCAN_SECONDS)
const scanning = ref(true)
const scanError = ref('')
const bluetoothDisabled = ref(false)
let unsubscribeFound: (() => void) | undefined
let timer: ReturnType<typeof setInterval> | undefined
function resetScanTimer() {
if (timer) clearInterval(timer)
secondsLeft.value = SCAN_SECONDS
scanning.value = true
timer = setInterval(() => {
if (secondsLeft.value <= 0) {
scanning.value = false
return
}
secondsLeft.value -= 1
if (secondsLeft.value === 0) {
scanning.value = false
void stopBluetoothDiscovery().catch(() => {})
}
}, 1000)
}
function upsertDevice(item: ScannedDeviceItem) {
const idx = devices.value.findIndex((d) => d.id === item.id)
@@ -36,10 +62,19 @@ export function useScanDevice() {
function ingestBluetoothDevices(found: UniApp.BluetoothDeviceInfo[]) {
for (const device of found) {
upsertDevice(mapBluetoothDevice(device))
const item = mapBluetoothDevice(device)
if (item) upsertDevice(item)
}
}
function handleBluetoothDisabled() {
scanning.value = false
bluetoothDisabled.value = true
scanError.value = BLUETOOTH_DISABLED_MESSAGE
void stopBluetoothDiscovery().catch(() => {})
promptEnableBluetooth()
}
async function beginDiscovery() {
if (!isBluetoothApiSupported()) {
scanning.value = false
@@ -47,9 +82,13 @@ export function useScanDevice() {
return
}
try {
await ensureBluetoothReady()
bluetoothDisabled.value = false
scanError.value = ''
try {
await assertBluetoothEnabledForScan()
unsubscribeFound?.()
unsubscribeFound = subscribeBluetoothDevicesFound((found) => {
ingestBluetoothDevices(found)
})
@@ -59,34 +98,53 @@ export function useScanDevice() {
await startBluetoothDiscovery()
} catch (err) {
if (isBluetoothDisabledError(err)) {
handleBluetoothDisabled()
return
}
scanning.value = false
scanError.value = getBluetoothErrorMessage(err)
uni.showToast({ title: scanError.value, icon: 'none' })
}
}
function onRetryScan() {
void beginDiscovery()
resetScanTimer()
}
function onOpenBluetoothSettings() {
promptEnableBluetooth()
}
onMounted(() => {
resetScanTimer()
void beginDiscovery()
})
const timer = setInterval(() => {
if (secondsLeft.value <= 0) {
scanning.value = false
return
}
secondsLeft.value -= 1
if (secondsLeft.value === 0) {
scanning.value = false
void stopBluetoothDiscovery().catch(() => {})
}
}, 1000)
onShow(() => {
if (!bluetoothDisabled.value) return
void beginDiscovery()
resetScanTimer()
})
onUnmounted(() => {
clearInterval(timer)
if (timer) clearInterval(timer)
unsubscribeFound?.()
void stopBluetoothDiscovery().catch(() => {})
})
function applyBindHomeId(homeId?: string | number) {
const parsed = parseId(homeId)
if (parsed) {
bindHomeId.value = parsed
return
}
if (!bindHomeId.value) {
bindHomeId.value = readStoredHomeId()
}
}
function onSelectDevice(id: string) {
selectedId.value = id
}
@@ -105,6 +163,7 @@ export function useScanDevice() {
model: device.model,
imei: device.imei,
mac: device.mac,
...(bindHomeId.value ? { homeId: bindHomeId.value } : {}),
})
uni.navigateTo({ url: `/pages/add-device/pair/index?${q}` })
}
@@ -116,6 +175,10 @@ export function useScanDevice() {
secondsLeft,
scanning,
scanError,
bluetoothDisabled,
applyBindHomeId,
onRetryScan,
onOpenBluetoothSettings,
onSelectDevice,
onDeviceAction,
}

View File

@@ -1,5 +1,13 @@
import { ref } from 'vue'
import { ensureBluetoothReady, getBluetoothErrorMessage } from '@/utils/bluetooth'
import {
assertBluetoothEnabledForScan,
getBluetoothErrorMessage,
isBluetoothApiSupported,
isBluetoothPermissionError,
promptEnableBluetooth,
} from '@/utils/bluetooth'
import { parseId } from '@/utils/device-id'
import { readStoredHomeId } from '@/utils/selected-home'
import { staticAssets } from '@/utils/static-assets'
import type { BindFeatureItem, BindStepItem } from './add-device.types'
@@ -34,20 +42,46 @@ export const BIND_FEATURES: BindFeatureItem[] = [
export function useAddDevice() {
const currentStep = 1
const opening = ref(false)
const bindHomeId = ref('')
function applyBindHomeId(homeId?: string | number) {
const parsed = parseId(homeId)
if (parsed) {
bindHomeId.value = parsed
return
}
if (!bindHomeId.value) {
bindHomeId.value = readStoredHomeId()
}
}
async function onOpenBluetooth() {
if (opening.value) return
opening.value = true
try {
await ensureBluetoothReady()
uni.navigateTo({ url: '/pages/add-device/scan/index' })
if (!isBluetoothApiSupported()) {
uni.showModal({
title: '无法使用蓝牙',
content: '当前环境不支持蓝牙,请使用 App 或微信小程序',
showCancel: false,
confirmText: '知道了',
})
return
}
await assertBluetoothEnabledForScan()
const q = bindHomeId.value ? `?homeId=${bindHomeId.value}` : ''
uni.navigateTo({ url: `/pages/add-device/scan/index${q}` })
} catch (err) {
uni.showModal({
title: '无法开启蓝牙',
content: getBluetoothErrorMessage(err),
showCancel: false,
confirmText: '知道了',
})
if (isBluetoothPermissionError(err)) {
uni.showModal({
title: '需要相关权限',
content: getBluetoothErrorMessage(err),
showCancel: false,
confirmText: '知道了',
})
return
}
promptEnableBluetooth()
} finally {
opening.value = false
}
@@ -60,6 +94,7 @@ export function useAddDevice() {
return {
currentStep,
opening,
applyBindHomeId,
onOpenBluetooth,
onBindLater,
}

View File

@@ -1,4 +1,4 @@
import { request } from '@/api/request'
import { requestPublic } from '@/api/request'
import type { ForgetPasswordResetBody } from '@/types/api'
import type { ChangePasswordForm } from './change-password.types'
@@ -9,7 +9,7 @@ export function resetPasswordByToken(data: ChangePasswordForm) {
newPassword: data.newPassword,
confirmPassword: data.confirmPassword,
}
return request<void>({
return requestPublic<void>({
url: '/app/auth/forgetPassword/doReset',
method: 'POST',
data: body,

View File

@@ -1,20 +1,38 @@
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error'
import { teardownMessageInbox } from '@/hooks/use-message-inbox'
import { ApiError, getErrorMessage } from '@/utils/api-error'
import { clearStoredToken } from '@/utils/auth-token'
import { markPasswordModified } from '@/utils/password-modified-at'
import { isValidStrongPassword, PASSWORD_INVALID_TOAST } from '@/utils/validate'
import { resetPasswordByToken } from './change-password.api'
const LOGIN_ROUTE = '/pages/login/index'
function isSessionInvalidError(err: unknown): boolean {
if (!(err instanceof ApiError)) return false
if (err.code === 401) return true
return /登录|token|认证|授权/i.test(err.message)
}
function redirectToLoginAfterPasswordChange(toastTitle = '密码修改成功,请重新登录') {
teardownMessageInbox()
clearStoredToken()
uni.showToast({ title: toastTitle, icon: 'none' })
setTimeout(() => {
uni.reLaunch({ url: LOGIN_ROUTE })
}, 800)
}
export function useChangePassword() {
const password = ref('')
const confirmPassword = ref('')
const resetToken = ref('')
const fromPrivacy = ref(false)
const loading = ref(false)
onLoad((query) => {
const raw = (query?.resetToken as string) || ''
resetToken.value = raw ? decodeURIComponent(raw) : ''
fromPrivacy.value = query?.from === 'privacy'
if (!resetToken.value) {
uni.showToast({ title: '请先完成验证码校验', icon: 'none' })
setTimeout(() => uni.navigateBack(), 1500)
@@ -42,15 +60,14 @@ export function useChangePassword() {
newPassword: password.value,
confirmPassword: confirmPassword.value,
})
uni.showToast({ title: '密码修改成功', icon: 'success' })
setTimeout(() => {
if (fromPrivacy.value) {
uni.navigateBack({ delta: 2 })
return
}
uni.reLaunch({ url: '/pages/login/index' })
}, 800)
markPasswordModified()
redirectToLoginAfterPasswordChange()
} catch (err) {
if (isSessionInvalidError(err)) {
markPasswordModified()
redirectToLoginAfterPasswordChange('登录状态已失效,请使用新密码重新登录')
return
}
uni.showToast({ title: getErrorMessage(err, '修改失败,请重试'), icon: 'none' })
} finally {
loading.value = false

View File

@@ -79,8 +79,8 @@ defineEmits<{
.device-empty__btn {
width: 100%;
width: 335px;
height: 48px;
max-width: 670rpx;
height: 96rpx;
border-radius: 15rpx;
display: flex;
align-items: center;
@@ -88,7 +88,7 @@ defineEmits<{
position: relative;
flex-shrink: 0;
background: linear-gradient(98deg, #45d685 0%, #21c25e 100%);
box-shadow: 0px 4px 14px 0px rgba(33, 194, 94, 0.28);
box-shadow: 0 8rpx 28rpx 0 rgba(33, 194, 94, 0.28);
}
.device-empty__btn-text {

View File

@@ -24,19 +24,26 @@
/>
<view v-if="pickerOpen" class="device-header__dropdown">
<view
class="device-header__option device-header__option--active"
@tap.stop="selectHome"
v-for="home in homes"
:key="String(home.id)"
class="device-header__option"
:class="{ 'device-header__option--active': isActiveHome(home) }"
@tap.stop="onSelectHome(home)"
>
<text class="device-header__option-text device-header__option-text--active">
{{ homeName }}
<text
class="device-header__option-text"
:class="{ 'device-header__option-text--active': isActiveHome(home) }"
>
{{ home.homeName || '我的家' }}
</text>
<image
v-if="isActiveHome(home)"
class="device-header__check-icon"
:src="staticAssets.iconHomeSelected"
mode="aspectFit"
/>
</view>
<view class="device-header__option" @tap.stop="selectManage">
<view class="device-header__option device-header__option--manage" @tap.stop="selectManage">
<text class="device-header__option-text">家庭管理</text>
</view>
</view>
@@ -74,10 +81,14 @@
<script setup lang="ts">
import { ref } from 'vue'
import { hasUnreadMessages } from '@/hooks/use-message-inbox'
import type { AppHomeVo } from '@/types/location'
import { parseId, sameId } from '@/utils/device-id'
import { staticAssets } from '@/utils/static-assets'
defineProps<{
const props = defineProps<{
homeName: string
homeId: string
homes: AppHomeVo[]
}>()
const emit = defineEmits<{
@@ -85,6 +96,7 @@ const emit = defineEmits<{
'add-device': []
scan: []
manage: []
'select-home': [home: AppHomeVo]
}>()
const pickerOpen = ref(false)
@@ -107,8 +119,14 @@ function closePicker() {
pickerOpen.value = false
}
function selectHome() {
function isActiveHome(home: AppHomeVo) {
const id = parseId(home.id)
return !!id && sameId(id, props.homeId)
}
function onSelectHome(home: AppHomeVo) {
closePicker()
emit('select-home', home)
}
function selectManage() {
@@ -221,6 +239,10 @@ function onScan() {
background: linear-gradient(98deg, #45d685 0%, #21c25e 100%);
}
.device-header__option--manage {
border-top: 1rpx solid #f0f0f0;
}
.device-header__option-text {
font-size: 30rpx;
font-weight: 500;

View File

@@ -54,6 +54,14 @@ defineEmits<{
.hot-devices__scroll {
width: 100%;
white-space: nowrap;
/* #ifdef APP-PLUS */
::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
/* #endif */
}
.hot-devices__list {

View File

@@ -1,20 +1,27 @@
<template>
<scroll-view class="room-tabs" scroll-x :show-scrollbar="false">
<view class="room-tabs__inner">
<view
v-for="room in rooms"
:key="room.id"
class="room-tabs__item"
:class="{ 'room-tabs__item--active': room.id === activeId }"
@tap="$emit('select', room.id)"
>
<text class="room-tabs__text">{{ room.name }}</text>
<view class="room-tabs-wrap">
<scroll-view
class="room-tabs"
scroll-x
:show-scrollbar="false"
:enable-flex="true"
>
<view class="room-tabs__inner">
<view
v-for="room in rooms"
:key="room.id"
class="room-tabs__item"
:class="{ 'room-tabs__item--active': room.id === activeId }"
@tap="$emit('select', room.id)"
>
<text class="room-tabs__text">{{ room.name }}</text>
</view>
<view class="room-tabs__item room-tabs__item--add" @tap="$emit('add')">
<text class="room-tabs__text">+ 添加</text>
</view>
</view>
<view class="room-tabs__item room-tabs__item--add" @tap="$emit('add')">
<text class="room-tabs__text">+ 添加</text>
</view>
</view>
</scroll-view>
</scroll-view>
</view>
</template>
<script setup lang="ts">
@@ -32,22 +39,37 @@ defineEmits<{
</script>
<style lang="scss" scoped>
.room-tabs-wrap {
padding: 8rpx 32rpx 24rpx;
box-sizing: border-box;
}
.room-tabs {
width: 100%;
white-space: nowrap;
padding: 8rpx 32rpx 24rpx;
/* #ifdef APP-PLUS */
::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
/* #endif */
}
.room-tabs__inner {
display: inline-flex;
align-items: center;
gap: 16rpx;
min-width: 100%;
box-sizing: border-box;
}
.room-tabs__item {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
padding: 16rpx 36rpx;
border-radius: 40rpx;
background: transparent;

View File

@@ -236,6 +236,12 @@
align-items: center;
justify-content: center;
box-sizing: border-box;
transition: background 0.15s ease, box-shadow 0.15s ease, transform 0.1s ease;
}
.device-detail-mode-item--pressed {
transform: scale(0.97);
opacity: 0.88;
}
.device-detail-mode-item--active {
@@ -266,6 +272,12 @@
display: flex;
align-items: center;
justify-content: center;
transition: background 0.15s ease, box-shadow 0.15s ease, transform 0.1s ease;
}
.device-detail-fan-item--pressed {
transform: scale(0.97);
opacity: 0.88;
}
.device-detail-fan-item--active {

View File

@@ -41,11 +41,10 @@ export function formatConnectionText(options: {
}): string {
const { status, bluetoothConnected, locationName } = options
if (status === '0') return `未激活 · ${locationName}`
if (status === '2' || !isDeviceOnline(status)) {
return `设备离线 · ${locationName}`
if (isBluetoothConnected(bluetoothConnected)) {
return `蓝牙已连接 · ${locationName}`
}
const btText = isBluetoothConnected(bluetoothConnected) ? '蓝牙已连接' : '蓝牙未连接'
return `${btText} · ${locationName}`
return `设备离线 · ${locationName}`
}
/** 供电模式:0USB 1电池 */

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="device-detail-page">
<view class="device-detail-hero" :style="{ paddingTop: statusBarHeight + 'px' }">
<image
@@ -65,6 +65,8 @@
:key="item.value"
class="device-detail-mode-item"
:class="{ 'device-detail-mode-item--active': runMode === item.value }"
hover-class="device-detail-mode-item--pressed"
hover-stay-time="80"
@tap="onSelectRunMode(item.value)"
>
<text class="device-detail-mode-item__text">{{ item.label }}</text>
@@ -84,6 +86,8 @@
:key="item.value"
class="device-detail-fan-item"
:class="{ 'device-detail-fan-item--active': fanLevel === item.value }"
hover-class="device-detail-fan-item--pressed"
hover-stay-time="80"
@tap="onSelectFanLevel(item.value)"
>
<text class="device-detail-fan-item__text">{{ item.label }}</text>

View File

@@ -1,4 +1,4 @@
import { onUnload } from '@dcloudio/uni-app'
import { onShow, onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error'
import {
@@ -6,6 +6,7 @@ import {
ensureBleConnection,
ensureBluetoothReady,
getBluetoothErrorMessage,
getConnectedBleDeviceByMac,
getDiscoveredBluetoothDevices,
isBluetoothApiSupported,
rssiToSignalLevel,
@@ -38,27 +39,14 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
let syncTimer: ReturnType<typeof setInterval> | undefined
let unsubscribeConnection: (() => void) | undefined
let active = false
let tearingDown = false
let hadSuccessfulSync = false
function setSyncText(text: string) {
context.onSyncTextChange(text)
}
async function reportBleDisconnected() {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
try {
await updateDeviceRuntime({
deviceId,
bluetoothConnected: '0',
signalLevel: '0',
})
} catch {
// 上报失败时保留本地状态
}
}
async function reportDeviceOffline() {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
@@ -74,6 +62,69 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
}
}
function reportBleLinkLostLocal() {
context.onBluetoothConnectedChange(false)
}
async function resolveBleTarget(
mac: string,
preferredBleId?: string,
): Promise<UniApp.BluetoothDeviceInfo | null> {
const connected = await getConnectedBleDeviceByMac(mac)
if (connected) return connected
if (preferredBleId) {
const discovered = await getDiscoveredBluetoothDevices()
const cached = discovered.find((item) => item.deviceId === preferredBleId)
if (cached) return cached
}
const deviceName = context.getDeviceName?.()
return scanForBleDeviceByMac(mac, {
timeoutMs: SCAN_TIMEOUT_MS,
name: deviceName,
skipCached: !preferredBleId && !hadSuccessfulSync,
})
}
async function syncBleData(
targetBleId: string,
foundDevice: UniApp.BluetoothDeviceInfo | null,
): Promise<boolean> {
const deviceId = context.getDeviceId()
if (!deviceId) return false
setSyncText('正在同步设备数据…')
const blePayload = await readRuntimeFromBle(targetBleId)
const hasBleData = Object.keys(blePayload).length > 0
if (!hasBleData) {
throw new Error('设备无响应,请确认已开机并靠近手机')
}
hadSuccessfulSync = true
context.onBluetoothConnectedChange(true)
context.onBleRuntimeRead?.(blePayload)
const runtimePatch = context.getRuntimePatch()
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
try {
await updateDeviceRuntime({
deviceId,
...runtimePatch,
...blePayload,
status: '1',
bluetoothConnected: '1',
signalLevel,
})
setSyncText('刚刚更新 · 数据实时同步中')
await context.onSynced?.()
} catch (apiErr) {
setSyncText(`蓝牙已连接 · 云端同步失败:${getErrorMessage(apiErr, '请检查网络')}`)
}
return true
}
async function connectAndSync(): Promise<boolean> {
const deviceId = context.getDeviceId()
const mac = context.getMac()
@@ -92,78 +143,48 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (syncing.value) return false
syncing.value = true
let connected = false
let targetBleId = bleDeviceId.value
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
try {
setSyncText('正在连接蓝牙…')
await ensureBluetoothReady()
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
if (!targetBleId) {
const deviceName = context.getDeviceName?.()
foundDevice = await scanForBleDeviceByMac(mac ?? '', {
timeoutMs: SCAN_TIMEOUT_MS,
name: deviceName,
})
if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机')
await reportDeviceOffline()
return false
foundDevice = await resolveBleTarget(mac, targetBleId)
if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机')
if (!tearingDown) {
reportBleLinkLostLocal()
}
targetBleId = foundDevice.deviceId
bleDeviceId.value = targetBleId
} else {
const discovered = await getDiscoveredBluetoothDevices()
foundDevice = discovered.find((item) => item.deviceId === targetBleId) ?? null
return false
}
targetBleId = foundDevice.deviceId
bleDeviceId.value = targetBleId
if (!hadSuccessfulSync) {
setSyncText('正在连接蓝牙…')
}
await ensureBleConnection(targetBleId)
connected = true
context.onBluetoothConnectedChange(true)
setSyncText('正在同步设备数据…')
const blePayload = await readRuntimeFromBle(targetBleId)
if (Object.keys(blePayload).length) {
context.onBleRuntimeRead?.(blePayload)
}
const runtimePatch = context.getRuntimePatch()
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
const hasBleData = Object.keys(blePayload).length > 0
try {
await updateDeviceRuntime({
deviceId,
...runtimePatch,
...blePayload,
status: '1',
bluetoothConnected: '1',
signalLevel,
})
if (!hasBleData) {
setSyncText('蓝牙已连接,等待设备上报数据…')
} else {
setSyncText('刚刚更新 · 数据实时同步中')
}
await context.onSynced?.()
} catch (apiErr) {
if (hasBleData) {
setSyncText('蓝牙已连接 · 本地数据已更新,云端同步失败')
} else {
setSyncText(
`蓝牙已连接 · 云端同步失败:${getErrorMessage(apiErr, '请检查网络')}`,
)
}
}
return true
return await syncBleData(targetBleId, foundDevice)
} catch (err) {
const stillConnected = await getConnectedBleDeviceByMac(mac)
if (stillConnected) {
bleDeviceId.value = stillConnected.deviceId
context.onBluetoothConnectedChange(true)
try {
return await syncBleData(stillConnected.deviceId, stillConnected)
} catch (retryErr) {
setSyncText(getBluetoothErrorMessage(retryErr))
return true
}
}
setSyncText(getBluetoothErrorMessage(err))
if (!connected) {
if (!tearingDown) {
bleDeviceId.value = undefined
clearZ2BleHandleCache(targetBleId)
await reportDeviceOffline()
reportBleLinkLostLocal()
}
return false
} finally {
@@ -199,11 +220,24 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
active = true
unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
if (tearingDown) return
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
if (!res.connected) {
bleDeviceId.value = undefined
void reportBleDisconnected()
setSyncText('蓝牙已断开,正在尝试重连…')
void (async () => {
const mac = context.getMac()
if (mac) {
const stillConnected = await getConnectedBleDeviceByMac(mac)
if (stillConnected) {
bleDeviceId.value = stillConnected.deviceId
return
}
}
bleDeviceId.value = undefined
clearZ2BleHandleCache(res.deviceId)
void reportBleDisconnected()
setSyncText('蓝牙已断开,正在尝试重连…')
void connectAndSync()
})()
}
})
@@ -215,7 +249,9 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
}
async function stopSync() {
tearingDown = true
active = false
hadSuccessfulSync = false
if (syncTimer) {
clearInterval(syncTimer)
syncTimer = undefined
@@ -229,10 +265,15 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (currentBleId) {
clearZ2BleHandleCache(currentBleId)
await closeBleConnection(currentBleId).catch(() => {})
await reportBleDisconnected()
}
tearingDown = false
}
onShow(() => {
if (!active || tearingDown) return
void connectAndSync()
})
onUnload(() => {
void stopSync()
})

View File

@@ -45,9 +45,8 @@ export function useDeviceDetail() {
const deviceStatus = ref<string>()
const bluetoothConnected = ref(false)
const charging = ref(false)
const isOnline = ref(false)
const loading = ref(false)
const updating = ref(false)
const isOnline = computed(() => bluetoothConnected.value)
const runMode = ref<RunMode>('0')
const fanLevel = ref<FanLevel>('0')
@@ -148,13 +147,15 @@ export function useDeviceDetail() {
filterLife.value = view.filterLife
filterRemainText.value = view.filterRemainText
filterReplaced.value = view.filterReplaced
isOnline.value = view.isOnline
if (data.deviceBattery != null) applyBatteryLevel(data.deviceBattery, false)
if (data.status !== undefined) deviceStatus.value = data.status
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)
@@ -171,10 +172,13 @@ export function useDeviceDetail() {
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
if (matched) locationName.value = matched.name
}
bluetoothConnected.value = isBluetoothConnected(device.bluetoothConnected)
charging.value = device.charging === '1'
if (device.status !== undefined) deviceStatus.value = device.status
isOnline.value = device.status === '1'
if (!bleConnectedLocally) {
bluetoothConnected.value = isBluetoothConnected(device.bluetoothConnected)
deviceStatus.value = bluetoothConnected.value
? '1'
: (device.status === '0' ? '0' : '2')
}
} catch {
// 列表刷新失败时保留路由参数状态
}
@@ -198,28 +202,37 @@ export function useDeviceDetail() {
}
async function patchRuntime(patch: { runMode?: RunMode; fanLevel?: FanLevel }) {
if (!deviceId.value || updating.value) return
updating.value = true
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 bleCmd = patch.runMode != null
? encodeRunModeBleCommand(patch.runMode)
: patch.fanLevel != null
? encodeFanLevelBleCommand(patch.fanLevel)
: undefined
if (bleCmd) {
await sendBleCommand(bleCmd)
}
await updateDeviceRuntime({
const apiTask = updateDeviceRuntime({
deviceId: deviceId.value,
...patch,
})
const data = await fetchDeviceRuntime({ deviceId: deviceId.value })
applyRuntime(data)
await refreshDeviceMeta()
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' })
} finally {
updating.value = false
}
}
@@ -278,10 +291,7 @@ export function useDeviceDetail() {
}),
onBluetoothConnectedChange: (connected) => {
bluetoothConnected.value = connected
if (connected) {
isOnline.value = true
deviceStatus.value = '1'
}
deviceStatus.value = connected ? '1' : '2'
},
onSyncTextChange: (text) => {
syncText.value = text
@@ -309,12 +319,9 @@ export function useDeviceDetail() {
const parsedHomeId = parseId(query?.homeId)
if (parsedHomeId) homeId.value = parsedHomeId
if (query?.model) productModel.value = decodeURIComponent(String(query.model))
if (query?.status) {
deviceStatus.value = String(query.status)
isOnline.value = query.status === '1'
}
if (query?.mac) deviceMac.value = decodeURIComponent(String(query.mac))
bluetoothConnected.value = isBluetoothConnected(query?.bluetoothConnected)
bluetoothConnected.value = false
deviceStatus.value = '2'
charging.value = query?.charging === '1'
void loadRuntime().then(() => {
startSyncLoop()

View File

@@ -0,0 +1,18 @@
import type { AppDeviceVo } from './device.types'
/** 云端记录为在线:status=1 且蓝牙已连接 */
export function isDeviceCloudOnline(
device?: Pick<AppDeviceVo, 'status' | 'bluetoothConnected'>,
): boolean {
return device?.status === '1' && device.bluetoothConnected === '1'
}
/** 列表展示用在线态(默认不信任仅 status=1 的云端缓存) */
export function resolveDeviceListOnline(
device: Pick<AppDeviceVo, 'status' | 'bluetoothConnected'>,
blePresent?: boolean,
): boolean {
if (blePresent === true) return true
if (blePresent === false) return false
return isDeviceCloudOnline(device)
}

View File

@@ -0,0 +1,52 @@
const missCounts = new Map<string, number>()
const lastSeenAt = new Map<string, number>()
/** 连续扫描未命中次数达到该值后才判定离线 */
const OFFLINE_AFTER_MISSES = 2
/** 最近一次 BLE 命中后的宽限期(避免切换页面时瞬时扫不到) */
const ONLINE_GRACE_MS = 45_000
function deviceKey(deviceId: string | number | undefined): string {
return deviceId != null ? String(deviceId) : ''
}
export function recordPresenceHit(deviceId: string | number) {
const key = deviceKey(deviceId)
if (!key) return
missCounts.set(key, 0)
lastSeenAt.set(key, Date.now())
}
export function recordPresenceMiss(deviceId: string | number) {
const key = deviceKey(deviceId)
if (!key) return
missCounts.set(key, (missCounts.get(key) ?? 0) + 1)
}
/** 是否应将设备展示为离线(需连续未命中且超出宽限期) */
export function shouldMarkDeviceOffline(
deviceId: string | number,
wasOnline = false,
): boolean {
if (!wasOnline) return true
const key = deviceKey(deviceId)
const misses = missCounts.get(key) ?? 0
if (misses < OFFLINE_AFTER_MISSES) return false
const lastSeen = lastSeenAt.get(key) ?? 0
if (lastSeen && Date.now() - lastSeen < ONLINE_GRACE_MS) return false
return true
}
export function resetPresenceState(deviceId?: string | number) {
if (deviceId == null) {
missCounts.clear()
lastSeenAt.clear()
return
}
const key = deviceKey(deviceId)
missCounts.delete(key)
lastSeenAt.delete(key)
}

View File

@@ -1,14 +1,22 @@
import { buildBleDeviceName } from '@/utils/ble-device-name'
import {
findDeviceInBleScan,
isBluetoothApiSupported,
scanBluetoothDevices,
} from '@/utils/bluetooth'
import { sameId } from '@/utils/device-id'
import {
recordPresenceHit,
recordPresenceMiss,
shouldMarkDeviceOffline,
} from './device-presence-state'
import { updateDeviceRuntime } from './detail/device-detail.api'
import type { DeviceListItem } from './device.types'
let syncing = false
const PRESENCE_SCAN_MS = 8000
const PRESENCE_DEBUG = import.meta.env.DEV
|| import.meta.env.VITE_BLE_DEBUG === 'true'
@@ -23,27 +31,57 @@ function logPresence(message: string, payload?: unknown) {
function applyPresence(
device: DeviceListItem,
present: boolean,
blePresent: boolean,
): DeviceListItem {
const nextStatus = present ? '1' : '2'
const nextBluetooth = present ? '1' : '0'
if (!device.deviceId) return device
if (blePresent) {
recordPresenceHit(device.deviceId)
return {
...device,
status: '1',
bluetoothConnected: '1',
isOnline: true,
}
}
recordPresenceMiss(device.deviceId)
if (!shouldMarkDeviceOffline(device.deviceId, device.isOnline)) {
return device
}
return {
...device,
status: nextStatus,
bluetoothConnected: nextBluetooth,
isOnline: present,
status: '2',
bluetoothConnected: '0',
isOnline: false,
}
}
/** 通过 BLE 扫描刷新设备在线状态(status: 1在线 / 2离线) */
/** 列表页仅上报「确认在线」,不因单次扫描未命中把云端写成离线 */
async function reportPresenceOnlineToCloud(device: DeviceListItem) {
if (!device.deviceId) return
if (device.status === '1' && device.bluetoothConnected === '1') return
try {
await updateDeviceRuntime({
deviceId: device.deviceId,
status: '1',
bluetoothConnected: '1',
})
} catch (err) {
logPresence('updateRuntime failed', err)
}
}
/** 通过 BLE 扫描刷新设备在线状态(仅 MAC 精确匹配,不用缓存广播) */
export async function refreshDevicePresence(
devices: DeviceListItem[],
): Promise<DeviceListItem[]> {
if (!isBluetoothApiSupported()) return devices
const targets = devices.filter((item) => item.deviceId && (item.mac || item.name))
const targets = devices.filter((item) => item.deviceId && item.mac)
if (!targets.length) {
logPresence('skip: no mac/name on devices')
logPresence('skip: no mac on devices')
return devices
}
@@ -51,7 +89,7 @@ export async function refreshDevicePresence(
syncing = true
try {
const scanned = await scanBluetoothDevices({ timeoutMs: 5000 })
const scanned = await scanBluetoothDevices({ timeoutMs: PRESENCE_SCAN_MS })
logPresence('scan result', {
count: scanned.length,
names: scanned.map((item) => item.name || item.localName || item.deviceId),
@@ -62,42 +100,27 @@ export async function refreshDevicePresence(
const isTarget = targets.some((item) => sameId(item.deviceId, device.deviceId))
if (!isTarget) return device
const found = findDeviceInBleScan(
{ mac: device.mac, name: device.name },
scanned,
{ strictName: true },
)
const found = device.mac
? findDeviceInBleScan({ mac: device.mac }, scanned, { strictName: true })
: null
const present = !!found
logPresence('device presence', {
name: device.name,
mac: device.mac,
present,
foundId: found?.deviceId,
bleName: device.mac ? buildBleDeviceName(device.mac) : '',
})
return applyPresence(device, present)
})
void Promise.allSettled(
targets.map(async (device) => {
const found = findDeviceInBleScan(
{ mac: device.mac, name: device.name },
scanned,
{ strictName: true },
)
const present = !!found
const nextStatus = present ? '1' : '2'
const nextBluetooth = present ? '1' : '0'
if (device.status === nextStatus && device.bluetoothConnected === nextBluetooth) {
return
}
try {
await updateDeviceRuntime({
deviceId: device.deviceId!,
status: nextStatus,
bluetoothConnected: nextBluetooth,
})
} catch (err) {
logPresence('updateRuntime failed', err)
const found = device.mac
? findDeviceInBleScan({ mac: device.mac }, scanned, { strictName: true })
: null
if (found) {
await reportPresenceOnlineToCloud(device)
}
}),
)

View File

@@ -3,6 +3,7 @@
background: $color-bg-page;
padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
box-sizing: border-box;
overflow-x: hidden;
}
.device-page__loading {

View File

@@ -1,6 +1,7 @@
import type { AppDeviceVo, DeviceListItem, RoomTab } from './device.types'
import type { RoomOption } from '@/types/location'
import { sameId } from '@/utils/device-id'
import { resolveDeviceListOnline } from './device-online'
export type LocationMap = Map<string, RoomOption[]>
@@ -22,7 +23,7 @@ export function mapDeviceItem(
return {
...device,
locationName: resolveLocationName(device.locationId, locations),
isOnline: device.status === '1',
isOnline: resolveDeviceListOnline(device),
isCharging: device.charging === '1',
}
}

View File

@@ -2,14 +2,14 @@
<view v-if="visible" class="home-name-dialog">
<view class="home-name-dialog__mask" @tap="onCancel" />
<view class="home-name-dialog__panel" @tap.stop>
<text class="home-name-dialog__title">家庭名称</text>
<text class="home-name-dialog__title">{{ title }}</text>
<view class="home-name-dialog__input-wrap">
<input
v-model="inputValue"
class="home-name-dialog__input"
type="text"
maxlength="10"
placeholder="请输入家庭名称"
:placeholder="placeholder"
placeholder-class="home-name-dialog__placeholder"
:focus="visible"
/>
@@ -21,7 +21,7 @@
<view class="home-name-dialog__divider-v" />
<view class="home-name-dialog__btn" @tap.stop="onConfirm">
<text class="home-name-dialog__btn-text home-name-dialog__btn-text--primary">
确定
{{ confirmText }}
</text>
</view>
</view>
@@ -32,10 +32,20 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
const props = defineProps<{
visible: boolean
value: string
}>()
const props = withDefaults(
defineProps<{
visible: boolean
value: string
title?: string
placeholder?: string
confirmText?: string
}>(),
{
title: '家庭名称',
placeholder: '请输入家庭名称',
confirmText: '确定',
},
)
const emit = defineEmits<{
'update:visible': [value: boolean]

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="home-manage-page">
<app-navbar title="家庭管理" />

View File

@@ -5,6 +5,31 @@
flex-direction: column;
}
.home-manage-page :deep(.app-navbar__right) {
width: auto;
min-width: 80rpx;
padding-left: 16rpx;
}
.home-manage-page__add {
width: 56rpx;
height: 56rpx;
display: flex;
align-items: center;
justify-content: center;
}
.home-manage-page__add--disabled {
opacity: 0.45;
}
.home-manage-page__add-icon {
font-size: 44rpx;
line-height: 1;
color: #999;
font-weight: 300;
}
.home-manage-page__scroll {
width: 100%;
}

View File

@@ -1,6 +1,16 @@
<template>
<template>
<view class="home-manage-page">
<app-navbar title="家庭管理" />
<app-navbar title="家庭管理">
<template #right>
<view
class="home-manage-page__add"
:class="{ 'home-manage-page__add--disabled': creating }"
@tap="onAddHome"
>
<text class="home-manage-page__add-icon">+</text>
</view>
</template>
</app-navbar>
<page-scroll-view class="home-manage-page__scroll">
<view class="home-manage-page__body">
@@ -28,14 +38,33 @@
</view>
</view>
</page-scroll-view>
<home-name-dialog
v-model:visible="createDialogVisible"
:value="createHomeName"
title="新增家庭"
placeholder="请输入新家庭名称"
confirm-text="创建"
@confirm="onConfirmCreateHome"
/>
</view>
</template>
<script setup lang="ts">
import { staticAssets } from '@/utils/static-assets'
import HomeNameDialog from './components/home-name-dialog/index.vue'
import { useHomeList } from './use-home-list'
const { homes, loading, onSelectHome } = useHomeList()
const {
homes,
loading,
creating,
createDialogVisible,
createHomeName,
onSelectHome,
onAddHome,
onConfirmCreateHome,
} = useHomeList()
</script>
<style lang="scss" scoped>

View File

@@ -1,30 +1,26 @@
<template>
<!-- #ifdef H5 -->
<view class="location-map">
<view :id="mapDomId" class="location-map__canvas" />
<view v-if="hintText" class="location-map__hint">
<text class="location-map__hint-text">{{ hintText }}</text>
<map
:id="mapId"
class="location-map__canvas"
provider="amap"
:latitude="mapLatitude"
:longitude="mapLongitude"
:scale="16"
:show-location="true"
:enable-3d="false"
:show-compass="false"
@regionchange="onRegionChange"
/>
<view class="location-map__pin" aria-hidden="true">
<view class="location-map__pin-dot" />
<view class="location-map__pin-stick" />
</view>
</view>
<!-- #endif -->
<!-- #ifndef H5 -->
<map
class="location-map"
:latitude="latitude"
:longitude="longitude"
:scale="16"
:show-location="true"
:enable-3d="false"
:show-compass="false"
@regionchange="onRegionChange"
/>
<!-- #endif -->
</template>
<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { getTencentMapKey, loadTencentMapGl, type TencentMapInstance } from '@/utils/tencent-map-loader'
import { getCurrentInstance, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
const props = defineProps<{
latitude: number
@@ -32,87 +28,55 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
'center-change': [center: { latitude: number; longitude: number }]
ready: []
regionchange: [event: UniHelper.MapRegionChangeEvent]
}>()
// #ifdef H5
const mapDomId = `location-map-${Math.random().toString(36).slice(2, 10)}`
const hintText = ref('')
let mapInstance: TencentMapInstance | null = null
let syncingFromDrag = false
const instance = getCurrentInstance()
const mapId = `location-map-${Math.random().toString(36).slice(2, 10)}`
async function initH5Map() {
const key = getTencentMapKey()
if (!key) {
hintText.value = '请在 .env 中配置 VITE_TENCENT_MAP_KEY(腾讯地图 Web 端 Key)'
return
}
try {
await loadTencentMapGl()
await nextTick()
const container = document.getElementById(mapDomId)
if (!container || !window.TMap) {
hintText.value = '地图容器初始化失败'
return
}
hintText.value = ''
mapInstance = new window.TMap.Map(container, {
center: new window.TMap.LatLng(props.latitude, props.longitude),
zoom: 16,
pitch: 0,
rotation: 0,
showControl: false,
baseMap: {
type: 'vector',
},
})
const emitCenter = () => {
if (!mapInstance) return
const center = mapInstance.getCenter()
syncingFromDrag = true
emit('center-change', {
latitude: center.lat,
longitude: center.lng,
})
setTimeout(() => {
syncingFromDrag = false
}, 0)
}
mapInstance.on('dragend', emitCenter)
mapInstance.on('zoom_changed', emitCenter)
} catch (err) {
hintText.value = err instanceof Error ? err.message : '地图加载失败'
}
function getMapContext() {
return uni.createMapContext(mapId, instance)
}
const mapLatitude = ref(props.latitude)
const mapLongitude = ref(props.longitude)
let syncingFromParent = false
let destroyed = false
watch(
() => [props.latitude, props.longitude],
([lat, lng]) => {
if (!mapInstance || syncingFromDrag || !window.TMap) return
mapInstance.setCenter(new window.TMap.LatLng(lat, lng))
if (syncingFromParent) return
mapLatitude.value = lat
mapLongitude.value = lng
},
)
onMounted(() => {
void initH5Map()
})
onUnmounted(() => {
mapInstance?.destroy?.()
mapInstance = null
})
// #endif
// #ifndef H5
function onRegionChange(event: UniHelper.MapRegionChangeEvent) {
emit('regionchange', event)
}
// #endif
onMounted(() => {
emit('ready')
})
defineExpose({
moveTo(lng: number, lat: number) {
syncingFromParent = true
mapLatitude.value = lat
mapLongitude.value = lng
void nextTick(() => {
syncingFromParent = false
})
},
moveToUserLocation() {
if (destroyed) return
void nextTick(() => {
if (destroyed) return
getMapContext().moveToLocation({})
})
},
})
</script>
<style lang="scss" scoped>
@@ -127,21 +91,32 @@ function onRegionChange(event: UniHelper.MapRegionChangeEvent) {
height: 100%;
}
.location-map__hint {
.location-map__pin {
position: absolute;
inset: 0;
left: 50%;
top: 50%;
transform: translate(-50%, -100%);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48rpx;
background: #eef1f5;
z-index: 1;
pointer-events: none;
z-index: 2;
}
.location-map__hint-text {
font-size: 28rpx;
color: #667085;
line-height: 1.6;
text-align: center;
.location-map__pin-dot {
width: 28rpx;
height: 28rpx;
border-radius: 50%;
background: $color-primary;
border: 4rpx solid #fff;
box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
}
.location-map__pin-stick {
width: 4rpx;
height: 16rpx;
margin-top: -2rpx;
background: $color-primary;
border-radius: 2rpx;
}
</style>

View File

@@ -0,0 +1,227 @@
<template>
<view class="location-search" :style="panelStyle">
<view class="location-search__bar">
<view class="location-search__input-wrap">
<text class="location-search__icon">⌕</text>
<input
class="location-search__input"
type="text"
:value="keyword"
placeholder="搜索地点"
confirm-type="search"
:focus="true"
:adjust-position="true"
@input="onInput"
@confirm="onSubmit"
/>
</view>
<text class="location-search__cancel" @tap="emit('close')">取消</text>
</view>
<scroll-view class="location-search__list" scroll-y :show-scrollbar="false">
<view v-if="loading" class="location-search__hint">正在搜索…</view>
<view v-else-if="configError" class="location-search__hint location-search__hint--error">
{{ configError }}
</view>
<view v-else-if="keyword && !results.length" class="location-search__hint">
未找到相关地点,请换个关键词试试
</view>
<view v-else-if="!keyword" class="location-search__hint">输入地点名称进行搜索</view>
<view
v-for="(item, index) in results"
:key="`${item.longitude}-${item.latitude}-${index}`"
class="location-search__item"
@tap="emit('select', item)"
>
<text class="location-search__item-name">{{ item.name || item.address }}</text>
<text v-if="item.address && item.name !== item.address" class="location-search__item-address">
{{ item.address }}
</text>
</view>
</scroll-view>
</view>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { hasAmapWebKey, searchAmapPlaces, type MapLocationPoint } from '@/utils/amap'
const props = defineProps<{
latitude: number
longitude: number
city?: string
topOffset: number
}>()
const emit = defineEmits<{
select: [point: MapLocationPoint]
close: []
}>()
const keyword = ref('')
const results = ref<MapLocationPoint[]>([])
const loading = ref(false)
const configError = ref('')
let searchTimer: ReturnType<typeof setTimeout> | null = null
let searchSeq = 0
const panelStyle = computed(() => ({
top: `${props.topOffset}px`,
height: `calc(100vh - ${props.topOffset}px)`,
}))
onMounted(() => {
if (!hasAmapWebKey()) {
configError.value = '地图搜索服务未配置,请联系管理员'
}
})
function onInput(event: UniHelper.InputEvent) {
keyword.value = String(event.detail?.value ?? '')
scheduleSearch()
}
function onSubmit() {
scheduleSearch(true)
}
function scheduleSearch(immediate = false) {
if (searchTimer) clearTimeout(searchTimer)
const run = () => {
void runSearch()
}
if (immediate) {
run()
return
}
searchTimer = setTimeout(run, 300)
}
async function runSearch() {
const query = keyword.value.trim()
if (!query) {
results.value = []
loading.value = false
return
}
if (!hasAmapWebKey()) {
configError.value = '地图搜索服务未配置,请联系管理员'
results.value = []
return
}
const seq = ++searchSeq
loading.value = true
configError.value = ''
const { places, error } = await searchAmapPlaces(query, {
latitude: props.latitude,
longitude: props.longitude,
city: props.city,
})
if (seq !== searchSeq) return
results.value = places
configError.value = error || ''
loading.value = false
}
watch(
() => [props.latitude, props.longitude],
() => {
if (keyword.value.trim()) scheduleSearch(true)
},
)
</script>
<style lang="scss" scoped>
.location-search {
position: fixed;
left: 0;
right: 0;
z-index: 90;
background: #f5f6f8;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.location-search__bar {
display: flex;
align-items: center;
gap: 16rpx;
padding: 16rpx 24rpx;
background: #fff;
box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
flex-shrink: 0;
}
.location-search__input-wrap {
flex: 1;
height: 72rpx;
padding: 0 24rpx;
border-radius: 16rpx;
background: #f5f6f8;
display: flex;
align-items: center;
gap: 12rpx;
}
.location-search__icon {
font-size: 30rpx;
color: #999;
line-height: 1;
}
.location-search__input {
flex: 1;
height: 72rpx;
font-size: 28rpx;
color: $color-text;
}
.location-search__cancel {
font-size: 28rpx;
color: $color-primary;
line-height: 1;
padding: 8rpx 0;
flex-shrink: 0;
}
.location-search__list {
flex: 1;
min-height: 0;
background: #fff;
margin-top: 16rpx;
}
.location-search__hint {
padding: 48rpx 32rpx;
font-size: 28rpx;
color: #999;
text-align: center;
}
.location-search__hint--error {
color: #e54d4d;
}
.location-search__item {
padding: 28rpx 32rpx;
border-bottom: 1rpx solid #f0f0f0;
}
.location-search__item-name {
display: block;
font-size: 30rpx;
color: $color-text;
line-height: 1.4;
}
.location-search__item-address {
display: block;
margin-top: 8rpx;
font-size: 24rpx;
color: #999;
line-height: 1.4;
}
</style>

View File

@@ -6,6 +6,12 @@
overflow: hidden;
}
.home-location-page__header {
flex-shrink: 0;
z-index: 100;
background: #f5f6f8;
}
.home-location-page__confirm {
width: 56rpx;
height: 56rpx;
@@ -61,35 +67,6 @@
height: 100%;
}
.home-location-page__pin {
position: absolute;
left: 50%;
top: 50%;
width: 40rpx;
height: 72rpx;
transform: translate(-50%, -100%);
pointer-events: none;
z-index: 2;
}
.home-location-page__pin-head {
width: 40rpx;
height: 40rpx;
margin: 0 auto;
border-radius: 50% 50% 50% 0;
background: $color-primary;
transform: rotate(-45deg);
box-shadow: 0 4rpx 12rpx rgba(31, 168, 92, 0.35);
}
.home-location-page__pin-tail {
width: 16rpx;
height: 16rpx;
margin: 8rpx auto 0;
border-radius: 50%;
background: rgba(31, 168, 92, 0.25);
}
.home-location-page__locate {
position: absolute;
right: 24rpx;

View File

@@ -1,34 +1,32 @@
<template>
<template>
<view class="home-location-page">
<app-navbar title="家庭位置">
<template #right>
<view class="home-location-page__confirm" @tap="onConfirm">
<text class="home-location-page__confirm-icon">✓</text>
</view>
</template>
</app-navbar>
<view class="home-location-page__header">
<app-navbar title="家庭位置">
<template #right>
<view class="home-location-page__confirm" @tap="onConfirm">
<text class="home-location-page__confirm-icon">✓</text>
</view>
</template>
</app-navbar>
</view>
<view class="home-location-page__search" @tap="onChooseLocation">
<view v-if="!searchVisible" class="home-location-page__search" @tap="onOpenSearch">
<text class="home-location-page__search-icon">⌕</text>
<text class="home-location-page__search-text">
{{ searchKeyword || '搜索地点' }}
</text>
</view>
<view class="home-location-page__map-wrap">
<view v-show="!searchVisible" class="home-location-page__map-wrap">
<location-map
ref="locationMapRef"
class="home-location-page__map"
:latitude="latitude"
:longitude="longitude"
@center-change="onMapCenterChange"
@ready="onMapReady"
@regionchange="onRegionChange"
/>
<view class="home-location-page__pin" aria-hidden="true">
<view class="home-location-page__pin-head" />
<view class="home-location-page__pin-tail" />
</view>
<view
class="home-location-page__locate"
:class="{ 'home-location-page__locate--loading': locating }"
@@ -38,19 +36,36 @@
</view>
</view>
<view class="home-location-page__footer">
<view v-show="!searchVisible" class="home-location-page__footer">
<text class="home-location-page__address-label">当前位置</text>
<text class="home-location-page__address-text">
{{ resolvingAddress ? '正在解析地址…' : (addressText || '拖动地图选择家庭位置') }}
</text>
</view>
<location-search
v-if="searchVisible"
:latitude="latitude"
:longitude="longitude"
:city="searchCity"
:top-offset="searchPanelTop"
@select="onSelectSearchPlace"
@close="onCloseSearch"
/>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const sys = uni.getSystemInfoSync()
const searchPanelTop = (sys.statusBarHeight ?? 0) + uni.upx2px(88)
import LocationMap from './components/location-map/index.vue'
import LocationSearch from './components/location-search/index.vue'
import { useHomeLocation } from './use-home-location'
const locationMapRef = ref<{ moveTo: (lng: number, lat: number) => void } | null>(null)
const {
latitude,
longitude,
@@ -58,12 +73,18 @@ const {
addressText,
locating,
resolvingAddress,
onMapReady,
onRegionChange,
onMapCenterChange,
onChooseLocation,
searchVisible,
searchCity,
onOpenSearch,
onCloseSearch,
onSelectSearchPlace,
onLocate,
onConfirm,
} = useHomeLocation()
} = useHomeLocation({
locationMapRef,
})
</script>
<style lang="scss" scoped>

View File

@@ -1,4 +1,5 @@
import { onLoad } from '@dcloudio/uni-app'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import type { Ref } from 'vue'
import { ref } from 'vue'
import {
buildUpdateHomeBody,
@@ -7,25 +8,46 @@ import {
} from '@/api/home'
import { getErrorMessage } from '@/utils/api-error'
import { parseId } from '@/utils/device-id'
import { formatCoordinateAddress, reverseGeocode } from '@/utils/map-geocode'
import {
formatMapLocation,
reverseGeocodeAmapDetail,
type MapLocationPoint,
} from '@/utils/amap'
import { ensureLocationPermission, getLocationFailHint } from '@/utils/location-permission'
import { formatCoordinateAddress } from '@/utils/map-geocode'
import { loadHomeGeo, saveHomeGeo } from '../use-home-manage'
import type { HomeGeoInfo } from '../home-manage.types'
const DEFAULT_LATITUDE = 39.9042
const DEFAULT_LONGITUDE = 116.4074
function requestUserLocation(): Promise<UniApp.GetLocationSuccess> {
interface LocationMapExpose {
moveTo: (lng: number, lat: number) => void
moveToUserLocation: () => void
}
interface UseHomeLocationOptions {
locationMapRef?: Ref<LocationMapExpose | null>
}
async function requestUserLocation(): Promise<UniApp.GetLocationSuccess> {
const permitted = await ensureLocationPermission()
if (!permitted) {
throw new Error('location permission denied')
}
return new Promise((resolve, reject) => {
uni.getLocation({
type: 'gcj02',
isHighAccuracy: true,
highAccuracyExpireTime: 10000,
geocode: false,
success: resolve,
fail: reject,
})
})
}
export function useHomeLocation() {
export function useHomeLocation(options: UseHomeLocationOptions = {}) {
const homeId = ref('')
const homeName = ref('我的家')
const saving = ref(false)
@@ -35,25 +57,58 @@ export function useHomeLocation() {
const addressText = ref('')
const locating = ref(false)
const resolvingAddress = ref(false)
const mapReady = ref(false)
const searchVisible = ref(false)
const searchCity = ref('')
let geocodeTimer: ReturnType<typeof setTimeout> | null = null
let pendingMapCenter: { lng: number; lat: number } | null = null
let disposed = false
function setMapCenter(lat: number, lng: number) {
latitude.value = lat
longitude.value = lng
function clearGeocodeTimer() {
if (geocodeTimer) {
clearTimeout(geocodeTimer)
geocodeTimer = null
}
}
function syncMapView(lng: number, lat: number) {
if (!mapReady.value) {
pendingMapCenter = { lng, lat }
return
}
options.locationMapRef?.value?.moveTo(lng, lat)
}
function onMapReady() {
mapReady.value = true
if (pendingMapCenter) {
options.locationMapRef?.value?.moveTo(pendingMapCenter.lng, pendingMapCenter.lat)
pendingMapCenter = null
}
}
function applyMapLocation(point: MapLocationPoint) {
latitude.value = point.latitude
longitude.value = point.longitude
addressText.value = formatMapLocation(point) || formatCoordinateAddress(point.latitude, point.longitude)
searchKeyword.value = point.name || point.address || ''
syncMapView(point.longitude, point.latitude)
}
function scheduleAddressResolve() {
if (geocodeTimer) clearTimeout(geocodeTimer)
clearGeocodeTimer()
geocodeTimer = setTimeout(() => {
void resolveAddressFromCoords()
}, 400)
}
async function resolveAddressFromCoords() {
if (disposed) return
resolvingAddress.value = true
try {
const address = await reverseGeocode(latitude.value, longitude.value)
addressText.value = address
const detail = await reverseGeocodeAmapDetail(latitude.value, longitude.value)
if (detail?.city) searchCity.value = detail.city
addressText.value = detail?.address
|| formatCoordinateAddress(latitude.value, longitude.value)
} finally {
resolvingAddress.value = false
@@ -65,6 +120,7 @@ export function useHomeLocation() {
latitude.value = saved.latitude
longitude.value = saved.longitude
addressText.value = saved.address
syncMapView(saved.longitude, saved.latitude)
return
}
@@ -73,15 +129,18 @@ export function useHomeLocation() {
const location = await requestUserLocation()
latitude.value = location.latitude
longitude.value = location.longitude
syncMapView(location.longitude, location.latitude)
if (location.address) {
addressText.value = location.address
} else {
await resolveAddressFromCoords()
}
} catch {
} catch (err) {
latitude.value = DEFAULT_LATITUDE
longitude.value = DEFAULT_LONGITUDE
syncMapView(longitude.value, latitude.value)
addressText.value = formatCoordinateAddress(latitude.value, longitude.value)
uni.showToast({ title: getLocationFailHint(err), icon: 'none' })
} finally {
locating.value = false
}
@@ -94,35 +153,24 @@ export function useHomeLocation() {
}
function onRegionChange(e: UniHelper.MapRegionChangeEvent) {
if (disposed) return
if (e.type !== 'end') return
const center = e.detail?.centerLocation
if (!center) return
applyMapCenter(center)
}
function onMapCenterChange(center: { latitude: number; longitude: number }) {
applyMapCenter(center)
function onOpenSearch() {
searchVisible.value = true
}
function onChooseLocation() {
uni.chooseLocation({
latitude: latitude.value,
longitude: longitude.value,
success: (res) => {
latitude.value = res.latitude
longitude.value = res.longitude
addressText.value = res.name
? `${res.name}${res.address ? ` · ${res.address}` : ''}`
: (res.address || formatCoordinateAddress(res.latitude, res.longitude))
searchKeyword.value = res.name || res.address || ''
setMapCenter(res.latitude, res.longitude)
},
fail: (err) => {
const msg = String(err?.errMsg || '')
if (/cancel/i.test(msg) || /取消/.test(msg)) return
uni.showToast({ title: '无法打开地图选点,请检查定位权限', icon: 'none' })
},
})
function onCloseSearch() {
searchVisible.value = false
}
function onSelectSearchPlace(point: MapLocationPoint) {
applyMapLocation(point)
searchVisible.value = false
}
async function onLocate() {
@@ -131,14 +179,15 @@ export function useHomeLocation() {
const location = await requestUserLocation()
latitude.value = location.latitude
longitude.value = location.longitude
setMapCenter(location.latitude, location.longitude)
syncMapView(location.longitude, location.latitude)
options.locationMapRef?.value?.moveToUserLocation()
if (location.address) {
addressText.value = location.address
} else {
await resolveAddressFromCoords()
}
} catch {
uni.showToast({ title: '定位失败,请检查定位权限', icon: 'none' })
} catch (err) {
uni.showToast({ title: getLocationFailHint(err), icon: 'none' })
} finally {
locating.value = false
}
@@ -181,6 +230,12 @@ export function useHomeLocation() {
}
}
onUnload(() => {
disposed = true
clearGeocodeTimer()
pendingMapCenter = null
})
onLoad((query?: Record<string, string | undefined>) => {
homeId.value = parseId(query?.homeId)
if (query?.homeName) {
@@ -202,9 +257,13 @@ export function useHomeLocation() {
addressText,
locating,
resolvingAddress,
onMapReady,
onRegionChange,
onMapCenterChange,
onChooseLocation,
searchVisible,
searchCity,
onOpenSearch,
onCloseSearch,
onSelectSearchPlace,
onLocate,
onConfirm,
}

View File

@@ -1,6 +1,11 @@
import { onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { fetchHomeList } from '@/api/home'
import { nextTick, ref } from 'vue'
import {
buildUpdateHomeBody,
createHome,
fetchHomeList,
isValidHomeName,
} from '@/api/home'
import { getErrorMessage } from '@/utils/api-error'
import { parseId } from '@/utils/device-id'
import type { AppHomeVo } from '@/types/location'
@@ -8,6 +13,9 @@ import type { AppHomeVo } from '@/types/location'
export function useHomeList() {
const homes = ref<AppHomeVo[]>([])
const loading = ref(false)
const creating = ref(false)
const createDialogVisible = ref(false)
const createHomeName = ref('')
async function loadHomes() {
loading.value = true
@@ -35,6 +43,37 @@ export function useHomeList() {
})
}
function onAddHome() {
if (creating.value) return
createHomeName.value = ''
createDialogVisible.value = true
}
async function onConfirmCreateHome(name: string) {
const trimmed = name.trim()
if (!isValidHomeName(trimmed)) {
uni.showToast({ title: '家庭名称需 2-10 个字符', icon: 'none' })
await nextTick()
createDialogVisible.value = true
return
}
if (creating.value) return
creating.value = true
try {
await createHome(buildUpdateHomeBody(trimmed))
await loadHomes()
uni.showToast({ title: '新增家庭成功', icon: 'success' })
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '新增家庭失败'), icon: 'none' })
await nextTick()
createDialogVisible.value = true
createHomeName.value = trimmed
} finally {
creating.value = false
}
}
onShow(() => {
void loadHomes()
})
@@ -42,7 +81,12 @@ export function useHomeList() {
return {
homes,
loading,
creating,
createDialogVisible,
createHomeName,
onSelectHome,
onAddHome,
onConfirmCreateHome,
loadHomes,
}
}

View File

@@ -1,7 +1,10 @@
<template>
<template>
<view class="device-page">
<device-header
:home-name="homeName"
:home-id="homeId"
:homes="homes"
@select-home="onSelectHome"
@manage="onHomeManage"
@notify="onNotify"
@add-device="onStartBind"
@@ -54,6 +57,8 @@ const { tabCurrent } = useTabPage('device')
const {
homeName,
homeId,
homes,
rooms,
activeRoomId,
devices,
@@ -72,6 +77,7 @@ const {
onGoMall,
onNotify,
onHomeManage,
onSelectHome,
onManageDevices,
onSelectDevice,
} = useDevice()

View File

@@ -1,11 +1,21 @@
.device-settings-page {
min-height: 100vh;
height: 100vh;
overflow: hidden;
background: #f5f6f8;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.device-settings-page__top {
flex-shrink: 0;
z-index: 10;
background: #f5f6f8;
}
.device-settings-page__scroll {
flex: 1;
min-height: 0;
width: 100%;
}

View File

@@ -1,8 +1,10 @@
<template>
<template>
<view class="device-settings-page">
<app-navbar title="设备设置" />
<view class="device-settings-page__top">
<app-navbar title="设备设置" />
</view>
<page-scroll-view class="device-settings-page__scroll">
<page-scroll-view class="device-settings-page__scroll" :scroll-style="scrollStyle">
<view class="device-settings-page__body">
<view class="device-settings-card">
<view class="device-settings-card__top">
@@ -89,7 +91,10 @@
</template>
<script setup lang="ts">
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
import { staticAssets } from '@/utils/static-assets'
const { scrollStyle } = usePageScrollHeight({ topSelector: '.device-settings-page__top' })
import DeviceNameDialog from './components/device-name-dialog/index.vue'
import UnbindConfirmDialog from './components/unbind-confirm-dialog/index.vue'
import { useDeviceSettings } from './use-device-settings'

View File

@@ -1,13 +1,16 @@
<template>
<template>
<view class="device-room-page">
<app-navbar title="所在房间">
<template #right>
<view class="device-room-page__add-btn" @tap="onOpenAddDialog">
<text class="device-room-page__add-icon">+</text>
</view>
</template>
</app-navbar>
<view class="device-room-page__top">
<app-navbar title="所在房间">
<template #right>
<view class="device-room-page__add-btn" @tap="onOpenAddDialog">
<text class="device-room-page__add-icon">+</text>
</view>
</template>
</app-navbar>
</view>
<page-scroll-view class="device-room-page__scroll" :scroll-style="scrollStyle">
<view v-if="listLoading" class="device-room-page__loading">
<text class="device-room-page__loading-text">加载中...</text>
</view>
@@ -36,6 +39,7 @@
</view>
</view>
</view>
</page-scroll-view>
<room-location-dialog
v-model:visible="addDialogVisible"
@@ -46,7 +50,10 @@
</template>
<script setup lang="ts">
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
import RoomLocationDialog from '../../components/room-location-dialog/index.vue'
const { scrollStyle } = usePageScrollHeight({ topSelector: '.device-room-page__top' })
import { useDeviceRoom } from './use-device-room'
const {

View File

@@ -1,6 +1,22 @@
.device-room-page {
min-height: 100vh;
height: 100vh;
overflow: hidden;
background: #fff;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.device-room-page__top {
flex-shrink: 0;
z-index: 10;
background: #fff;
}
.device-room-page__scroll {
flex: 1;
min-height: 0;
width: 100%;
}
.device-room-page__add-btn {

View File

@@ -1,15 +1,23 @@
import { onHide, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
import { fetchHomeList, resolveValidHomeId } from '@/api/home'
import {
fetchHomeList,
findHomeById,
getHomeId,
pickDefaultHome,
resolveValidHomeId,
} from '@/api/home'
import { getStoredToken } from '@/utils/auth-token'
import { parseId, sameId } from '@/utils/device-id'
import type { AppHomeVo } from '@/types/location'
import { createLocation } from '@/api/location'
import { getErrorMessage } from '@/utils/api-error'
import { fetchRoomList } from '@/api/location'
import { fetchDeviceList } from './device.api'
import type { DeviceListItem, HotDeviceItem, RoomTab } from './device.types'
import type { LocationMap } from './device.utils'
import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home'
import { refreshDevicePresence } from './device-presence'
import {
buildRoomTabs,
@@ -37,6 +45,7 @@ const DEFAULT_HOT_DEVICES: HotDeviceItem[] = [
export function useDevice() {
const homeName = ref('我的家')
const homeId = ref('')
const homes = ref<AppHomeVo[]>([])
const rooms = ref<RoomTab[]>([{ id: 'all', name: '全部' }])
const activeRoomId = ref('all')
const devices = ref<DeviceListItem[]>([])
@@ -82,31 +91,54 @@ export function useDevice() {
}
}
function applyCurrentHome(homeList: AppHomeVo[]) {
const currentHome = findHomeById(homeList, homeId.value) ?? pickDefaultHome(homeList)
const currentId = getHomeId(currentHome)
if (currentId) {
homeId.value = currentId
saveSelectedHomeId(currentId)
}
homeName.value = currentHome?.homeName?.trim() || '我的家'
}
async function loadHomeList() {
homes.value = await fetchHomeList() ?? []
if (!homes.value.length) {
const defaultId = await resolveValidHomeId()
homes.value = await fetchHomeList() ?? []
if (defaultId) homeId.value = defaultId
}
if (!homeId.value || !findHomeById(homes.value, homeId.value)) {
const storedId = readStoredHomeId()
if (storedId && findHomeById(homes.value, storedId)) {
homeId.value = storedId
} else {
homeId.value = getHomeId(pickDefaultHome(homes.value)) || await resolveValidHomeId()
}
}
applyCurrentHome(homes.value)
}
async function loadDevicesForHome(targetHomeId?: string) {
if (targetHomeId) homeId.value = targetHomeId
if (!homeId.value) {
await loadHomeList()
}
if (!homeId.value) return
const locationMap = await buildLocationMap([homeId.value])
const list = await fetchDeviceList({ homeId: homeId.value }) ?? []
applyRoomTabs(locationMap)
const mapped = list.map((item) => mapDeviceItem(item, locationMap))
devices.value = await refreshDevicePresence(mapped)
}
async function loadDevices() {
if (loading.value) return
loading.value = true
try {
const list = await fetchDeviceList() ?? []
const homeIds = [
...new Set(
list
.map((item) => parseId(item.homeId))
.filter((id) => id !== ''),
),
]
if (!homeIds.length) {
const defaultHomeId = await resolveValidHomeId()
if (defaultHomeId) homeIds.push(defaultHomeId)
}
const locationMap = await buildLocationMap(homeIds)
const deviceHomeId = parseId(list.find((item) => item.homeId != null)?.homeId)
homeId.value = await resolveValidHomeId(deviceHomeId || homeIds[0])
const homes = await fetchHomeList()
const currentHome = homes?.find((item) => sameId(item.id, homeId.value))
if (currentHome?.homeName) homeName.value = currentHome.homeName
applyRoomTabs(locationMap)
devices.value = list.map((item) => mapDeviceItem(item, locationMap))
devices.value = await refreshDevicePresence(devices.value)
await loadHomeList()
await loadDevicesForHome()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载设备失败'), icon: 'none' })
} finally {
@@ -114,6 +146,25 @@ export function useDevice() {
}
}
async function onSelectHome(home: AppHomeVo) {
const nextHomeId = parseId(home.id)
if (!nextHomeId || sameId(nextHomeId, homeId.value)) return
homeId.value = nextHomeId
homeName.value = home.homeName?.trim() || '我的家'
saveSelectedHomeId(nextHomeId)
activeRoomId.value = 'all'
loading.value = true
try {
await loadDevicesForHome(nextHomeId)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '切换家庭失败'), icon: 'none' })
} finally {
loading.value = false
}
}
async function refreshPresenceOnly() {
if (!devices.value.length || loading.value) return
devices.value = await refreshDevicePresence(devices.value)
@@ -136,7 +187,11 @@ export function useDevice() {
uni.reLaunch({ url: '/pages/login/index' })
return
}
void loadDevices()
if (devices.value.length) {
void refreshPresenceOnly()
} else {
void loadDevices()
}
void refreshUnreadMessageCount()
startPresencePolling()
})
@@ -178,7 +233,8 @@ export function useDevice() {
}
function onStartBind() {
uni.navigateTo({ url: '/pages/add-device/index' })
const params = homeId.value ? `?homeId=${homeId.value}` : ''
uni.navigateTo({ url: `/pages/add-device/index${params}` })
}
function onScan() {
@@ -223,6 +279,8 @@ export function useDevice() {
return {
homeName,
homeId,
homes,
rooms,
activeRoomId,
devices: filteredDevices,
@@ -241,6 +299,7 @@ export function useDevice() {
onGoMall,
onNotify,
onHomeManage,
onSelectHome,
onManageDevices,
onSelectDevice,
loadDevices,

View File

@@ -31,7 +31,7 @@
<view class="login-page__footer">
<view class="login-page__agreement">
<agreement-checkbox v-model="agreed" />
<agreement-checkbox v-model="agreed" confirm-before-agree />
</view>
<primary-button text="登录" @click="submit" />
<view class="login-page__register">

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="change-phone-page">
<app-navbar title="手机号换绑" />
<view class="change-phone-page__body">

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="change-phone-page">
<app-navbar title="手机号换绑" />
<view class="change-phone-page__body">

View File

@@ -110,13 +110,6 @@
opacity: 0.45;
}
.edit-profile-page__change-phone {
font-size: 28rpx;
color: $color-primary;
flex-shrink: 0;
margin-left: 16rpx;
}
.edit-profile-page__divider {
height: 1rpx;
background: #eee;

View File

@@ -5,9 +5,8 @@ export interface ProfileFormState {
province: string
city: string
district: string
phonenumber: string
avatarUrl: string
avatarOssId: string
}
export type ProfileFieldKey = 'nickName' | 'gender' | 'birthday' | 'location' | 'phone'
export type ProfileFieldKey = 'nickName' | 'gender' | 'birthday' | 'location'

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="edit-profile-page">
<view class="edit-profile-page__navbar">
<app-navbar title="编辑资料" />
@@ -102,20 +102,6 @@
/>
</view>
</view>
<view class="edit-profile-page__divider" />
<view class="edit-profile-page__item">
<text class="edit-profile-page__label">手机号</text>
<view class="edit-profile-page__right">
<text class="edit-profile-page__value">
{{ maskedPhone || '未绑定' }}
</text>
<text class="edit-profile-page__change-phone" @tap.stop="onChangePhone">
更换
</text>
</view>
</view>
</view>
</view>
</page-scroll-view>
@@ -166,7 +152,6 @@ const {
saving,
uploadingAvatar,
form,
maskedPhone,
genderText,
locationText,
regionPickerVisible,
@@ -182,7 +167,6 @@ const {
onBirthdayChange,
onOpenRegionPicker,
onConfirmRegion,
onChangePhone,
onSave,
} = useEditProfile()
</script>

View File

@@ -1,4 +1,4 @@
import { onLoad, onShow } from '@dcloudio/uni-app'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { fetchProfile, updateProfile, uploadProfileAvatar } from '@/api/profile'
import { getErrorMessage } from '@/utils/api-error'
@@ -16,12 +16,6 @@ const GENDER_OPTIONS = [
{ value: '0', label: '未知' },
]
function maskPhone(phone: string): string {
const digits = phone.replace(/\D/g, '')
if (digits.length < 7) return phone
return digits.replace(/(\d{3})\d{4}(\d+)/, '$1****$2')
}
function formatLocation(province: string, city: string, district: string): string {
const primary = province || city
if (primary && district) return `${primary} · ${district}`
@@ -36,7 +30,6 @@ function createEmptyForm(): ProfileFormState {
province: '',
city: '',
district: '',
phonenumber: '',
avatarUrl: '',
avatarOssId: '',
}
@@ -51,7 +44,6 @@ export function useEditProfile() {
const nicknameDialogVisible = ref(false)
const regionPickerVisible = ref(false)
const maskedPhone = computed(() => maskPhone(form.value.phonenumber))
const genderText = computed(() => GENDER_LABELS[form.value.gender] || '未知')
const locationText = computed(() =>
formatLocation(form.value.province, form.value.city, form.value.district),
@@ -64,7 +56,6 @@ export function useEditProfile() {
province: profile.province || '',
city: profile.city || '',
district: profile.district || '',
phonenumber: profile.phonenumber || profile.userName || '',
avatarUrl: profile.avatarUrl || '',
avatarOssId: profile.avatarOssId ? String(profile.avatarOssId) : '',
}
@@ -177,10 +168,6 @@ export function useEditProfile() {
form.value.district = value.district
}
function onChangePhone() {
uni.navigateTo({ url: '/pages/mine/change-phone/index' })
}
async function onSave() {
const nickName = form.value.nickName.trim()
if (!nickName) {
@@ -218,16 +205,11 @@ export function useEditProfile() {
void loadProfile()
})
onShow(() => {
void refreshPhoneFromServer()
})
return {
loading,
saving,
uploadingAvatar,
form,
maskedPhone,
genderText,
locationText,
regionPickerVisible,
@@ -243,7 +225,6 @@ export function useEditProfile() {
onBirthdayChange,
onOpenRegionPicker,
onConfirmRegion,
onChangePhone,
onSave,
}
}

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="mine-page">
<view class="mine-page__content" :style="{ paddingTop: statusBarHeight + 16 + 'px' }">
<view class="mine-page__profile">

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="notify-page">
<app-navbar title="通知">
<template #right>

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="privacy-page">
<app-navbar title="账号与安全" />

View File

@@ -5,6 +5,10 @@ import { fetchProfile } from '@/api/profile'
import { getErrorMessage } from '@/utils/api-error'
import { teardownMessageInbox } from '@/hooks/use-message-inbox'
import { clearStoredToken } from '@/utils/auth-token'
import {
formatPasswordModifiedDesc,
getPasswordModifiedAt,
} from '@/utils/password-modified-at'
import type { PrivacySection } from './privacy.types'
function maskPhone(phone?: string): string {
@@ -15,6 +19,7 @@ function maskPhone(phone?: string): string {
export function usePrivacy() {
const phone = ref('')
const passwordModifiedAt = ref<number | null>(null)
const cancelAccountDialogVisible = ref(false)
const cancelingAccount = ref(false)
@@ -26,7 +31,7 @@ export function usePrivacy() {
{
id: 'password',
title: '登录密码',
desc: '上次修改:30天前',
desc: formatPasswordModifiedDesc(passwordModifiedAt.value),
},
{
id: 'phone',
@@ -112,7 +117,12 @@ export function usePrivacy() {
})
}
function loadPasswordModifiedAt() {
passwordModifiedAt.value = getPasswordModifiedAt()
}
onShow(() => {
loadPasswordModifiedAt()
void loadProfile()
})

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="set-password-page">
<app-navbar title="设置新密码" />
<view class="set-password-page__body">

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="set-password-page">
<app-navbar title="验证手机号" />
<view class="set-password-page__body">

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="set-password-page">
<app-navbar title="身份验证" />
<view class="set-password-page__body">

View File

@@ -1,4 +1,4 @@
<template>
<template>
<view class="storage-page">
<app-navbar title="储存空间" />

View File

@@ -39,7 +39,7 @@ function resolveCsChatWsBase(): string {
const httpBase =
getApiBaseUrl()
|| import.meta.env.VITE_API_PROXY_TARGET?.trim()
|| 'http://192.168.0.222:8082'
|| 'https://smart.bugtc.com'
const wsBase = httpBase.replace(/^https/i, 'wss').replace(/^http/i, 'ws').replace(/\/$/, '')
return `${wsBase}/app/cs/chat`
}

View File

@@ -1,17 +1,18 @@
<template>
<template>
<view class="support-page">
<app-navbar title="在线客服">
<template #right>
<view v-if="showTransfer" class="support-page__nav-action" @tap="onTransferHuman">
<text class="support-page__nav-action-text">转人工</text>
</view>
<view v-else-if="showEndSession" class="support-page__nav-action" @tap="onEndSession">
<text class="support-page__nav-action-text support-page__nav-action-text--end">结束</text>
</view>
</template>
</app-navbar>
<view class="support-page__top">
<app-navbar title="在线客服">
<template #right>
<view v-if="showTransfer" class="support-page__nav-action" @tap="onTransferHuman">
<text class="support-page__nav-action-text">转人工</text>
</view>
<view v-else-if="showEndSession" class="support-page__nav-action" @tap="onEndSession">
<text class="support-page__nav-action-text support-page__nav-action-text--end">结束</text>
</view>
</template>
</app-navbar>
<view class="support-page__header">
<view class="support-page__header">
<view
class="support-page__header-avatar"
:class="`support-page__header-avatar--${headerInfo.avatarShape}`"
@@ -39,11 +40,13 @@
<text v-if="headerInfo.serviceHours" class="support-page__header-hours">
{{ headerInfo.serviceHours }}
</text>
</view>
</view>
<scroll-view
class="support-page__chat"
scroll-y
:scroll-top="scrollTop"
:scroll-into-view="scrollIntoView"
scroll-with-animation
>
@@ -247,6 +250,10 @@
<text v-else>我</text>
</view>
</view>
<view v-else-if="item.type === 'session-ended'" class="support-page__session-ended">
<text class="support-page__session-ended-text">{{ item.text }}</text>
</view>
</template>
<view id="chat-bottom" />
</view>
@@ -272,10 +279,13 @@
v-model="inputValue"
class="support-page__input"
type="text"
placeholder="输入你的问题.."
:placeholder="sessionEnded ? '输入消息开始新会话…' : '输入你的问题..'"
placeholder-class="support-page__input-placeholder"
confirm-type="send"
@confirm="onSend"
:adjust-position="true"
:cursor-spacing="0"
@focus="onInputFocus"
@confirm="handleSend"
/>
</view>
@@ -286,7 +296,7 @@
mode="aspectFit"
/>
</view>
<view class="support-page__send" @tap="onSend">
<view class="support-page__send" @tap="handleSend">
<image
class="support-page__send-icon"
:src="staticAssets.iconSupportSend"
@@ -299,9 +309,10 @@
</template>
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { computed, watch } from 'vue'
import { staticAssets } from '@/utils/static-assets'
import { useCsChatImage } from './use-cs-chat-image'
import { useSupportChatScroll } from './use-support-chat-scroll'
import { useSupport } from './use-support'
import type { DiagnosisItem } from './support.types'
@@ -312,6 +323,7 @@ const {
userAvatarUrl,
showTransfer,
showEndSession,
sessionEnded,
formattedQueueWait,
footerShortcuts,
onQuickAction,
@@ -325,21 +337,30 @@ const {
onPickImage,
} = useSupport()
const { scrollTop, scrollIntoView, scrollToBottom } = useSupportChatScroll(messages)
const humanAvatarText = computed(() => headerInfo.value.avatarText || '服')
const { displaySrc: chatImageDisplaySrc, onImageError: onChatImageError } = useCsChatImage(
() => messages.value,
)
const scrollIntoView = ref('chat-bottom')
watch(sessionEnded, (ended) => {
if (!ended) return
void scrollToBottom(80)
void scrollToBottom(300)
})
watch(
() => messages.value.length,
async () => {
await nextTick()
scrollIntoView.value = 'chat-bottom'
},
)
function onInputFocus() {
void scrollToBottom(80)
void scrollToBottom(280)
}
function handleSend() {
onSend()
void scrollToBottom(80)
void scrollToBottom(400)
}
function diagnosisStatusText(status: DiagnosisItem['status']): string {
if (status === 'done') return '已完成'

View File

@@ -1,11 +1,64 @@
/** 客服页运行时状态(模块级,确保离开页面后定时器可被彻底清理) */
let pageActive = false
let cachedCsSessionId = ''
let cachedHistorySessionId = ''
export function getCachedCsSessionId(): string {
return cachedCsSessionId
}
export function setCachedCsSessionId(sessionId: string) {
cachedCsSessionId = sessionId.trim()
}
export function clearCachedCsSessionId() {
cachedCsSessionId = ''
}
export function getCachedHistorySessionId(): string {
return cachedHistorySessionId
}
export function setCachedHistorySessionId(sessionId: string) {
cachedHistorySessionId = sessionId.trim()
}
export function clearCachedHistorySessionId() {
cachedHistorySessionId = ''
}
/** 排队等待起始时间(按会话缓存,离开页面后继续累计) */
export const QUEUE_WAIT_MAX_SECONDS = 30 * 60
let queueWaitStartedAt = 0
let queueWaitSessionId = ''
export function ensureQueueWaitTracking(sessionId: string) {
const sid = sessionId.trim()
if (!sid) return
if (queueWaitSessionId === sid && queueWaitStartedAt > 0) return
queueWaitSessionId = sid
queueWaitStartedAt = Date.now()
}
export function getQueueWaitElapsedSeconds(sessionId?: string): number {
const sid = (sessionId || queueWaitSessionId).trim()
if (!sid || sid !== queueWaitSessionId || !queueWaitStartedAt) return 0
const elapsed = Math.max(0, Math.floor((Date.now() - queueWaitStartedAt) / 1000))
return Math.min(elapsed, QUEUE_WAIT_MAX_SECONDS)
}
export function resetQueueWaitTracking() {
queueWaitStartedAt = 0
queueWaitSessionId = ''
}
let pollTimer: ReturnType<typeof setInterval> | null = null
let messagePollTimer: ReturnType<typeof setInterval> | null = null
let queueTimer: ReturnType<typeof setInterval> | null = null
const QUEUE_POLL_INTERVAL_MS = 5000
const MESSAGE_POLL_INTERVAL_MS = 10000
const MESSAGE_POLL_INTERVAL_MS = 5000
export function isSupportPageActive(): boolean {
return pageActive

View File

@@ -1,6 +1,6 @@
import { isCsAuthError, request, uploadAppFile } from '@/api/request'
import { getCsApiBaseUrl } from '@/config/app-env'
import { ApiError } from '@/utils/api-error'
import { ApiError, getErrorMessage } from '@/utils/api-error'
import {
isSessionEnded,
normalizeCsMediaUrl,
@@ -78,42 +78,100 @@ export function createCsSession(data: CsCreateSessionBody = {}) {
})
}
async function fetchActiveCsSession(): Promise<CsSessionVo | null> {
export async function fetchActiveCsSession(): Promise<CsSessionVo | null> {
const list = await fetchCsSessionList({ pageNum: 1, pageSize: 20 })
const active = list.find((item) => !isSessionEnded(item)) ?? list[0]
const active = list.find((item) => !isSessionEnded(item))
if (!active || !normalizeSessionId(active)) return null
return normalizeSessionResponse(active)
}
/** 创建或获取当前客服会话(兼容 action 包装、id 字段、需二次查询列表) */
export async function resolveCsSession(): Promise<CsResolvedSession> {
let resolved = unwrapCsActionResponse(await createCsSession())
let session = resolved.session
let messages = resolved.messages
let sessionId = normalizeSessionId(session)
/** 最近一条会话(含已结束),用于进入页面时展示历史对话 */
export async function fetchLatestCsSession(): Promise<CsSessionVo | null> {
const list = await fetchCsSessionList({ pageNum: 1, pageSize: 20 })
const latest = list.find((item) => normalizeSessionId(item))
if (!latest) return null
return normalizeSessionResponse(latest)
}
if (!sessionId) {
const active = await fetchActiveCsSession()
if (active) {
session = active
sessionId = normalizeSessionId(active)
messages = undefined
}
}
let resolveCsSessionPromise: Promise<CsResolvedSession> | null = null
function isRepeatSubmitError(err: unknown): boolean {
const msg = getErrorMessage(err, '').toLowerCase()
return msg.includes('repeat submit') || msg.includes('重复提交')
}
function delay(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms))
}
async function finalizeCsSession(
session: CsSessionVo,
messages?: CsMessageVo[],
): Promise<CsResolvedSession> {
const sessionId = normalizeSessionId(session)
if (!sessionId) {
throw new ApiError('未获取客服会话,请确认已登录后重试')
}
let normalized = session
if (session.status === undefined && session.sessionStatus === undefined) {
try {
session = normalizeSessionResponse(await fetchCsSessionDetail(sessionId))
normalized = normalizeSessionResponse(await fetchCsSessionDetail(sessionId))
} catch {
session = { ...session, sessionId }
normalized = { ...session, sessionId }
}
}
return { session, messages }
return { session: normalized, messages }
}
async function resolveCsSessionInternal(): Promise<CsResolvedSession> {
const existing = await fetchActiveCsSession()
if (existing) {
return finalizeCsSession(existing)
}
try {
const resolved = unwrapCsActionResponse(await createCsSession())
const session = resolved.session
const messages = resolved.messages
const sessionId = normalizeSessionId(session)
if (!sessionId) {
const active = await fetchActiveCsSession()
if (active) {
return finalizeCsSession(active)
}
throw new ApiError('未获取客服会话,请确认已登录后重试')
}
return finalizeCsSession(session, messages)
} catch (err) {
if (!isRepeatSubmitError(err)) throw err
for (const waitMs of [300, 600, 1000]) {
await delay(waitMs)
const active = await fetchActiveCsSession()
if (active) {
return finalizeCsSession(active)
}
}
throw err
}
}
/** 创建或获取当前客服会话(兼容 action 包装、id 字段、需二次查询列表) */
export async function resolveCsSession(): Promise<CsResolvedSession> {
if (resolveCsSessionPromise) return resolveCsSessionPromise
resolveCsSessionPromise = resolveCsSessionInternal()
try {
return await resolveCsSessionPromise
} finally {
resolveCsSessionPromise = null
}
}
/** GET /app/cs/session/list — 查询自己的会话 */
@@ -142,6 +200,38 @@ export function fetchCsMessages(sessionId: string, afterSeq = 0) {
}).then(unwrapRows)
}
function getMessageSeq(message: CsMessageVo): number {
const seq = message.seq
return typeof seq === 'number' && Number.isFinite(seq) ? seq : 0
}
/** 分页拉取完整会话历史(接口按 afterSeq 增量返回,需循环直到无新消息) */
export async function fetchAllCsMessages(sessionId: string): Promise<CsMessageVo[]> {
const merged = new Map<string, CsMessageVo>()
let afterSeq = 0
let guard = 0
while (guard < 100) {
guard += 1
const batch = await fetchCsMessages(sessionId, afterSeq)
if (!batch.length) break
let maxSeq = afterSeq
for (const message of batch) {
const key = message.messageId != null && message.messageId !== ''
? String(message.messageId)
: `seq-${getMessageSeq(message)}`
merged.set(key, message)
maxSeq = Math.max(maxSeq, getMessageSeq(message))
}
if (maxSeq <= afterSeq) break
afterSeq = maxSeq
}
return [...merged.values()].sort((a, b) => getMessageSeq(a) - getMessageSeq(b))
}
/** POST /app/cs/upload — 优先 212;鉴权失败时回退主站 222 */
export async function uploadCsChatImage(filePath: string): Promise<CzCsUploadVo> {
try {

View File

@@ -11,12 +11,18 @@ $support-danger: #f04438;
.support-page {
height: 100vh;
background: #fff;
display: flex;
flex-direction: column;
background: #fff;
overflow: hidden;
}
.support-page__top {
flex-shrink: 0;
z-index: 20;
background: #fff;
}
.support-page :deep(.app-navbar) {
background: #fff;
}
@@ -147,6 +153,7 @@ $support-danger: #f04438;
.support-page__chat {
flex: 1;
min-height: 0;
width: 100%;
padding: 0 24rpx;
box-sizing: border-box;
}
@@ -170,6 +177,21 @@ $support-danger: #f04438;
line-height: 1.4;
}
.support-page__session-ended {
display: flex;
justify-content: center;
margin: 16rpx 0 32rpx;
}
.support-page__session-ended-text {
padding: 8rpx 24rpx;
border-radius: 20rpx;
background: #eef1f5;
font-size: 22rpx;
color: $support-text-secondary;
line-height: 1.4;
}
.support-page__msg {
display: flex;
align-items: flex-start;
@@ -622,9 +644,11 @@ $support-danger: #f04438;
.support-page__footer {
flex-shrink: 0;
z-index: 30;
background: #fff;
padding: 12rpx 24rpx calc(12rpx + env(safe-area-inset-bottom));
border-top: 1rpx solid #f0f0f0;
box-sizing: border-box;
}
.support-page__footer-shortcuts {

View File

@@ -73,17 +73,19 @@ export interface CsCreateSessionBody {
accessType?: 'bot' | 'human'
}
export interface CsRobotVo {
kbId?: number | string
title?: string
content?: string
matched?: boolean
buttons?: Array<{ buttonCode?: string; label?: string }>
}
/** POST /app/cs/session 及发消息等操作返回 data */
export interface CsAppActionVo {
session?: CsSessionVo
messages?: CsMessageVo[]
robot?: {
kbId?: number | string
title?: string
content?: string
matched?: boolean
buttons?: Array<{ buttonCode?: string; label?: string }>
}
robot?: CsRobotVo
}
export interface CsResolvedSession {
@@ -118,7 +120,7 @@ export interface CsClickButtonBody {
buttonCode: CsButtonCode
}
export type SupportPhase = 'bot' | 'queue' | 'human'
export type SupportPhase = 'bot' | 'queue' | 'human' | 'ended'
export type ChatRole = 'user' | 'bot' | 'agent' | 'system'
@@ -186,6 +188,11 @@ export type SupportMessage =
src: string
createTime?: string
}
| {
id: string
type: 'session-ended'
text: string
}
export interface SupportHeaderInfo {
name: string

View File

@@ -2,6 +2,7 @@ import type {
ChatRole,
CsAppActionVo,
CsMessageVo,
CsRobotVo,
CsSessionVo,
QuickActionItem,
SupportMessage,
@@ -60,20 +61,22 @@ function resolveMediaBaseUrl(): string {
return envUrl.replace(/\/$/, '')
}
const QUICK_ACTIONS: QuickActionItem[] = [
export const DEFAULT_QUICK_ACTIONS: QuickActionItem[] = [
{ id: 'wifi', label: '设备连不上 Wi-Fi' },
{ id: 'order', label: '订单怎么修改' },
{ id: 'invoice', label: '申请电子发票' },
{ id: 'device', label: '设备使用问题' },
]
const QUICK_ACTIONS = DEFAULT_QUICK_ACTIONS
export function createClientMsgId(): string {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
export function unwrapCsActionResponse(
data: CsAppActionVo | CsSessionVo | string | null | undefined,
): { session: CsSessionVo; messages?: CsMessageVo[] } {
): { session: CsSessionVo; messages?: CsMessageVo[]; robot?: CsRobotVo } {
if (!data) return { session: {} }
if (typeof data === 'string') {
return { session: normalizeSessionResponse(data) }
@@ -82,16 +85,56 @@ export function unwrapCsActionResponse(
return {
session: normalizeSessionResponse(data.session),
messages: data.messages,
robot: data.robot,
}
}
const record = data as CsSessionVo & { messages?: CsMessageVo[] }
const { messages, ...session } = record
const record = data as CsSessionVo & CsAppActionVo
const { messages, robot, ...session } = record
return {
session: normalizeSessionResponse(session),
messages,
robot,
}
}
/** 将发消息接口返回的 robot 字段转为可展示消息 */
export function mapRobotReplyToMessages(robot?: CsRobotVo): SupportMessage[] {
if (!robot) return []
const result: SupportMessage[] = []
const title = robot.title?.trim()
const content = robot.content?.trim()
const text = title && content && title !== content
? `${title}\n${content}`
: (content || title || '')
if (text) {
result.push({
id: `robot-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
type: 'text',
role: 'bot',
content: text,
})
}
const actions = (robot.buttons ?? [])
.map((item, index) => ({
id: item.buttonCode?.trim() || `robot-btn-${index}`,
label: item.label?.trim() || '',
}))
.filter((item) => item.label)
if (actions.length) {
result.push({
id: `robot-actions-${Date.now()}`,
type: 'quick-actions',
actions,
})
}
return result
}
export function normalizeSessionResponse(
data: CsSessionVo | string | null | undefined,
): CsSessionVo {
@@ -146,7 +189,7 @@ export function isSessionEnded(session: CsSessionVo): boolean {
}
export function resolvePhaseFromSession(session: CsSessionVo): SupportPhase {
if (isSessionEnded(session)) return 'bot'
if (isSessionEnded(session)) return 'ended'
if (hasAssignedAgent(session)) return 'human'
const status = normalizeStatusToken(getSessionStatus(session))
if (status === CS_SESSION_STATUS.queue) return 'queue'
@@ -558,10 +601,10 @@ export function getMaxSeq(messages: SupportMessage[]): number {
return messages.reduce((max, item) => Math.max(max, item.seq ?? 0), 0)
}
export function buildQuickActionsMessage(): SupportMessage {
export function buildQuickActionsMessage(id?: string): SupportMessage {
return {
id: 'local-quick-actions',
id: id || `quick-actions-${Date.now()}`,
type: 'quick-actions',
actions: QUICK_ACTIONS,
actions: DEFAULT_QUICK_ACTIONS,
}
}

View File

@@ -0,0 +1,74 @@
import { getCurrentInstance, nextTick, onMounted, ref, watch, type Ref } from 'vue'
import type { SupportMessage } from './support.types'
export function useSupportChatScroll(messages: Ref<readonly SupportMessage[]>) {
const scrollTop = ref(0)
const scrollIntoView = ref('')
let scrollJob = 0
function queryChatInnerHeight(): Promise<number> {
return new Promise((resolve) => {
const query = uni.createSelectorQuery()
const instance = getCurrentInstance()
if (instance?.proxy) {
query.in(instance.proxy)
}
query
.select('.support-page__chat-inner')
.boundingClientRect()
.exec((rects) => {
const inner = rects?.[0]
const height = inner && !Array.isArray(inner) ? inner.height ?? 0 : 0
resolve(height)
})
})
}
async function scrollToBottom(delayMs = 0) {
const job = ++scrollJob
if (delayMs > 0) {
await new Promise<void>((resolve) => {
setTimeout(resolve, delayMs)
})
}
if (job !== scrollJob) return
scrollIntoView.value = ''
await nextTick()
const innerHeight = await queryChatInnerHeight()
if (job !== scrollJob) return
if (innerHeight > 0) {
scrollTop.value = innerHeight + job
}
scrollIntoView.value = 'chat-bottom'
await nextTick()
scrollIntoView.value = ''
await nextTick()
scrollIntoView.value = 'chat-bottom'
}
watch(
messages,
() => {
void scrollToBottom()
void scrollToBottom(120)
void scrollToBottom(320)
void scrollToBottom(600)
},
{ deep: true },
)
onMounted(() => {
void scrollToBottom(80)
void scrollToBottom(400)
})
return {
scrollTop,
scrollIntoView,
scrollToBottom,
}
}

View File

@@ -8,8 +8,11 @@ import { getStoredToken } from '@/utils/auth-token'
import {
clickCsButton,
endCsSession,
fetchActiveCsSession,
fetchAllCsMessages,
fetchCsMessages,
fetchCsSessionDetail,
fetchLatestCsSession,
resolveCsSession,
buildCsImageMessageBody,
sendCsMessage,
@@ -23,8 +26,17 @@ import {
onCsChatPush,
} from './cs-chat-socket'
import {
clearCachedCsSessionId,
clearCachedHistorySessionId,
getCachedCsSessionId,
getCachedHistorySessionId,
isSupportPageActive,
markSupportPageActive,
setCachedCsSessionId,
setCachedHistorySessionId,
ensureQueueWaitTracking,
getQueueWaitElapsedSeconds,
resetQueueWaitTracking,
startSupportMessagePolling,
startSupportQueuePolling,
startSupportQueueWaitTimer,
@@ -40,17 +52,19 @@ import type {
SupportPhase,
} from './support.types'
import {
buildQuickActionsMessage,
createClientMsgId,
buildQuickActionsMessage,
getMaxSeq,
getQueueEstimate,
getQueuePosition,
injectTimeDividers,
mapCsMessage,
mapRobotReplyToMessages,
mergeSupportMessages,
cacheSentImageRefs,
normalizeCsMediaUrl,
normalizeSessionId,
normalizeSessionResponse,
registerLocalImagePreview,
resolvePhaseFromSession,
unwrapCsActionResponse,
@@ -74,9 +88,18 @@ const HUMAN_HEADER: SupportHeaderInfo = {
avatarShape: 'square',
}
const FOOTER_SHORTCUTS = ['常见问题', '退改政策']
const ENDED_HEADER: SupportHeaderInfo = {
name: '智能客服 · 小智',
badgeText: '已结束',
badgeType: 'serving',
avatarText: '智',
avatarShape: 'square',
serviceHours: '7×24 小时',
}
const MESSAGE_SYNC_MIN_GAP_MS = 3000
const FOOTER_SHORTCUTS = ['常见问题']
const MESSAGE_SYNC_MIN_GAP_MS = 1500
function formatWait(seconds: number): string {
return `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`
@@ -112,21 +135,20 @@ export function useSupport() {
let syncingMessages = false
let lastMessageSyncAt = 0
const headerInfo = computed<SupportHeaderInfo>(() =>
phase.value === 'human' ? humanHeader.value : BOT_HEADER,
)
const headerInfo = computed<SupportHeaderInfo>(() => {
if (phase.value === 'ended') return ENDED_HEADER
if (phase.value === 'human') return humanHeader.value
return BOT_HEADER
})
const formattedQueueWait = computed(() => formatWait(queueWaitSeconds.value))
const showTransfer = computed(() => phase.value === 'bot')
const showTransfer = computed(() => phase.value === 'bot' || phase.value === 'ended')
const showEndSession = computed(() => phase.value === 'queue' || phase.value === 'human')
const sessionEnded = computed(() => phase.value === 'ended')
const messages = computed<SupportMessage[]>(() => {
const list = [...apiMessages.value]
const hasQuickActions = list.some((item) => item.type === 'quick-actions')
if (phase.value === 'bot' && !hasQuickActions) {
list.push(buildQuickActionsMessage())
}
if (phase.value === 'queue') {
list.push({
id: 'queue-card',
@@ -135,18 +157,55 @@ export function useSupport() {
estimateText: queueEstimate.value,
})
}
if (phase.value === 'ended') {
list.push({
id: 'session-ended',
type: 'session-ended',
text: '会话已结束',
})
}
return injectTimeDividers(list)
})
function clearQueueTimer() {
function stopSessionTransport() {
unbindChatSocket()
stopSupportPollTimer()
stopSupportMessagePollTimer()
clearQueueTimer()
}
function markSessionEnded() {
stopSessionTransport()
if (sessionId.value) {
setCachedHistorySessionId(sessionId.value)
}
clearCachedCsSessionId()
sessionId.value = ''
phase.value = 'ended'
}
function syncQueueWaitSeconds() {
queueWaitSeconds.value = getQueueWaitElapsedSeconds(sessionId.value)
}
function stopQueueWaitDisplay() {
stopSupportQueueTimer()
}
function clearQueueTimer() {
stopQueueWaitDisplay()
resetQueueWaitTracking()
queueWaitSeconds.value = 0
}
function startQueueTimer() {
clearQueueTimer()
stopQueueWaitDisplay()
if (sessionId.value) {
ensureQueueWaitTracking(sessionId.value)
}
syncQueueWaitSeconds()
startSupportQueueWaitTimer(() => {
queueWaitSeconds.value += 1
syncQueueWaitSeconds()
})
}
@@ -206,10 +265,12 @@ export function useSupport() {
}
function applyActionMessages(action: ReturnType<typeof unwrapCsActionResponse>) {
if (!action.messages?.length) return
const mapped = action.messages
.map(mapCsMessage)
.filter((item): item is SupportMessage => !!item)
const mapped = [
...(action.messages ?? [])
.map(mapCsMessage)
.filter((item): item is SupportMessage => !!item),
...mapRobotReplyToMessages(action.robot),
]
if (!mapped.length) return
apiMessages.value = mergeSupportMessages(apiMessages.value, mapped)
lastSeq.value = getMaxSeq(apiMessages.value)
@@ -220,6 +281,14 @@ export function useSupport() {
queuePosition.value = getQueuePosition(session)
queueEstimate.value = getQueueEstimate(session)
if (nextPhase === 'ended') {
phase.value = 'ended'
clearQueueTimer()
stopSupportPollTimer()
stopSupportMessagePollTimer()
return
}
if (nextPhase === 'human') {
humanHeader.value = buildHumanHeader(session)
phase.value = 'human'
@@ -232,7 +301,7 @@ export function useSupport() {
if (nextPhase === 'queue') {
phase.value = 'queue'
if (queueWaitSeconds.value === 0) startQueueTimer()
startQueueTimer()
updateQueuePolling()
updateMessagePolling()
return
@@ -245,16 +314,18 @@ export function useSupport() {
updateMessagePolling()
}
async function syncMessages(reset = false, force = false) {
if (!isSupportPageActive() || !sessionId.value || syncingMessages) return
async function syncMessages(reset = false, force = false, targetSessionId?: string) {
const sid = targetSessionId || sessionId.value
if (!isSupportPageActive() || !sid || syncingMessages) return
const now = Date.now()
if (!reset && !force && now - lastMessageSyncAt < MESSAGE_SYNC_MIN_GAP_MS) return
syncingMessages = true
try {
const afterSeq = reset ? 0 : lastSeq.value
const rows = await fetchCsMessages(sessionId.value, afterSeq)
const rows = reset
? await fetchAllCsMessages(sid)
: await fetchCsMessages(sid, lastSeq.value)
const mapped = rows.map(mapCsMessage).filter((item): item is SupportMessage => !!item)
if (reset) {
apiMessages.value = mapped
@@ -270,6 +341,67 @@ export function useSupport() {
}
}
async function loadHistorySession(targetSessionId: string) {
sessionInitializing.value = true
try {
const session = normalizeSessionResponse(
await fetchCsSessionDetail(targetSessionId),
)
setCachedHistorySessionId(targetSessionId)
sessionId.value = ''
clearCachedCsSessionId()
applySessionState(session)
lastSeq.value = 0
await syncMessages(true, true, targetSessionId)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '历史会话加载失败'), icon: 'none' })
} finally {
sessionInitializing.value = false
}
}
async function initSupportPage() {
if (sessionInitializing.value) return
sessionInitializing.value = true
try {
const active = await fetchActiveCsSession()
if (active) {
const nextSessionId = normalizeSessionId(active)
if (!nextSessionId) return
sessionId.value = nextSessionId
setCachedCsSessionId(nextSessionId)
applySessionState(active)
lastSeq.value = 0
await syncMessages(true, true, nextSessionId)
bindChatSocket(nextSessionId)
updateQueuePolling()
updateMessagePolling()
return
}
const historyId = getCachedHistorySessionId()
if (historyId) {
await loadHistorySession(historyId)
return
}
const latest = await fetchLatestCsSession()
const latestId = latest ? normalizeSessionId(latest) : ''
if (latest && latestId) {
await loadHistorySession(latestId)
return
}
await ensureSession()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '客服会话加载失败'), icon: 'none' })
} finally {
sessionInitializing.value = false
}
}
async function refreshSession() {
if (!isSupportPageActive() || !sessionId.value) return
try {
@@ -290,10 +422,10 @@ export function useSupport() {
function teardownPage() {
pausePage()
unbindChatSocket()
clearQueueTimer()
}
async function ensureSession() {
async function ensureSession(options: { resetMessages?: boolean } = {}) {
const resetMessages = options.resetMessages ?? true
if (ensureSessionPromise) return ensureSessionPromise
ensureSessionPromise = (async () => {
@@ -310,13 +442,14 @@ export function useSupport() {
const sessionChanged = sessionId.value !== nextSessionId
sessionId.value = nextSessionId
setCachedCsSessionId(nextSessionId)
applySessionState(session)
if (sessionChanged) {
lastSeq.value = 0
if (resolved.messages?.length) {
applyActionMessages(resolved)
} else {
} else if (resetMessages) {
await syncMessages(true)
}
} else if (resolved.messages?.length) {
@@ -363,6 +496,10 @@ export function useSupport() {
async function sendUserImageMessage(ossId: string | number, previewUrl?: string) {
if (!ossId || sending.value) return
if (sessionEnded.value) {
await startNewSession(true)
}
if (!sessionId.value) {
await ensureSession()
if (!sessionId.value) {
@@ -436,6 +573,10 @@ export function useSupport() {
const text = content.trim()
if (!text || sending.value) return
if (sessionEnded.value) {
await startNewSession(true)
}
if (!sessionId.value) {
await ensureSession()
if (!sessionId.value) {
@@ -454,11 +595,16 @@ export function useSupport() {
if (action.session) {
applySessionState(action.session)
}
if (action.messages?.length) {
const hasInlineReply = (action.messages?.length ?? 0) > 0
|| mapRobotReplyToMessages(action.robot).length > 0
if (hasInlineReply) {
applyActionMessages(action)
} else if (!isCsChatSocketConnected()) {
await syncMessages()
}
if (!hasInlineReply && action.robot?.matched === false) {
uni.showToast({ title: '暂无匹配解答,请换个描述或转人工', icon: 'none' })
}
await refreshSession()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '发送失败'), icon: 'none' })
@@ -473,7 +619,17 @@ export function useSupport() {
}
async function onTransferHuman() {
if (!sessionId.value || phase.value !== 'bot' || sending.value) return
if (sending.value || sessionInitializing.value) return
if (phase.value !== 'bot' && phase.value !== 'ended') return
if (sessionEnded.value || !sessionId.value) {
await startNewSession(true)
}
if (!sessionId.value) {
uni.showToast({ title: '会话未就绪,请稍后重试', icon: 'none' })
return
}
sending.value = true
try {
@@ -490,18 +646,25 @@ export function useSupport() {
}
}
async function restartSession() {
teardownPage()
async function startNewSession(keepHistory = false) {
if (sending.value || sessionInitializing.value) return
stopSessionTransport()
clearCachedCsSessionId()
sessionId.value = ''
apiMessages.value = []
if (!keepHistory) {
apiMessages.value = []
clearCachedHistorySessionId()
}
lastSeq.value = 0
phase.value = 'bot'
humanHeader.value = HUMAN_HEADER
markSupportPageActive(true)
await ensureSession()
await ensureSession({ resetMessages: !keepHistory })
}
async function onEndSession() {
if (!sessionId.value || sending.value) return
if (!sessionId.value || sending.value || sessionEnded.value) return
if (phase.value !== 'queue' && phase.value !== 'human') return
const confirmed = await new Promise<boolean>((resolve) => {
@@ -517,9 +680,10 @@ export function useSupport() {
if (!confirmed) return
sending.value = true
const endingSessionId = sessionId.value
try {
await endCsSession(sessionId.value)
await restartSession()
await endCsSession(endingSessionId)
markSessionEnded()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '结束会话失败'), icon: 'none' })
} finally {
@@ -532,7 +696,7 @@ export function useSupport() {
sending.value = true
try {
await endCsSession(sessionId.value)
await restartSession()
await startNewSession()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '取消排队失败'), icon: 'none' })
} finally {
@@ -555,7 +719,27 @@ export function useSupport() {
}
}
function appendFaqQuickActions() {
if (phase.value !== 'bot') return
const ts = Date.now()
const next: SupportMessage[] = [
{
id: `faq-user-${ts}`,
type: 'text',
role: 'user',
content: '常见问题',
createTime: new Date().toISOString(),
},
buildQuickActionsMessage(`faq-actions-${ts}`),
]
apiMessages.value = mergeSupportMessages(apiMessages.value, next)
}
function onFooterShortcut(label: string) {
if (label === '常见问题') {
appendFaqQuickActions()
return
}
void sendUserMessage(label)
}
@@ -573,6 +757,11 @@ export function useSupport() {
return
}
if (text === '常见问题' && phase.value === 'bot') {
appendFaqQuickActions()
return
}
void sendUserMessage(text)
}
@@ -594,14 +783,29 @@ export function useSupport() {
return
}
void loadUserProfile()
if (!sessionId.value) {
void ensureSession()
if (sessionId.value) {
bindChatSocket(sessionId.value)
updateQueuePolling()
updateMessagePolling()
const fullReload = phase.value === 'ended' || apiMessages.value.length === 0
void syncMessages(fullReload, true)
void refreshSession()
return
}
bindChatSocket(sessionId.value)
updateQueuePolling()
updateMessagePolling()
void syncMessages(false, true)
const cached = getCachedCsSessionId()
if (cached) {
sessionId.value = cached
bindChatSocket(cached)
updateQueuePolling()
updateMessagePolling()
void syncMessages(true, true)
void refreshSession()
return
}
void initSupportPage()
}
onShow(activatePage)
@@ -618,6 +822,7 @@ export function useSupport() {
userAvatarUrl,
showTransfer,
showEndSession,
sessionEnded,
formattedQueueWait,
footerShortcuts: FOOTER_SHORTCUTS,
onQuickAction,