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

@@ -1,9 +1,8 @@
VITE_API_BASE_URL=http://192.168.0.222:8082
VITE_API_PROXY_TARGET=http://192.168.0.222:8082
# 客服图片上传在 212(/app/cs/upload 仅 212 有该接口)
VITE_CS_API_BASE_URL=http://192.168.0.212:8082
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
# H5 开发:客服 WS 走本地 Vite 代理 → VITE_API_PROXY_TARGET(勿配 212 直连)
# 若必须直连 212,取消下行并设 VITE_CS_CHAT_WS_DIRECT=true
# VITE_CS_CHAT_WS_URL=ws://192.168.0.212:8082/app/cs/chat
VITE_API_BASE_URL=https://smart.bugtc.com
VITE_API_PROXY_TARGET=https://smart.bugtc.com
VITE_CS_API_BASE_URL=https://smart.bugtc.com
VITE_MESSAGE_WS_URL=ws://smart.bugtc.com/app/ws/message
VITE_API_CLIENT_ID=428a8310cd442757ae699df5d894f051
# 高德 Web 服务 Key(逆地理编码,https://console.amap.com/dev/key/app)
VITE_AMAP_WEB_KEY=38cd7fb803c600a58c5a13e644feab34

View File

@@ -34,5 +34,14 @@ VITE_API_CLIENT_ID=428a8310cd442757ae699df5d894f051
# VITE_BLE_NOTIFY_CHAR_UUID=0000fff1-0000-1000-8000-00805f9b34fb
# VITE_BLE_DEBUG=true
# 腾讯地图 Key(可选,用于拖动地图后逆地理编码显示详细地址)
# BLE 广播名前缀(完整格式:Z2_A_<12位MAC>,默认 Z2_A_)
# VITE_BLE_DEVICE_NAME_PREFIX=Z2_A_
# 腾讯地图 Key(可选,旧版逆地理编码)
# VITE_TENCENT_MAP_KEY=
# 高德 Web 服务 Key(家庭位置逆地理编码,https://console.amap.com/dev/key/app)
# VITE_AMAP_WEB_KEY=
# App 原生地图 SDK Key 请在 src/manifest.json → sdkConfigs.maps.amap 中配置
# H5 地图 Key 请在 manifest.json → h5.sdkConfigs.maps.amap 中配置

View File

@@ -1,6 +1,9 @@
# 正式打包(npm run build:* / HBuilderX 发行)读取
VITE_API_BASE_URL=http://192.168.0.222:8082
VITE_API_PROXY_TARGET=http://192.168.0.222:8082
VITE_CS_API_BASE_URL=http://192.168.0.212:8082
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
VITE_API_BASE_URL=https://smart.bugtc.com
VITE_API_PROXY_TARGET=https://smart.bugtc.com
VITE_CS_API_BASE_URL=https://smart.bugtc.com
VITE_MESSAGE_WS_URL=ws://smart.bugtc.com/app/ws/message
VITE_API_CLIENT_ID=428a8310cd442757ae699df5d894f051
# 高德 Web 服务 Key(逆地理编码)
VITE_AMAP_WEB_KEY=38cd7fb803c600a58c5a13e644feab34

View File

@@ -6,7 +6,7 @@ import {
getStoredToken,
saveStoredCsToken,
} from '@/utils/auth-token'
import { ApiError, isApiSuccess } from '@/utils/api-error'
import { ApiError, isApiSuccess, normalizeNetworkErrorMessage } from '@/utils/api-error'
import type { ApiResponse } from '@/types/api'
/** 与客服 API 同服同前缀(真机须为 .../app/auth/...,不能漏 /app) */
@@ -54,7 +54,7 @@ async function requestCsLogin(path: string, data: Record<string, unknown>): Prom
saveStoredCsToken(token)
resolve()
},
fail: (err) => reject(new ApiError(err.errMsg || 'CS 登录失败')),
fail: (err) => reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg, 'CS 登录失败'))),
})
})
}

View File

@@ -6,16 +6,26 @@ const DEFAULT_HOME_LONGITUDE = 116.4074
const DEFAULT_HOME_LATITUDE = 39.9042
const DEFAULT_HOME_ADDRESS = '未设置'
function normalizeHomeList(data: unknown): AppHomeVo[] {
if (!data) return []
if (Array.isArray(data)) return data
if (typeof data === 'object' && Array.isArray((data as { rows?: unknown }).rows)) {
return (data as { rows: AppHomeVo[] }).rows
}
return []
}
/** GET /app/home/list — 查询当前用户的家庭列表 */
export function fetchHomeList() {
return request<AppHomeVo[]>({
export async function fetchHomeList() {
const data = await request<AppHomeVo[] | { rows?: AppHomeVo[] }>({
url: '/app/home/list',
method: 'GET',
})
return normalizeHomeList(data)
}
/** POST /app/home/create — 创建家庭(返回 RVoid,需再拉列表取 ID) */
export function createHome(data: { homeName: string }) {
export function createHome(data: UpdateHomeBody) {
return request<void>({
url: '/app/home/create',
method: 'POST',
@@ -71,11 +81,15 @@ export function pickDefaultHome(homes: AppHomeVo[] | undefined): AppHomeVo | und
}
export function getHomeId(home?: AppHomeVo): string {
return parseId(home?.id)
if (!home) return ''
const raw = home.id ?? (home as { homeId?: string | number }).homeId
return parseId(raw)
}
export function findHomeById(homes: AppHomeVo[] | undefined, homeId: string | number) {
return homes?.find((item) => sameId(item.id, homeId))
return homes?.find(
(item) => sameId(item.id, homeId) || sameId((item as { homeId?: string | number }).homeId, homeId),
)
}
/**
@@ -95,7 +109,11 @@ export async function resolveValidHomeId(candidate?: string | number): Promise<s
let defaultId = getHomeId(pickDefaultHome(list))
if (defaultId) return defaultId
await createHome({ homeName: '我的家' })
try {
await createHome(buildUpdateHomeBody('我的家'))
} catch {
// 可能已存在同名家庭,继续拉列表取 ID
}
list = await fetchHomeList()
defaultId = getHomeId(pickDefaultHome(list))
return defaultId

View File

@@ -14,7 +14,7 @@ import {
getStoredToken,
saveStoredToken,
} from '@/utils/auth-token'
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
import { ApiError, isApiSuccess, normalizeNetworkErrorMessage, unwrapApiData } from '@/utils/api-error'
/** RuoYi-Vue-Plus App 端 clientId(登录等 JSON 接口) */
export const API_CLIENT_ID = getApiClientId()
@@ -64,6 +64,15 @@ export interface RequestOptions extends Omit<UniApp.RequestOptions, 'url'> {
url: string
}
/** 仅 clientId,不带登录 token(忘记密码 / 重置密码等) */
export function buildPublicHeaders(extra?: Record<string, unknown>): Record<string, string> {
return {
'Content-Type': 'application/json;charset=UTF-8',
clientId: API_CLIENT_ID,
...(extra as Record<string, string> | undefined),
}
}
/** 构建鉴权请求头:clientId + Authorization */
export function buildAuthHeaders(extra?: Record<string, unknown>): Record<string, string> {
const authorization = formatBearerAuthorization(getStoredToken())
@@ -192,7 +201,7 @@ function uploadViaUniMultipart<T>(
handleUploadSuccess<T>(res.statusCode, String(res.data ?? ''), resolve, reject)
},
fail: (err) => {
reject(new ApiError(err.errMsg || '上传失败'))
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg, '上传失败')))
},
})
})
@@ -304,7 +313,7 @@ function runRequest<T>(
dataType: 'text',
success: (res) => handleSuccess<T>(res, resolve, reject, saveTokenFromBody),
fail: (err) => {
reject(new ApiError(err.errMsg || '网络异常'))
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg)))
},
})
})
@@ -314,6 +323,11 @@ export function request<T = unknown>(options: RequestOptions): Promise<T> {
return runRequest<T>(options, `${getApiBaseUrl()}${options.url}`, buildAuthHeaders)
}
/** 无需登录态的 JSON 接口(仅传 clientId) */
export function requestPublic<T = unknown>(options: RequestOptions): Promise<T> {
return runRequest<T>(options, `${getApiBaseUrl()}${options.url}`, buildPublicHeaders)
}
/**
* 212 客服服务(与主站 222 的 CzCsMessageBo 不同:212 支持 ossId 字段)。
* 图片发消息须走此通道,且鉴权与 upload 一致(clientId=app + cs_token)。
@@ -349,7 +363,7 @@ export function requestLogin<T = unknown>(options: RequestOptions): Promise<T> {
dataType: 'text',
success: (res) => handleSuccess<T>(res, resolve, reject, true),
fail: (err) => {
reject(new ApiError(err.errMsg || '网络异常'))
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg)))
},
})
})

View File

@@ -25,6 +25,8 @@ import { staticAssets } from '@/utils/static-assets'
const props = defineProps<{
modelValue: boolean
/** 勾选前弹出确认;同意才勾选,不同意保持未勾选 */
confirmBeforeAgree?: boolean
}>()
const emit = defineEmits<{
@@ -32,6 +34,20 @@ const emit = defineEmits<{
}>()
function toggle() {
if (!props.modelValue && props.confirmBeforeAgree) {
uni.showModal({
title: '用户协议与隐私政策',
content: '请您仔细阅读并充分理解《用户服务协议》和《隐私政策》的全部内容。如您同意,请点击「同意」后继续。',
confirmText: '同意',
cancelText: '不同意',
success: (res) => {
if (res.confirm) {
emit('update:modelValue', true)
}
},
})
return
}
emit('update:modelValue', !props.modelValue)
}

View File

@@ -20,10 +20,13 @@ const props = defineProps<{
/** 外部传入时覆盖内部计算(如设备详情页自定义顶部区域) */
scrollStyle?: CSSProperties
extraBottomPx?: number
/** 页面顶部固定区域选择器(导航栏 + 步骤条等),用于计算滚动区高度 */
topSelector?: string
}>()
const { scrollStyle: defaultScrollStyle } = usePageScrollHeight({
extraBottomPx: props.extraBottomPx ?? 0,
topSelector: props.topSelector,
})
const mergedStyle = computed<CSSProperties>(() => props.scrollStyle ?? defaultScrollStyle.value)

View File

@@ -4,11 +4,14 @@
* 上线前请修改 APP_ENV_DEFAULTS,或通过 .env.production 覆盖。
*/
const APP_ENV_DEFAULTS = {
apiBaseUrl: 'http://192.168.0.222:8082',
csApiBaseUrl: 'http://192.168.0.212:8082',
messageWsUrl: 'ws://192.168.0.222:8082/app/ws/message',
apiBaseUrl: 'https://smart.bugtc.com',
csApiBaseUrl: 'https://smart.bugtc.com',
messageWsUrl: 'ws://smart.bugtc.com/app/ws/message',
apiClientId: '428a8310cd442757ae699df5d894f051',
uploadClientId: 'app',
/** HBuilderX 云打包可能未注入 .env,需在此保留 Web 服务 Key */
amapWebKey: '38cd7fb803c600a58c5a13e644feab34',
bleDeviceNamePrefix: 'Z2_A_',
} as const
function readViteEnv(key: string): string {
@@ -45,6 +48,16 @@ export function getUploadClientId(): string {
return readViteEnv('VITE_UPLOAD_CLIENT_ID') || APP_ENV_DEFAULTS.uploadClientId
}
/** 高德 Web 服务 Key(逆地理编码等 REST API) */
export function getAmapWebKey(): string {
return readViteEnv('VITE_AMAP_WEB_KEY') || APP_ENV_DEFAULTS.amapWebKey
}
/** BLE 广播名前缀,完整格式:Z2_A_<12位MAC> */
export function getBleDeviceNamePrefix(): string {
return readViteEnv('VITE_BLE_DEVICE_NAME_PREFIX') || APP_ENV_DEFAULTS.bleDeviceNamePrefix
}
/** App 打包后必须是绝对地址;H5 开发允许 /app 相对路径走代理 */
export function assertRequestUrl(url: string, hint = '接口地址'): void {
if (/^https?:\/\//i.test(url) || url.startsWith('/')) return

View File

@@ -2,7 +2,7 @@
"name" : "虫子智家",
"appid" : "__UNI__925D0CC",
"description" : "",
"versionName" : "1.0.0",
"versionName" : "1.1.6",
"versionCode" : "100",
"transformPx" : false,
/* 5+App特有相关 */
@@ -20,7 +20,9 @@
"modules" : {
"Bluetooth" : {},
"Camera" : {},
"Maps" : {}
"Push" : {},
"Maps" : {},
"Geolocation" : {}
},
/* 应用发布信息 */
"distribute" : {
@@ -39,6 +41,7 @@
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.INTERNET\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>",
@@ -53,11 +56,21 @@
},
/* ios打包配置 */
"ios" : {
"dSYMs" : false
"dSYMs" : false,
"privacyDescription" : {
"NSLocationWhenInUseUsageDescription" : "你的位置信息将用于在地图上选择家庭位置",
"NSLocationAlwaysAndWhenInUseUsageDescription" : "你的位置信息将用于在地图上选择家庭位置"
}
},
/* SDK配置 */
"sdkConfigs" : {
"maps" : {},
"maps" : {
"amap" : {
"name" : "amapxzEnK46i",
"appkey_ios" : "7d9a3ca1ef32775dd5cef9b11962ca49",
"appkey_android" : "6b0279ce51355d222b5023c1124f4581"
}
},
"push" : {
"unipush" : {
"version" : "2",

View File

@@ -108,7 +108,10 @@
"path": "pages/mine/support/index",
"style": {
"navigationStyle": "custom",
"navigationBarTitleText": "在线客服"
"navigationBarTitleText": "在线客服",
"app-plus": {
"softinputMode": "adjustResize"
}
}
},
{

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">
<view class="complete-page__top">
<app-navbar title="设备配置" />
<page-scroll-view class="complete-page__scroll">
</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">
<view class="pair-page__top">
<app-navbar title="设备配置" />
<page-scroll-view class="pair-page__scroll">
</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,8 +34,6 @@
<pair-check-list :items="checkItems" />
<pair-device-summary :device="device" :connect-status="connectStatus" />
</view>
</page-scroll-view>
<view class="pair-page__footer">
<view
v-if="connectStatus === 'failed'"
@@ -49,11 +49,14 @@
</view>
</view>
</view>
</page-scroll-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' })
} catch (err) {
if (!isBluetoothApiSupported()) {
uni.showModal({
title: '无法开启蓝牙',
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) {
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 })
markPasswordModified()
redirectToLoginAfterPasswordChange()
} catch (err) {
if (isSessionInvalidError(err)) {
markPasswordModified()
redirectToLoginAfterPasswordChange('登录状态已失效,请使用新密码重新登录')
return
}
uni.reLaunch({ url: '/pages/login/index' })
}, 800)
} catch (err) {
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,5 +1,11 @@
<template>
<scroll-view class="room-tabs" scroll-x :show-scrollbar="false">
<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"
@@ -15,6 +21,7 @@
</view>
</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
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,
})
try {
await ensureBluetoothReady()
foundDevice = await resolveBleTarget(mac, targetBleId)
if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机')
await reportDeviceOffline()
if (!tearingDown) {
reportBleLinkLostLocal()
}
return false
}
targetBleId = foundDevice.deviceId
bleDeviceId.value = targetBleId
} else {
const discovered = await getDiscoveredBluetoothDevices()
foundDevice = discovered.find((item) => item.deviceId === targetBleId) ?? null
}
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) {
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
try {
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
if (bleCmd) {
await sendBleCommand(bleCmd)
}
await updateDeviceRuntime({
try {
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: nextStatus,
bluetoothConnected: nextBluetooth,
isOnline: present,
status: '1',
bluetoothConnected: '1',
isOnline: true,
}
}
/** 通过 BLE 扫描刷新设备在线状态(status: 1在线 / 2离线) */
recordPresenceMiss(device.deviceId)
if (!shouldMarkDeviceOffline(device.deviceId, device.isOnline)) {
return device
}
return {
...device,
status: '2',
bluetoothConnected: '0',
isOnline: false,
}
}
/** 列表页仅上报「确认在线」,不因单次扫描未命中把云端写成离线 */
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<{
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>
</view>
</view>
<!-- #endif -->
<!-- #ifndef H5 -->
<map
class="location-map"
:latitude="latitude"
:longitude="longitude"
: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"
/>
<!-- #endif -->
<view class="location-map__pin" aria-hidden="true">
<view class="location-map__pin-dot" />
<view class="location-map__pin-stick" />
</view>
</view>
</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,5 +1,6 @@
<template>
<template>
<view class="home-location-page">
<view class="home-location-page__header">
<app-navbar title="家庭位置">
<template #right>
<view class="home-location-page__confirm" @tap="onConfirm">
@@ -7,28 +8,25 @@
</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">
<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,5 +1,6 @@
<template>
<template>
<view class="device-room-page">
<view class="device-room-page__top">
<app-navbar title="所在房间">
<template #right>
<view class="device-room-page__add-btn" @tap="onOpenAddDialog">
@@ -7,7 +8,9 @@
</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
}
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,5 +1,6 @@
<template>
<template>
<view class="support-page">
<view class="support-page__top">
<app-navbar title="在线客服">
<template #right>
<view v-if="showTransfer" class="support-page__nav-action" @tap="onTransferHuman">
@@ -40,10 +41,12 @@
{{ 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)
if (!sessionId) {
const active = await fetchActiveCsSession()
if (active) {
session = active
sessionId = normalizeSessionId(active)
messages = undefined
}
/** 最近一条会话(含已结束),用于进入页面时展示历史对话 */
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)
}
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'
}
/** POST /app/cs/session 及发消息等操作返回 data */
export interface CsAppActionVo {
session?: CsSessionVo
messages?: CsMessageVo[]
robot?: {
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?: 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
const mapped = [
...(action.messages ?? [])
.map(mapCsMessage)
.filter((item): item is SupportMessage => !!item)
.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 = ''
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()
return
}
if (sessionId.value) {
bindChatSocket(sessionId.value)
updateQueuePolling()
updateMessagePolling()
void syncMessages(false, true)
const fullReload = phase.value === 'ended' || apiMessages.value.length === 0
void syncMessages(fullReload, true)
void refreshSession()
return
}
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,

BIN
src/static/home-2@4x.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

BIN
src/static/house.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 352 B

BIN
src/static/linear@4x.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 434 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 382 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 559 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 461 B

BIN
src/static/user@4x (1).png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

BIN
src/static/user@4x.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@@ -1,10 +1,9 @@
@import './variables.scss';
page {
background-color: $color-bg-page;
color: $color-text;
font-size: 28rpx;
box-sizing: border-box;
overflow-x: hidden;
}
view,

306
src/utils/amap.ts Normal file
View File

@@ -0,0 +1,306 @@
import { getAmapWebKey } from '@/config/app-env'
export interface MapLocationPoint {
name?: string
address: string
latitude: number
longitude: number
}
export interface AmapSearchResult {
places: MapLocationPoint[]
error?: string
}
interface AmapBaseResponse {
status?: string | number
info?: string
infocode?: string
}
interface AmapRegeoResponse extends AmapBaseResponse {
regeocode?: {
formatted_address?: string
addressComponent?: {
province?: string
city?: string | string[]
district?: string
}
}
}
function getAmapApiBaseUrl(): string {
// #ifdef H5
if (import.meta.env.DEV) return '/amap-api'
// #endif
return 'https://restapi.amap.com'
}
interface AmapInputTip {
id?: string
name?: string
district?: string
address?: string
location?: string
}
interface AmapInputTipsResponse extends AmapBaseResponse {
tips?: AmapInputTip[]
}
interface AmapPoi {
name?: string
address?: string
pname?: string
cityname?: string
adname?: string
location?: string
distance?: string
}
interface AmapPlaceSearchResponse extends AmapBaseResponse {
pois?: AmapPoi[]
}
function isAmapOk(status?: string | number): boolean {
return String(status) === '1'
}
function parseAmapLocation(location?: string): { longitude: number; latitude: number } | null {
if (!location || location === '[]') return null
const [lngText, latText] = location.split(',')
const longitude = Number(lngText)
const latitude = Number(latText)
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null
return { longitude, latitude }
}
function parseAmapBody<T>(raw: unknown): T | null {
if (raw == null) return null
if (typeof raw === 'string') {
try {
return JSON.parse(raw) as T
} catch {
return null
}
}
return raw as T
}
function resolveCityName(component?: AmapRegeoResponse['regeocode']): string {
const city = component?.addressComponent?.city
if (Array.isArray(city)) {
const first = city.find((item) => item?.trim())
if (first) return first.trim()
} else if (typeof city === 'string' && city.trim()) {
return city.trim()
}
const province = component?.addressComponent?.province?.trim()
const district = component?.addressComponent?.district?.trim()
return province || district || ''
}
function dedupePlaces(list: MapLocationPoint[]): MapLocationPoint[] {
const seen = new Set<string>()
const result: MapLocationPoint[] = []
for (const item of list) {
const key = `${item.longitude.toFixed(6)},${item.latitude.toFixed(6)}`
if (seen.has(key)) continue
seen.add(key)
result.push(item)
}
return result
}
function mapPois(pois: AmapPoi[] | undefined): MapLocationPoint[] {
if (!Array.isArray(pois)) return []
const results: MapLocationPoint[] = []
for (const poi of pois) {
const name = poi.name?.trim()
if (!name) continue
const coords = parseAmapLocation(poi.location)
if (!coords) continue
const region = [poi.pname, poi.cityname, poi.adname].filter(Boolean).join('')
const address = poi.address?.trim() || region || name
results.push({
name,
address,
latitude: coords.latitude,
longitude: coords.longitude,
})
}
return results
}
function mapInputTips(body: AmapInputTipsResponse | null): MapLocationPoint[] {
if (!body || !isAmapOk(body.status) || !Array.isArray(body.tips)) return []
const results: MapLocationPoint[] = []
for (const tip of body.tips) {
const name = tip.name?.trim()
if (!name) continue
const coords = parseAmapLocation(tip.location)
if (!coords) continue
const address = tip.address?.trim() || tip.district?.trim() || name
results.push({
name,
address,
latitude: coords.latitude,
longitude: coords.longitude,
})
}
return results
}
function mapAmapError(body: AmapBaseResponse | null, fallback = '地点搜索失败'): string {
if (!body) return fallback
const info = body.info?.trim()
if (!info || info === 'OK') return fallback
if (/USERKEY_PLAT_NWM/i.test(info)) {
return '地图 Key 平台不匹配,请在高德控制台开启 Web 服务'
}
if (/INVALID_USER_KEY|USERKEY_PLAT/i.test(info)) {
return '地图服务 Key 无效,请检查配置'
}
return info
}
export function formatMapLocation(point: { name?: string; address?: string }): string {
const name = point.name?.trim()
const address = point.address?.trim()
if (name && address && name !== address) return `${name} · ${address}`
return name || address || ''
}
export function toMapCoords(point: Pick<MapLocationPoint, 'latitude' | 'longitude'>) {
return {
latitude: point.latitude,
longitude: point.longitude,
}
}
async function requestAmap<T extends AmapBaseResponse>(
url: string,
data: Record<string, string>,
): Promise<T | null> {
const key = getAmapWebKey()
if (!key) return null
try {
const res = await uni.request({
url: `${getAmapApiBaseUrl()}${url}`,
method: 'GET',
data: { ...data, key },
timeout: 15000,
})
const statusCode = res.statusCode ?? 200
if (statusCode < 200 || statusCode >= 300) return null
return parseAmapBody<T>(res.data)
} catch {
return null
}
}
/** 高德逆地理编码(需配置 VITE_AMAP_WEB_KEY) */
export async function reverseGeocodeAmap(
latitude: number,
longitude: number,
): Promise<string | undefined> {
const detail = await reverseGeocodeAmapDetail(latitude, longitude)
return detail?.address
}
/** 逆地理编码,附带城市信息(供搜索限定范围) */
export async function reverseGeocodeAmapDetail(
latitude: number,
longitude: number,
): Promise<{ address: string; city: string } | undefined> {
const data = await requestAmap<AmapRegeoResponse>('/v3/geocode/regeo', {
location: `${longitude},${latitude}`,
extensions: 'base',
})
if (!data || !isAmapOk(data.status)) return undefined
const address = data.regeocode?.formatted_address?.trim()
const city = resolveCityName(data.regeocode)
if (!address && !city) return undefined
return {
address: address || '',
city,
}
}
/** 高德地点搜索(周边 + 输入提示 + 文本搜索) */
export async function searchAmapPlaces(
keyword: string,
options?: { latitude?: number; longitude?: number; city?: string },
): Promise<AmapSearchResult> {
const trimmed = keyword.trim()
if (!trimmed) return { places: [] }
if (!getAmapWebKey()) {
return { places: [], error: '地图搜索服务未配置' }
}
const hasCoords = options?.latitude != null && options?.longitude != null
const location = hasCoords
? `${options!.longitude},${options!.latitude}`
: undefined
let city = options?.city?.trim() || ''
if (!city && hasCoords) {
const detail = await reverseGeocodeAmapDetail(options!.latitude!, options!.longitude!)
city = detail?.city || ''
}
const tipsData: Record<string, string> = {
keywords: trimmed,
datatype: 'all',
}
if (city) tipsData.city = city
if (location) tipsData.location = location
const textData: Record<string, string> = {
keywords: trimmed,
offset: '20',
page: '1',
extensions: 'base',
}
if (city) {
textData.city = city
textData.citylimit = 'true'
}
const [aroundBody, tipsBody, textBody] = await Promise.all([
location
? requestAmap<AmapPlaceSearchResponse>('/v3/place/around', {
keywords: trimmed,
location,
radius: '50000',
offset: '20',
page: '1',
extensions: 'base',
sortrule: 'distance',
})
: Promise.resolve(null),
requestAmap<AmapInputTipsResponse>('/v3/assistant/inputtips', tipsData),
requestAmap<AmapPlaceSearchResponse>('/v3/place/text', textData),
])
const places = dedupePlaces([
...mapPois(aroundBody?.pois),
...mapInputTips(tipsBody),
...mapPois(textBody?.pois),
])
if (places.length) {
return { places }
}
const failed = [aroundBody, tipsBody, textBody].find((item) => item && !isAmapOk(item.status))
if (failed) {
return { places: [], error: mapAmapError(failed) }
}
return { places: [] }
}
export function hasAmapWebKey(): boolean {
return !!getAmapWebKey()
}

View File

@@ -22,9 +22,30 @@ export function unwrapApiData<T>(body: ApiResponse<T> & Record<string, unknown>)
return body as T
}
const NETWORK_ERROR_PATTERN = /request:fail|network\s*error|unable to resolve host|no address associated|failed to connect|connection\s*(refused|reset|timed out|timeout)|timed?\s*out|offline|statuscode:\s*-1|err_connection|net::/i
/** 将 uni.request / 系统层英文网络错误转为中文提示 */
export function normalizeNetworkErrorMessage(
message?: string,
fallback = '网络异常,请检查网络后重试',
): string {
const text = message?.trim() ?? ''
if (!text) return fallback
if (NETWORK_ERROR_PATTERN.test(text)) return fallback
return text
}
export function getErrorMessage(err: unknown, fallback = '请求失败'): string {
if (err instanceof ApiError) return err.message
if (err instanceof Error && err.message) return err.message
if (err instanceof ApiError) {
return normalizeNetworkErrorMessage(err.message, fallback)
}
if (err instanceof Error && err.message) {
return normalizeNetworkErrorMessage(err.message, fallback)
}
if (err && typeof err === 'object' && 'errMsg' in err) {
const errMsg = String((err as { errMsg?: string }).errMsg || '')
if (errMsg) return normalizeNetworkErrorMessage(errMsg, fallback)
}
if (err && typeof err === 'object' && 'data' in err) {
const data = (err as { data?: ApiResponse }).data
if (data?.msg) return data.msg

View File

@@ -0,0 +1,84 @@
import { getBleDeviceNamePrefix } from '@/config/app-env'
import { compactMacAddress, normalizeMacAddress } from '@/utils/bluetooth'
export { getBleDeviceNamePrefix }
const BLE_NAME_SUFFIX_PATTERN = /^[0-9A-Fa-f]{12}$/
/** 从广播名解析 12 位 MAC(无分隔符) */
export function parseMacFromBleDeviceName(name: string): string | undefined {
const prefix = getBleDeviceNamePrefix()
const trimmed = name.trim()
if (!trimmed.startsWith(prefix)) return undefined
const suffix = trimmed.slice(prefix.length)
if (!BLE_NAME_SUFFIX_PATTERN.test(suffix)) return undefined
return suffix.toUpperCase()
}
/** 是否为本品牌 BLE 设备(广播名符合 Z2_A_<12位MAC>) */
export function isValidBleDeviceName(name: string): boolean {
return !!parseMacFromBleDeviceName(name)
}
export function isBrandBleDevice(device: UniApp.BluetoothDeviceInfo): boolean {
const candidates = [device.name, device.localName]
.filter(Boolean)
.map((item) => String(item).trim())
return candidates.some((item) => isValidBleDeviceName(item))
}
/** 生成标准蓝牙广播名:Z2_A_<12位MAC> */
export function buildBleDeviceName(mac: string): string {
const compact = compactMacAddress(mac)
if (compact.length !== 12) {
throw new Error('MAC 地址无效,无法生成蓝牙名称')
}
return `${getBleDeviceNamePrefix()}${compact}`
}
/** 广播名已是标准格式时无需再下发改名指令(避免设备重启导致断连) */
export function isStandardBleDeviceName(mac: string, name?: string): boolean {
const value = name?.trim()
if (!value || !mac) return false
try {
return value === buildBleDeviceName(mac)
} catch {
return isValidBleDeviceName(value) && parseMacFromBleDeviceName(value) === compactMacAddress(mac)
}
}
/** 优先从 deviceId(Android)或广播名(iOS)解析 MAC */
export function resolveBleDeviceMac(device: UniApp.BluetoothDeviceInfo): string | undefined {
const fromId = normalizeMacAddress(device.deviceId)
if (fromId) return compactMacAddress(fromId)
const candidates = [device.name, device.localName]
.filter(Boolean)
.map((item) => String(item).trim())
for (const name of candidates) {
const parsed = parseMacFromBleDeviceName(name)
if (parsed) return parsed
}
return undefined
}
export function resolveBleDeviceDisplayName(device: UniApp.BluetoothDeviceInfo): string {
const candidates = [device.name, device.localName]
.filter(Boolean)
.map((item) => String(item).trim())
const matched = candidates.find((item) => isValidBleDeviceName(item))
if (matched) return matched
const mac = resolveBleDeviceMac(device)
if (mac) {
try {
return buildBleDeviceName(mac)
} catch {
// ignore
}
}
return candidates[0] || '未命名设备'
}

View File

@@ -10,6 +10,8 @@ export class BluetoothError extends Error {
type UniFail = UniApp.GeneralCallbackResult
export const BLUETOOTH_DISABLED_MESSAGE = '请先打开手机蓝牙后再试'
function toBluetoothError(err: UniFail, fallback: string): BluetoothError {
const msg = err.errMsg || fallback
return new BluetoothError(getBluetoothErrorMessage({ errCode: err.errCode, errMsg: msg }), err.errCode)
@@ -64,7 +66,70 @@ export async function ensureBluetoothReady(): Promise<void> {
const state = await getAdapterState()
if (!state.available) {
throw new BluetoothError('本机不支持蓝牙', 10009)
throw new BluetoothError(BLUETOOTH_DISABLED_MESSAGE, 10001)
}
}
export function isBluetoothDisabledError(err: unknown): boolean {
if (err instanceof BluetoothError && err.errCode === 10001) return true
const code = (err as UniFail)?.errCode
if (code === 10001) return true
const message = err instanceof BluetoothError
? err.message
: String((err as UniFail)?.errMsg || (err instanceof Error ? err.message : ''))
const lower = message.toLowerCase()
return (
message === BLUETOOTH_DISABLED_MESSAGE
|| /请先打开手机蓝牙/.test(message)
|| /bluetooth adapter not available|adapter not available|not init|not open|bluetooth.*off/i.test(lower)
)
}
export function openSystemBluetoothSetting(): Promise<void> {
return new Promise((resolve, reject) => {
if (typeof uni.openSystemBluetoothSetting !== 'function') {
reject(new BluetoothError('当前环境无法打开系统蓝牙设置'))
return
}
uni.openSystemBluetoothSetting({
success: () => resolve(),
fail: (err) => reject(toBluetoothError(err, '无法打开蓝牙设置')),
})
})
}
export function promptEnableBluetooth(content?: string) {
uni.showModal({
title: '请开启蓝牙',
content: content || '添加设备需要使用手机蓝牙,请先在系统设置中打开蓝牙',
confirmText: '去开启',
cancelText: '取消',
success: (res) => {
if (!res.confirm) return
void openSystemBluetoothSetting().catch(() => {
uni.showToast({ title: BLUETOOTH_DISABLED_MESSAGE, icon: 'none' })
})
},
})
}
export function isBluetoothPermissionError(err: unknown): boolean {
const message = getBluetoothErrorMessage(err)
return /定位权限|蓝牙相关权限|permission/i.test(message)
}
/** 确认蓝牙已开启且可扫描(添加设备流程入口使用) */
export async function assertBluetoothEnabledForScan(): Promise<void> {
try {
await ensureBluetoothReady()
await startBluetoothDiscovery()
await stopBluetoothDiscovery()
} catch (err) {
if (isBluetoothDisabledError(err) || isBluetoothPermissionError(err)) {
throw err
}
// 部分机型蓝牙未开时 openAdapter 仍成功,扫描失败会落到通用错误
throw new BluetoothError(BLUETOOTH_DISABLED_MESSAGE, 10001)
}
}
@@ -217,6 +282,53 @@ export function closeBleConnection(bleDeviceId: string): Promise<void> {
})
}
/** 断开当前已连接的全部 BLE 设备,避免重连时 operate timeout */
export async function closeAllBleConnections(): Promise<void> {
if (typeof uni.getConnectedBluetoothDevices !== 'function') return
try {
const res = await new Promise<UniApp.GetConnectedBluetoothDevicesSuccess>((resolve, reject) => {
uni.getConnectedBluetoothDevices({
success: resolve,
fail: reject,
})
})
for (const device of res.devices ?? []) {
await closeBleConnection(device.deviceId).catch(() => {})
}
} catch {
// ignore
}
}
export async function releaseBleDevice(bleDeviceId?: string): Promise<void> {
if (!bleDeviceId) return
await closeBleConnection(bleDeviceId).catch(() => {})
}
/** 从系统已连接 BLE 列表中按 MAC 查找(GATT 已连接时扫描往往找不到设备) */
export async function getConnectedBleDeviceByMac(
mac: string,
): Promise<UniApp.BluetoothDeviceInfo | null> {
if (typeof uni.getConnectedBluetoothDevices !== 'function') return null
const normalizedMac = normalizeMacAddress(mac)
if (!normalizedMac) return null
try {
const res = await new Promise<UniApp.GetConnectedBluetoothDevicesSuccess>((resolve, reject) => {
uni.getConnectedBluetoothDevices({
success: resolve,
fail: reject,
})
})
for (const device of res.devices ?? []) {
if (deviceMatchesMac(device, normalizedMac)) return device
}
} catch {
// ignore
}
return null
}
export function subscribeBleConnectionStateChange(
onChange: (res: { deviceId: string; connected: boolean }) => void,
): () => void {
@@ -245,11 +357,12 @@ function deviceMatchesName(
/** 扫描并匹配 MAC 或广播名的 BLE 设备(iOS 需依赖名称) */
export async function scanForBleDeviceByMac(
mac: string,
options: { timeoutMs?: number; name?: string } = {},
options: { timeoutMs?: number; name?: string; skipCached?: boolean } = {},
): Promise<UniApp.BluetoothDeviceInfo | null> {
const timeoutMs = options.timeoutMs ?? 15000
const normalizedMac = normalizeMacAddress(mac)
const targetName = options.name?.trim()
const skipCached = options.skipCached ?? false
if (!normalizedMac && !targetName) return null
@@ -263,7 +376,7 @@ export async function scanForBleDeviceByMac(
matched = device
return true
}
if (targetName && deviceMatchesName(device, targetName)) {
if (!normalizedMac && targetName && deviceMatchesName(device, targetName)) {
matched = device
return true
}
@@ -271,10 +384,12 @@ export async function scanForBleDeviceByMac(
return false
}
if (!skipCached) {
const existing = await getDiscoveredBluetoothDevices()
if (pickMatch(existing)) {
return matched
}
}
const unsubscribe = subscribeBluetoothDevicesFound((devices) => {
pickMatch(devices)
@@ -371,11 +486,70 @@ export function findDeviceInBleScan(
return null
}
function mapBluetoothErrMsg(msg?: string): string | null {
if (!msg) return null
const lower = msg.toLowerCase()
if (
lower.includes('operate time out')
|| lower.includes('operation timeout')
|| lower.includes('timed out')
|| lower.includes('time out')
) {
return '蓝牙连接超时,请确认设备已开机并靠近手机后重试'
}
if (lower.includes('createbleconnection')) {
return '蓝牙连接失败,请确认设备已开机并靠近手机后重试'
}
if (lower.includes('already connect') || lower.includes('already connected')) {
return '设备已连接'
}
if (
lower.includes('bluetooth adapter not available')
|| lower.includes('adapter not available')
|| lower.includes('not init')
|| lower.includes('not open')
) {
return '请先打开手机蓝牙后再试'
}
if (lower.includes('no device') || lower.includes('device not found')) {
return '没有找到指定设备,请确认已开机并靠近手机'
}
if (lower.includes('connection fail') || lower.includes('connect fail')) {
return '蓝牙连接失败,请靠近设备后重试'
}
if (lower.includes('location') && lower.includes('permission')) {
return '请开启定位权限后再使用蓝牙功能'
}
if (lower.includes('permission')) {
return '请授予蓝牙相关权限后重试'
}
if (/:fail\b/i.test(msg) && /[a-z]/i.test(msg)) {
return '蓝牙操作失败,请重试'
}
return null
}
export function getBluetoothErrorMessage(err: unknown): string {
if (err instanceof BluetoothError) return err.message
if (err instanceof BluetoothError) {
const mapped = mapBluetoothErrMsg(err.message)
if (mapped) return mapped
return err.message
}
const code = (err as UniFail)?.errCode
const msg = (err as UniFail)?.errMsg
const mapped = mapBluetoothErrMsg(msg)
if (mapped) return mapped
switch (code) {
case 10001:
@@ -408,6 +582,6 @@ export function getBluetoothErrorMessage(err: unknown): string {
case 10013:
return '设备标识无效'
default:
return msg || '蓝牙不可用,请检查权限与系统设置'
return mapBluetoothErrMsg(msg) || '蓝牙不可用,请检查权限与系统设置'
}
}

View File

@@ -0,0 +1,72 @@
/** App 端请求定位权限(Android 需运行时授权;iOS 依赖 manifest 隐私描述) */
export async function ensureLocationPermission(): Promise<boolean> {
// #ifdef APP-PLUS
const system = uni.getSystemInfoSync()
if (system.platform === 'android') {
return requestAndroidLocationPermission()
}
// #endif
return true
}
// #ifdef APP-PLUS
function requestAndroidLocationPermission(): Promise<boolean> {
return new Promise((resolve) => {
plus.android.requestPermissions(
[
'android.permission.ACCESS_FINE_LOCATION',
'android.permission.ACCESS_COARSE_LOCATION',
],
(result) => {
const granted = (result.granted?.length ?? 0) > 0
if (!granted) {
promptOpenAppSettings('请在系统设置中允许使用位置信息,以便选择家庭位置')
}
resolve(granted)
},
() => resolve(false),
)
})
}
function promptOpenAppSettings(content: string) {
uni.showModal({
title: '需要定位权限',
content,
confirmText: '去设置',
success: (res) => {
if (!res.confirm) return
try {
const Intent = plus.android.importClass('android.content.Intent') as {
new (action: string): { setData: (uri: unknown) => void }
}
const Settings = plus.android.importClass('android.provider.Settings') as {
ACTION_APPLICATION_DETAILS_SETTINGS: string
}
const Uri = plus.android.importClass('android.net.Uri') as {
parse: (uri: string) => unknown
}
const main = plus.android.runtimeMainActivity() as { getPackageName: () => string; startActivity: (intent: unknown) => void }
const intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.setData(Uri.parse(`package:${main.getPackageName()}`))
main.startActivity(intent)
} catch {
// ignore
}
},
})
}
// #endif
export function getLocationFailHint(err: unknown): string {
const message = err && typeof err === 'object' && 'errMsg' in err
? String((err as { errMsg?: string }).errMsg || '')
: ''
if (/auth|denied|permission|authorize/i.test(message)) {
return '定位权限未开启,请在系统设置中允许使用位置信息'
}
if (/timeout|timed out/i.test(message)) {
return '定位超时,请确认已开启手机定位服务后重试'
}
return '定位失败,请检查定位权限与手机定位服务'
}

View File

@@ -61,7 +61,7 @@ function resolveMessageWsBase(): string {
return configured.replace(/[?#].*$/, '').replace(/\/$/, '')
}
const httpBase = getApiBaseUrl() || 'http://192.168.0.222:8082'
const httpBase = getApiBaseUrl() || 'https://smart.bugtc.com'
const wsBase = httpBase.replace(/^https/i, 'wss').replace(/^http/i, 'ws')
return `${wsBase}/app/ws/message`
}

View File

@@ -0,0 +1,32 @@
const STORAGE_KEY = 'czzj_password_modified_at'
/** 密码修改成功后记录时间戳 */
export function markPasswordModified(at = Date.now()): void {
uni.setStorageSync(STORAGE_KEY, at)
}
export function getPasswordModifiedAt(): number | null {
const value = uni.getStorageSync(STORAGE_KEY)
if (typeof value === 'number' && value > 0) return value
if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value)
return null
}
/** 展示「上次修改:刚刚 / 3天前」等文案 */
export function formatPasswordModifiedDesc(at: number | null): string {
if (!at) return '上次修改:暂无记录'
const diff = Date.now() - at
if (diff < 0) return '上次修改:刚刚'
const minute = 60 * 1000
const hour = 60 * minute
const day = 24 * hour
if (diff < minute) return '上次修改:刚刚'
if (diff < hour) return `上次修改:${Math.floor(diff / minute)}分钟前`
if (diff < day) return `上次修改:${Math.floor(diff / hour)}小时前`
if (diff < 30 * day) return `上次修改:${Math.floor(diff / day)}天前`
if (diff < 365 * day) return `上次修改:${Math.floor(diff / (30 * day))}个月前`
return `上次修改:${Math.floor(diff / (365 * day))}年前`
}

View File

@@ -0,0 +1,16 @@
import { parseId } from '@/utils/device-id'
export const SELECTED_HOME_ID_KEY = 'device_selected_home_id'
export function readStoredHomeId(): string {
try {
return parseId(uni.getStorageSync(SELECTED_HOME_ID_KEY) as string | number | undefined)
} catch {
return ''
}
}
export function saveSelectedHomeId(id: string) {
if (!id) return
uni.setStorageSync(SELECTED_HOME_ID_KEY, id)
}

Some files were not shown because too many files have changed in this diff Show More