Compare commits
8 Commits
4b93b50e50
...
2ec91cca26
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ec91cca26 | ||
|
|
98402548eb | ||
|
|
91bca314ba | ||
|
|
c369127166 | ||
|
|
c288d6914e | ||
|
|
28531c8120 | ||
|
|
e4276b0853 | ||
|
|
83a1e961ea |
@@ -1,7 +1,8 @@
|
||||
VITE_API_BASE_URL=http://192.168.0.222:8082
|
||||
VITE_API_PROXY_TARGET=http://192.168.0.222: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
|
||||
|
||||
18
.env.example
18
.env.example
@@ -1,4 +1,5 @@
|
||||
# 接口根地址(App / 小程序 / H5 直连)
|
||||
# 正式打包读 .env.production;未配置时 src/config/app-env.ts 有兜底地址
|
||||
VITE_API_BASE_URL=http://192.168.0.222:8082
|
||||
|
||||
# H5 开发:BASE_URL 留空时可走 vite 代理 /app
|
||||
@@ -10,6 +11,12 @@ VITE_API_PROXY_TARGET=http://192.168.0.222:8082
|
||||
# 消息推送 WebSocket(不含 token,连接时自动拼接 ?token=)
|
||||
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
|
||||
|
||||
# 客服图片上传等 CS 服务地址(若与主 API 不同,如上传在 212、主接口在 222)
|
||||
# VITE_CS_API_BASE_URL=http://192.168.0.212:8082
|
||||
|
||||
# 文件上传 clientId(与 Postman /app/cs/upload 一致,默认 app)
|
||||
# VITE_UPLOAD_CLIENT_ID=app
|
||||
|
||||
# 在线客服 WebSocket(App/小程序直连;H5 开发默认走 Vite 代理,可不配此项)
|
||||
# VITE_CS_CHAT_WS_URL=ws://192.168.0.222:8082/app/cs/chat
|
||||
# H5 仍要直连内网 IP 时设为 true(如客服 WS 只在 212 上)
|
||||
@@ -27,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 中配置
|
||||
|
||||
9
.env.production
Normal file
9
.env.production
Normal file
@@ -0,0 +1,9 @@
|
||||
# 正式打包(npm run build:* / HBuilderX 发行)读取
|
||||
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
|
||||
871
package-lock.json
generated
871
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
49
package.json
49
package.json
@@ -37,34 +37,35 @@
|
||||
"type-check": "vue-tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dcloudio/uni-app": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-app-harmony": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-app-plus": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-components": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-h5": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-alipay": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-baidu": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-harmony": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-jd": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-kuaishou": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-lark": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-qq": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-toutiao": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-app": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-app-harmony": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-app-plus": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-components": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-h5": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-alipay": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-baidu": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-harmony": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-jd": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-kuaishou": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-lark": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-qq": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-toutiao": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-weixin": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-mp-xhs": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-quickapp-webview": "3.0.0-5020620260917001",
|
||||
"element-china-area-data": "^6.1.0",
|
||||
"vue": "^3.4.21",
|
||||
"vue-i18n": "^9.1.9"
|
||||
"vue": "3.4.21",
|
||||
"vue-i18n": "9.14.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@dcloudio/types": "^3.4.8",
|
||||
"@dcloudio/uni-automator": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-cli-shared": "3.0.0-5020420260813003",
|
||||
"@dcloudio/uni-stacktracey": "3.0.0-5020420260813003",
|
||||
"@dcloudio/vite-plugin-uni": "3.0.0-5020420260813003",
|
||||
"@vue/runtime-core": "^3.4.21",
|
||||
"@dcloudio/types": "3.4.31",
|
||||
"@dcloudio/uni-automator": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-cli-shared": "3.0.0-5020620260917001",
|
||||
"@dcloudio/uni-stacktracey": "3.0.0-5020620260917001",
|
||||
"@dcloudio/vite-plugin-uni": "3.0.0-5020620260917001",
|
||||
"@vue/runtime-core": "3.5.44",
|
||||
"@vue/tsconfig": "^0.1.3",
|
||||
"rollup": "4.14.3",
|
||||
"sass": "^1.105.1",
|
||||
"typescript": "^4.9.4",
|
||||
"vite": "5.2.8",
|
||||
|
||||
25
src/App.vue
25
src/App.vue
@@ -1,12 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { onLaunch, onShow } from '@dcloudio/uni-app'
|
||||
import { setupMessageInbox } from '@/hooks/use-message-inbox'
|
||||
import {
|
||||
connectMessageSocket,
|
||||
isMessageSocketConnected,
|
||||
isMessageSocketConnecting,
|
||||
} from '@/utils/message-socket'
|
||||
import { ensureLoggedInOnForeground, LOGIN_ROUTE } from '@/utils/auth-session'
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import { installLocalizedToast } from '@/utils/localized-toast'
|
||||
import { staticAssets } from '@/utils/static-assets'
|
||||
|
||||
function applyH5Favicon() {
|
||||
@@ -25,18 +22,26 @@ function applyH5Favicon() {
|
||||
// #endif
|
||||
}
|
||||
|
||||
onLaunch(() => {
|
||||
applyH5Favicon()
|
||||
function bootstrapAuthRoute() {
|
||||
if (getStoredToken()) {
|
||||
setupMessageInbox()
|
||||
return
|
||||
}
|
||||
uni.reLaunch({ url: LOGIN_ROUTE })
|
||||
}
|
||||
|
||||
onLaunch(() => {
|
||||
installLocalizedToast()
|
||||
applyH5Favicon()
|
||||
bootstrapAuthRoute()
|
||||
})
|
||||
|
||||
onShow(() => {
|
||||
if (!getStoredToken()) return
|
||||
if (!isMessageSocketConnected() && !isMessageSocketConnecting()) {
|
||||
connectMessageSocket()
|
||||
if (getStoredToken()) {
|
||||
setupMessageInbox()
|
||||
return
|
||||
}
|
||||
ensureLoggedInOnForeground()
|
||||
})
|
||||
</script>
|
||||
<style lang="scss">
|
||||
|
||||
93
src/api/cs-auth.ts
Normal file
93
src/api/cs-auth.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { getApiBaseUrl } from '@/config/app-env'
|
||||
import { resolveCsAppBaseUrl, UPLOAD_CLIENT_ID } from './request'
|
||||
import {
|
||||
clearStoredCsToken,
|
||||
extractAuthToken,
|
||||
getStoredToken,
|
||||
saveStoredCsToken,
|
||||
} from '@/utils/auth-token'
|
||||
import { ApiError, isApiSuccess, normalizeNetworkErrorMessage } from '@/utils/api-error'
|
||||
import type { ApiResponse } from '@/types/api'
|
||||
|
||||
/** 与客服 API 同服同前缀(真机须为 .../app/auth/...,不能漏 /app) */
|
||||
function resolveCsAuthUrl(path: string): string {
|
||||
const normalized = path.startsWith('/') ? path : `/${path}`
|
||||
const csBase = resolveCsAppBaseUrl()
|
||||
if (csBase) return `${csBase}${normalized}`
|
||||
return `${getApiBaseUrl()}/app${normalized}`
|
||||
}
|
||||
|
||||
function parseBody(data: unknown): unknown {
|
||||
if (typeof data === 'string') {
|
||||
if (!data) return {}
|
||||
try {
|
||||
return JSON.parse(data)
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
return data ?? {}
|
||||
}
|
||||
|
||||
async function requestCsLogin(path: string, data: Record<string, unknown>): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.request({
|
||||
url: resolveCsAuthUrl(path),
|
||||
method: 'POST',
|
||||
header: {
|
||||
'Content-Type': 'application/json;charset=UTF-8',
|
||||
clientId: UPLOAD_CLIENT_ID,
|
||||
},
|
||||
data,
|
||||
dataType: 'text',
|
||||
success: (res) => {
|
||||
const body = parseBody(res.data) as ApiResponse
|
||||
if (res.statusCode < 200 || res.statusCode >= 300 || !isApiSuccess(body)) {
|
||||
reject(new ApiError(body?.msg || body?.message || 'CS 登录失败', body?.code ?? res.statusCode))
|
||||
return
|
||||
}
|
||||
const token = extractAuthToken(body)
|
||||
if (!token) {
|
||||
reject(new ApiError('CS 登录失败,未获取到令牌'))
|
||||
return
|
||||
}
|
||||
saveStoredCsToken(token)
|
||||
resolve()
|
||||
},
|
||||
fail: (err) => reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg, 'CS 登录失败'))),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** 主站登录后,向 212 用 clientId=app 同步登录,获取上传专用 token */
|
||||
export async function syncCsAuthByPassword(account: string, password: string): Promise<void> {
|
||||
try {
|
||||
clearStoredCsToken()
|
||||
await requestCsLogin('/auth/login/password', {
|
||||
account: account.trim(),
|
||||
password,
|
||||
})
|
||||
} catch {
|
||||
// 212 不可达时不阻断主登录;会话接口仍可用主站 token
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncCsAuthBySms(phone: string, code: string): Promise<void> {
|
||||
try {
|
||||
clearStoredCsToken()
|
||||
await requestCsLogin('/auth/login/sms', {
|
||||
phonenumber: phone.trim(),
|
||||
smsCode: code.trim(),
|
||||
})
|
||||
} catch {
|
||||
// 同上
|
||||
}
|
||||
}
|
||||
|
||||
/** 进入客服页前:确认主站已登录(勿把主站 token 写入 cs_token) */
|
||||
export function ensureCsSessionReady(): void {
|
||||
if (!getStoredToken()) {
|
||||
throw new ApiError('请先登录', 401)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,31 @@
|
||||
import { request } from '@/api/request'
|
||||
|
||||
import type { AppHomeVo, UpdateHomeBody } from '@/types/location'
|
||||
import { parseId, sameId } from '@/utils/device-id'
|
||||
|
||||
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 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: UpdateHomeBody) {
|
||||
return request<void>({
|
||||
url: '/app/home/create',
|
||||
method: 'POST',
|
||||
@@ -19,6 +33,43 @@ export function createHome(data: { homeName: string }) {
|
||||
})
|
||||
}
|
||||
|
||||
/** PUT /app/home/{homeId} — 修改家庭名称与位置 */
|
||||
export function updateHome(homeId: string | number, data: UpdateHomeBody) {
|
||||
return request<void>({
|
||||
url: `/app/home/${encodeURIComponent(String(homeId))}`,
|
||||
method: 'PUT',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/** 组装修改家庭接口必填字段(名称 2-10 字,位置四项均必填) */
|
||||
export function buildUpdateHomeBody(
|
||||
homeName: string,
|
||||
options?: {
|
||||
geo?: { address: string; latitude: number; longitude: number }
|
||||
home?: AppHomeVo
|
||||
},
|
||||
): UpdateHomeBody {
|
||||
const geo = options?.geo
|
||||
const home = options?.home
|
||||
return {
|
||||
homeName: homeName.trim(),
|
||||
homeLocationLongitude:
|
||||
geo?.longitude ?? home?.homeLocationLongitude ?? DEFAULT_HOME_LONGITUDE,
|
||||
homeLocationLatitude:
|
||||
geo?.latitude ?? home?.homeLocationLatitude ?? DEFAULT_HOME_LATITUDE,
|
||||
homeLocationAddress:
|
||||
geo?.address?.trim()
|
||||
|| home?.homeLocationAddress?.trim()
|
||||
|| DEFAULT_HOME_ADDRESS,
|
||||
}
|
||||
}
|
||||
|
||||
export function isValidHomeName(name: string): boolean {
|
||||
const value = name.trim()
|
||||
return value.length >= 2 && value.length <= 10
|
||||
}
|
||||
|
||||
function isDefaultHome(home: AppHomeVo): boolean {
|
||||
const value = home.isDefault
|
||||
return value === '1' || value === 1 || value === true
|
||||
@@ -30,11 +81,15 @@ export function pickDefaultHome(homes: AppHomeVo[] | undefined): AppHomeVo | und
|
||||
}
|
||||
|
||||
export function getHomeId(home?: AppHomeVo): string {
|
||||
method: 'POST',
|
||||
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) || sameId((item as { homeId?: string | number }).homeId, homeId),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,7 +109,11 @@ export async function resolveValidHomeId(candidate?: string | number): Promise<s
|
||||
let defaultId = getHomeId(pickDefaultHome(list))
|
||||
if (defaultId) return defaultId
|
||||
|
||||
return homes.find(isDefaultHome) ?? homes[0]
|
||||
try {
|
||||
await createHome(buildUpdateHomeBody('我的家'))
|
||||
} catch {
|
||||
// 可能已存在同名家庭,继续拉列表取 ID
|
||||
}
|
||||
list = await fetchHomeList()
|
||||
defaultId = getHomeId(pickDefaultHome(list))
|
||||
return defaultId
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import { API_CLIENT_ID, request } from '@/api/request'
|
||||
import type { ApiResponse } from '@/types/api'
|
||||
import { request, uploadAppFile } from '@/api/request'
|
||||
import type { AppUserProfileVo, AvatarUploadVo, UpdateProfileBo } from '@/types/profile'
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
|
||||
|
||||
const BASE_URL = import.meta.env.VITE_API_BASE_URL ?? ''
|
||||
|
||||
/** GET /app/profile — 获取当前用户资料 */
|
||||
export function fetchProfile() {
|
||||
@@ -25,37 +20,5 @@ export function updateProfile(data: UpdateProfileBo) {
|
||||
|
||||
/** POST /app/profile/avatar — 上传用户头像 */
|
||||
export function uploadProfileAvatar(filePath: string): Promise<AvatarUploadVo> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const token = getStoredToken()
|
||||
uni.uploadFile({
|
||||
url: `${BASE_URL}/app/profile/avatar`,
|
||||
filePath,
|
||||
name: 'file',
|
||||
header: {
|
||||
clientId: API_CLIENT_ID,
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
success: (res) => {
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
reject(new ApiError(`上传失败(${res.statusCode})`, res.statusCode))
|
||||
return
|
||||
}
|
||||
let body: ApiResponse<AvatarUploadVo>
|
||||
try {
|
||||
body = JSON.parse(res.data) as ApiResponse<AvatarUploadVo>
|
||||
} catch {
|
||||
reject(new ApiError('上传响应解析失败'))
|
||||
return
|
||||
}
|
||||
if (!isApiSuccess(body)) {
|
||||
reject(new ApiError(body.msg || body.message || '上传失败', body.code))
|
||||
return
|
||||
}
|
||||
resolve(unwrapApiData(body))
|
||||
},
|
||||
fail: (err) => {
|
||||
reject(new ApiError(err.errMsg || '上传失败'))
|
||||
},
|
||||
})
|
||||
})
|
||||
return uploadAppFile<AvatarUploadVo>('/app/profile/avatar', filePath, 'file')
|
||||
}
|
||||
|
||||
@@ -1,30 +1,54 @@
|
||||
import type { ApiResponse } from '@/types/api'
|
||||
import { extractAuthToken, getStoredToken, saveStoredToken } from '@/utils/auth-token'
|
||||
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
|
||||
import {
|
||||
assertRequestUrl,
|
||||
getApiBaseUrl,
|
||||
getApiClientId,
|
||||
getCsApiBaseUrl,
|
||||
getUploadClientId,
|
||||
} from '@/config/app-env'
|
||||
import {
|
||||
clearStoredCsToken,
|
||||
extractAuthToken,
|
||||
formatBearerAuthorization,
|
||||
getStoredCsToken,
|
||||
getStoredToken,
|
||||
saveStoredToken,
|
||||
} from '@/utils/auth-token'
|
||||
import { isAuthSessionExpiredError, notifyAuthSessionExpired } from '@/utils/auth-session'
|
||||
import { ApiError, isApiSuccess, normalizeNetworkErrorMessage, unwrapApiData } from '@/utils/api-error'
|
||||
|
||||
/** H5 开发走 Vite 代理;App/小程序使用完整后端地址 */
|
||||
function resolveBaseUrl(): string {
|
||||
const envUrl = import.meta.env.VITE_API_BASE_URL ?? ''
|
||||
// #ifdef H5
|
||||
if (import.meta.env.DEV) return ''
|
||||
// #endif
|
||||
return envUrl
|
||||
}
|
||||
/** RuoYi-Vue-Plus App 端 clientId(登录等 JSON 接口) */
|
||||
export const API_CLIENT_ID = getApiClientId()
|
||||
|
||||
const BASE_URL = resolveBaseUrl()
|
||||
/** RuoYi-Vue-Plus App 端 clientId(请求头 clientid,与 Postman 一致) */
|
||||
export const API_CLIENT_ID =
|
||||
import.meta.env.VITE_API_CLIENT_ID || '428a8310cd442757ae699df5d894f051'
|
||||
/** 文件上传 clientId(与 Postman /app/cs/upload 一致) */
|
||||
export const UPLOAD_CLIENT_ID = getUploadClientId()
|
||||
|
||||
/** 将响应 JSON 中的 int64 主键字段转为字符串,避免 JS 精度丢失 */
|
||||
function parseJsonPreserveIdFields(text: string): unknown {
|
||||
const safe = text.replace(
|
||||
/"(deviceId|homeId|locationId|productId|sessionId|messageId|alertId|seq|id)"\s*:\s*(\d+)/g,
|
||||
/"(deviceId|homeId|locationId|productId|sessionId|messageId|alertId|ossId|seq|id)"\s*:\s*(\d+)/g,
|
||||
'"$1":"$2"',
|
||||
)
|
||||
return JSON.parse(safe)
|
||||
}
|
||||
|
||||
/** 212 客服服务根路径(含 /app) */
|
||||
export function resolveCsAppBaseUrl(): string {
|
||||
// #ifdef H5
|
||||
if (import.meta.env.DEV) return '/cs-app'
|
||||
// #endif
|
||||
const csBase = getCsApiBaseUrl()
|
||||
return csBase ? `${csBase}/app` : ''
|
||||
}
|
||||
|
||||
function buildCsAppRequestUrl(path: string): string {
|
||||
const csBase = resolveCsAppBaseUrl()
|
||||
if (!csBase) return `${getApiBaseUrl()}${path}`
|
||||
if (path.startsWith('/app/')) return `${csBase}${path.slice(4)}`
|
||||
if (path.startsWith('/app')) return `${csBase}${path.slice(4)}`
|
||||
return `${csBase}${path.startsWith('/') ? path : `/${path}`}`
|
||||
}
|
||||
|
||||
function parseResponseBody(data: unknown): unknown {
|
||||
if (typeof data === 'string') {
|
||||
if (!data) return {}
|
||||
@@ -41,37 +65,328 @@ export interface RequestOptions extends Omit<UniApp.RequestOptions, 'url'> {
|
||||
url: string
|
||||
}
|
||||
|
||||
/** 构建鉴权请求头:clientid + Authorization */
|
||||
export function buildAuthHeaders(extra?: Record<string, unknown>): Record<string, string> {
|
||||
const token = getStoredToken()
|
||||
/** 仅 clientId,不带登录 token(忘记密码 / 重置密码等) */
|
||||
export function buildPublicHeaders(extra?: Record<string, unknown>): Record<string, string> {
|
||||
return {
|
||||
'Content-Type': 'application/json;charset=UTF-8',
|
||||
clientId: API_CLIENT_ID,
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...(extra as Record<string, string> | undefined),
|
||||
}
|
||||
}
|
||||
|
||||
/** 构建鉴权请求头:clientId + Authorization */
|
||||
export function buildAuthHeaders(extra?: Record<string, unknown>): Record<string, string> {
|
||||
const authorization = formatBearerAuthorization(getStoredToken())
|
||||
return {
|
||||
'Content-Type': 'application/json;charset=UTF-8',
|
||||
clientId: API_CLIENT_ID,
|
||||
...(authorization ? { Authorization: authorization } : {}),
|
||||
...(extra as Record<string, string> | undefined),
|
||||
}
|
||||
}
|
||||
|
||||
/** 头像等主服务上传鉴权头 */
|
||||
export function buildUploadAuthHeaders(): Record<string, string> {
|
||||
const authorization = formatBearerAuthorization(getStoredToken())
|
||||
return {
|
||||
clientId: API_CLIENT_ID,
|
||||
...(authorization ? { Authorization: authorization } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** 下载 OSS 等资源(GET),勿带 Content-Type */
|
||||
export function buildDownloadAuthHeaders(): Record<string, string> {
|
||||
const authorization = formatBearerAuthorization(getStoredToken())
|
||||
return {
|
||||
clientId: API_CLIENT_ID,
|
||||
...(authorization ? { Authorization: authorization } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** 客服 WebSocket / 会话鉴权用 token(优先 212 cs_token,否则主站 token) */
|
||||
export function resolveCsAppToken(): string {
|
||||
return getStoredCsToken() || getStoredToken()
|
||||
}
|
||||
|
||||
/** 客服 JSON:有 cs_token 用 clientId=app;否则用主站 token + 主站 clientId */
|
||||
export function resolveCsAppClientId(): string {
|
||||
return getStoredCsToken() ? UPLOAD_CLIENT_ID : API_CLIENT_ID
|
||||
}
|
||||
|
||||
/** 客服图片上传:有 cs_token 用 clientId=app;否则与主站一致(主站 token + 主站 clientId) */
|
||||
export function buildCsUploadAuthHeaders(): Record<string, string> {
|
||||
const csToken = getStoredCsToken()
|
||||
const token = csToken || getStoredToken()
|
||||
const authorization = formatBearerAuthorization(token)
|
||||
return {
|
||||
clientId: csToken ? UPLOAD_CLIENT_ID : API_CLIENT_ID,
|
||||
...(authorization ? { Authorization: authorization } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** 212 客服 JSON 接口鉴权 */
|
||||
export function buildCsAppAuthHeaders(extra?: Record<string, unknown>): Record<string, string> {
|
||||
const authorization = formatBearerAuthorization(resolveCsAppToken())
|
||||
return {
|
||||
'Content-Type': 'application/json;charset=UTF-8',
|
||||
clientId: resolveCsAppClientId(),
|
||||
...(authorization ? { Authorization: authorization } : {}),
|
||||
...(extra as Record<string, string> | undefined),
|
||||
}
|
||||
}
|
||||
|
||||
export function isCsAuthError(err: unknown): boolean {
|
||||
return isAuthSessionExpiredError(err)
|
||||
}
|
||||
|
||||
export type UploadAuthMode = 'default' | 'cs'
|
||||
|
||||
function resolveUploadAuthHeaders(mode: UploadAuthMode): Record<string, string> {
|
||||
return mode === 'cs' ? buildCsUploadAuthHeaders() : buildUploadAuthHeaders()
|
||||
}
|
||||
|
||||
function resolveUploadUrl(url: string): string {
|
||||
if (/^https?:\/\//i.test(url)) return url
|
||||
const path = url.startsWith('/') ? url : `/${url}`
|
||||
return `${getApiBaseUrl()}${path}`
|
||||
}
|
||||
|
||||
const UPLOAD_NETWORK_ERROR = '网络异常,请检查网络后重试'
|
||||
|
||||
function isUploadTransportError(rawData: string, errMsg?: string): boolean {
|
||||
const payload = `${errMsg || ''} ${rawData}`.trim()
|
||||
if (!payload) return false
|
||||
return /uploadFile:fail|downloadFile:fail|request:fail|statusCode:\s*null/i.test(payload)
|
||||
}
|
||||
|
||||
function rejectRequestError(
|
||||
err: ApiError,
|
||||
requestPath: string,
|
||||
reject: (reason: ApiError) => void,
|
||||
) {
|
||||
notifyAuthSessionExpired(err, requestPath)
|
||||
reject(err)
|
||||
}
|
||||
|
||||
function handleUploadSuccess<T>(
|
||||
statusCode: number | undefined,
|
||||
rawData: string,
|
||||
resolve: (value: T) => void,
|
||||
reject: (reason: ApiError) => void,
|
||||
errMsg?: string,
|
||||
requestPath = '',
|
||||
) {
|
||||
if (isUploadTransportError(rawData, errMsg)) {
|
||||
reject(new ApiError(UPLOAD_NETWORK_ERROR))
|
||||
return
|
||||
}
|
||||
|
||||
if (statusCode == null || statusCode < 200 || statusCode >= 300) {
|
||||
let message = statusCode == null
|
||||
? UPLOAD_NETWORK_ERROR
|
||||
: `上传失败(${statusCode})`
|
||||
try {
|
||||
const body = JSON.parse(rawData) as ApiResponse
|
||||
const apiMessage = body.msg || body.message
|
||||
if (apiMessage && !/^[a-z0-9_.\-:()\s]+$/i.test(apiMessage)) {
|
||||
message = apiMessage
|
||||
}
|
||||
rejectRequestError(new ApiError(message, body.code ?? statusCode), requestPath, reject)
|
||||
return
|
||||
} catch {
|
||||
rejectRequestError(new ApiError(message, statusCode), requestPath, reject)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
let body: ApiResponse<T>
|
||||
try {
|
||||
body = parseResponseBody(rawData) as ApiResponse<T>
|
||||
} catch {
|
||||
reject(new ApiError('上传响应解析失败'))
|
||||
return
|
||||
}
|
||||
if (!isApiSuccess(body)) {
|
||||
rejectRequestError(
|
||||
new ApiError(body.msg || body.message || '上传失败', body.code),
|
||||
requestPath,
|
||||
reject,
|
||||
)
|
||||
return
|
||||
}
|
||||
const data = unwrapApiData<T>(body as ApiResponse<T> & Record<string, unknown>)
|
||||
if (data == null || (typeof data === 'object' && !Object.keys(data as object).length)) {
|
||||
reject(new ApiError(UPLOAD_NETWORK_ERROR))
|
||||
return
|
||||
}
|
||||
resolve(data)
|
||||
}
|
||||
|
||||
function uploadViaUniMultipart<T>(
|
||||
targetUrl: string,
|
||||
filePath: string,
|
||||
fieldName: string,
|
||||
authMode: UploadAuthMode,
|
||||
requestPath: string,
|
||||
): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.uploadFile({
|
||||
url: targetUrl,
|
||||
filePath,
|
||||
name: fieldName,
|
||||
header: resolveUploadAuthHeaders(authMode),
|
||||
success: (res) => {
|
||||
handleUploadSuccess<T>(
|
||||
res.statusCode,
|
||||
String(res.data ?? ''),
|
||||
resolve,
|
||||
reject,
|
||||
res.errMsg,
|
||||
requestPath,
|
||||
)
|
||||
},
|
||||
fail: (err) => {
|
||||
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg, UPLOAD_NETWORK_ERROR)))
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** H5 用 fetch 发送 multipart,确保 Authorization: Bearer xxx 能带上 */
|
||||
/** App 端用 plus.uploader,避免 uni.uploadFile 失败时框架自动弹英文 toast */
|
||||
function uploadViaPlusUploader<T>(
|
||||
targetUrl: string,
|
||||
filePath: string,
|
||||
fieldName: string,
|
||||
authMode: UploadAuthMode,
|
||||
requestPath: string,
|
||||
): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof plus === 'undefined' || typeof plus.uploader?.createUpload !== 'function') {
|
||||
uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode, requestPath)
|
||||
.then(resolve)
|
||||
.catch(reject)
|
||||
return
|
||||
}
|
||||
|
||||
const task = plus.uploader.createUpload(
|
||||
targetUrl,
|
||||
{ method: 'POST' },
|
||||
(upload, status) => {
|
||||
const rawData = upload.responseText || ''
|
||||
if (status == null || status < 0) {
|
||||
reject(new ApiError(UPLOAD_NETWORK_ERROR))
|
||||
return
|
||||
}
|
||||
handleUploadSuccess<T>(status, rawData, resolve, reject, undefined, requestPath)
|
||||
},
|
||||
)
|
||||
|
||||
const headers = authMode === 'cs'
|
||||
? buildCsUploadAuthHeaders()
|
||||
: buildUploadAuthHeaders()
|
||||
Object.entries(headers).forEach(([key, value]) => {
|
||||
task.setRequestHeader(key, value)
|
||||
})
|
||||
task.addFile(filePath, { key: fieldName })
|
||||
task.start()
|
||||
})
|
||||
}
|
||||
|
||||
async function uploadViaFetchH5<T>(
|
||||
targetUrl: string,
|
||||
filePath: string,
|
||||
fieldName: string,
|
||||
authMode: UploadAuthMode,
|
||||
requestPath: string,
|
||||
): Promise<T> {
|
||||
try {
|
||||
const blobRes = await fetch(filePath)
|
||||
const blob = await blobRes.blob()
|
||||
const ext = blob.type.split('/')[1] || 'jpg'
|
||||
const formData = new FormData()
|
||||
formData.append(fieldName, blob, `upload.${ext}`)
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
headers: resolveUploadAuthHeaders(authMode),
|
||||
body: formData,
|
||||
})
|
||||
const rawData = await response.text()
|
||||
return await new Promise<T>((resolve, reject) => {
|
||||
handleUploadSuccess<T>(response.status, rawData, resolve, reject, undefined, requestPath)
|
||||
})
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
throw new ApiError(normalizeNetworkErrorMessage(message, UPLOAD_NETWORK_ERROR))
|
||||
}
|
||||
}
|
||||
|
||||
async function runUpload<T>(
|
||||
targetUrl: string,
|
||||
filePath: string,
|
||||
fieldName: string,
|
||||
authMode: UploadAuthMode,
|
||||
requestPath: string,
|
||||
): Promise<T> {
|
||||
// #ifdef H5
|
||||
return uploadViaFetchH5<T>(targetUrl, filePath, fieldName, authMode, requestPath)
|
||||
// #endif
|
||||
|
||||
// #ifdef APP-PLUS
|
||||
return uploadViaPlusUploader<T>(targetUrl, filePath, fieldName, authMode, requestPath)
|
||||
// #endif
|
||||
|
||||
return uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode, requestPath)
|
||||
}
|
||||
|
||||
/** multipart/form-data 上传;H5 走 fetch 确保 Bearer token 发出 */
|
||||
export function uploadAppFile<T>(
|
||||
url: string,
|
||||
filePath: string,
|
||||
fieldName = 'file',
|
||||
authMode: UploadAuthMode = 'default',
|
||||
): Promise<T> {
|
||||
const targetUrl = resolveUploadUrl(url)
|
||||
const hadCsToken = authMode === 'cs' && !!getStoredCsToken()
|
||||
|
||||
const requestPath = url.startsWith('/') ? url : `/${url}`
|
||||
|
||||
return runUpload<T>(targetUrl, filePath, fieldName, authMode, requestPath).catch((err) => {
|
||||
if (authMode !== 'cs' || !isCsAuthError(err)) throw err
|
||||
if (!hadCsToken) throw err
|
||||
clearStoredCsToken()
|
||||
return runUpload<T>(targetUrl, filePath, fieldName, authMode, requestPath)
|
||||
})
|
||||
}
|
||||
|
||||
function handleSuccess<T>(
|
||||
res: UniApp.RequestSuccessCallbackResult,
|
||||
resolve: (value: T) => void,
|
||||
reject: (reason: ApiError) => void,
|
||||
saveTokenFromBody = false,
|
||||
requestPath = '',
|
||||
) {
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
const body = parseResponseBody(res.data) as ApiResponse | undefined
|
||||
reject(
|
||||
rejectRequestError(
|
||||
new ApiError(
|
||||
body?.msg || body?.message || `请求失败(${res.statusCode})`,
|
||||
body?.code ?? res.statusCode,
|
||||
),
|
||||
requestPath,
|
||||
reject,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const body = parseResponseBody(res.data) as ApiResponse<T> & Record<string, unknown>
|
||||
if (!isApiSuccess(body)) {
|
||||
reject(new ApiError(body.msg || body.message || '请求失败', body.code))
|
||||
rejectRequestError(
|
||||
new ApiError(body.msg || body.message || '请求失败', body.code),
|
||||
requestPath,
|
||||
reject,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -83,32 +398,78 @@ function handleSuccess<T>(
|
||||
resolve(unwrapApiData<T>(body))
|
||||
}
|
||||
|
||||
export function request<T = unknown>(options: RequestOptions): Promise<T> {
|
||||
function runRequest<T>(
|
||||
options: RequestOptions,
|
||||
url: string,
|
||||
buildHeaders: (extra?: Record<string, unknown>) => Record<string, string>,
|
||||
saveTokenFromBody = false,
|
||||
): Promise<T> {
|
||||
const requestPath = options.url
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
assertRequestUrl(url)
|
||||
} catch (err) {
|
||||
reject(new ApiError(err instanceof Error ? err.message : '接口地址未配置'))
|
||||
return
|
||||
}
|
||||
uni.request({
|
||||
...options,
|
||||
url: `${BASE_URL}${options.url}`,
|
||||
header: buildAuthHeaders(options.header),
|
||||
url,
|
||||
header: buildHeaders(options.header),
|
||||
dataType: 'text',
|
||||
success: (res) => handleSuccess<T>(res, resolve, reject),
|
||||
success: (res) => handleSuccess<T>(res, resolve, reject, saveTokenFromBody, requestPath),
|
||||
fail: (err) => {
|
||||
reject(new ApiError(err.errMsg || '网络异常'))
|
||||
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg)))
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
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)。
|
||||
*/
|
||||
export function requestCsApp<T = unknown>(options: RequestOptions): Promise<T> {
|
||||
const csBase = resolveCsAppBaseUrl()
|
||||
if (!csBase) return request<T>(options)
|
||||
|
||||
const url = buildCsAppRequestUrl(options.url)
|
||||
const hadCsToken = !!getStoredCsToken()
|
||||
|
||||
return runRequest<T>(options, url, buildCsAppAuthHeaders).catch((err) => {
|
||||
if (!hadCsToken || !isCsAuthError(err)) throw err
|
||||
clearStoredCsToken()
|
||||
return runRequest<T>(options, url, buildCsAppAuthHeaders)
|
||||
})
|
||||
}
|
||||
|
||||
/** 登录类接口:从完整响应体提取并保存 token */
|
||||
export function requestLogin<T = unknown>(options: RequestOptions): Promise<T> {
|
||||
const url = `${getApiBaseUrl()}${options.url}`
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
assertRequestUrl(url)
|
||||
} catch (err) {
|
||||
reject(new ApiError(err instanceof Error ? err.message : '接口地址未配置'))
|
||||
return
|
||||
}
|
||||
uni.request({
|
||||
...options,
|
||||
url: `${BASE_URL}${options.url}`,
|
||||
url,
|
||||
header: buildAuthHeaders(options.header),
|
||||
dataType: 'text',
|
||||
success: (res) => handleSuccess<T>(res, resolve, reject, true),
|
||||
success: (res) => handleSuccess<T>(res, resolve, reject, true, options.url),
|
||||
fail: (err) => {
|
||||
reject(new ApiError(err.errMsg || '网络异常'))
|
||||
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg)))
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
40
src/components/page-scroll-view/index.vue
Normal file
40
src/components/page-scroll-view/index.vue
Normal file
@@ -0,0 +1,40 @@
|
||||
<template>
|
||||
<scroll-view
|
||||
class="page-scroll-view"
|
||||
scroll-y
|
||||
:style="mergedStyle"
|
||||
v-bind="$attrs"
|
||||
>
|
||||
<slot />
|
||||
</scroll-view>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { CSSProperties } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
|
||||
|
||||
defineOptions({ inheritAttrs: false })
|
||||
|
||||
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)
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.page-scroll-view {
|
||||
flex-shrink: 0;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
</style>
|
||||
65
src/config/app-env.ts
Normal file
65
src/config/app-env.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* 运行环境配置。
|
||||
* HBuilderX 云打包时 import.meta.env 可能未注入,此处提供源码级兜底地址。
|
||||
* 上线前请修改 APP_ENV_DEFAULTS,或通过 .env.production 覆盖。
|
||||
*/
|
||||
const APP_ENV_DEFAULTS = {
|
||||
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 {
|
||||
const value = (import.meta.env as Record<string, string | undefined>)[key]
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
/** 主 API 根地址(App/小程序须为 http(s)://...;H5 开发返回空走代理) */
|
||||
export function getApiBaseUrl(): string {
|
||||
// #ifdef H5
|
||||
if (import.meta.env.DEV) return ''
|
||||
// #endif
|
||||
|
||||
const fromEnv = readViteEnv('VITE_API_BASE_URL') || readViteEnv('VITE_API_PROXY_TARGET')
|
||||
const base = fromEnv || APP_ENV_DEFAULTS.apiBaseUrl
|
||||
return base.replace(/\/$/, '')
|
||||
}
|
||||
|
||||
/** 客服服务根地址(不含 /app) */
|
||||
export function getCsApiBaseUrl(): string {
|
||||
const base = readViteEnv('VITE_CS_API_BASE_URL') || APP_ENV_DEFAULTS.csApiBaseUrl
|
||||
return base.replace(/\/$/, '')
|
||||
}
|
||||
|
||||
export function getMessageWsUrl(): string {
|
||||
return readViteEnv('VITE_MESSAGE_WS_URL') || APP_ENV_DEFAULTS.messageWsUrl
|
||||
}
|
||||
|
||||
export function getApiClientId(): string {
|
||||
return readViteEnv('VITE_API_CLIENT_ID') || APP_ENV_DEFAULTS.apiClientId
|
||||
}
|
||||
|
||||
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
|
||||
throw new Error(`${hint}无效:${url || '(空)'},需以 http(s):// 或 / 开头`)
|
||||
}
|
||||
79
src/hooks/use-page-scroll-height.ts
Normal file
79
src/hooks/use-page-scroll-height.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { type CSSProperties, computed, getCurrentInstance, nextTick, onMounted, ref } from 'vue'
|
||||
|
||||
const NAVBAR_BAR_RPX = 88
|
||||
|
||||
export interface PageScrollHeightOptions {
|
||||
/** 从底部额外减去的 px(如底部固定栏) */
|
||||
extraBottomPx?: number
|
||||
/**
|
||||
* 页面顶部已占用区域的选择器(如自定义 hero),测量其高度作为顶部偏移。
|
||||
* 未设置时默认按 statusBar + 导航栏(88rpx) 计算。
|
||||
*/
|
||||
topSelector?: string
|
||||
}
|
||||
|
||||
function getNavbarTopPx() {
|
||||
const sys = uni.getSystemInfoSync()
|
||||
const statusBar = sys.statusBarHeight ?? 0
|
||||
const navbarBar = uni.upx2px(NAVBAR_BAR_RPX)
|
||||
return statusBar + navbarBar
|
||||
}
|
||||
|
||||
export function usePageScrollHeight(options: PageScrollHeightOptions = {}) {
|
||||
const { extraBottomPx = 0, topSelector } = options
|
||||
const heightPx = ref(0)
|
||||
|
||||
function applyHeight(topPx: number) {
|
||||
const sys = uni.getSystemInfoSync()
|
||||
const windowHeight = sys.windowHeight ?? sys.screenHeight ?? 667
|
||||
heightPx.value = Math.max(0, windowHeight - topPx - extraBottomPx)
|
||||
}
|
||||
|
||||
function measureNavbarHeight() {
|
||||
applyHeight(getNavbarTopPx())
|
||||
}
|
||||
|
||||
function measureCustomTop() {
|
||||
if (!topSelector) {
|
||||
measureNavbarHeight()
|
||||
return
|
||||
}
|
||||
|
||||
const instance = getCurrentInstance()
|
||||
const query = instance
|
||||
? uni.createSelectorQuery().in(instance.proxy!)
|
||||
: uni.createSelectorQuery()
|
||||
|
||||
query
|
||||
.select(topSelector)
|
||||
.boundingClientRect((rect) => {
|
||||
const top =
|
||||
rect && !Array.isArray(rect) && rect.height
|
||||
? rect.height
|
||||
: getNavbarTopPx()
|
||||
applyHeight(top)
|
||||
})
|
||||
.exec()
|
||||
}
|
||||
|
||||
function remeasureScrollHeight() {
|
||||
if (topSelector) {
|
||||
nextTick(measureCustomTop)
|
||||
return
|
||||
}
|
||||
measureNavbarHeight()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
nextTick(remeasureScrollHeight)
|
||||
})
|
||||
|
||||
remeasureScrollHeight()
|
||||
|
||||
const scrollStyle = computed<CSSProperties>(() => ({
|
||||
height: `${heightPx.value}px`,
|
||||
width: '100%',
|
||||
}))
|
||||
|
||||
return { scrollHeight: heightPx, scrollStyle, remeasureScrollHeight }
|
||||
}
|
||||
44
src/hooks/use-page-show-refresh.ts
Normal file
44
src/hooks/use-page-show-refresh.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
|
||||
function clearStaleNativeLoading() {
|
||||
try {
|
||||
uni.hideLoading()
|
||||
} catch {
|
||||
// 部分端无 loading 时 hideLoading 可能抛错,忽略即可
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面再次显示时执行刷新(从子页返回、切换 Tab 等)。
|
||||
* - skipInitialShow:首屏由 onLoad 加载时设为 true,避免与 onLoad 重复请求
|
||||
* - 自动清掉残留的原生 showLoading(避免改名等流程的 loading 串到其他页)
|
||||
* - 短防抖 + 进行中跳过,避免连点返回/快速切页触发重复请求或闪提示
|
||||
*/
|
||||
export function usePageShowRefresh(
|
||||
handler: () => void | Promise<void>,
|
||||
options?: { skipInitialShow?: boolean; debounceMs?: number },
|
||||
) {
|
||||
let skipFirst = Boolean(options?.skipInitialShow)
|
||||
let inflight = false
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const debounceMs = options?.debounceMs ?? 280
|
||||
|
||||
onShow(() => {
|
||||
clearStaleNativeLoading()
|
||||
if (skipFirst) {
|
||||
skipFirst = false
|
||||
return
|
||||
}
|
||||
if (timer) clearTimeout(timer)
|
||||
timer = setTimeout(() => {
|
||||
if (inflight) return
|
||||
inflight = true
|
||||
Promise.resolve()
|
||||
.then(() => handler())
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
inflight = false
|
||||
})
|
||||
}, debounceMs)
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { createSSRApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
import { registerGlobalComponents } from "./plugins/register-global-components";
|
||||
import { installLocalizedToast } from "./utils/localized-toast";
|
||||
|
||||
installLocalizedToast();
|
||||
|
||||
export function createApp() {
|
||||
const app = createSSRApp(App);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name" : "",
|
||||
"appid" : "",
|
||||
"name" : "虫子智家",
|
||||
"appid" : "__UNI__925D0CC",
|
||||
"description" : "",
|
||||
"versionName" : "1.0.0",
|
||||
"versionName" : "1.2.3",
|
||||
"versionCode" : "100",
|
||||
"transformPx" : false,
|
||||
/* 5+App特有相关 */
|
||||
@@ -18,6 +18,9 @@
|
||||
},
|
||||
/* 模块配置 */
|
||||
"modules" : {
|
||||
"Bluetooth" : {},
|
||||
"Camera" : {},
|
||||
"Push" : {},
|
||||
"Maps" : {}
|
||||
},
|
||||
/* 应用发布信息 */
|
||||
@@ -50,9 +53,57 @@
|
||||
]
|
||||
},
|
||||
/* ios打包配置 */
|
||||
"ios" : {},
|
||||
"ios" : {
|
||||
"dSYMs" : false
|
||||
},
|
||||
/* SDK配置 */
|
||||
"sdkConfigs" : {}
|
||||
"sdkConfigs" : {
|
||||
"maps" : {
|
||||
"amap" : {
|
||||
"name" : "amapxzEnK46i",
|
||||
"appkey_ios" : "7d9a3ca1ef32775dd5cef9b11962ca49",
|
||||
"appkey_android" : "6b0279ce51355d222b5023c1124f4581"
|
||||
}
|
||||
},
|
||||
"push" : {
|
||||
"unipush" : {
|
||||
"version" : "2",
|
||||
"offline" : false
|
||||
}
|
||||
}
|
||||
},
|
||||
"icons" : {
|
||||
"android" : {
|
||||
"hdpi" : "unpackage/res/icons/72x72.png",
|
||||
"xhdpi" : "unpackage/res/icons/96x96.png",
|
||||
"xxhdpi" : "unpackage/res/icons/144x144.png",
|
||||
"xxxhdpi" : "unpackage/res/icons/192x192.png"
|
||||
},
|
||||
"ios" : {
|
||||
"appstore" : "unpackage/res/icons/1024x1024.png",
|
||||
"ipad" : {
|
||||
"app" : "unpackage/res/icons/76x76.png",
|
||||
"app@2x" : "unpackage/res/icons/152x152.png",
|
||||
"notification" : "unpackage/res/icons/20x20.png",
|
||||
"notification@2x" : "unpackage/res/icons/40x40.png",
|
||||
"proapp@2x" : "unpackage/res/icons/167x167.png",
|
||||
"settings" : "unpackage/res/icons/29x29.png",
|
||||
"settings@2x" : "unpackage/res/icons/58x58.png",
|
||||
"spotlight" : "unpackage/res/icons/40x40.png",
|
||||
"spotlight@2x" : "unpackage/res/icons/80x80.png"
|
||||
},
|
||||
"iphone" : {
|
||||
"app@2x" : "unpackage/res/icons/120x120.png",
|
||||
"app@3x" : "unpackage/res/icons/180x180.png",
|
||||
"notification@2x" : "unpackage/res/icons/40x40.png",
|
||||
"notification@3x" : "unpackage/res/icons/60x60.png",
|
||||
"settings@2x" : "unpackage/res/icons/58x58.png",
|
||||
"settings@3x" : "unpackage/res/icons/87x87.png",
|
||||
"spotlight@2x" : "unpackage/res/icons/80x80.png",
|
||||
"spotlight@3x" : "unpackage/res/icons/120x120.png"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
/* 快应用特有相关 */
|
||||
@@ -101,8 +152,8 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"uniStatistics": {
|
||||
"enable": false
|
||||
"uniStatistics" : {
|
||||
"enable" : false
|
||||
},
|
||||
"vueVersion" : "3"
|
||||
}
|
||||
|
||||
@@ -6,13 +6,6 @@
|
||||
}
|
||||
},
|
||||
"pages": [
|
||||
{
|
||||
"path": "pages/login/index",
|
||||
"style": {
|
||||
"navigationStyle": "custom",
|
||||
"navigationBarTitleText": "登录"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "pages/device/index",
|
||||
"style": {
|
||||
@@ -20,6 +13,13 @@
|
||||
"navigationBarTitleText": "设备"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "pages/login/index",
|
||||
"style": {
|
||||
"navigationStyle": "custom",
|
||||
"navigationBarTitleText": "登录"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "pages/device/detail/index",
|
||||
"style": {
|
||||
@@ -108,7 +108,10 @@
|
||||
"path": "pages/mine/support/index",
|
||||
"style": {
|
||||
"navigationStyle": "custom",
|
||||
"navigationBarTitleText": "在线客服"
|
||||
"navigationBarTitleText": "在线客服",
|
||||
"app-plus": {
|
||||
"softinputMode": "adjustResize"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -7,8 +7,7 @@
|
||||
}
|
||||
|
||||
.add-device-page__scroll {
|
||||
flex: 1;
|
||||
height: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.add-device-page__body {
|
||||
@@ -46,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);
|
||||
@@ -62,6 +61,8 @@
|
||||
font-size: 32rpx;
|
||||
font-weight: 500;
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.add-device-page__btn-badge {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
import { request } from '@/api/request'
|
||||
import type { ProductOption } from './complete.types'
|
||||
|
||||
/** POST /app/device/productOptions — 获取产品型号下拉列表 */
|
||||
function normalizeProductOption(item: ProductOption): ProductOption {
|
||||
const model = item.model?.trim() || item.name?.trim() || ''
|
||||
return {
|
||||
...item,
|
||||
model,
|
||||
name: item.name?.trim() || model,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /app/device/productOptions
|
||||
* 返回所有启用状态的产品型号,供添加设备页下拉选择;无需再传 status。
|
||||
*/
|
||||
export function fetchProductOptions() {
|
||||
return request<ProductOption[]>({
|
||||
url: '/app/device/productOptions',
|
||||
method: 'POST',
|
||||
data: {},
|
||||
})
|
||||
method: 'GET',
|
||||
}).then((rows) => (Array.isArray(rows) ? rows.map(normalizeProductOption) : []))
|
||||
}
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
.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;
|
||||
height: 0;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.complete-page__body {
|
||||
@@ -168,6 +176,7 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.complete-page__select-text,
|
||||
.complete-page__room-text {
|
||||
flex: 1;
|
||||
font-size: 28rpx;
|
||||
@@ -217,6 +226,7 @@
|
||||
}
|
||||
|
||||
.complete-page__footer {
|
||||
flex-shrink: 0;
|
||||
padding: 16rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
|
||||
background: $color-bg-page;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
/** POST /app/device/productOptions 返回项 */
|
||||
/** GET /app/device/productOptions — 启用状态产品型号(AppProductOptionVo) */
|
||||
export interface ProductOption {
|
||||
productId?: string | number
|
||||
model?: string
|
||||
name?: string
|
||||
category?: string
|
||||
connectTypes?: string
|
||||
filterEnabled?: boolean
|
||||
filterTotalDays?: number
|
||||
capabilities?: string[]
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<template>
|
||||
<view class="complete-page">
|
||||
<view class="complete-page__top">
|
||||
<app-navbar title="设备配置" />
|
||||
<scroll-view class="complete-page__scroll" scroll-y>
|
||||
</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 />
|
||||
@@ -55,15 +57,11 @@
|
||||
</view>
|
||||
<view class="complete-page__field">
|
||||
<text class="complete-page__label">产品型号</text>
|
||||
<picker
|
||||
mode="selector"
|
||||
:range="productOptions"
|
||||
range-key="model"
|
||||
:value="productIndex"
|
||||
:disabled="productOptionsLoading || !productOptions.length"
|
||||
@change="onProductChange"
|
||||
<view
|
||||
class="complete-page__select-row"
|
||||
hover-class="complete-page__select-row--hover"
|
||||
@tap.stop="onPickProduct"
|
||||
>
|
||||
<view class="complete-page__select-row">
|
||||
<text
|
||||
class="complete-page__select-text"
|
||||
:class="{ 'complete-page__select-text--placeholder': !productSelected }"
|
||||
@@ -76,7 +74,6 @@
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
</picker>
|
||||
</view>
|
||||
<view class="complete-page__field">
|
||||
<text class="complete-page__label">所在房间</text>
|
||||
@@ -112,7 +109,7 @@
|
||||
</text>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</page-scroll-view>
|
||||
<view class="complete-page__footer">
|
||||
<view
|
||||
class="complete-page__submit"
|
||||
@@ -129,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'
|
||||
@@ -139,8 +144,6 @@ const {
|
||||
currentStep,
|
||||
deviceName,
|
||||
serialMasked,
|
||||
productOptions,
|
||||
productIndex,
|
||||
productDisplayText,
|
||||
productSelected,
|
||||
productOptionsLoading,
|
||||
@@ -151,7 +154,7 @@ const {
|
||||
bluetoothConnected,
|
||||
bluetoothStatusText,
|
||||
initPage,
|
||||
onProductChange,
|
||||
onPickProduct,
|
||||
onPickRoom,
|
||||
onFinishAdd,
|
||||
} = useCompleteDevice()
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
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'
|
||||
import { fetchRoomList } from '@/api/location'
|
||||
import type { RoomOption } from '@/types/location'
|
||||
import { fetchDeviceList } from '@/pages/device/device.api'
|
||||
import { fetchAllDeviceList } from '@/pages/device/device.api'
|
||||
import { updateDeviceRuntime } from '@/pages/device/detail/device-detail.api'
|
||||
import { updateDeviceSettings } from '@/pages/device/settings/device-settings.api'
|
||||
import { buildBleDeviceName, isStandardBleDeviceName } from '@/utils/ble-device-name'
|
||||
import { releaseBleDevice } from '@/utils/bluetooth'
|
||||
import { clearZ2BleHandleCache, sendZ2BleRenameCommand } from '@/utils/z2-ble'
|
||||
import { bindDevice } from '../add-device.api'
|
||||
import { parseId, sameId } from '@/utils/device-id'
|
||||
import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home'
|
||||
import { readBindDeviceContext } from '../add-device.types'
|
||||
import { fetchProductOptions } from './complete.api'
|
||||
import type { ProductOption } from './complete.types'
|
||||
@@ -16,6 +21,8 @@ export function useCompleteDevice() {
|
||||
const currentStep = 4
|
||||
const deviceNo = ref('')
|
||||
const deviceName = ref('Z2 空气净化器')
|
||||
/** 配对时读到的 BLE 广播名,与用户可改的云端显示名无关 */
|
||||
const pairedBleName = ref('')
|
||||
const serialMasked = ref('****A3B2')
|
||||
const productId = ref('')
|
||||
const model = ref('')
|
||||
@@ -32,6 +39,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)
|
||||
@@ -135,7 +143,10 @@ export function useCompleteDevice() {
|
||||
function applyQuery(query: Record<string, string | undefined>) {
|
||||
const ctx = readBindDeviceContext(query)
|
||||
if (ctx.deviceNo) deviceNo.value = ctx.deviceNo
|
||||
if (ctx.name) deviceName.value = ctx.name
|
||||
if (ctx.name) {
|
||||
deviceName.value = ctx.name
|
||||
pairedBleName.value = ctx.name
|
||||
}
|
||||
if (ctx.serialMasked) serialMasked.value = ctx.serialMasked
|
||||
const parsedProductId = parseId(ctx.productId)
|
||||
if (parsedProductId) productId.value = parsedProductId
|
||||
@@ -145,7 +156,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,15 +167,36 @@ 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
|
||||
}
|
||||
|
||||
function onProductChange(event: { detail: { value: number } }) {
|
||||
const index = Number(event.detail.value)
|
||||
const option = productOptions.value[index]
|
||||
if (!option) return
|
||||
applyProduct(option)
|
||||
function onPickProduct() {
|
||||
if (productOptionsLoading.value) {
|
||||
uni.showToast({ title: '产品型号加载中', icon: 'none' })
|
||||
return
|
||||
}
|
||||
const options = productOptions.value
|
||||
if (!options.length) {
|
||||
uni.showToast({ title: '暂无产品型号,请稍后重试', icon: 'none' })
|
||||
void loadProductOptions()
|
||||
return
|
||||
}
|
||||
|
||||
const labels = options.map((item) => item.model || item.name || '未知型号')
|
||||
uni.showActionSheet({
|
||||
itemList: labels.slice(0, 6),
|
||||
success: (res) => {
|
||||
const option = options[res.tapIndex]
|
||||
if (option) applyProduct(option)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function onPickRoom() {
|
||||
@@ -213,8 +248,24 @@ export function useCompleteDevice() {
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
if (bleDeviceId.value && bluetoothConnected.value && mac.value) {
|
||||
const bleName = buildBleDeviceName(mac.value)
|
||||
const needRename = pairedBleName.value
|
||||
&& !isStandardBleDeviceName(mac.value, pairedBleName.value)
|
||||
if (needRename) {
|
||||
try {
|
||||
await sendZ2BleRenameCommand(bleDeviceId.value, bleName, {
|
||||
timeoutMs: 25000,
|
||||
})
|
||||
} catch {
|
||||
// 蓝牙名称同步失败不影响云端绑定,静默继续
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const validHomeId = await resolveValidHomeId(homeId.value)
|
||||
homeId.value = validHomeId
|
||||
if (validHomeId) saveSelectedHomeId(validHomeId)
|
||||
await bindDevice({
|
||||
deviceNo: deviceNo.value.trim(),
|
||||
name,
|
||||
@@ -226,9 +277,16 @@ export function useCompleteDevice() {
|
||||
...(locationId.value ? { locationId: locationId.value } : {}),
|
||||
})
|
||||
|
||||
const list = await fetchDeviceList()
|
||||
const list = await fetchAllDeviceList()
|
||||
const bound = list?.find((item) => item.deviceNo === deviceNo.value.trim())
|
||||
if (bound?.deviceId != null) {
|
||||
const boundName = bound.name?.trim()
|
||||
if (boundName !== name) {
|
||||
await updateDeviceSettings({
|
||||
deviceId: bound.deviceId,
|
||||
name,
|
||||
})
|
||||
}
|
||||
await updateDeviceRuntime({
|
||||
deviceId: bound.deviceId,
|
||||
status: bluetoothConnected.value ? '1' : '2',
|
||||
@@ -248,10 +306,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,
|
||||
@@ -268,7 +335,7 @@ export function useCompleteDevice() {
|
||||
bluetoothConnected,
|
||||
bluetoothStatusText,
|
||||
initPage,
|
||||
onProductChange,
|
||||
onPickProduct,
|
||||
onPickRoom,
|
||||
onFinishAdd,
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="add-device-page">
|
||||
<app-navbar title="添加设备" />
|
||||
<scroll-view class="add-device-page__scroll" scroll-y>
|
||||
<page-scroll-view class="add-device-page__scroll">
|
||||
<view class="add-device-page__body">
|
||||
<bind-steps :steps="BIND_STEPS" :current="currentStep" />
|
||||
<bind-bluetooth-hero />
|
||||
@@ -25,17 +25,22 @@
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</page-scroll-view>
|
||||
</view>
|
||||
</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>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="pair-page">
|
||||
<view class="pair-page__top">
|
||||
<app-navbar title="设备配置" />
|
||||
<scroll-view class="pair-page__scroll" scroll-y>
|
||||
</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>
|
||||
</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 ?? '',
|
||||
|
||||
@@ -1,18 +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;
|
||||
height: 0;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.pair-page__body {
|
||||
padding-bottom: 24rpx;
|
||||
padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.pair-page__status {
|
||||
@@ -118,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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="scan-page">
|
||||
<app-navbar title="扫描设备" />
|
||||
<scroll-view class="scan-page__scroll" scroll-y>
|
||||
<page-scroll-view class="scan-page__scroll">
|
||||
<view class="scan-page__body">
|
||||
<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">
|
||||
@@ -41,12 +52,13 @@
|
||||
|
||||
<scan-help-tip />
|
||||
</view>
|
||||
</scroll-view>
|
||||
</page-scroll-view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<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) {
|
||||
|
||||
@@ -7,8 +7,7 @@
|
||||
}
|
||||
|
||||
.scan-page__scroll {
|
||||
flex: 1;
|
||||
height: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.scan-page__body {
|
||||
@@ -92,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;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
<template>
|
||||
<view class="agreement-page">
|
||||
<app-navbar :title="title" />
|
||||
<scroll-view class="agreement-page__scroll" scroll-y>
|
||||
<page-scroll-view class="agreement-page__scroll">
|
||||
<view class="agreement-page__content">
|
||||
<view v-if="loading" class="agreement-page__loading">
|
||||
<text>加载中...</text>
|
||||
</view>
|
||||
<text v-else class="agreement-page__text">{{ content }}</text>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</page-scroll-view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
@@ -27,8 +27,7 @@ const { title, content, loading } = useAgreement()
|
||||
}
|
||||
|
||||
.agreement-page__scroll {
|
||||
flex: 1;
|
||||
height: calc(100vh - 88rpx);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.agreement-page__content {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<base-input v-model="password" icon="lock" type="password" placeholder="请输入密码" />
|
||||
<base-input v-model="confirmPassword" icon="lock" type="password" placeholder="确认密码" />
|
||||
|
||||
<text class="auth-form-page__hint">8-20位字符,须包含字母、数字、符号中的至少2种。</text>
|
||||
<text class="auth-form-page__hint">{{ passwordRuleHint }}</text>
|
||||
|
||||
<view class="auth-form-page__btn">
|
||||
<primary-button text="确认修改" @click="submit" />
|
||||
@@ -17,8 +17,11 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { PASSWORD_RULE_HINT } from '@/utils/validate'
|
||||
import { useChangePassword } from './use-change-password'
|
||||
|
||||
const passwordRuleHint = `${PASSWORD_RULE_HINT}。`
|
||||
|
||||
const { password, confirmPassword, submit } = useChangePassword()
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,20 +1,39 @@
|
||||
import { onLoad } from '@dcloudio/uni-app'
|
||||
import { ref } from 'vue'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { isValidStrongPassword } from '@/utils/validate'
|
||||
import {
|
||||
handleAuthSessionExpired,
|
||||
isAuthSessionExpiredError,
|
||||
} from '@/utils/auth-session'
|
||||
import { markPasswordModifiedPendingForPhone } from '@/utils/password-modified-at'
|
||||
import { isValidStrongPassword, PASSWORD_INVALID_TOAST } from '@/utils/validate'
|
||||
import { resetPasswordByToken } from './change-password.api'
|
||||
|
||||
function redirectToLoginAfterPasswordChange(toastTitle = '密码修改成功,请重新登录') {
|
||||
handleAuthSessionExpired({
|
||||
message: toastTitle,
|
||||
forceNavigateToLogin: true,
|
||||
})
|
||||
}
|
||||
|
||||
/** 改密后勿再请求 profile,避免 401 触发全局踢登抢占跳转 */
|
||||
function recordPasswordModifiedAfterReset(fallbackPhone: string) {
|
||||
if (!fallbackPhone.trim()) return
|
||||
markPasswordModifiedPendingForPhone(fallbackPhone)
|
||||
}
|
||||
|
||||
export function useChangePassword() {
|
||||
const password = ref('')
|
||||
const confirmPassword = ref('')
|
||||
const resetToken = ref('')
|
||||
const fromPrivacy = ref(false)
|
||||
const boundPhone = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
onLoad((query) => {
|
||||
const raw = (query?.resetToken as string) || ''
|
||||
resetToken.value = raw ? decodeURIComponent(raw) : ''
|
||||
fromPrivacy.value = query?.from === 'privacy'
|
||||
const phoneRaw = (query?.phone as string) || ''
|
||||
boundPhone.value = phoneRaw ? decodeURIComponent(phoneRaw) : ''
|
||||
if (!resetToken.value) {
|
||||
uni.showToast({ title: '请先完成验证码校验', icon: 'none' })
|
||||
setTimeout(() => uni.navigateBack(), 1500)
|
||||
@@ -27,10 +46,7 @@ export function useChangePassword() {
|
||||
return
|
||||
}
|
||||
if (!isValidStrongPassword(password.value)) {
|
||||
uni.showToast({
|
||||
title: '密码需8-20位,且包含字母、数字、符号中至少2种',
|
||||
icon: 'none',
|
||||
})
|
||||
uni.showToast({ title: PASSWORD_INVALID_TOAST, icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (password.value !== confirmPassword.value) {
|
||||
@@ -45,15 +61,14 @@ export function useChangePassword() {
|
||||
newPassword: password.value,
|
||||
confirmPassword: confirmPassword.value,
|
||||
})
|
||||
uni.showToast({ title: '密码修改成功', icon: 'success' })
|
||||
setTimeout(() => {
|
||||
if (fromPrivacy.value) {
|
||||
uni.navigateBack({ delta: 2 })
|
||||
recordPasswordModifiedAfterReset(boundPhone.value)
|
||||
redirectToLoginAfterPasswordChange()
|
||||
} catch (err) {
|
||||
if (isAuthSessionExpiredError(err)) {
|
||||
recordPasswordModifiedAfterReset(boundPhone.value)
|
||||
redirectToLoginAfterPasswordChange('登录状态已失效,请使用新密码重新登录')
|
||||
return
|
||||
}
|
||||
uni.reLaunch({ url: '/pages/login/index' })
|
||||
}, 800)
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '修改失败,请重试'), icon: 'none' })
|
||||
} finally {
|
||||
loading.value = false
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -21,22 +21,37 @@
|
||||
v-if="pickerOpen"
|
||||
class="device-header__mask"
|
||||
@tap="closePicker"
|
||||
@touchmove.stop.prevent="preventTouchMove"
|
||||
/>
|
||||
<view v-if="pickerOpen" class="device-header__dropdown">
|
||||
<view
|
||||
class="device-header__option device-header__option--active"
|
||||
@tap.stop="selectHome"
|
||||
<scroll-view
|
||||
class="device-header__dropdown-scroll"
|
||||
scroll-y
|
||||
:show-scrollbar="false"
|
||||
:style="dropdownScrollStyle"
|
||||
>
|
||||
<text class="device-header__option-text device-header__option-text--active">
|
||||
{{ homeName }}
|
||||
<view
|
||||
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"
|
||||
: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">
|
||||
</scroll-view>
|
||||
<view class="device-header__option device-header__option--manage" @tap.stop="selectManage">
|
||||
<text class="device-header__option-text">家庭管理</text>
|
||||
</view>
|
||||
</view>
|
||||
@@ -72,12 +87,16 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { computed, ref, watch } 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,12 +104,30 @@ const emit = defineEmits<{
|
||||
'add-device': []
|
||||
scan: []
|
||||
manage: []
|
||||
'select-home': [home: AppHomeVo]
|
||||
'picker-open-change': [open: boolean]
|
||||
}>()
|
||||
|
||||
/** 单行选项约 88rpx,列表最多展示约 8 行高度 */
|
||||
const DROPDOWN_ITEM_RPX = 88
|
||||
const DROPDOWN_LIST_MAX_RPX = 704
|
||||
|
||||
const dropdownScrollStyle = computed(() => {
|
||||
const count = Math.max(props.homes.length, 1)
|
||||
const heightRpx = Math.min(count * DROPDOWN_ITEM_RPX, DROPDOWN_LIST_MAX_RPX)
|
||||
return { height: `${uni.upx2px(heightRpx)}px` }
|
||||
})
|
||||
|
||||
const pickerOpen = ref(false)
|
||||
const addMenuOpen = ref(false)
|
||||
const hasUnreadNotify = hasUnreadMessages
|
||||
|
||||
watch(pickerOpen, (open) => {
|
||||
emit('picker-open-change', open)
|
||||
})
|
||||
|
||||
function preventTouchMove() {}
|
||||
|
||||
const sys = uni.getSystemInfoSync()
|
||||
const statusBarHeight = sys.statusBarHeight ?? 0
|
||||
const headerPaddingTop =
|
||||
@@ -107,8 +144,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() {
|
||||
@@ -207,6 +250,13 @@ function onScan() {
|
||||
background: #fff;
|
||||
box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
|
||||
z-index: 300;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.device-header__dropdown-scroll {
|
||||
flex-shrink: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.device-header__option {
|
||||
@@ -221,6 +271,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;
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
<text class="device-list__badge-text">{{ onlineCount }} 台在线</text>
|
||||
</view>
|
||||
</view>
|
||||
<text class="device-list__manage" @tap="$emit('manage')">管理 ></text>
|
||||
</view>
|
||||
|
||||
<view class="device-list__grid">
|
||||
@@ -31,7 +30,6 @@ defineProps<{
|
||||
}>()
|
||||
|
||||
defineEmits<{
|
||||
manage: []
|
||||
select: [device: DeviceListItem]
|
||||
}>()
|
||||
</script>
|
||||
@@ -44,7 +42,6 @@ defineEmits<{
|
||||
.device-list__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 24rpx;
|
||||
}
|
||||
|
||||
@@ -72,11 +69,6 @@ defineEmits<{
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.device-list__manage {
|
||||
font-size: 26rpx;
|
||||
color: $color-text-secondary;
|
||||
}
|
||||
|
||||
.device-list__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<template>
|
||||
<view
|
||||
v-if="visible"
|
||||
class="ble-reconnect-loading"
|
||||
:style="{ top: `${topOffsetPx}px` }"
|
||||
@tap.stop.prevent
|
||||
@touchmove.stop.prevent
|
||||
>
|
||||
<view class="ble-reconnect-loading__center" @tap.stop.prevent>
|
||||
<view class="ble-reconnect-loading__spinner" aria-hidden="true">
|
||||
<view class="ble-reconnect-loading__ring" />
|
||||
<view class="ble-reconnect-loading__core" />
|
||||
</view>
|
||||
<text class="ble-reconnect-loading__title">{{ title }}</text>
|
||||
<text class="ble-reconnect-loading__desc">{{ desc }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
visible?: boolean
|
||||
title?: string
|
||||
desc?: string
|
||||
/** 顶部留白(状态栏+导航),保证返回/设置可点 */
|
||||
topOffsetPx?: number
|
||||
}>(),
|
||||
{
|
||||
visible: false,
|
||||
title: '设备连接中',
|
||||
desc: '正在重新连接蓝牙,请靠近设备并稍候',
|
||||
topOffsetPx: 88,
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.ble-reconnect-loading {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
background: rgba(16, 24, 40, 0.28);
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 420rpx;
|
||||
padding: 48rpx 36rpx 44rpx;
|
||||
border-radius: 28rpx;
|
||||
background: #fff;
|
||||
box-shadow: 0 16rpx 48rpx rgba(16, 24, 40, 0.16);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__spinner {
|
||||
position: relative;
|
||||
width: 96rpx;
|
||||
height: 96rpx;
|
||||
margin-bottom: 28rpx;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__ring {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 50%;
|
||||
border: 6rpx solid #e8f8ef;
|
||||
border-top-color: #21c25e;
|
||||
animation: ble-reconnect-spin 0.9s linear infinite;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__core {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 18rpx;
|
||||
height: 18rpx;
|
||||
margin: -9rpx 0 0 -9rpx;
|
||||
border-radius: 50%;
|
||||
background: #21c25e;
|
||||
opacity: 0.85;
|
||||
animation: ble-reconnect-pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__title {
|
||||
font-size: 32rpx;
|
||||
font-weight: 600;
|
||||
color: #1a1a1a;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__desc {
|
||||
margin-top: 12rpx;
|
||||
font-size: 24rpx;
|
||||
color: #667085;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@keyframes ble-reconnect-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes ble-reconnect-pulse {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(0.85);
|
||||
opacity: 0.55;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +1,9 @@
|
||||
import {
|
||||
mapZ2StateToRuntimePatch,
|
||||
Z2_BLE_CMD,
|
||||
type Z2AirQuality,
|
||||
} from '@/utils/z2-ble-protocol'
|
||||
import { queryZ2BleState } from '@/utils/z2-ble'
|
||||
import { queryZ2BleState, sendZ2BleCommand } from '@/utils/z2-ble'
|
||||
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
|
||||
|
||||
export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & {
|
||||
@@ -11,12 +12,61 @@ export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & {
|
||||
airQuality?: Z2AirQuality
|
||||
}
|
||||
|
||||
/** 通过 Z2 BLE 协议查询设备运行数据 */
|
||||
function toUpdateRuntimeBody(patch: BleRuntimePatch): Partial<UpdateDeviceRuntimeBody> {
|
||||
const {
|
||||
runMode,
|
||||
fanLevel,
|
||||
tvoc,
|
||||
powerMode,
|
||||
deviceBattery,
|
||||
filterLife,
|
||||
charging,
|
||||
status,
|
||||
bluetoothConnected,
|
||||
signalLevel,
|
||||
} = patch
|
||||
return {
|
||||
...(runMode != null ? { runMode } : {}),
|
||||
...(fanLevel != null ? { fanLevel } : {}),
|
||||
...(tvoc != null ? { tvoc } : {}),
|
||||
...(powerMode != null ? { powerMode } : {}),
|
||||
...(deviceBattery != null ? { deviceBattery } : {}),
|
||||
...(filterLife != null ? { filterLife } : {}),
|
||||
...(charging != null ? { charging } : {}),
|
||||
...(status != null ? { status } : {}),
|
||||
...(bluetoothConnected != null ? { bluetoothConnected } : {}),
|
||||
...(signalLevel != null ? { signalLevel } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** 通过 Z2 BLE 协议查询设备运行数据(Q 全量 + I 滤芯,滤芯始终单独查) */
|
||||
export async function readRuntimeFromBle(
|
||||
bleDeviceId: string,
|
||||
): Promise<BleRuntimePatch> {
|
||||
if (typeof uni.readBLECharacteristicValue !== 'function') return {}
|
||||
|
||||
const state = await queryZ2BleState(bleDeviceId)
|
||||
return mapZ2StateToRuntimePatch(state)
|
||||
let patch = mapZ2StateToRuntimePatch(state)
|
||||
|
||||
// 滤芯衰减靠嵌入式维护,Q 里经常没有;每次同步都发 I,避免一直显示云端旧百分比
|
||||
try {
|
||||
const filterState = await sendZ2BleCommand(bleDeviceId, Z2_BLE_CMD.QUERY_FILTER, {
|
||||
timeoutMs: 4000,
|
||||
})
|
||||
const filterPatch = mapZ2StateToRuntimePatch(filterState)
|
||||
if (filterPatch.filterLife != null) {
|
||||
patch = { ...patch, filterLife: filterPatch.filterLife }
|
||||
} else if (import.meta.env.DEV || import.meta.env.VITE_BLE_DEBUG === 'true') {
|
||||
console.log('[Z2 BLE] filter query returned no filterLife', filterState)
|
||||
}
|
||||
} catch (err) {
|
||||
if (import.meta.env.DEV || import.meta.env.VITE_BLE_DEBUG === 'true') {
|
||||
console.log('[Z2 BLE] filter query failed', err)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...toUpdateRuntimeBody(patch),
|
||||
...(patch.airQuality != null ? { airQuality: patch.airQuality } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,8 @@
|
||||
|
||||
.device-detail-hero__bar {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
/* 高于连接遮罩,保证加载中返回/设置可点 */
|
||||
z-index: 10001;
|
||||
height: 88rpx;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -97,11 +98,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
.device-detail-hero__status-spinner {
|
||||
width: 20rpx;
|
||||
height: 20rpx;
|
||||
border-radius: 50%;
|
||||
border: 3rpx solid rgba(255, 255, 255, 0.35);
|
||||
border-top-color: #fff;
|
||||
animation: device-detail-status-spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.device-detail-hero__status-text {
|
||||
font-size: 24rpx;
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
}
|
||||
|
||||
@keyframes device-detail-status-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.device-detail-hero__metric-row {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
@@ -163,8 +179,7 @@
|
||||
.device-detail-page__scroll {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
flex: 1;
|
||||
height: 0;
|
||||
width: 100%;
|
||||
margin-top: -40rpx;
|
||||
}
|
||||
|
||||
@@ -237,6 +252,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 {
|
||||
@@ -267,6 +288,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 {
|
||||
|
||||
@@ -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电池 */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="device-detail-page">
|
||||
<view class="device-detail-hero" :style="{ paddingTop: statusBarHeight + 'px' }">
|
||||
<image
|
||||
@@ -22,6 +22,12 @@
|
||||
|
||||
<view class="device-detail-hero__status">
|
||||
<view
|
||||
v-if="showReconnectLoading"
|
||||
class="device-detail-hero__status-spinner"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<view
|
||||
v-else
|
||||
class="device-detail-hero__status-dot"
|
||||
:class="{ 'device-detail-hero__status-dot--offline': !isOnline }"
|
||||
/>
|
||||
@@ -41,7 +47,7 @@
|
||||
<text class="device-detail-hero__sync">{{ syncText }}</text>
|
||||
</view>
|
||||
|
||||
<scroll-view class="device-detail-page__scroll" scroll-y>
|
||||
<page-scroll-view class="device-detail-page__scroll" :scroll-style="detailScrollStyle">
|
||||
<view class="device-detail-panel">
|
||||
<view class="device-detail-panel__dash" aria-hidden="true" />
|
||||
|
||||
@@ -65,6 +71,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 +92,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>
|
||||
@@ -140,34 +150,48 @@
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</page-scroll-view>
|
||||
|
||||
<filter-replace-dialog
|
||||
v-model:visible="filterReplaceDialogVisible"
|
||||
@confirm="onConfirmFilterReplace"
|
||||
/>
|
||||
<run-mode-explain-dialog v-model:visible="runModeExplainVisible" />
|
||||
|
||||
<!-- 页面居中加载,挡住下方操作区;顶栏返回/设置仍可点 -->
|
||||
<ble-reconnect-loading
|
||||
:visible="showReconnectLoading"
|
||||
:title="reconnectLoadingTitle"
|
||||
:desc="reconnectLoadingDesc"
|
||||
:top-offset-px="statusBarHeight + navBarHeightPx"
|
||||
/>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
|
||||
import { staticAssets } from '@/utils/static-assets'
|
||||
import BleReconnectLoading from './components/ble-reconnect-loading/index.vue'
|
||||
import FilterReplaceDialog from './components/filter-replace-dialog/index.vue'
|
||||
import RunModeExplainDialog from './components/run-mode-explain-dialog/index.vue'
|
||||
import { useDeviceDetail } from './use-device-detail'
|
||||
|
||||
const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight ?? 0)
|
||||
/** 与 .device-detail-hero__bar 高度 88rpx 对齐,避免遮罩盖住设置按钮 */
|
||||
const navBarHeightPx = uni.upx2px(88)
|
||||
const { scrollStyle: detailScrollStyle } = usePageScrollHeight({
|
||||
topSelector: '.device-detail-hero',
|
||||
})
|
||||
const runModeExplainVisible = ref(false)
|
||||
|
||||
function onOpenRunModeExplain() {
|
||||
runModeExplainVisible.value = true
|
||||
}
|
||||
|
||||
const {
|
||||
deviceName,
|
||||
connectionText,
|
||||
isOnline,
|
||||
showReconnectLoading,
|
||||
reconnectLoadingTitle,
|
||||
reconnectLoadingDesc,
|
||||
tvocDisplay,
|
||||
tvocLevel,
|
||||
syncText,
|
||||
@@ -191,6 +215,11 @@ const {
|
||||
onConfirmFilterReplace,
|
||||
} = useDeviceDetail()
|
||||
|
||||
function onOpenRunModeExplain() {
|
||||
if (showReconnectLoading.value) return
|
||||
runModeExplainVisible.value = true
|
||||
}
|
||||
|
||||
function onBack() {
|
||||
const pages = getCurrentPages()
|
||||
if (pages.length > 1) {
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { onUnload } from '@dcloudio/uni-app'
|
||||
import { onShow, onUnload } from '@dcloudio/uni-app'
|
||||
import { ref } from 'vue'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { buildBleDeviceName } from '@/utils/ble-device-name'
|
||||
import { recallBleDeviceId, rememberBleDeviceId } from '@/utils/ble-device-id-cache'
|
||||
import {
|
||||
closeBleConnection,
|
||||
ensureBleConnection,
|
||||
ensureBluetoothReady,
|
||||
getBluetoothErrorMessage,
|
||||
getDiscoveredBluetoothDevices,
|
||||
getConnectedBleDeviceByMac,
|
||||
isBleDeviceConnected,
|
||||
isBluetoothApiSupported,
|
||||
rssiToSignalLevel,
|
||||
scanForBleDeviceByMac,
|
||||
@@ -19,7 +22,10 @@ import { readRuntimeFromBle, type BleRuntimePatch } from './device-bluetooth-rea
|
||||
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
|
||||
|
||||
const SYNC_INTERVAL_MS = 15000
|
||||
const SCAN_TIMEOUT_MS = 15000
|
||||
const QUICK_SCAN_MS = 5000
|
||||
const RETRY_SCAN_MS = 10000
|
||||
/** 断连事件防抖:避免 create/notify 过程中的瞬时断连触发重连循环 */
|
||||
const DISCONNECT_CONFIRM_MS = 700
|
||||
|
||||
export interface DeviceBluetoothSyncContext {
|
||||
getDeviceId: () => string | number
|
||||
@@ -34,31 +40,35 @@ export interface DeviceBluetoothSyncContext {
|
||||
|
||||
export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
const syncing = ref(false)
|
||||
const connecting = ref(false)
|
||||
const bleDeviceId = ref<string>()
|
||||
let syncTimer: ReturnType<typeof setInterval> | undefined
|
||||
let disconnectTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let unsubscribeConnection: (() => void) | undefined
|
||||
let active = false
|
||||
let tearingDown = false
|
||||
let hadSuccessfulSync = false
|
||||
/** 正在主动建连,忽略期间的断连回调 */
|
||||
let linking = false
|
||||
|
||||
function setSyncText(text: string) {
|
||||
context.onSyncTextChange(text)
|
||||
}
|
||||
|
||||
async function reportBleDisconnected() {
|
||||
const deviceId = context.getDeviceId()
|
||||
if (!deviceId) return
|
||||
context.onBluetoothConnectedChange(false)
|
||||
function resolveBleBroadcastName(mac: string): string | undefined {
|
||||
try {
|
||||
await updateDeviceRuntime({
|
||||
deviceId,
|
||||
bluetoothConnected: '0',
|
||||
signalLevel: '0',
|
||||
})
|
||||
return buildBleDeviceName(mac)
|
||||
} catch {
|
||||
// 上报失败时保留本地状态
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function reportDeviceOffline() {
|
||||
function persistBleId(mac: string, id: string) {
|
||||
bleDeviceId.value = id
|
||||
rememberBleDeviceId(mac, id)
|
||||
}
|
||||
|
||||
async function reportBleDisconnected() {
|
||||
const deviceId = context.getDeviceId()
|
||||
if (!deviceId) return
|
||||
context.onBluetoothConnectedChange(false)
|
||||
@@ -74,6 +84,146 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
}
|
||||
}
|
||||
|
||||
function reportBleLinkLostLocal() {
|
||||
context.onBluetoothConnectedChange(false)
|
||||
}
|
||||
|
||||
function clearDisconnectTimer() {
|
||||
if (disconnectTimer) {
|
||||
clearTimeout(disconnectTimer)
|
||||
disconnectTimer = undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveBleTarget(mac: string): Promise<UniApp.BluetoothDeviceInfo | null> {
|
||||
const bleName = resolveBleBroadcastName(mac)
|
||||
const preferredBleId = bleDeviceId.value || recallBleDeviceId(mac)
|
||||
|
||||
const connected = await getConnectedBleDeviceByMac(mac, {
|
||||
name: bleName,
|
||||
preferredBleId,
|
||||
})
|
||||
if (connected) {
|
||||
persistBleId(mac, connected.deviceId)
|
||||
return connected
|
||||
}
|
||||
|
||||
if (preferredBleId) {
|
||||
try {
|
||||
linking = true
|
||||
await ensureBleConnection(preferredBleId, { settleMs: 200 })
|
||||
const after = await getConnectedBleDeviceByMac(mac, {
|
||||
name: bleName,
|
||||
preferredBleId,
|
||||
})
|
||||
if (after) {
|
||||
persistBleId(mac, after.deviceId)
|
||||
return after
|
||||
}
|
||||
if (await isBleDeviceConnected(preferredBleId)) {
|
||||
persistBleId(mac, preferredBleId)
|
||||
return {
|
||||
deviceId: preferredBleId,
|
||||
name: bleName,
|
||||
localName: bleName,
|
||||
} as UniApp.BluetoothDeviceInfo
|
||||
}
|
||||
} catch {
|
||||
if (bleDeviceId.value === preferredBleId) bleDeviceId.value = undefined
|
||||
} finally {
|
||||
linking = false
|
||||
}
|
||||
}
|
||||
|
||||
const foundQuick = await scanForBleDeviceByMac(mac, {
|
||||
timeoutMs: QUICK_SCAN_MS,
|
||||
name: bleName,
|
||||
skipCached: false,
|
||||
})
|
||||
if (foundQuick) {
|
||||
persistBleId(mac, foundQuick.deviceId)
|
||||
return foundQuick
|
||||
}
|
||||
|
||||
const foundRetry = await scanForBleDeviceByMac(mac, {
|
||||
timeoutMs: RETRY_SCAN_MS,
|
||||
name: bleName,
|
||||
skipCached: true,
|
||||
})
|
||||
if (foundRetry) persistBleId(mac, foundRetry.deviceId)
|
||||
return foundRetry
|
||||
}
|
||||
|
||||
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)
|
||||
// 先更新本地 UI(含滤芯),再上报云端
|
||||
context.onBleRuntimeRead?.(blePayload)
|
||||
|
||||
const runtimePatch = context.getRuntimePatch()
|
||||
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
|
||||
const {
|
||||
airQuality: _airQuality,
|
||||
...bleRuntimeBody
|
||||
} = blePayload
|
||||
|
||||
try {
|
||||
await updateDeviceRuntime({
|
||||
deviceId,
|
||||
...runtimePatch,
|
||||
...bleRuntimeBody,
|
||||
status: '1',
|
||||
bluetoothConnected: '1',
|
||||
signalLevel,
|
||||
})
|
||||
setSyncText('刚刚更新 · 数据实时同步中')
|
||||
await context.onSynced?.()
|
||||
} catch (apiErr) {
|
||||
setSyncText(`蓝牙已连接 · 云端同步失败:${getErrorMessage(apiErr, '请检查网络')}`)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** 已连上时只拉数据,绝不重新 createBLEConnection */
|
||||
async function syncIfAlreadyConnected(mac: string): Promise<boolean | null> {
|
||||
const bleName = resolveBleBroadcastName(mac)
|
||||
const preferredBleId = bleDeviceId.value || recallBleDeviceId(mac)
|
||||
const connected = await getConnectedBleDeviceByMac(mac, {
|
||||
name: bleName,
|
||||
preferredBleId,
|
||||
})
|
||||
if (!connected) {
|
||||
if (preferredBleId && await isBleDeviceConnected(preferredBleId)) {
|
||||
persistBleId(mac, preferredBleId)
|
||||
try {
|
||||
return await syncBleData(preferredBleId, null)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
persistBleId(mac, connected.deviceId)
|
||||
try {
|
||||
return await syncBleData(connected.deviceId, connected)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function connectAndSync(): Promise<boolean> {
|
||||
const deviceId = context.getDeviceId()
|
||||
const mac = context.getMac()
|
||||
@@ -91,86 +241,111 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
|
||||
if (syncing.value) return false
|
||||
syncing.value = true
|
||||
connecting.value = !hadSuccessfulSync
|
||||
|
||||
let connected = false
|
||||
let targetBleId = bleDeviceId.value
|
||||
let targetBleId = bleDeviceId.value || recallBleDeviceId(mac)
|
||||
|
||||
try {
|
||||
setSyncText('正在连接蓝牙…')
|
||||
if (connecting.value) {
|
||||
setSyncText('正在搜索并连接设备…')
|
||||
}
|
||||
await ensureBluetoothReady()
|
||||
|
||||
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
|
||||
// 周期同步 / 回前台:链路还在就只读数据,避免反复建连闪断
|
||||
const quiet = await syncIfAlreadyConnected(mac)
|
||||
if (quiet != null) return quiet
|
||||
|
||||
if (!targetBleId) {
|
||||
const deviceName = context.getDeviceName?.()
|
||||
foundDevice = await scanForBleDeviceByMac(mac ?? '', {
|
||||
timeoutMs: SCAN_TIMEOUT_MS,
|
||||
name: deviceName,
|
||||
})
|
||||
const foundDevice = await resolveBleTarget(mac)
|
||||
if (!foundDevice) {
|
||||
setSyncText('未找到设备,请确认已开机并靠近手机')
|
||||
await reportDeviceOffline()
|
||||
if (!tearingDown) {
|
||||
if (hadSuccessfulSync) {
|
||||
hadSuccessfulSync = false
|
||||
void reportBleDisconnected()
|
||||
} else {
|
||||
reportBleLinkLostLocal()
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
targetBleId = foundDevice.deviceId
|
||||
bleDeviceId.value = targetBleId
|
||||
} else {
|
||||
const discovered = await getDiscoveredBluetoothDevices()
|
||||
foundDevice = discovered.find((item) => item.deviceId === targetBleId) ?? null
|
||||
persistBleId(mac, targetBleId)
|
||||
|
||||
const alreadyLinked = await isBleDeviceConnected(targetBleId)
|
||||
if (!alreadyLinked) {
|
||||
if (!hadSuccessfulSync) {
|
||||
connecting.value = true
|
||||
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
|
||||
|
||||
linking = true
|
||||
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, '请检查网络')}`,
|
||||
)
|
||||
await ensureBleConnection(targetBleId)
|
||||
} finally {
|
||||
linking = false
|
||||
}
|
||||
}
|
||||
return true
|
||||
|
||||
return await syncBleData(targetBleId, foundDevice)
|
||||
} catch (err) {
|
||||
const bleName = resolveBleBroadcastName(mac)
|
||||
const stillConnected = await getConnectedBleDeviceByMac(mac, {
|
||||
name: bleName,
|
||||
preferredBleId: targetBleId,
|
||||
})
|
||||
if (stillConnected) {
|
||||
persistBleId(mac, stillConnected.deviceId)
|
||||
context.onBluetoothConnectedChange(true)
|
||||
try {
|
||||
return await syncBleData(stillConnected.deviceId, stillConnected)
|
||||
} catch (retryErr) {
|
||||
setSyncText(getBluetoothErrorMessage(retryErr))
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
setSyncText(getBluetoothErrorMessage(err))
|
||||
if (!connected) {
|
||||
bleDeviceId.value = undefined
|
||||
if (!tearingDown) {
|
||||
clearZ2BleHandleCache(targetBleId)
|
||||
await reportDeviceOffline()
|
||||
if (hadSuccessfulSync) {
|
||||
hadSuccessfulSync = false
|
||||
void reportBleDisconnected()
|
||||
} else {
|
||||
reportBleLinkLostLocal()
|
||||
}
|
||||
}
|
||||
return false
|
||||
} finally {
|
||||
syncing.value = false
|
||||
connecting.value = active && !hadSuccessfulSync && !tearingDown
|
||||
}
|
||||
}
|
||||
|
||||
async function handleConfirmedDisconnect(disconnectedId: string) {
|
||||
if (tearingDown || !active) return
|
||||
const mac = context.getMac()
|
||||
if (mac) {
|
||||
const stillConnected = await getConnectedBleDeviceByMac(mac, {
|
||||
name: resolveBleBroadcastName(mac),
|
||||
preferredBleId: bleDeviceId.value || disconnectedId,
|
||||
})
|
||||
if (stillConnected) {
|
||||
persistBleId(mac, stillConnected.deviceId)
|
||||
return
|
||||
}
|
||||
if (await isBleDeviceConnected(disconnectedId)) return
|
||||
}
|
||||
|
||||
hadSuccessfulSync = false
|
||||
reportBleLinkLostLocal()
|
||||
connecting.value = true
|
||||
setSyncText('蓝牙已断开,正在尝试重连…')
|
||||
if (bleDeviceId.value === disconnectedId) bleDeviceId.value = undefined
|
||||
clearZ2BleHandleCache(disconnectedId)
|
||||
void reportBleDisconnected()
|
||||
if (!syncing.value) void connectAndSync()
|
||||
}
|
||||
|
||||
async function sendBleCommand(command: string): Promise<boolean> {
|
||||
if (!bleDeviceId.value) {
|
||||
const ok = await connectAndSync()
|
||||
@@ -183,39 +358,73 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
context.onBleRuntimeRead?.(runtimePatch)
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
const ok = await connectAndSync()
|
||||
if (!ok || !bleDeviceId.value) return false
|
||||
try {
|
||||
const state = await sendZ2BleCommand(bleDeviceId.value, command)
|
||||
const runtimePatch = mapZ2StateToRuntimePatch(state)
|
||||
if (Object.keys(runtimePatch).length) {
|
||||
context.onBleRuntimeRead?.(runtimePatch)
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function startSyncLoop() {
|
||||
if (active) return
|
||||
|
||||
if (!isBluetoothApiSupported()) {
|
||||
connecting.value = false
|
||||
setSyncText('云端数据已加载 · 实时同步请使用 App 或微信小程序')
|
||||
return
|
||||
}
|
||||
|
||||
active = true
|
||||
connecting.value = true
|
||||
setSyncText('正在搜索并连接设备…')
|
||||
|
||||
const mac = context.getMac()
|
||||
if (mac) {
|
||||
const cached = recallBleDeviceId(mac)
|
||||
if (cached) bleDeviceId.value = cached
|
||||
}
|
||||
|
||||
unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
|
||||
if (tearingDown || !active) return
|
||||
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
|
||||
if (!res.connected) {
|
||||
bleDeviceId.value = undefined
|
||||
void reportBleDisconnected()
|
||||
setSyncText('蓝牙已断开,正在尝试重连…')
|
||||
if (res.connected) {
|
||||
clearDisconnectTimer()
|
||||
return
|
||||
}
|
||||
// 主动建连 / 同步中的瞬时断连忽略,等结束后再判定
|
||||
if (linking || syncing.value) return
|
||||
|
||||
clearDisconnectTimer()
|
||||
disconnectTimer = setTimeout(() => {
|
||||
disconnectTimer = undefined
|
||||
void handleConfirmedDisconnect(res.deviceId)
|
||||
}, DISCONNECT_CONFIRM_MS)
|
||||
})
|
||||
|
||||
void connectAndSync()
|
||||
|
||||
syncTimer = setInterval(() => {
|
||||
if (syncing.value || tearingDown || linking) return
|
||||
void connectAndSync()
|
||||
}, SYNC_INTERVAL_MS)
|
||||
}
|
||||
|
||||
async function stopSync() {
|
||||
tearingDown = true
|
||||
active = false
|
||||
hadSuccessfulSync = false
|
||||
connecting.value = false
|
||||
linking = false
|
||||
clearDisconnectTimer()
|
||||
if (syncTimer) {
|
||||
clearInterval(syncTimer)
|
||||
syncTimer = undefined
|
||||
@@ -229,16 +438,27 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
if (currentBleId) {
|
||||
clearZ2BleHandleCache(currentBleId)
|
||||
await closeBleConnection(currentBleId).catch(() => {})
|
||||
await reportBleDisconnected()
|
||||
}
|
||||
tearingDown = false
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
try {
|
||||
uni.hideLoading()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
if (!active || tearingDown) return
|
||||
void connectAndSync()
|
||||
})
|
||||
|
||||
onUnload(() => {
|
||||
void stopSync()
|
||||
})
|
||||
|
||||
return {
|
||||
syncing,
|
||||
connecting,
|
||||
startSyncLoop,
|
||||
stopSync,
|
||||
connectAndSync,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { onLoad } from '@dcloudio/uni-app'
|
||||
import { usePageShowRefresh } from '@/hooks/use-page-show-refresh'
|
||||
import { computed, ref } from 'vue'
|
||||
import { fetchRoomList } from '@/api/location'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { parseDeviceId, parseId, sameId } from '@/utils/device-id'
|
||||
import { fetchProductOptions } from '@/pages/add-device/complete/complete.api'
|
||||
import { fetchDeviceList } from '../device.api'
|
||||
import { fetchAllDeviceList } from '../device.api'
|
||||
import { findPatchedDeviceLocation, findPatchedDeviceName } from '../device-list-patch'
|
||||
import { fetchDeviceRuntime, updateDeviceRuntime } from './device-detail.api'
|
||||
import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types'
|
||||
import {
|
||||
@@ -33,6 +35,8 @@ import {
|
||||
import type { BleRuntimePatch } from './device-bluetooth-read'
|
||||
import { useDeviceBluetoothSync } from './use-device-bluetooth-sync'
|
||||
|
||||
const DEVICE_CONTROL_WAIT_TOAST = '设备连接中,请稍候'
|
||||
|
||||
export function useDeviceDetail() {
|
||||
const deviceId = ref('')
|
||||
const deviceNo = ref('')
|
||||
@@ -45,9 +49,10 @@ 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 awaitingBleStart = ref(true)
|
||||
const isOnline = computed(() => bluetoothConnected.value)
|
||||
|
||||
const runMode = ref<RunMode>('0')
|
||||
const fanLevel = ref<FanLevel>('0')
|
||||
@@ -61,6 +66,8 @@ export function useDeviceDetail() {
|
||||
const filterReplaceDialogVisible = ref(false)
|
||||
const batteryLevel = ref<number | null>(null)
|
||||
let pendingBatteryReading: number | null = null
|
||||
/** 本页已从蓝牙读到滤芯后,避免云端旧值盖住实时衰减 */
|
||||
let filterLifeFromBle = false
|
||||
const syncText = ref('数据实时同步中')
|
||||
|
||||
const tvocDisplay = computed(() => formatTvocValue(tvoc.value ?? undefined))
|
||||
@@ -72,13 +79,6 @@ export function useDeviceDetail() {
|
||||
const batteryDisplay = computed(() =>
|
||||
batteryLevel.value != null ? `${batteryLevel.value}%` : '--',
|
||||
)
|
||||
const connectionText = computed(() =>
|
||||
formatConnectionText({
|
||||
status: deviceStatus.value,
|
||||
bluetoothConnected: bluetoothConnected.value ? '1' : '0',
|
||||
locationName: locationName.value,
|
||||
}),
|
||||
)
|
||||
const showFanLevelControl = computed(() => isAutoRunMode(runMode.value))
|
||||
const fanLevelOptions = computed(() =>
|
||||
showFanLevelControl.value ? AUTO_FAN_LEVEL_OPTIONS : [],
|
||||
@@ -132,6 +132,7 @@ export function useDeviceDetail() {
|
||||
if (patch.powerMode != null) powerMode.value = patch.powerMode
|
||||
if (patch.filterLife != null) {
|
||||
filterLife.value = patch.filterLife
|
||||
filterLifeFromBle = true
|
||||
updateFilterRemainText()
|
||||
}
|
||||
if (patch.deviceBattery != null) applyBatteryLevel(patch.deviceBattery, true)
|
||||
@@ -145,36 +146,66 @@ export function useDeviceDetail() {
|
||||
fanLevel.value = view.fanLevel
|
||||
if (view.tvoc != null) tvoc.value = view.tvoc
|
||||
powerMode.value = view.powerMode
|
||||
// 蓝牙已读到实时滤芯时,不以云端缓存覆盖(否则 15 分钟衰减看不到)
|
||||
if (!filterLifeFromBle) {
|
||||
filterLife.value = view.filterLife
|
||||
filterRemainText.value = view.filterRemainText
|
||||
} else {
|
||||
updateFilterRemainText()
|
||||
}
|
||||
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
|
||||
const patchedName = findPatchedDeviceName(deviceId.value)
|
||||
if (patchedName) deviceName.value = patchedName
|
||||
const patchedLocation = findPatchedDeviceLocation(deviceId.value)
|
||||
if (patchedLocation) {
|
||||
locationId.value = patchedLocation.locationId
|
||||
locationName.value = patchedLocation.locationName
|
||||
}
|
||||
try {
|
||||
const list = await fetchDeviceList()
|
||||
const list = await fetchAllDeviceList()
|
||||
const device = list?.find((item) => String(item.deviceId) === deviceId.value)
|
||||
if (!device) return
|
||||
if (device.deviceId != null) deviceId.value = String(device.deviceId)
|
||||
if (device.deviceNo) deviceNo.value = device.deviceNo
|
||||
if (device.mac) deviceMac.value = device.mac
|
||||
const parsedLocationId = parseId(device.locationId)
|
||||
if (parsedLocationId) locationId.value = parsedLocationId
|
||||
// 本地刚改名优先,避免 onShow 刷新用接口旧名称盖回去
|
||||
if (patchedName && device.name !== patchedName) {
|
||||
deviceName.value = patchedName
|
||||
} else if (device.name) {
|
||||
deviceName.value = device.name
|
||||
}
|
||||
const parsedHomeId = parseId(device.homeId)
|
||||
if (parsedHomeId) homeId.value = parsedHomeId
|
||||
if (patchedLocation) {
|
||||
// 本地刚切换的房间优先,避免接口短暂延迟把展示盖回旧房间
|
||||
} else {
|
||||
const parsedLocationId = parseId(device.locationId)
|
||||
if (parsedLocationId) locationId.value = parsedLocationId
|
||||
if (parsedHomeId && parsedLocationId) {
|
||||
const locations = await fetchRoomList(parsedHomeId)
|
||||
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'
|
||||
// 详情页连接态以本地 BLE 为准:云端不能把状态打成「已连接」,
|
||||
// 否则会提前关掉重连加载遮罩(列表/接口常有脏在线态)
|
||||
if (!bleConnectedLocally) {
|
||||
const apiConnected = isBluetoothConnected(device.bluetoothConnected)
|
||||
if (!apiConnected) {
|
||||
bluetoothConnected.value = false
|
||||
deviceStatus.value = device.status === '0' ? '0' : '2'
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 列表刷新失败时保留路由参数状态
|
||||
}
|
||||
@@ -197,38 +228,60 @@ export function useDeviceDetail() {
|
||||
}
|
||||
}
|
||||
|
||||
function promptWaitForDeviceOnline(): boolean {
|
||||
if (bluetoothConnected.value) return true
|
||||
uni.showToast({ title: DEVICE_CONTROL_WAIT_TOAST, icon: 'none' })
|
||||
return false
|
||||
}
|
||||
|
||||
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
|
||||
if (!promptWaitForDeviceOnline()) 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) {
|
||||
uni.showToast({ title: getErrorMessage(err, '设置失败'), icon: 'none' })
|
||||
} finally {
|
||||
updating.value = false
|
||||
runMode.value = snapshot.runMode
|
||||
fanLevel.value = snapshot.fanLevel
|
||||
const fallback = bluetoothConnected.value ? '设置失败' : DEVICE_CONTROL_WAIT_TOAST
|
||||
const message = bluetoothConnected.value
|
||||
? getErrorMessage(err, fallback)
|
||||
: DEVICE_CONTROL_WAIT_TOAST
|
||||
uni.showToast({ title: message, icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
function onSelectRunMode(mode: RunMode) {
|
||||
if (showReconnectLoading.value) return
|
||||
if (runMode.value === mode) return
|
||||
void patchRuntime({ runMode: mode })
|
||||
}
|
||||
|
||||
function onSelectFanLevel(level: FanLevel) {
|
||||
if (showReconnectLoading.value) return
|
||||
if (!isAutoRunMode(runMode.value)) return
|
||||
if (fanLevel.value === level) return
|
||||
void patchRuntime({ fanLevel: level })
|
||||
@@ -253,19 +306,33 @@ export function useDeviceDetail() {
|
||||
}
|
||||
|
||||
function onFilterReplace() {
|
||||
if (showReconnectLoading.value) return
|
||||
if (filterReplaced.value) return
|
||||
filterReplaceDialogVisible.value = true
|
||||
}
|
||||
|
||||
async function onConfirmFilterReplace() {
|
||||
await sendBleCommand(Z2_BLE_CMD.FILTER_RESET)
|
||||
if (!promptWaitForDeviceOnline()) return
|
||||
const ok = await sendBleCommand(Z2_BLE_CMD.FILTER_RESET)
|
||||
if (!ok) {
|
||||
uni.showToast({
|
||||
title: bluetoothConnected.value ? '操作失败,请重试' : DEVICE_CONTROL_WAIT_TOAST,
|
||||
icon: 'none',
|
||||
})
|
||||
return
|
||||
}
|
||||
filterReplaced.value = true
|
||||
filterLife.value = 100
|
||||
filterLifeFromBle = true
|
||||
updateFilterRemainText()
|
||||
uni.showToast({ title: '操作成功', icon: 'success' })
|
||||
}
|
||||
|
||||
const { startSyncLoop, sendBleCommand } = useDeviceBluetoothSync({
|
||||
const {
|
||||
connecting: bleConnecting,
|
||||
startSyncLoop,
|
||||
sendBleCommand,
|
||||
} = useDeviceBluetoothSync({
|
||||
getDeviceId: () => deviceId.value,
|
||||
getMac: () => deviceMac.value,
|
||||
getDeviceName: () => deviceName.value,
|
||||
@@ -278,10 +345,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
|
||||
@@ -294,6 +358,33 @@ export function useDeviceDetail() {
|
||||
},
|
||||
})
|
||||
|
||||
/** 仅离线进入或断线重连时展示;在线进入 / 改名返回不闪遮罩 */
|
||||
const showReconnectLoading = computed(
|
||||
() => !bluetoothConnected.value && (awaitingBleStart.value || bleConnecting.value),
|
||||
)
|
||||
|
||||
const reconnectLoadingTitle = computed(() => {
|
||||
if (/重连/.test(syncText.value)) return '设备重连中'
|
||||
return '设备连接中'
|
||||
})
|
||||
|
||||
const reconnectLoadingDesc = computed(() => {
|
||||
const text = syncText.value.trim()
|
||||
if (text && /连接|搜索|同步|重连/.test(text)) return text
|
||||
return '正在重新连接蓝牙,请靠近设备并稍候'
|
||||
})
|
||||
|
||||
const connectionText = computed(() => {
|
||||
if (showReconnectLoading.value) {
|
||||
return reconnectLoadingTitle.value
|
||||
}
|
||||
return formatConnectionText({
|
||||
status: deviceStatus.value,
|
||||
bluetoothConnected: bluetoothConnected.value ? '1' : '0',
|
||||
locationName: locationName.value,
|
||||
})
|
||||
})
|
||||
|
||||
onLoad((query?: DeviceDetailRouteQuery) => {
|
||||
deviceId.value = parseDeviceId(query?.deviceId)
|
||||
if (query?.deviceNo) {
|
||||
@@ -309,22 +400,31 @@ 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)
|
||||
// 以列表带入的在线态为准:在线进入不闪重连遮罩;离线进入才展示连接中
|
||||
const enteredOnline = isBluetoothConnected(query?.bluetoothConnected)
|
||||
|| query?.status === '1'
|
||||
bluetoothConnected.value = enteredOnline
|
||||
deviceStatus.value = enteredOnline ? '1' : (query?.status === '0' ? '0' : '2')
|
||||
awaitingBleStart.value = !enteredOnline
|
||||
charging.value = query?.charging === '1'
|
||||
void loadRuntime().then(() => {
|
||||
void loadRuntime()
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
startSyncLoop()
|
||||
awaitingBleStart.value = false
|
||||
})
|
||||
})
|
||||
|
||||
usePageShowRefresh(() => refreshDeviceMeta(), { skipInitialShow: true })
|
||||
|
||||
return {
|
||||
deviceName,
|
||||
connectionText,
|
||||
isOnline,
|
||||
showReconnectLoading,
|
||||
reconnectLoadingTitle,
|
||||
reconnectLoadingDesc,
|
||||
tvocDisplay,
|
||||
tvocLevel,
|
||||
syncText,
|
||||
|
||||
157
src/pages/device/device-list-patch.ts
Normal file
157
src/pages/device/device-list-patch.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
import { sameId } from '@/utils/device-id'
|
||||
import type { DeviceListItem } from './device.types'
|
||||
|
||||
/** 设置页改名 / 换房等本地补丁:接口尚未返回新值时也能立刻展示 */
|
||||
const namePatches = new Map<string, string>()
|
||||
const locationPatches = new Map<string, { locationId: string; locationName: string }>()
|
||||
|
||||
export function rememberDeviceNamePatch(deviceId: string | number, name: string) {
|
||||
const id = String(deviceId).trim()
|
||||
const trimmed = name.trim()
|
||||
if (!id || !trimmed) return
|
||||
namePatches.set(id, trimmed)
|
||||
}
|
||||
|
||||
export function clearDeviceNamePatch(deviceId: string | number) {
|
||||
namePatches.delete(String(deviceId).trim())
|
||||
}
|
||||
|
||||
export function rememberDeviceLocationPatch(
|
||||
deviceId: string | number,
|
||||
locationId: string | number,
|
||||
locationName: string,
|
||||
) {
|
||||
const id = String(deviceId).trim()
|
||||
const nextId = String(locationId).trim()
|
||||
const nextName = locationName.trim()
|
||||
if (!id || !nextId || !nextName) return
|
||||
locationPatches.set(id, { locationId: nextId, locationName: nextName })
|
||||
}
|
||||
|
||||
export function clearDeviceLocationPatch(deviceId: string | number) {
|
||||
locationPatches.delete(String(deviceId).trim())
|
||||
}
|
||||
|
||||
export function findPatchedDeviceLocation(
|
||||
deviceId: string | number | undefined,
|
||||
): { locationId: string; locationName: string } | undefined {
|
||||
if (deviceId == null) return undefined
|
||||
return locationPatches.get(String(deviceId))
|
||||
}
|
||||
|
||||
const ROOM_SELECT_STORAGE_KEY = 'czzj_device_room_selected'
|
||||
|
||||
/** 房间页选择结果兜底(部分端 EventChannel 不可靠) */
|
||||
export function stashRoomSelection(payload: {
|
||||
deviceId?: string | number
|
||||
locationId: string | number
|
||||
name: string
|
||||
}) {
|
||||
try {
|
||||
uni.setStorageSync(ROOM_SELECT_STORAGE_KEY, {
|
||||
deviceId: payload.deviceId != null ? String(payload.deviceId) : '',
|
||||
locationId: String(payload.locationId),
|
||||
name: payload.name.trim(),
|
||||
at: Date.now(),
|
||||
})
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export function consumeRoomSelection(deviceId?: string | number): {
|
||||
locationId: string
|
||||
name: string
|
||||
} | null {
|
||||
try {
|
||||
const raw = uni.getStorageSync(ROOM_SELECT_STORAGE_KEY) as {
|
||||
deviceId?: string
|
||||
locationId?: string
|
||||
name?: string
|
||||
at?: number
|
||||
} | null
|
||||
uni.removeStorageSync(ROOM_SELECT_STORAGE_KEY)
|
||||
if (!raw?.locationId || !raw.name) return null
|
||||
if (raw.at && Date.now() - raw.at > 60_000) return null
|
||||
if (deviceId != null && raw.deviceId && String(deviceId) !== String(raw.deviceId)) {
|
||||
return null
|
||||
}
|
||||
return { locationId: String(raw.locationId), name: raw.name }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function applyDeviceListPatches(devices: DeviceListItem[]): DeviceListItem[] {
|
||||
if (!namePatches.size && !locationPatches.size) return devices
|
||||
return devices.map((device) => {
|
||||
if (device.deviceId == null) return device
|
||||
const key = String(device.deviceId)
|
||||
let next = device
|
||||
|
||||
const patchedName = namePatches.get(key)
|
||||
if (patchedName) {
|
||||
if (device.name === patchedName) {
|
||||
namePatches.delete(key)
|
||||
} else {
|
||||
next = { ...next, name: patchedName }
|
||||
}
|
||||
}
|
||||
|
||||
const patchedLocation = locationPatches.get(key)
|
||||
if (patchedLocation) {
|
||||
if (sameId(device.locationId, patchedLocation.locationId)) {
|
||||
locationPatches.delete(key)
|
||||
if (device.locationName !== patchedLocation.locationName) {
|
||||
next = { ...next, locationName: patchedLocation.locationName }
|
||||
}
|
||||
} else {
|
||||
next = {
|
||||
...next,
|
||||
locationId: patchedLocation.locationId,
|
||||
locationName: patchedLocation.locationName,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
/** 在线扫描结果只合并在线相关字段,避免用旧快照整表覆盖名称等元数据 */
|
||||
export function mergeDevicePresenceFields(
|
||||
current: DeviceListItem[],
|
||||
scanned: DeviceListItem[],
|
||||
): DeviceListItem[] {
|
||||
if (!scanned.length) return current
|
||||
const byId = new Map(
|
||||
scanned
|
||||
.filter((item) => item.deviceId != null)
|
||||
.map((item) => [String(item.deviceId), item]),
|
||||
)
|
||||
return current.map((device) => {
|
||||
if (device.deviceId == null) return device
|
||||
const next = byId.get(String(device.deviceId))
|
||||
if (!next) return device
|
||||
if (
|
||||
device.status === next.status
|
||||
&& device.bluetoothConnected === next.bluetoothConnected
|
||||
&& device.isOnline === next.isOnline
|
||||
) {
|
||||
return device
|
||||
}
|
||||
return {
|
||||
...device,
|
||||
status: next.status,
|
||||
bluetoothConnected: next.bluetoothConnected,
|
||||
isOnline: next.isOnline,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function findPatchedDeviceName(
|
||||
deviceId: string | number | undefined,
|
||||
): string | undefined {
|
||||
if (deviceId == null) return undefined
|
||||
return namePatches.get(String(deviceId))
|
||||
}
|
||||
18
src/pages/device/device-online.ts
Normal file
18
src/pages/device/device-online.ts
Normal 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)
|
||||
}
|
||||
67
src/pages/device/device-presence-state.ts
Normal file
67
src/pages/device/device-presence-state.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
const missCounts = new Map<string, number>()
|
||||
const lastSeenAt = new Map<string, number>()
|
||||
/** 已向云端上报离线的设备,避免轮询重复写库 */
|
||||
const cloudOfflineReported = new Set<string>()
|
||||
|
||||
/**
|
||||
* 扫描未命中次数达到该值后判定离线。
|
||||
* 关机后广播立刻消失,1 次完整扫描未命中即可标离线(不再做长宽限)。
|
||||
*/
|
||||
const OFFLINE_AFTER_MISSES = 1
|
||||
|
||||
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())
|
||||
cloudOfflineReported.delete(key)
|
||||
}
|
||||
|
||||
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 {
|
||||
const key = deviceKey(deviceId)
|
||||
const misses = missCounts.get(key) ?? 0
|
||||
return misses >= OFFLINE_AFTER_MISSES
|
||||
}
|
||||
|
||||
export function resetPresenceState(deviceId?: string | number) {
|
||||
if (deviceId == null) {
|
||||
missCounts.clear()
|
||||
lastSeenAt.clear()
|
||||
cloudOfflineReported.clear()
|
||||
return
|
||||
}
|
||||
const key = deviceKey(deviceId)
|
||||
missCounts.delete(key)
|
||||
lastSeenAt.delete(key)
|
||||
cloudOfflineReported.delete(key)
|
||||
}
|
||||
|
||||
export function shouldReportPresenceOfflineToCloud(deviceId: string | number): boolean {
|
||||
const key = deviceKey(deviceId)
|
||||
if (!key) return false
|
||||
return !cloudOfflineReported.has(key)
|
||||
}
|
||||
|
||||
export function markPresenceOfflineReportedToCloud(deviceId: string | number) {
|
||||
const key = deviceKey(deviceId)
|
||||
if (!key) return
|
||||
cloudOfflineReported.add(key)
|
||||
}
|
||||
|
||||
export function getLastPresenceSeenAt(deviceId: string | number): number {
|
||||
return lastSeenAt.get(deviceKey(deviceId)) ?? 0
|
||||
}
|
||||
@@ -1,14 +1,26 @@
|
||||
import { buildBleDeviceName } from '@/utils/ble-device-name'
|
||||
import {
|
||||
findDeviceInBleScan,
|
||||
getConnectedBleDeviceByMac,
|
||||
isBluetoothApiSupported,
|
||||
scanBluetoothDevices,
|
||||
} from '@/utils/bluetooth'
|
||||
import { sameId } from '@/utils/device-id'
|
||||
import {
|
||||
markPresenceOfflineReportedToCloud,
|
||||
recordPresenceHit,
|
||||
recordPresenceMiss,
|
||||
shouldMarkDeviceOffline,
|
||||
shouldReportPresenceOfflineToCloud,
|
||||
} from './device-presence-state'
|
||||
import { updateDeviceRuntime } from './detail/device-detail.api'
|
||||
import type { DeviceListItem } from './device.types'
|
||||
|
||||
let syncing = false
|
||||
|
||||
/** 关机后广播马上消失,缩短扫描窗口以便更快判定离线 */
|
||||
const PRESENCE_SCAN_MS = 4500
|
||||
|
||||
const PRESENCE_DEBUG = import.meta.env.DEV
|
||||
|| import.meta.env.VITE_BLE_DEBUG === 'true'
|
||||
|
||||
@@ -21,29 +33,108 @@ function logPresence(message: string, payload?: unknown) {
|
||||
console.log(`[Device Presence] ${message}`)
|
||||
}
|
||||
|
||||
function applyPresence(
|
||||
device: DeviceListItem,
|
||||
present: boolean,
|
||||
): DeviceListItem {
|
||||
const nextStatus = present ? '1' : '2'
|
||||
const nextBluetooth = present ? '1' : '0'
|
||||
return {
|
||||
...device,
|
||||
status: nextStatus,
|
||||
bluetoothConnected: nextBluetooth,
|
||||
isOnline: present,
|
||||
function wasDeviceOnlineInCloud(device: DeviceListItem): boolean {
|
||||
return device.status === '1' && device.bluetoothConnected === '1'
|
||||
}
|
||||
|
||||
function resolveBleName(mac?: string): string | undefined {
|
||||
if (!mac) return undefined
|
||||
try {
|
||||
return buildBleDeviceName(mac)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** 通过 BLE 扫描刷新设备在线状态(status: 1在线 / 2离线) */
|
||||
function findDeviceInPresenceScan(
|
||||
device: DeviceListItem,
|
||||
scanned: UniApp.BluetoothDeviceInfo[],
|
||||
): UniApp.BluetoothDeviceInfo | null {
|
||||
if (!device.mac) return null
|
||||
return findDeviceInBleScan(
|
||||
{ mac: device.mac, name: resolveBleName(device.mac) },
|
||||
scanned,
|
||||
{ strictName: true },
|
||||
)
|
||||
}
|
||||
|
||||
function applyPresence(
|
||||
device: DeviceListItem,
|
||||
blePresent: boolean,
|
||||
): DeviceListItem {
|
||||
if (!device.deviceId) return device
|
||||
|
||||
if (blePresent) {
|
||||
recordPresenceHit(device.deviceId)
|
||||
return {
|
||||
...device,
|
||||
status: '1',
|
||||
bluetoothConnected: '1',
|
||||
isOnline: true,
|
||||
}
|
||||
}
|
||||
|
||||
recordPresenceMiss(device.deviceId)
|
||||
if (!shouldMarkDeviceOffline(device.deviceId, device.isOnline)) {
|
||||
return device
|
||||
}
|
||||
|
||||
return {
|
||||
...device,
|
||||
status: '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('online updateRuntime failed', err)
|
||||
}
|
||||
}
|
||||
|
||||
async function reportPresenceOfflineToCloud(device: DeviceListItem) {
|
||||
if (!device.deviceId) return
|
||||
if (!shouldReportPresenceOfflineToCloud(device.deviceId)) return
|
||||
try {
|
||||
await updateDeviceRuntime({
|
||||
deviceId: device.deviceId,
|
||||
status: '2',
|
||||
bluetoothConnected: '0',
|
||||
signalLevel: '0',
|
||||
})
|
||||
markPresenceOfflineReportedToCloud(device.deviceId)
|
||||
logPresence('reported offline to cloud', { deviceId: device.deviceId })
|
||||
} catch (err) {
|
||||
logPresence('offline updateRuntime failed', err)
|
||||
}
|
||||
}
|
||||
|
||||
function shouldSyncOfflineToCloud(before: DeviceListItem, after: DeviceListItem): boolean {
|
||||
if (!after.deviceId) return false
|
||||
if (after.status !== '2' || after.bluetoothConnected !== '0') return false
|
||||
if (!after.isOnline && before.isOnline) return true
|
||||
if (wasDeviceOnlineInCloud(before) && !wasDeviceOnlineInCloud(after)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/** 通过 BLE 扫描刷新设备在线状态;扫描未命中即刻离线 */
|
||||
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,57 +142,59 @@ export async function refreshDevicePresence(
|
||||
syncing = true
|
||||
|
||||
try {
|
||||
const scanned = await scanBluetoothDevices({ timeoutMs: 5000 })
|
||||
// 先看 GATT 是否仍连接:已断开的在线设备可立刻标离线,不必等完整扫描
|
||||
const connectedFlags = await Promise.all(
|
||||
targets.map(async (device) => {
|
||||
if (!device.mac || !device.isOnline) return false
|
||||
const connected = await getConnectedBleDeviceByMac(device.mac, {
|
||||
name: resolveBleName(device.mac),
|
||||
})
|
||||
return !!connected
|
||||
}),
|
||||
)
|
||||
|
||||
const scanned = await scanBluetoothDevices({ timeoutMs: PRESENCE_SCAN_MS })
|
||||
logPresence('scan result', {
|
||||
count: scanned.length,
|
||||
names: scanned.map((item) => item.name || item.localName || item.deviceId),
|
||||
})
|
||||
|
||||
const offlineReports: DeviceListItem[] = []
|
||||
|
||||
const nextDevices = devices.map((device) => {
|
||||
if (!device.deviceId) return device
|
||||
const isTarget = targets.some((item) => sameId(item.deviceId, device.deviceId))
|
||||
if (!isTarget) return device
|
||||
const targetIndex = targets.findIndex((item) => sameId(item.deviceId, device.deviceId))
|
||||
if (targetIndex < 0) return device
|
||||
|
||||
const found = findDeviceInBleScan(
|
||||
{ mac: device.mac, name: device.name },
|
||||
scanned,
|
||||
{ strictName: true },
|
||||
)
|
||||
const present = !!found
|
||||
const found = findDeviceInPresenceScan(device, scanned)
|
||||
const gattConnected = connectedFlags[targetIndex]
|
||||
const present = !!found || gattConnected
|
||||
logPresence('device presence', {
|
||||
name: device.name,
|
||||
mac: device.mac,
|
||||
present,
|
||||
foundId: found?.deviceId,
|
||||
found: !!found,
|
||||
gattConnected,
|
||||
bleName: resolveBleName(device.mac),
|
||||
})
|
||||
return applyPresence(device, present)
|
||||
const next = applyPresence(device, present)
|
||||
if (shouldSyncOfflineToCloud(device, next)) {
|
||||
offlineReports.push(next)
|
||||
}
|
||||
return next
|
||||
})
|
||||
|
||||
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 = findDeviceInPresenceScan(device, scanned)
|
||||
if (found) {
|
||||
await reportPresenceOnlineToCloud(device)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
void Promise.allSettled(offlineReports.map((device) => reportPresenceOfflineToCloud(device)))
|
||||
|
||||
return nextDevices
|
||||
} catch (err) {
|
||||
logPresence('scan failed', err)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { request } from '@/api/request'
|
||||
import type { AppDeviceVo, DeviceQueryBody } from './device.types'
|
||||
|
||||
/** POST /app/device/list — 查询当前用户的设备列表 */
|
||||
/** POST /app/device/list — 按家庭/房间查询设备(首页设备 Tab 等) */
|
||||
export function fetchDeviceList(query: DeviceQueryBody = {}) {
|
||||
return request<AppDeviceVo[]>({
|
||||
url: '/app/device/list',
|
||||
@@ -9,3 +9,12 @@ export function fetchDeviceList(query: DeviceQueryBody = {}) {
|
||||
data: query,
|
||||
})
|
||||
}
|
||||
|
||||
/** POST /app/device/listAll — 当前用户绑定的全部设备(选择设备、我的设备等跨家庭场景) */
|
||||
export function fetchAllDeviceList() {
|
||||
return request<AppDeviceVo[]>({
|
||||
url: '/app/device/listAll',
|
||||
method: 'GET',
|
||||
data: {},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,4 +3,23 @@
|
||||
background: $color-bg-page;
|
||||
padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
|
||||
box-sizing: border-box;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.device-page--scroll-lock {
|
||||
overflow: hidden;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.device-page__loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 360rpx;
|
||||
padding: 48rpx 32rpx;
|
||||
}
|
||||
|
||||
.device-page__loading-text {
|
||||
font-size: 28rpx;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
@@ -10,12 +10,14 @@ export interface HotDeviceItem {
|
||||
desc: string
|
||||
}
|
||||
|
||||
/** POST /app/device/list 查询参数 */
|
||||
/** POST /app/device/list 查询参数(按家庭/房间筛选) */
|
||||
export interface DeviceQueryBody {
|
||||
homeId?: string | number
|
||||
locationId?: string | number
|
||||
}
|
||||
|
||||
/** POST /app/device/listAll — 无筛选参数,返回当前用户全部绑定设备 */
|
||||
|
||||
/** 设备状态:0未激活 1在线 2离线 */
|
||||
export type DeviceStatus = '0' | '1' | '2'
|
||||
|
||||
@@ -26,6 +28,12 @@ export interface AppDeviceVo {
|
||||
name?: string
|
||||
imei?: string
|
||||
mac?: string
|
||||
sn?: string
|
||||
/** 产品主键(绑定时常写入;列表若返回则可据此解析型号) */
|
||||
productId?: string | number
|
||||
/** 产品型号,如 CZ-Z2023(OpenAPI 可能未声明,后端可能仍返回) */
|
||||
model?: string
|
||||
productName?: string
|
||||
homeId?: string | number
|
||||
locationId?: string | number
|
||||
status?: DeviceStatus | string
|
||||
|
||||
@@ -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',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="home-manage-page">
|
||||
<app-navbar title="家庭管理" />
|
||||
|
||||
<scroll-view class="home-manage-page__scroll" scroll-y>
|
||||
<page-scroll-view class="home-manage-page__scroll">
|
||||
<view class="home-manage-page__body">
|
||||
<text class="home-manage-page__summary">{{ summaryText }}</text>
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</page-scroll-view>
|
||||
|
||||
<home-name-dialog
|
||||
v-model:visible="nameDialogVisible"
|
||||
|
||||
@@ -5,9 +5,33 @@
|
||||
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 {
|
||||
flex: 1;
|
||||
height: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.home-manage-page__body {
|
||||
@@ -73,11 +97,18 @@
|
||||
margin-left: 32rpx;
|
||||
}
|
||||
|
||||
.home-manage-page__loading,
|
||||
.home-manage-page__empty {
|
||||
padding: 120rpx 32rpx;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.home-manage-page__loading-text {
|
||||
font-size: 28rpx;
|
||||
color: #999;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.home-manage-page__empty-text {
|
||||
font-size: 28rpx;
|
||||
color: #999;
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
<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>
|
||||
|
||||
<scroll-view class="home-manage-page__scroll" scroll-y>
|
||||
<page-scroll-view class="home-manage-page__scroll">
|
||||
<view class="home-manage-page__body">
|
||||
<view v-if="homes.length" class="home-manage-page__list">
|
||||
<view
|
||||
@@ -20,19 +30,41 @@
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view v-else-if="!loading" class="home-manage-page__empty">
|
||||
<view v-else-if="loading" class="home-manage-page__loading">
|
||||
<text class="home-manage-page__loading-text">加载中...</text>
|
||||
</view>
|
||||
<view v-else class="home-manage-page__empty">
|
||||
<text class="home-manage-page__empty-text">暂无家庭</text>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,51 +1,114 @@
|
||||
import { onLoad } from '@dcloudio/uni-app'
|
||||
import { onLoad, onUnload } from '@dcloudio/uni-app'
|
||||
import type { Ref } from 'vue'
|
||||
import { ref } from 'vue'
|
||||
import {
|
||||
buildUpdateHomeBody,
|
||||
isValidHomeName,
|
||||
updateHome,
|
||||
} 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)
|
||||
const latitude = ref(DEFAULT_LATITUDE)
|
||||
const longitude = ref(DEFAULT_LONGITUDE)
|
||||
const searchKeyword = ref('')
|
||||
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
|
||||
@@ -57,6 +120,7 @@ export function useHomeLocation() {
|
||||
latitude.value = saved.latitude
|
||||
longitude.value = saved.longitude
|
||||
addressText.value = saved.address
|
||||
syncMapView(saved.longitude, saved.latitude)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -65,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
|
||||
}
|
||||
@@ -86,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() {
|
||||
@@ -123,24 +179,31 @@ 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
|
||||
}
|
||||
}
|
||||
|
||||
function onConfirm() {
|
||||
async function onConfirm() {
|
||||
if (!homeId.value) {
|
||||
uni.navigateBack()
|
||||
return
|
||||
}
|
||||
if (!isValidHomeName(homeName.value)) {
|
||||
uni.showToast({ title: '家庭名称需 2-10 个字符', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (saving.value) return
|
||||
|
||||
const address = addressText.value.trim()
|
||||
|| formatCoordinateAddress(latitude.value, longitude.value)
|
||||
const geo: HomeGeoInfo = {
|
||||
@@ -148,15 +211,36 @@ export function useHomeLocation() {
|
||||
latitude: latitude.value,
|
||||
longitude: longitude.value,
|
||||
}
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
await updateHome(
|
||||
homeId.value,
|
||||
buildUpdateHomeBody(homeName.value, { geo }),
|
||||
)
|
||||
saveHomeGeo(homeId.value, geo)
|
||||
uni.showToast({ title: '保存成功', icon: 'success' })
|
||||
setTimeout(() => {
|
||||
uni.navigateBack()
|
||||
}, 300)
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '保存家庭位置失败'), icon: 'none' })
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onUnload(() => {
|
||||
disposed = true
|
||||
clearGeocodeTimer()
|
||||
pendingMapCenter = null
|
||||
})
|
||||
|
||||
onLoad((query?: Record<string, string | undefined>) => {
|
||||
homeId.value = parseId(query?.homeId)
|
||||
if (query?.homeName) {
|
||||
homeName.value = decodeURIComponent(String(query.homeName))
|
||||
}
|
||||
const saved = homeId.value ? loadHomeGeo(homeId.value) : undefined
|
||||
if (query?.address) {
|
||||
addressText.value = decodeURIComponent(String(query.address))
|
||||
@@ -173,9 +257,13 @@ export function useHomeLocation() {
|
||||
addressText,
|
||||
locating,
|
||||
resolvingAddress,
|
||||
onMapReady,
|
||||
onRegionChange,
|
||||
onMapCenterChange,
|
||||
onChooseLocation,
|
||||
searchVisible,
|
||||
searchCity,
|
||||
onOpenSearch,
|
||||
onCloseSearch,
|
||||
onSelectSearchPlace,
|
||||
onLocate,
|
||||
onConfirm,
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { onLoad, onShow } from '@dcloudio/uni-app'
|
||||
import { computed, ref } from 'vue'
|
||||
import { resolveValidHomeId } from '@/api/home'
|
||||
import {
|
||||
buildUpdateHomeBody,
|
||||
isValidHomeName,
|
||||
resolveValidHomeId,
|
||||
updateHome,
|
||||
} from '@/api/home'
|
||||
import type { AppHomeVo } from '@/types/location'
|
||||
import { fetchRoomList } from '@/api/location'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { fetchHomeManageStats } from './home-manage.api'
|
||||
@@ -31,6 +37,8 @@ export function useHomeManage() {
|
||||
const homeAddress = ref('')
|
||||
const loading = ref(false)
|
||||
const nameDialogVisible = ref(false)
|
||||
const currentHome = ref<AppHomeVo>()
|
||||
const savingName = ref(false)
|
||||
|
||||
const summaryText = computed(
|
||||
() => `共${roomCount.value}个房间,${deviceCount.value}个设备`,
|
||||
@@ -44,11 +52,22 @@ export function useHomeManage() {
|
||||
fetchHomeManageStats(homeId.value),
|
||||
fetchRoomList(homeId.value),
|
||||
])
|
||||
currentHome.value = stats.home
|
||||
if (stats.home?.homeName) homeName.value = stats.home.homeName
|
||||
roomCount.value = rooms.length || stats.roomCount
|
||||
deviceCount.value = stats.deviceCount
|
||||
const geo = loadHomeGeo(homeId.value)
|
||||
homeAddress.value = geo?.address ?? ''
|
||||
homeAddress.value =
|
||||
stats.home?.homeLocationAddress?.trim()
|
||||
|| geo?.address
|
||||
|| ''
|
||||
if (stats.home?.homeLocationAddress && stats.home.homeLocationLatitude != null) {
|
||||
saveHomeGeo(homeId.value, {
|
||||
address: stats.home.homeLocationAddress,
|
||||
latitude: stats.home.homeLocationLatitude,
|
||||
longitude: stats.home.homeLocationLongitude ?? 116.4074,
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '加载家庭信息失败'), icon: 'none' })
|
||||
} finally {
|
||||
@@ -68,14 +87,31 @@ export function useHomeManage() {
|
||||
nameDialogVisible.value = true
|
||||
}
|
||||
|
||||
function onConfirmHomeName(name: string) {
|
||||
async function onConfirmHomeName(name: string) {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) {
|
||||
uni.showToast({ title: '请输入家庭名称', icon: 'none' })
|
||||
if (!isValidHomeName(trimmed)) {
|
||||
uni.showToast({ title: '家庭名称需 2-10 个字符', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (!homeId.value || savingName.value) return
|
||||
|
||||
savingName.value = true
|
||||
try {
|
||||
const geo = loadHomeGeo(homeId.value)
|
||||
await updateHome(
|
||||
homeId.value,
|
||||
buildUpdateHomeBody(trimmed, { geo, home: currentHome.value }),
|
||||
)
|
||||
homeName.value = trimmed
|
||||
uni.showToast({ title: '家庭名称修改接口待对接', icon: 'none' })
|
||||
if (currentHome.value) {
|
||||
currentHome.value = { ...currentHome.value, homeName: trimmed }
|
||||
}
|
||||
uni.showToast({ title: '修改成功', icon: 'success' })
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '修改家庭名称失败'), icon: 'none' })
|
||||
} finally {
|
||||
savingName.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onOpenLocation() {
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
<template>
|
||||
<view class="device-page">
|
||||
<template>
|
||||
<view class="device-page" :class="{ 'device-page--scroll-lock': homePickerOpen }">
|
||||
<device-header
|
||||
:home-name="homeName"
|
||||
:home-id="homeId"
|
||||
:homes="homes"
|
||||
@select-home="onSelectHome"
|
||||
@manage="onHomeManage"
|
||||
@notify="onNotify"
|
||||
@add-device="onStartBind"
|
||||
@scan="onScan"
|
||||
@picker-open-change="homePickerOpen = $event"
|
||||
/>
|
||||
<room-tabs
|
||||
:rooms="rooms"
|
||||
@@ -18,10 +22,12 @@
|
||||
v-if="hasDevices"
|
||||
:devices="devices"
|
||||
:online-count="onlineCount"
|
||||
@manage="onManageDevices"
|
||||
@select="onSelectDevice"
|
||||
/>
|
||||
<template v-else-if="!loading">
|
||||
<view v-else-if="loading" class="device-page__loading">
|
||||
<text class="device-page__loading-text">加载中...</text>
|
||||
</view>
|
||||
<template v-else>
|
||||
<device-empty :step-hint="bindStepHint" @bind="onStartBind" />
|
||||
<hot-devices :items="hotDevices" @mall="onGoMall" />
|
||||
</template>
|
||||
@@ -37,6 +43,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useTabPage } from '@/hooks/use-tab-page'
|
||||
import DeviceEmpty from './components/device-empty/index.vue'
|
||||
import DeviceHeader from './components/device-header/index.vue'
|
||||
@@ -48,9 +55,12 @@ import RoomTabs from './components/room-tabs/index.vue'
|
||||
import { useDevice } from './use-device'
|
||||
|
||||
const { tabCurrent } = useTabPage('device')
|
||||
const homePickerOpen = ref(false)
|
||||
|
||||
const {
|
||||
homeName,
|
||||
homeId,
|
||||
homes,
|
||||
rooms,
|
||||
activeRoomId,
|
||||
devices,
|
||||
@@ -69,7 +79,7 @@ const {
|
||||
onGoMall,
|
||||
onNotify,
|
||||
onHomeManage,
|
||||
onManageDevices,
|
||||
onSelectHome,
|
||||
onSelectDevice,
|
||||
} = useDevice()
|
||||
</script>
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
.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;
|
||||
height: 0;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.device-settings-page__body {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="device-settings-page">
|
||||
<view class="device-settings-page__top">
|
||||
<app-navbar title="设备设置" />
|
||||
</view>
|
||||
|
||||
<scroll-view class="device-settings-page__scroll" scroll-y>
|
||||
<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">
|
||||
@@ -74,7 +76,7 @@
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</page-scroll-view>
|
||||
|
||||
<device-name-dialog
|
||||
v-model:visible="nameDialogVisible"
|
||||
@@ -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'
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -5,12 +5,14 @@ import { createLocation, fetchRoomList } from '@/api/location'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { parseId, sameId } from '@/utils/device-id'
|
||||
import type { RoomOption } from '@/types/location'
|
||||
import { stashRoomSelection } from '../../device-list-patch'
|
||||
import type { DeviceRoomRouteQuery } from './room.types'
|
||||
|
||||
let openerEventChannel: UniApp.EventChannel | undefined
|
||||
|
||||
export function useDeviceRoom() {
|
||||
const homeId = ref('')
|
||||
const deviceId = ref('')
|
||||
const selectedLocationId = ref('')
|
||||
const pendingLocationName = ref<string>()
|
||||
const roomOptions = ref<RoomOption[]>([])
|
||||
@@ -20,6 +22,7 @@ export function useDeviceRoom() {
|
||||
const initialized = ref(false)
|
||||
|
||||
function applyQuery(query?: DeviceRoomRouteQuery) {
|
||||
if (query?.deviceId) deviceId.value = String(query.deviceId)
|
||||
const locationId = parseId(query?.locationId)
|
||||
if (locationId) {
|
||||
selectedLocationId.value = locationId
|
||||
@@ -124,10 +127,16 @@ export function useDeviceRoom() {
|
||||
|
||||
selectedLocationId.value = String(room.locationId)
|
||||
pendingLocationName.value = room.name
|
||||
openerEventChannel?.emit('roomSelected', {
|
||||
const payload = {
|
||||
locationId: room.locationId,
|
||||
name: room.name,
|
||||
}
|
||||
stashRoomSelection({
|
||||
deviceId: deviceId.value,
|
||||
locationId: payload.locationId,
|
||||
name: payload.name,
|
||||
})
|
||||
openerEventChannel?.emit('roomSelected', payload)
|
||||
uni.navigateBack()
|
||||
}
|
||||
|
||||
|
||||
@@ -2,15 +2,22 @@ import { onLoad } from '@dcloudio/uni-app'
|
||||
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import { usePageShowRefresh } from '@/hooks/use-page-show-refresh'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
|
||||
import { resolveValidHomeId } from '@/api/home'
|
||||
import { isValidDeviceId, parseDeviceId, parseId } from '@/utils/device-id'
|
||||
|
||||
import { fetchDeviceList } from '../device.api'
|
||||
import { fetchRoomList } from '@/api/location'
|
||||
import { isValidDeviceId, parseDeviceId, parseId, sameId } from '@/utils/device-id'
|
||||
|
||||
import { fetchAllDeviceList } from '../device.api'
|
||||
import {
|
||||
consumeRoomSelection,
|
||||
findPatchedDeviceLocation,
|
||||
findPatchedDeviceName,
|
||||
rememberDeviceLocationPatch,
|
||||
rememberDeviceNamePatch,
|
||||
} from '../device-list-patch'
|
||||
import { isBluetoothConnected } from '../detail/device-detail.utils'
|
||||
|
||||
import { unbindDevice, updateDeviceSettings } from './device-settings.api'
|
||||
|
||||
import type { DeviceSettingsRouteQuery } from './device-settings.types'
|
||||
@@ -87,7 +94,7 @@ export function useDeviceSettings() {
|
||||
|
||||
async function syncDeviceFromList() {
|
||||
|
||||
const list = await fetchDeviceList()
|
||||
const list = await fetchAllDeviceList()
|
||||
|
||||
const device = list?.find((item) => {
|
||||
|
||||
@@ -113,14 +120,35 @@ export function useDeviceSettings() {
|
||||
|
||||
if (device.deviceNo) deviceNo.value = device.deviceNo
|
||||
|
||||
if (device.name) deviceName.value = device.name
|
||||
const namePatch = findPatchedDeviceName(deviceId.value)
|
||||
if (namePatch && device.name !== namePatch) {
|
||||
deviceName.value = namePatch
|
||||
} else if (device.name) {
|
||||
deviceName.value = device.name
|
||||
}
|
||||
|
||||
const parsedHomeId = parseId(device.homeId)
|
||||
if (parsedHomeId) homeId.value = parsedHomeId
|
||||
|
||||
const locationPatch = findPatchedDeviceLocation(deviceId.value)
|
||||
if (locationPatch) {
|
||||
locationId.value = locationPatch.locationId
|
||||
locationName.value = locationPatch.locationName
|
||||
} else {
|
||||
const parsedLocationId = parseId(device.locationId)
|
||||
if (parsedLocationId) locationId.value = parsedLocationId
|
||||
|
||||
if (parsedHomeId && parsedLocationId) {
|
||||
try {
|
||||
const locations = await fetchRoomList(parsedHomeId)
|
||||
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
|
||||
if (matched?.name) locationName.value = matched.name
|
||||
} catch {
|
||||
// 房间列表失败时保留当前展示
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
@@ -178,11 +206,21 @@ export function useDeviceSettings() {
|
||||
|
||||
|
||||
async function onConfirmRoom(data: { locationId: string | number; name: string }) {
|
||||
if (!isValidDeviceId(deviceId.value)) {
|
||||
locationId.value = String(data.locationId)
|
||||
locationName.value = data.name
|
||||
const nextLocationId = String(data.locationId)
|
||||
const nextLocationName = data.name?.trim() || ''
|
||||
if (!nextLocationId || !nextLocationName) return
|
||||
if (sameId(locationId.value, nextLocationId) && locationName.value === nextLocationName) {
|
||||
return
|
||||
}
|
||||
|
||||
// 先更新 UI,避免返回设置页时 onShow 拉旧数据把展示盖回去
|
||||
locationId.value = nextLocationId
|
||||
locationName.value = nextLocationName
|
||||
if (isValidDeviceId(deviceId.value)) {
|
||||
rememberDeviceLocationPatch(deviceId.value, nextLocationId, nextLocationName)
|
||||
}
|
||||
|
||||
if (!isValidDeviceId(deviceId.value)) return
|
||||
if (saving.value) return
|
||||
|
||||
saving.value = true
|
||||
@@ -192,10 +230,8 @@ export function useDeviceSettings() {
|
||||
await updateDeviceSettings({
|
||||
deviceId: deviceId.value,
|
||||
homeId: validHomeId,
|
||||
locationId: data.locationId,
|
||||
locationId: nextLocationId,
|
||||
})
|
||||
locationId.value = String(data.locationId)
|
||||
locationName.value = data.name
|
||||
uni.showToast({ title: '修改成功', icon: 'success' })
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '修改房间失败'), icon: 'none' })
|
||||
@@ -233,6 +269,7 @@ export function useDeviceSettings() {
|
||||
await updateDeviceSettings({ deviceId: deviceId.value, name: trimmed })
|
||||
|
||||
deviceName.value = trimmed
|
||||
rememberDeviceNamePatch(deviceId.value, trimmed)
|
||||
|
||||
uni.showToast({ title: '修改成功', icon: 'success' })
|
||||
|
||||
@@ -302,18 +339,22 @@ export function useDeviceSettings() {
|
||||
|
||||
|
||||
|
||||
onLoad((query?: DeviceSettingsRouteQuery) => {
|
||||
|
||||
applyQuery(query)
|
||||
|
||||
void (async () => {
|
||||
async function reloadFromServer() {
|
||||
const pendingRoom = consumeRoomSelection(deviceId.value)
|
||||
if (pendingRoom) {
|
||||
// 仅消费房间选择结果;已与当前一致则不再请求/弹 toast
|
||||
await onConfirmRoom(pendingRoom)
|
||||
}
|
||||
await syncDeviceFromList()
|
||||
homeId.value = await resolveValidHomeId(homeId.value)
|
||||
})()
|
||||
}
|
||||
|
||||
onLoad((query?: DeviceSettingsRouteQuery) => {
|
||||
applyQuery(query)
|
||||
void reloadFromServer()
|
||||
})
|
||||
|
||||
|
||||
usePageShowRefresh(() => reloadFromServer(), { skipInitialShow: true })
|
||||
|
||||
return {
|
||||
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
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 {
|
||||
applyDeviceListPatches,
|
||||
mergeDevicePresenceFields,
|
||||
} from './device-list-patch'
|
||||
import {
|
||||
buildRoomTabs,
|
||||
countOnlineDevices,
|
||||
@@ -17,6 +30,9 @@ import {
|
||||
mapDeviceItem,
|
||||
} from './device.utils'
|
||||
|
||||
/** 在线态轮询:缩短以便关机后尽快变为离线 */
|
||||
const PRESENCE_INTERVAL_MS = 8000
|
||||
|
||||
const DEFAULT_HOT_DEVICES: HotDeviceItem[] = [
|
||||
{
|
||||
id: 'z2',
|
||||
@@ -33,6 +49,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[]>([])
|
||||
@@ -42,6 +59,8 @@ export function useDevice() {
|
||||
const roomDialogVisible = ref(false)
|
||||
const successToastVisible = ref(false)
|
||||
|
||||
let presenceTimer: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
const hasDevices = computed(() => devices.value.length > 0)
|
||||
|
||||
const filteredDevices = computed(() =>
|
||||
@@ -76,43 +95,130 @@ export function useDevice() {
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
function applyCurrentHome(homeList: AppHomeVo[]) {
|
||||
const currentHome = findHomeById(homeList, homeId.value) ?? pickDefaultHome(homeList)
|
||||
const currentId = getHomeId(currentHome)
|
||||
if (currentId) {
|
||||
homeId.value = currentId
|
||||
saveSelectedHomeId(currentId)
|
||||
}
|
||||
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
|
||||
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)
|
||||
}
|
||||
|
||||
let presenceEpoch = 0
|
||||
|
||||
function commitDevices(next: DeviceListItem[]) {
|
||||
devices.value = applyDeviceListPatches(next)
|
||||
}
|
||||
|
||||
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)
|
||||
devices.value = list.map((item) => mapDeviceItem(item, locationMap))
|
||||
devices.value = await refreshDevicePresence(devices.value)
|
||||
const mapped = list.map((item) => mapDeviceItem(item, locationMap))
|
||||
// 先写入接口数据(含最新名称),再异步合并在线状态,避免 BLE 扫描旧快照覆盖改名
|
||||
commitDevices(mapped)
|
||||
const epoch = ++presenceEpoch
|
||||
const presence = await refreshDevicePresence(mapped)
|
||||
if (epoch !== presenceEpoch) return
|
||||
commitDevices(mergeDevicePresenceFields(devices.value, presence))
|
||||
}
|
||||
|
||||
async function loadDevices(silent = false) {
|
||||
if (loading.value) return
|
||||
if (!silent) loading.value = true
|
||||
try {
|
||||
await loadHomeList()
|
||||
await loadDevicesForHome()
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '加载设备失败'), icon: 'none' })
|
||||
} finally {
|
||||
if (!silent) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
const snapshot = devices.value
|
||||
const epoch = ++presenceEpoch
|
||||
const presence = await refreshDevicePresence(snapshot)
|
||||
if (epoch !== presenceEpoch) return
|
||||
commitDevices(mergeDevicePresenceFields(devices.value, presence))
|
||||
}
|
||||
|
||||
function startPresencePolling() {
|
||||
stopPresencePolling()
|
||||
presenceTimer = setInterval(() => {
|
||||
void refreshPresenceOnly()
|
||||
}, PRESENCE_INTERVAL_MS)
|
||||
}
|
||||
|
||||
function stopPresencePolling() {
|
||||
if (presenceTimer) clearInterval(presenceTimer)
|
||||
presenceTimer = undefined
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
void loadDevices()
|
||||
try {
|
||||
uni.hideLoading()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
if (!getStoredToken()) {
|
||||
uni.reLaunch({ url: '/pages/login/index' })
|
||||
return
|
||||
}
|
||||
// 已有列表时静默刷新,避免改名返回首页再闪「加载中」
|
||||
void loadDevices(devices.value.length > 0)
|
||||
void refreshUnreadMessageCount()
|
||||
startPresencePolling()
|
||||
})
|
||||
|
||||
onHide(stopPresencePolling)
|
||||
|
||||
function showOperationSuccess() {
|
||||
successToastVisible.value = true
|
||||
}
|
||||
@@ -148,7 +254,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() {
|
||||
@@ -167,10 +274,6 @@ export function useDevice() {
|
||||
uni.navigateTo({ url: '/pages/device/home-manage/index' })
|
||||
}
|
||||
|
||||
function onManageDevices() {
|
||||
uni.showToast({ title: '设备管理功能开发中', icon: 'none' })
|
||||
}
|
||||
|
||||
function onSelectDevice(device: DeviceListItem) {
|
||||
if (!device.deviceId) {
|
||||
uni.showToast({ title: '设备信息不完整', icon: 'none' })
|
||||
@@ -193,6 +296,8 @@ export function useDevice() {
|
||||
|
||||
return {
|
||||
homeName,
|
||||
homeId,
|
||||
homes,
|
||||
rooms,
|
||||
activeRoomId,
|
||||
devices: filteredDevices,
|
||||
@@ -211,7 +316,7 @@ export function useDevice() {
|
||||
onGoMall,
|
||||
onNotify,
|
||||
onHomeManage,
|
||||
onManageDevices,
|
||||
onSelectHome,
|
||||
onSelectDevice,
|
||||
loadDevices,
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ export function useForgotPassword() {
|
||||
return
|
||||
}
|
||||
uni.navigateTo({
|
||||
url: `/pages/change-password/index?resetToken=${encodeURIComponent(res.resetToken)}&from=${fromPrivacy.value ? 'privacy' : 'login'}`,
|
||||
url: `/pages/change-password/index?resetToken=${encodeURIComponent(res.resetToken)}&phone=${encodeURIComponent(phone.value)}&from=${fromPrivacy.value ? 'privacy' : 'login'}`,
|
||||
})
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' })
|
||||
|
||||
@@ -8,7 +8,16 @@
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<template v-if="mode === 'code'">
|
||||
<template v-if="mode === 'password'">
|
||||
<base-input v-model="account" icon="phone" placeholder="请输入账号" />
|
||||
<base-input v-model="password" icon="lock" type="password" placeholder="请输入密码" />
|
||||
<view class="login-page__links">
|
||||
<text class="login-page__link" @tap="switchMode('code')">验证码登录</text>
|
||||
<text class="login-page__link" @tap="goForgotPassword">忘记密码?</text>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<base-input v-model="phone" icon="phone" type="number" placeholder="请输入手机号" :maxlength="11" />
|
||||
<base-input v-model="code" icon="shield" type="number" placeholder="请输入验证码" :maxlength="6">
|
||||
<template #suffix>
|
||||
@@ -20,18 +29,9 @@
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<base-input v-model="account" icon="phone" placeholder="请输入账号" />
|
||||
<base-input v-model="password" icon="lock" type="password" placeholder="请输入密码" />
|
||||
<view class="login-page__links">
|
||||
<text class="login-page__link" @tap="switchMode('code')">验证码登录</text>
|
||||
<text class="login-page__link" @tap="goForgotPassword">忘记密码?</text>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<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">
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
import { ref } from 'vue'
|
||||
import { useSmsCode } from '@/hooks/use-sms-code'
|
||||
import { isValidPassword, isValidPhone, isValidSmsCode } from '@/utils/validate'
|
||||
import {
|
||||
isValidPassword,
|
||||
isValidPhone,
|
||||
isValidSmsCode,
|
||||
LOGIN_PASSWORD_EMPTY_TOAST,
|
||||
} from '@/utils/validate'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { setupMessageInbox } from '@/hooks/use-message-inbox'
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import { clearLocalUserDataPreservingAuth } from '@/utils/clear-local-user-data'
|
||||
import { SMS_CODE_SCENE } from '@/types/api'
|
||||
import { syncCsAuthByPassword, syncCsAuthBySms } from '@/api/cs-auth'
|
||||
import { loginByPassword, loginBySms } from './login.api'
|
||||
import type { LoginMode } from './login.types'
|
||||
|
||||
export function useLogin() {
|
||||
const mode = ref<LoginMode>('code')
|
||||
const agreed = ref(true)
|
||||
const mode = ref<LoginMode>('password')
|
||||
const agreed = ref(false)
|
||||
const phone = ref('')
|
||||
const code = ref('')
|
||||
const account = ref('')
|
||||
@@ -46,11 +54,16 @@ export function useLogin() {
|
||||
return
|
||||
}
|
||||
await loginBySms({ phone: phone.value, code: code.value })
|
||||
await syncCsAuthBySms(phone.value, code.value)
|
||||
} else {
|
||||
if (!account.value.trim()) {
|
||||
uni.showToast({ title: '请输入账号', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (!password.value.trim()) {
|
||||
uni.showToast({ title: LOGIN_PASSWORD_EMPTY_TOAST, icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (!isValidPassword(password.value)) {
|
||||
uni.showToast({ title: '密码至少 6 位', icon: 'none' })
|
||||
return
|
||||
@@ -59,11 +72,13 @@ export function useLogin() {
|
||||
account: account.value,
|
||||
password: password.value,
|
||||
})
|
||||
await syncCsAuthByPassword(account.value, password.value)
|
||||
}
|
||||
if (!getStoredToken()) {
|
||||
uni.showToast({ title: '登录失败,未获取到令牌', icon: 'none' })
|
||||
return
|
||||
}
|
||||
clearLocalUserDataPreservingAuth()
|
||||
setupMessageInbox()
|
||||
uni.showToast({ title: '登录成功', icon: 'success' })
|
||||
uni.reLaunch({ url: '/pages/device/index' })
|
||||
@@ -82,6 +97,12 @@ export function useLogin() {
|
||||
uni.navigateTo({ url: '/pages/forgot-password/index' })
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
if (!getStoredToken()) return
|
||||
setupMessageInbox()
|
||||
uni.reLaunch({ url: '/pages/device/index' })
|
||||
})
|
||||
|
||||
return {
|
||||
mode,
|
||||
agreed,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="change-phone-page">
|
||||
<app-navbar title="手机号换绑" />
|
||||
<view class="change-phone-page__body">
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { onLoad } from '@dcloudio/uni-app'
|
||||
import { onLoad, onShow } from '@dcloudio/uni-app'
|
||||
import { ref } from 'vue'
|
||||
import { fetchProfile } from '@/api/profile'
|
||||
import { useSmsCode } from '@/hooks/use-sms-code'
|
||||
import { SMS_CODE_SCENE } from '@/types/api'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { isValidPhone, isValidSmsCode } from '@/utils/validate'
|
||||
import { isSamePhone, isValidPhone, isValidSmsCode } from '@/utils/validate'
|
||||
import { verifyNewPhone } from '../change-phone.api'
|
||||
|
||||
export function useChangePhoneBind() {
|
||||
const phone = ref('')
|
||||
const code = ref('')
|
||||
const changeToken = ref('')
|
||||
const boundPhone = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.changePhoneNew, {
|
||||
@@ -28,7 +30,30 @@ export function useChangePhoneBind() {
|
||||
}
|
||||
})
|
||||
|
||||
async function loadBoundPhone() {
|
||||
try {
|
||||
const profile = await fetchProfile()
|
||||
boundPhone.value = profile?.phonenumber || profile?.userName || ''
|
||||
} catch {
|
||||
// 新号校验依赖当前绑定号;加载失败时仍走格式校验
|
||||
}
|
||||
}
|
||||
|
||||
function ensureNewPhoneDiffersFromBound(): boolean {
|
||||
if (!isValidPhone(phone.value)) {
|
||||
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
|
||||
return false
|
||||
}
|
||||
const bound = boundPhone.value.trim()
|
||||
if (bound && isSamePhone(phone.value, bound)) {
|
||||
uni.showToast({ title: '新手机号不能与当前手机号相同', icon: 'none' })
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function onSendCode() {
|
||||
if (!ensureNewPhoneDiffersFromBound()) return
|
||||
sendCode(phone.value)
|
||||
}
|
||||
|
||||
@@ -37,10 +62,7 @@ export function useChangePhoneBind() {
|
||||
uni.showToast({ title: '换绑令牌无效,请重新验证', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (!isValidPhone(phone.value)) {
|
||||
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (!ensureNewPhoneDiffersFromBound()) return
|
||||
if (!isValidSmsCode(code.value)) {
|
||||
uni.showToast({ title: '请输入验证码', icon: 'none' })
|
||||
return
|
||||
@@ -61,6 +83,10 @@ export function useChangePhoneBind() {
|
||||
}
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
void loadBoundPhone()
|
||||
})
|
||||
|
||||
return {
|
||||
phone,
|
||||
code,
|
||||
|
||||
@@ -33,17 +33,6 @@
|
||||
margin-top: 16rpx;
|
||||
}
|
||||
|
||||
.change-phone-page__link-row {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 24rpx;
|
||||
}
|
||||
|
||||
.change-phone-page__link {
|
||||
font-size: 26rpx;
|
||||
color: $color-primary;
|
||||
}
|
||||
|
||||
.change-phone-page__form :deep(.base-input) {
|
||||
border: none;
|
||||
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="change-phone-page">
|
||||
<app-navbar title="手机号换绑" />
|
||||
<view class="change-phone-page__body">
|
||||
@@ -17,10 +17,6 @@
|
||||
<view class="change-phone-page__btn">
|
||||
<primary-button text="下一步" @click="nextStep" />
|
||||
</view>
|
||||
|
||||
<view class="change-phone-page__link-row">
|
||||
<text class="change-phone-page__link" @tap="onUnavailablePhone">原手机号码已不可用?</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
@@ -28,8 +24,7 @@
|
||||
<script setup lang="ts">
|
||||
import { useChangePhoneVerify } from './use-change-phone-verify'
|
||||
|
||||
const { phone, code, counting, seconds, subtitle, onSendCode, onUnavailablePhone, nextStep } =
|
||||
useChangePhoneVerify()
|
||||
const { phone, code, counting, seconds, subtitle, onSendCode, nextStep } = useChangePhoneVerify()
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@@ -4,11 +4,11 @@ import { fetchProfile } from '@/api/profile'
|
||||
import { useSmsCode } from '@/hooks/use-sms-code'
|
||||
import { SMS_CODE_SCENE } from '@/types/api'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { isValidPhone, isValidSmsCode } from '@/utils/validate'
|
||||
import { isSamePhone, isValidPhone, isValidSmsCode, normalizePhoneDigits } from '@/utils/validate'
|
||||
import { verifyOldPhone } from './change-phone.api'
|
||||
|
||||
function maskPhone(phone: string): string {
|
||||
const digits = phone.replace(/\D/g, '')
|
||||
const digits = normalizePhoneDigits(phone)
|
||||
if (digits.length < 7) return phone
|
||||
return digits.replace(/(\d{3})\d{4}(\d+)/, '$1****$2')
|
||||
}
|
||||
@@ -38,27 +38,31 @@ export function useChangePhoneVerify() {
|
||||
}
|
||||
}
|
||||
|
||||
function ensureInputMatchesBoundPhone(): boolean {
|
||||
const bound = boundPhone.value.trim()
|
||||
if (!bound) {
|
||||
uni.showToast({ title: '正在加载账号手机号,请稍后', icon: 'none' })
|
||||
void loadBoundPhone()
|
||||
return false
|
||||
}
|
||||
if (!isValidPhone(phone.value)) {
|
||||
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
|
||||
return false
|
||||
}
|
||||
if (!isSamePhone(phone.value, bound)) {
|
||||
uni.showToast({ title: '请输入当前账号绑定的原手机号', icon: 'none' })
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function onSendCode() {
|
||||
if (!ensureInputMatchesBoundPhone()) return
|
||||
sendCode(phone.value)
|
||||
}
|
||||
|
||||
function onUnavailablePhone() {
|
||||
uni.showModal({
|
||||
title: '原手机号不可用',
|
||||
content: '如原手机号已停用,请联系在线客服协助处理。',
|
||||
confirmText: '联系客服',
|
||||
success: (res) => {
|
||||
if (!res.confirm) return
|
||||
uni.navigateTo({ url: '/pages/mine/support/index' })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function nextStep() {
|
||||
if (!isValidPhone(phone.value)) {
|
||||
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (!ensureInputMatchesBoundPhone()) return
|
||||
if (!isValidSmsCode(code.value)) {
|
||||
uni.showToast({ title: '请输入验证码', icon: 'none' })
|
||||
return
|
||||
@@ -93,7 +97,6 @@ export function useChangePhoneVerify() {
|
||||
seconds,
|
||||
subtitle,
|
||||
onSendCode,
|
||||
onUnavailablePhone,
|
||||
nextStep,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,7 @@
|
||||
}
|
||||
|
||||
.edit-profile-page__scroll {
|
||||
flex: 1;
|
||||
height: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.edit-profile-page__body {
|
||||
@@ -111,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;
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="edit-profile-page">
|
||||
<view class="edit-profile-page__navbar">
|
||||
<app-navbar title="编辑资料" />
|
||||
</view>
|
||||
|
||||
<scroll-view class="edit-profile-page__scroll" scroll-y>
|
||||
<page-scroll-view class="edit-profile-page__scroll">
|
||||
<view class="edit-profile-page__body">
|
||||
<view class="edit-profile-page__avatar-section">
|
||||
<view class="edit-profile-page__avatar-wrap">
|
||||
@@ -102,23 +102,9 @@
|
||||
/>
|
||||
</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>
|
||||
</scroll-view>
|
||||
</page-scroll-view>
|
||||
|
||||
<view class="edit-profile-page__footer">
|
||||
<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>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { 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,16 +44,11 @@ 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),
|
||||
)
|
||||
async function loadProfile() {
|
||||
if (loading.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
const profile = await fetchProfile()
|
||||
function applyProfile(profile: Awaited<ReturnType<typeof fetchProfile>>) {
|
||||
form.value = {
|
||||
nickName: profile.nickName || profile.userName || '',
|
||||
gender: profile.gender || '0',
|
||||
@@ -68,10 +56,16 @@ 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) : '',
|
||||
}
|
||||
}
|
||||
|
||||
async function loadProfile() {
|
||||
if (loading.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
applyProfile(await fetchProfile())
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '加载资料失败'), icon: 'none' })
|
||||
} finally {
|
||||
@@ -79,6 +73,16 @@ export function useEditProfile() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 从换绑手机号等子页返回时只刷新手机号,避免覆盖未保存的头像等编辑 */
|
||||
async function refreshPhoneFromServer() {
|
||||
try {
|
||||
const profile = await fetchProfile()
|
||||
form.value.phonenumber = profile.phonenumber || profile.userName || ''
|
||||
} catch {
|
||||
// 静默失败,保留当前表单
|
||||
}
|
||||
}
|
||||
|
||||
function onOpenAvatarSheet() {
|
||||
avatarSheetVisible.value = true
|
||||
}
|
||||
@@ -105,6 +109,7 @@ export function useEditProfile() {
|
||||
const filePath = res.tempFilePaths[0]
|
||||
if (!filePath) return
|
||||
|
||||
form.value.avatarUrl = filePath
|
||||
uploadingAvatar.value = true
|
||||
uni.showLoading({ title: '上传中...', mask: true })
|
||||
const uploaded = await uploadProfileAvatar(filePath)
|
||||
@@ -163,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) {
|
||||
@@ -200,7 +201,7 @@ export function useEditProfile() {
|
||||
}
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
onLoad(() => {
|
||||
void loadProfile()
|
||||
})
|
||||
|
||||
@@ -209,7 +210,6 @@ export function useEditProfile() {
|
||||
saving,
|
||||
uploadingAvatar,
|
||||
form,
|
||||
maskedPhone,
|
||||
genderText,
|
||||
locationText,
|
||||
regionPickerVisible,
|
||||
@@ -225,7 +225,6 @@ export function useEditProfile() {
|
||||
onBirthdayChange,
|
||||
onOpenRegionPicker,
|
||||
onConfirmRegion,
|
||||
onChangePhone,
|
||||
onSave,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -1,13 +1,29 @@
|
||||
import { resolveValidHomeId } from '@/api/home'
|
||||
import { fetchProfile } from '@/api/profile'
|
||||
import { fetchDeviceList } from '../device/device.api'
|
||||
import { fetchAllDeviceList, fetchDeviceList } from '../device/device.api'
|
||||
|
||||
export async function fetchMineOverview() {
|
||||
const [profile, devices] = await Promise.all([
|
||||
fetchProfile(),
|
||||
fetchDeviceList(),
|
||||
])
|
||||
return {
|
||||
profile,
|
||||
deviceCount: devices?.length ?? 0,
|
||||
async function fetchDeviceCountForMine(): Promise<number> {
|
||||
try {
|
||||
const devices = await fetchAllDeviceList()
|
||||
return devices?.length ?? 0
|
||||
} catch {
|
||||
try {
|
||||
const homeId = await resolveValidHomeId()
|
||||
if (!homeId) return 0
|
||||
const devices = await fetchDeviceList({ homeId })
|
||||
return devices?.length ?? 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 我的页概览:资料与设备数分开拉取,避免 listAll 失败导致头像昵称不展示 */
|
||||
export async function fetchMineOverview() {
|
||||
const profile = await fetchProfile()
|
||||
const deviceCount = await fetchDeviceCountForMine()
|
||||
return {
|
||||
profile,
|
||||
deviceCount,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +1,91 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="notify-page">
|
||||
<app-navbar title="通知">
|
||||
<template #right>
|
||||
<view class="notify-page__mark-all" @tap="onMarkAllRead">
|
||||
<text class="notify-page__mark-all-text">全部已读</text>
|
||||
</view>
|
||||
</template>
|
||||
</app-navbar>
|
||||
<view class="notify-page__top">
|
||||
<app-navbar title="通知" />
|
||||
|
||||
<scroll-view
|
||||
<view class="notify-page__filter-wrap">
|
||||
<view class="notify-page__filter" @tap.stop="toggleHomePicker">
|
||||
<text class="notify-page__filter-text">{{ selectedHomeLabel }}</text>
|
||||
<image
|
||||
class="notify-page__filter-arrow"
|
||||
:class="{ 'notify-page__filter-arrow--open': homePickerOpen }"
|
||||
:src="staticAssets.iconNotifyFilterArrow"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
|
||||
<view
|
||||
v-if="homePickerOpen"
|
||||
class="notify-page__picker-mask"
|
||||
@tap="closeHomePicker"
|
||||
@touchmove.stop.prevent
|
||||
/>
|
||||
<view v-if="homePickerOpen" class="notify-page__picker" @tap.stop>
|
||||
<view
|
||||
class="notify-page__picker-item"
|
||||
:class="{ 'notify-page__picker-item--active': !selectedHomeId }"
|
||||
@tap="onSelectHome(allHomesId)"
|
||||
>
|
||||
<text>全部家庭</text>
|
||||
</view>
|
||||
<view
|
||||
v-for="home in homes"
|
||||
:key="String(home.id)"
|
||||
class="notify-page__picker-item"
|
||||
:class="{ 'notify-page__picker-item--active': isHomeOptionActive(home) }"
|
||||
@tap="onSelectHome(parseHomeId(home) || '')"
|
||||
>
|
||||
<text>{{ home.homeName || '我的家' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<page-scroll-view
|
||||
class="notify-page__scroll"
|
||||
scroll-y
|
||||
top-selector=".notify-page__top"
|
||||
refresher-enabled
|
||||
:refresher-triggered="loading"
|
||||
:refresher-triggered="refreshing"
|
||||
:lower-threshold="120"
|
||||
@refresherrefresh="onRefresh"
|
||||
@scrolltolower="onLoadMore"
|
||||
>
|
||||
<view class="notify-page__body">
|
||||
<text class="notify-page__section">{{ sectionTitle }}</text>
|
||||
<view class="notify-page__card">
|
||||
<view class="notify-page__card-head">
|
||||
<text class="notify-page__unread">{{ unreadCountText }}</text>
|
||||
<view class="notify-page__mark-all" @tap="onMarkAllRead">
|
||||
<text class="notify-page__mark-all-text">全部已读</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view v-if="messages.length" class="notify-page__list">
|
||||
<view v-if="messageRows.length" class="notify-page__list">
|
||||
<view
|
||||
v-for="item in messages"
|
||||
:key="normalizeId(item)"
|
||||
v-for="row in messageRows"
|
||||
:key="row.id"
|
||||
class="notify-page__item"
|
||||
@tap="onItemTap(item)"
|
||||
@tap="onItemTap(row.raw)"
|
||||
>
|
||||
<view class="notify-page__thumb-wrap">
|
||||
<image
|
||||
class="notify-page__thumb"
|
||||
:src="staticAssets.logo"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
<view v-if="row.unread" class="notify-page__thumb-dot" />
|
||||
</view>
|
||||
<view class="notify-page__item-main">
|
||||
<view class="notify-page__item-head">
|
||||
<view class="notify-page__title-wrap">
|
||||
<view v-if="isUnreadMessage(item)" class="notify-page__dot" />
|
||||
<text class="notify-page__title">{{ item.title || '系统通知' }}</text>
|
||||
<text class="notify-page__title">{{ row.title }}</text>
|
||||
</view>
|
||||
<text class="notify-page__time">{{ formatNotifyTime(item) }}</text>
|
||||
<text class="notify-page__time">{{ row.timeText }}</text>
|
||||
</view>
|
||||
<text v-if="row.locationText" class="notify-page__location">
|
||||
{{ row.locationText }}
|
||||
</text>
|
||||
<text class="notify-page__content">{{ row.content }}</text>
|
||||
</view>
|
||||
<text class="notify-page__content">{{ item.content || '暂无详情' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -41,38 +93,44 @@
|
||||
暂无通知消息
|
||||
</view>
|
||||
|
||||
<view v-if="loading && !messages.length" class="notify-page__loading">
|
||||
<view v-if="loading && !messageRows.length" class="notify-page__loading">
|
||||
加载中...
|
||||
</view>
|
||||
|
||||
<view v-else-if="messages.length && !hasMore" class="notify-page__footer-tip">
|
||||
<view v-else-if="messageRows.length && !hasMore" class="notify-page__footer-tip">
|
||||
没有更多了
|
||||
</view>
|
||||
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
</page-scroll-view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { AppMessageVo } from '@/types/message'
|
||||
import { formatNotifyTime, isUnreadMessage, normalizeMessageId } from './notify.utils'
|
||||
import { staticAssets } from '@/utils/static-assets'
|
||||
import { useNotify } from './use-notify'
|
||||
|
||||
const {
|
||||
messages,
|
||||
messageRows,
|
||||
homes,
|
||||
selectedHomeId,
|
||||
selectedHomeLabel,
|
||||
homePickerOpen,
|
||||
unreadCountText,
|
||||
loading,
|
||||
refreshing,
|
||||
hasMore,
|
||||
sectionTitle,
|
||||
toggleHomePicker,
|
||||
closeHomePicker,
|
||||
onSelectHome,
|
||||
isHomeOptionActive,
|
||||
onRefresh,
|
||||
onLoadMore,
|
||||
onItemTap,
|
||||
onMarkAllRead,
|
||||
allHomesId,
|
||||
parseHomeId,
|
||||
} = useNotify()
|
||||
|
||||
function normalizeId(item: AppMessageVo) {
|
||||
return normalizeMessageId(item) || `${item.title}-${item.timestamp}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@@ -1,25 +1,111 @@
|
||||
.notify-page {
|
||||
min-height: 100vh;
|
||||
background: #fff;
|
||||
height: 100vh;
|
||||
background: #f7f8fa;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.notify-page__top {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.notify-page__scroll {
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
height: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.notify-page__body {
|
||||
min-height: 100%;
|
||||
padding: 0 24rpx 32rpx;
|
||||
}
|
||||
|
||||
.notify-page__section {
|
||||
display: block;
|
||||
padding: 16rpx 32rpx 8rpx;
|
||||
.notify-page__filter-wrap {
|
||||
position: relative;
|
||||
z-index: 30;
|
||||
padding: 8rpx 32rpx 16rpx;
|
||||
background: #f7f8fa;
|
||||
}
|
||||
|
||||
.notify-page__filter {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8rpx;
|
||||
}
|
||||
|
||||
.notify-page__filter-text {
|
||||
font-size: 30rpx;
|
||||
font-weight: 600;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
|
||||
.notify-page__filter-arrow {
|
||||
width: 24rpx;
|
||||
height: 24rpx;
|
||||
flex-shrink: 0;
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&--open {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
}
|
||||
|
||||
.notify-page__picker-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 40;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.notify-page__picker {
|
||||
position: absolute;
|
||||
left: 24rpx;
|
||||
right: 24rpx;
|
||||
top: 100%;
|
||||
margin-top: 8rpx;
|
||||
z-index: 50;
|
||||
background: #fff;
|
||||
border-radius: 16rpx;
|
||||
box-shadow: 0 12rpx 40rpx rgba(16, 24, 40, 0.12);
|
||||
max-height: 480rpx;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.notify-page__picker-item {
|
||||
padding: 28rpx 32rpx;
|
||||
font-size: 28rpx;
|
||||
color: #344054;
|
||||
border-bottom: 1rpx solid #f2f4f7;
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
&--active {
|
||||
color: #1ec671;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.notify-page__card {
|
||||
background: #fff;
|
||||
border-radius: 24rpx;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 2rpx 12rpx rgba(16, 24, 40, 0.04);
|
||||
}
|
||||
|
||||
.notify-page__card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 24rpx 28rpx;
|
||||
border-bottom: 1rpx solid #f2f4f7;
|
||||
}
|
||||
|
||||
.notify-page__unread {
|
||||
font-size: 26rpx;
|
||||
color: #98a2b3;
|
||||
line-height: 1.4;
|
||||
color: #667085;
|
||||
}
|
||||
|
||||
.notify-page__list {
|
||||
@@ -27,34 +113,65 @@
|
||||
}
|
||||
|
||||
.notify-page__item {
|
||||
padding: 28rpx 32rpx;
|
||||
display: flex;
|
||||
gap: 20rpx;
|
||||
padding: 28rpx;
|
||||
border-bottom: 1rpx solid #f2f4f7;
|
||||
}
|
||||
|
||||
.notify-page__thumb-wrap {
|
||||
position: relative;
|
||||
width: 96rpx;
|
||||
height: 96rpx;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.notify-page__thumb {
|
||||
width: 96rpx;
|
||||
height: 96rpx;
|
||||
border-radius: 12rpx;
|
||||
background-color: #f2f4f7;
|
||||
padding: 12rpx;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.notify-page__thumb-dot {
|
||||
position: absolute;
|
||||
top: -4rpx;
|
||||
right: -4rpx;
|
||||
width: 16rpx;
|
||||
height: 16rpx;
|
||||
border-radius: 50%;
|
||||
background: #f04438;
|
||||
border: 2rpx solid #fff;
|
||||
}
|
||||
|
||||
.notify-page__item-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.notify-page__item-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 24rpx;
|
||||
gap: 16rpx;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.notify-page__title-wrap {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12rpx;
|
||||
}
|
||||
|
||||
.notify-page__dot {
|
||||
width: 12rpx;
|
||||
height: 12rpx;
|
||||
border-radius: 50%;
|
||||
background: #1ec671;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.notify-page__title {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 30rpx;
|
||||
font-weight: 600;
|
||||
color: #1a1a1a;
|
||||
@@ -62,7 +179,16 @@
|
||||
}
|
||||
|
||||
.notify-page__time {
|
||||
flex-shrink: 0;
|
||||
flex: 0 0 auto;
|
||||
font-size: 24rpx;
|
||||
color: #98a2b3;
|
||||
line-height: 1.4;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.notify-page__location {
|
||||
display: block;
|
||||
margin-top: 8rpx;
|
||||
font-size: 24rpx;
|
||||
color: #98a2b3;
|
||||
line-height: 1.4;
|
||||
@@ -72,36 +198,37 @@
|
||||
display: block;
|
||||
margin-top: 12rpx;
|
||||
font-size: 26rpx;
|
||||
color: #98a2b3;
|
||||
color: #667085;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.notify-page__empty,
|
||||
.notify-page__loading {
|
||||
margin: 32rpx;
|
||||
margin: 32rpx 28rpx;
|
||||
padding: 24rpx;
|
||||
border-radius: 16rpx;
|
||||
background: #f7f8fa;
|
||||
text-align: center;
|
||||
font-size: 26rpx;
|
||||
color: #98a2b3;
|
||||
}
|
||||
|
||||
.notify-page__footer-tip {
|
||||
padding: 80rpx 32rpx;
|
||||
padding: 48rpx 32rpx;
|
||||
text-align: center;
|
||||
font-size: 26rpx;
|
||||
color: #98a2b3;
|
||||
}
|
||||
|
||||
.notify-page__mark-all {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding: 8rpx 0;
|
||||
padding: 8rpx 20rpx;
|
||||
border: 1rpx solid #93c5fd;
|
||||
border-radius: 28rpx;
|
||||
}
|
||||
|
||||
.notify-page__mark-all-text {
|
||||
font-size: 26rpx;
|
||||
color: #1ec671;
|
||||
font-size: 24rpx;
|
||||
color: #3b82f6;
|
||||
white-space: nowrap;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,45 @@
|
||||
import type { AppMessageVo } from '@/types/message'
|
||||
import { buildMessageFromPush, normalizeMessageId } from '@/utils/message-push'
|
||||
import {
|
||||
buildMessageFromPush,
|
||||
correctPowerNotifyText,
|
||||
normalizeMessageId,
|
||||
} from '@/utils/message-push'
|
||||
import { sameId } from '@/utils/device-id'
|
||||
|
||||
export { buildMessageFromPush, normalizeMessageId }
|
||||
|
||||
export function messageMatchesHome(
|
||||
message: AppMessageVo,
|
||||
homeId: string,
|
||||
homeName: string,
|
||||
): boolean {
|
||||
if (!homeId) return true
|
||||
if (message.homeId != null && sameId(message.homeId, homeId)) return true
|
||||
const msgHome = message.homeName?.trim()
|
||||
if (msgHome && homeName && msgHome === homeName) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export function formatNotifyLocation(message: AppMessageVo): string {
|
||||
const home = message.homeName?.trim()
|
||||
const room = message.locationName?.trim()
|
||||
if (home && room) return `${home} | ${room}`
|
||||
return home || room || ''
|
||||
}
|
||||
|
||||
export function isUnreadMessage(message: AppMessageVo): boolean {
|
||||
const flag = message.readFlag
|
||||
return flag === 0 || flag === '0'
|
||||
}
|
||||
|
||||
function pad2(value: number): string {
|
||||
return String(value).padStart(2, '0')
|
||||
}
|
||||
|
||||
function formatNotifyDateTime(date: Date): string {
|
||||
return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${pad2(date.getHours())}:${pad2(date.getMinutes())}`
|
||||
}
|
||||
|
||||
export function formatNotifyTime(message: AppMessageVo): string {
|
||||
const raw = message.timestamp || message.createTime
|
||||
if (!raw) return ''
|
||||
@@ -16,6 +48,12 @@ export function formatNotifyTime(message: AppMessageVo): string {
|
||||
|
||||
const date = /^\d{13,}$/.test(text) ? new Date(Number(text)) : new Date(text)
|
||||
if (Number.isNaN(date.getTime())) return text
|
||||
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
|
||||
return formatNotifyDateTime(date)
|
||||
}
|
||||
|
||||
export function formatNotifyContent(message: AppMessageVo): string {
|
||||
const raw = message.content?.trim()
|
||||
if (!raw) return '暂无详情'
|
||||
return correctPowerNotifyText(raw)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { onShow, onUnload } from '@dcloudio/uni-app'
|
||||
import { computed, ref } from 'vue'
|
||||
import { fetchHomeList, getHomeId } from '@/api/home'
|
||||
import {
|
||||
fetchMessagePage,
|
||||
markAllMessagesRead,
|
||||
@@ -7,6 +8,7 @@ import {
|
||||
} from '@/api/message'
|
||||
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { sameId } from '@/utils/device-id'
|
||||
import { onMessagePush } from '@/utils/message-socket'
|
||||
import {
|
||||
clearPushCache,
|
||||
@@ -15,42 +17,108 @@ import {
|
||||
rememberPushPayload,
|
||||
} from '@/utils/message-push-cache'
|
||||
import type { AppMessageVo } from '@/types/message'
|
||||
import type { AppHomeVo } from '@/types/location'
|
||||
import {
|
||||
formatNotifyContent,
|
||||
formatNotifyLocation,
|
||||
formatNotifyTime,
|
||||
isUnreadMessage,
|
||||
messageMatchesHome,
|
||||
normalizeMessageId,
|
||||
} from './notify.utils'
|
||||
|
||||
export interface NotifyListRow {
|
||||
id: string
|
||||
raw: AppMessageVo
|
||||
title: string
|
||||
timeText: string
|
||||
locationText: string
|
||||
content: string
|
||||
unread: boolean
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
const ALL_HOMES_ID = ''
|
||||
|
||||
export function useNotify() {
|
||||
const messages = ref<AppMessageVo[]>([])
|
||||
const homes = ref<AppHomeVo[]>([])
|
||||
const selectedHomeId = ref(ALL_HOMES_ID)
|
||||
const homePickerOpen = ref(false)
|
||||
const loading = ref(false)
|
||||
const refreshing = ref(false)
|
||||
const loadingMore = ref(false)
|
||||
const pageNum = ref(1)
|
||||
const total = ref(0)
|
||||
const sectionTitle = ref('全部家庭')
|
||||
|
||||
const hasMore = computed(() => messages.value.length < total.value)
|
||||
|
||||
const selectedHome = computed(() =>
|
||||
homes.value.find((home) => sameId(getHomeId(home), selectedHomeId.value)),
|
||||
)
|
||||
|
||||
const selectedHomeLabel = computed(() => {
|
||||
if (!selectedHomeId.value) return '全部家庭'
|
||||
return selectedHome.value?.homeName?.trim() || '我的家'
|
||||
})
|
||||
|
||||
const unreadCount = computed(
|
||||
() => messages.value.filter((item) => isUnreadMessage(item)).length,
|
||||
)
|
||||
|
||||
const unreadCountText = computed(() => `${unreadCount.value}条未读`)
|
||||
|
||||
const messageRows = computed<NotifyListRow[]>(() =>
|
||||
messages.value.map((item) => {
|
||||
const id = normalizeMessageId(item) || `${item.title}-${item.timestamp}`
|
||||
return {
|
||||
id,
|
||||
raw: item,
|
||||
title: item.deviceName || item.title || '系统通知',
|
||||
timeText: formatNotifyTime(item),
|
||||
locationText: formatNotifyLocation(item),
|
||||
content: formatNotifyContent(item),
|
||||
unread: isUnreadMessage(item),
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
let unsubscribePush: (() => void) | null = null
|
||||
|
||||
async function loadHomes() {
|
||||
try {
|
||||
homes.value = await fetchHomeList() ?? []
|
||||
} catch {
|
||||
homes.value = []
|
||||
}
|
||||
}
|
||||
|
||||
function filterMessagesForHome(rows: AppMessageVo[]): AppMessageVo[] {
|
||||
if (!selectedHomeId.value) return rows
|
||||
const homeName = selectedHome.value?.homeName?.trim() || ''
|
||||
return rows.filter((item) => messageMatchesHome(item, selectedHomeId.value, homeName))
|
||||
}
|
||||
|
||||
async function loadMessages(reset = false) {
|
||||
if (loading.value || loadingMore.value) return
|
||||
if (reset) {
|
||||
pageNum.value = 1
|
||||
if (!messages.value.length) {
|
||||
loading.value = true
|
||||
}
|
||||
} else {
|
||||
if (!hasMore.value && messages.value.length > 0) return
|
||||
loadingMore.value = true
|
||||
}
|
||||
|
||||
try {
|
||||
const { rows, total: nextTotal } = await fetchMessagePage({
|
||||
const query = {
|
||||
pageNum: pageNum.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
})
|
||||
const mergedRows = mergeCachedMessages(rows)
|
||||
...(selectedHomeId.value ? { homeId: selectedHomeId.value } : {}),
|
||||
}
|
||||
const { rows, total: nextTotal } = await fetchMessagePage(query)
|
||||
const mergedRows = filterMessagesForHome(mergeCachedMessages(rows))
|
||||
if (reset) {
|
||||
messages.value = mergedRows
|
||||
} else {
|
||||
@@ -62,8 +130,6 @@ export function useNotify() {
|
||||
messages.value = Array.from(map.values())
|
||||
}
|
||||
total.value = Math.max(nextTotal, messages.value.length)
|
||||
const homeName = rows.find((item) => item.homeName)?.homeName
|
||||
if (homeName) sectionTitle.value = homeName
|
||||
if (rows.length > 0) {
|
||||
pageNum.value += 1
|
||||
}
|
||||
@@ -75,12 +141,38 @@ export function useNotify() {
|
||||
}
|
||||
}
|
||||
|
||||
async function onRefresh() {
|
||||
function toggleHomePicker() {
|
||||
homePickerOpen.value = !homePickerOpen.value
|
||||
}
|
||||
|
||||
function closeHomePicker() {
|
||||
homePickerOpen.value = false
|
||||
}
|
||||
|
||||
async function onSelectHome(homeId: string) {
|
||||
if (sameId(selectedHomeId.value, homeId)) {
|
||||
closeHomePicker()
|
||||
return
|
||||
}
|
||||
selectedHomeId.value = homeId
|
||||
closeHomePicker()
|
||||
await loadMessages(true)
|
||||
await refreshUnreadMessageCount()
|
||||
}
|
||||
|
||||
async function onRefresh() {
|
||||
if (refreshing.value) return
|
||||
refreshing.value = true
|
||||
try {
|
||||
await loadMessages(true)
|
||||
await refreshUnreadMessageCount()
|
||||
} finally {
|
||||
refreshing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function onLoadMore() {
|
||||
if (loadingMore.value || !hasMore.value) return
|
||||
await loadMessages(false)
|
||||
}
|
||||
|
||||
@@ -125,6 +217,9 @@ export function useNotify() {
|
||||
const incoming = rememberPushPayload(payload)
|
||||
if (!incoming) return
|
||||
|
||||
const homeName = selectedHome.value?.homeName?.trim() || ''
|
||||
if (!messageMatchesHome(incoming, selectedHomeId.value, homeName)) return
|
||||
|
||||
const incomingId = normalizeMessageId(incoming)
|
||||
const exists = messages.value.some((item) => normalizeMessageId(item) === incomingId)
|
||||
if (exists) return
|
||||
@@ -133,12 +228,20 @@ export function useNotify() {
|
||||
total.value = messages.value.length
|
||||
}
|
||||
|
||||
function isHomeOptionActive(home: AppHomeVo): boolean {
|
||||
return sameId(getHomeId(home), selectedHomeId.value)
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
unsubscribePush?.()
|
||||
unsubscribePush = onMessagePush((payload) => {
|
||||
prependPushMessage(payload)
|
||||
})
|
||||
void onRefresh()
|
||||
void loadHomes()
|
||||
void (async () => {
|
||||
await loadMessages(true)
|
||||
await refreshUnreadMessageCount()
|
||||
})()
|
||||
})
|
||||
|
||||
onUnload(() => {
|
||||
@@ -148,15 +251,25 @@ export function useNotify() {
|
||||
|
||||
return {
|
||||
messages,
|
||||
messageRows,
|
||||
homes,
|
||||
selectedHomeId,
|
||||
selectedHomeLabel,
|
||||
homePickerOpen,
|
||||
unreadCountText,
|
||||
loading,
|
||||
refreshing,
|
||||
loadingMore,
|
||||
hasMore,
|
||||
sectionTitle,
|
||||
formatNotifyTime,
|
||||
isUnreadMessage,
|
||||
toggleHomePicker,
|
||||
closeHomePicker,
|
||||
onSelectHome,
|
||||
isHomeOptionActive,
|
||||
onRefresh,
|
||||
onLoadMore,
|
||||
onItemTap,
|
||||
onMarkAllRead,
|
||||
allHomesId: ALL_HOMES_ID,
|
||||
parseHomeId: getHomeId,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
<template>
|
||||
<view v-if="visible" class="cancel-account-dialog">
|
||||
<view class="cancel-account-dialog__mask" @tap="onCancel" />
|
||||
<view class="cancel-account-dialog__panel" @tap.stop>
|
||||
<text class="cancel-account-dialog__title">注销账号</text>
|
||||
<view class="cancel-account-dialog__body">
|
||||
<text class="cancel-account-dialog__warn">
|
||||
注销后账号及所有数据将被永久删除,且无法恢复,请谨慎操作。
|
||||
</text>
|
||||
<text class="cancel-account-dialog__item">· 已绑定的智能设备将全部解绑</text>
|
||||
<text class="cancel-account-dialog__item">· 家庭、订单及客服记录将无法找回</text>
|
||||
<text class="cancel-account-dialog__item">· 注销完成后需重新注册才能使用</text>
|
||||
</view>
|
||||
<view class="cancel-account-dialog__footer">
|
||||
<view class="cancel-account-dialog__btn" @tap.stop="onCancel">
|
||||
<text class="cancel-account-dialog__btn-text">我再想想</text>
|
||||
</view>
|
||||
<view class="cancel-account-dialog__divider-v" />
|
||||
<view
|
||||
class="cancel-account-dialog__btn"
|
||||
:class="{ 'cancel-account-dialog__btn--disabled': !canConfirm }"
|
||||
@tap.stop="onConfirm"
|
||||
>
|
||||
<text
|
||||
class="cancel-account-dialog__btn-text cancel-account-dialog__btn-text--danger"
|
||||
:class="{ 'cancel-account-dialog__btn-text--disabled': !canConfirm }"
|
||||
>
|
||||
{{ confirmText }}
|
||||
</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onUnmounted, ref, watch } from 'vue'
|
||||
|
||||
const COUNTDOWN_SECONDS = 10
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:visible': [value: boolean]
|
||||
confirm: []
|
||||
}>()
|
||||
|
||||
const countdown = ref(COUNTDOWN_SECONDS)
|
||||
let timer: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
const canConfirm = computed(() => countdown.value <= 0)
|
||||
|
||||
const confirmText = computed(() =>
|
||||
canConfirm.value ? '确认注销' : `确认注销(${countdown.value}s)`,
|
||||
)
|
||||
|
||||
function clearTimer() {
|
||||
if (timer) clearInterval(timer)
|
||||
timer = undefined
|
||||
}
|
||||
|
||||
function startCountdown() {
|
||||
clearTimer()
|
||||
countdown.value = COUNTDOWN_SECONDS
|
||||
timer = setInterval(() => {
|
||||
if (countdown.value <= 1) {
|
||||
countdown.value = 0
|
||||
clearTimer()
|
||||
return
|
||||
}
|
||||
countdown.value -= 1
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(visible) => {
|
||||
if (visible) startCountdown()
|
||||
else clearTimer()
|
||||
},
|
||||
)
|
||||
|
||||
onUnmounted(clearTimer)
|
||||
|
||||
function onCancel() {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
function onConfirm() {
|
||||
if (!canConfirm.value) return
|
||||
emit('confirm')
|
||||
emit('update:visible', false)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.cancel-account-dialog {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 500;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.cancel-account-dialog__mask {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
|
||||
.cancel-account-dialog__panel {
|
||||
position: relative;
|
||||
width: 600rpx;
|
||||
background: #fff;
|
||||
border-radius: 24rpx;
|
||||
overflow: hidden;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.cancel-account-dialog__title {
|
||||
display: block;
|
||||
padding: 48rpx 40rpx 24rpx;
|
||||
font-size: 34rpx;
|
||||
font-weight: 600;
|
||||
color: $color-text;
|
||||
text-align: center;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.cancel-account-dialog__body {
|
||||
padding: 0 40rpx 40rpx;
|
||||
}
|
||||
|
||||
.cancel-account-dialog__warn {
|
||||
display: block;
|
||||
margin-bottom: 20rpx;
|
||||
font-size: 28rpx;
|
||||
color: #f04438;
|
||||
line-height: 1.6;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.cancel-account-dialog__item {
|
||||
display: block;
|
||||
font-size: 26rpx;
|
||||
color: $color-text-secondary;
|
||||
line-height: 1.65;
|
||||
text-align: left;
|
||||
margin-bottom: 10rpx;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.cancel-account-dialog__footer {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
border-top: 1rpx solid #ebedf0;
|
||||
}
|
||||
|
||||
.cancel-account-dialog__btn {
|
||||
flex: 1;
|
||||
height: 96rpx;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&--disabled {
|
||||
opacity: 0.45;
|
||||
}
|
||||
}
|
||||
|
||||
.cancel-account-dialog__divider-v {
|
||||
width: 1rpx;
|
||||
background: #ebedf0;
|
||||
}
|
||||
|
||||
.cancel-account-dialog__btn-text {
|
||||
font-size: 30rpx;
|
||||
color: $color-text;
|
||||
line-height: 1;
|
||||
|
||||
&--danger {
|
||||
color: #f04438;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
&--disabled {
|
||||
color: #98a2b3;
|
||||
font-weight: 400;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +1,8 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="privacy-page">
|
||||
<app-navbar title="账号与安全" />
|
||||
|
||||
<scroll-view class="privacy-page__scroll" scroll-y>
|
||||
<page-scroll-view class="privacy-page__scroll">
|
||||
<view class="privacy-page__body">
|
||||
<view
|
||||
v-for="section in sections"
|
||||
@@ -54,15 +54,27 @@
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</page-scroll-view>
|
||||
|
||||
<cancel-account-dialog
|
||||
v-model:visible="cancelAccountDialogVisible"
|
||||
@confirm="onConfirmCancelAccount"
|
||||
/>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { staticAssets } from '@/utils/static-assets'
|
||||
import CancelAccountDialog from './components/cancel-account-dialog/index.vue'
|
||||
import { usePrivacy } from './use-privacy'
|
||||
|
||||
const { sections, onItemTap, onLogout } = usePrivacy()
|
||||
const {
|
||||
sections,
|
||||
cancelAccountDialogVisible,
|
||||
onItemTap,
|
||||
onLogout,
|
||||
onConfirmCancelAccount,
|
||||
} = usePrivacy()
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@@ -6,8 +6,7 @@
|
||||
}
|
||||
|
||||
.privacy-page__scroll {
|
||||
flex: 1;
|
||||
height: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.privacy-page__body {
|
||||
|
||||
@@ -3,8 +3,18 @@ import { computed, ref } from 'vue'
|
||||
import { cancelAccount, logout } from '@/api/auth'
|
||||
import { fetchProfile } from '@/api/profile'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import {
|
||||
beginVoluntaryLogout,
|
||||
endVoluntaryLogout,
|
||||
} from '@/utils/auth-session'
|
||||
import { teardownMessageInbox } from '@/hooks/use-message-inbox'
|
||||
import { clearStoredToken } from '@/utils/auth-token'
|
||||
import { clearLocalUserData } from '@/utils/clear-local-user-data'
|
||||
import { clearAppFileCacheOnDevice } from '@/pages/mine/storage/storage.utils'
|
||||
import {
|
||||
adoptPendingPasswordModifiedForUser,
|
||||
formatPasswordModifiedDesc,
|
||||
getPasswordModifiedAt,
|
||||
} from '@/utils/password-modified-at'
|
||||
import type { PrivacySection } from './privacy.types'
|
||||
|
||||
function maskPhone(phone?: string): string {
|
||||
@@ -15,6 +25,9 @@ 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)
|
||||
|
||||
const sections = computed<PrivacySection[]>(() => [
|
||||
{
|
||||
@@ -24,7 +37,7 @@ export function usePrivacy() {
|
||||
{
|
||||
id: 'password',
|
||||
title: '登录密码',
|
||||
desc: '上次修改:30天前',
|
||||
desc: formatPasswordModifiedDesc(passwordModifiedAt.value),
|
||||
},
|
||||
{
|
||||
id: 'phone',
|
||||
@@ -51,8 +64,12 @@ export function usePrivacy() {
|
||||
try {
|
||||
const profile = await fetchProfile()
|
||||
phone.value = profile?.phonenumber || profile?.userName || ''
|
||||
const boundPhone = profile?.phonenumber || profile?.userName || ''
|
||||
passwordModifiedAt.value = getPasswordModifiedAt(profile?.userId)
|
||||
?? adoptPendingPasswordModifiedForUser(profile?.userId ?? '', boundPhone)
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '加载账号信息失败'), icon: 'none' })
|
||||
passwordModifiedAt.value = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,26 +83,33 @@ export function usePrivacy() {
|
||||
return
|
||||
}
|
||||
if (itemId === 'delete-account') {
|
||||
uni.showModal({
|
||||
title: '注销账号',
|
||||
content: '注销后账号及所有数据将被永久删除,且无法恢复。确定继续吗?',
|
||||
confirmColor: '#f04438',
|
||||
success: (res) => {
|
||||
if (!res.confirm) return
|
||||
void (async () => {
|
||||
cancelAccountDialogVisible.value = true
|
||||
}
|
||||
}
|
||||
|
||||
async function onConfirmCancelAccount() {
|
||||
if (cancelingAccount.value) return
|
||||
cancelingAccount.value = true
|
||||
beginVoluntaryLogout()
|
||||
try {
|
||||
await cancelAccount()
|
||||
teardownMessageInbox()
|
||||
clearStoredToken()
|
||||
await cancelAccount()
|
||||
clearLocalUserData()
|
||||
try {
|
||||
await clearAppFileCacheOnDevice()
|
||||
} catch {
|
||||
// 非 App 或清理失败不阻断注销流程
|
||||
}
|
||||
uni.showToast({ title: '账号已注销', icon: 'success' })
|
||||
uni.reLaunch({ url: '/pages/login/index' })
|
||||
} catch (err) {
|
||||
endVoluntaryLogout()
|
||||
uni.showToast({ title: getErrorMessage(err, '注销失败'), icon: 'none' })
|
||||
} finally {
|
||||
cancelingAccount.value = false
|
||||
}
|
||||
})()
|
||||
},
|
||||
})
|
||||
}
|
||||
// 成功跳转后稍后再关,避免在途 401 仍弹「登录状态异常」
|
||||
setTimeout(() => endVoluntaryLogout(), 1500)
|
||||
}
|
||||
|
||||
function onLogout() {
|
||||
@@ -95,17 +119,19 @@ export function usePrivacy() {
|
||||
success: (res) => {
|
||||
if (!res.confirm) return
|
||||
void (async () => {
|
||||
beginVoluntaryLogout()
|
||||
try {
|
||||
// 先停消息通道,避免 logout 后在途请求 401 误报
|
||||
teardownMessageInbox()
|
||||
try {
|
||||
await logout()
|
||||
} catch (err) {
|
||||
uni.showToast({
|
||||
title: getErrorMessage(err, '退出登录失败'),
|
||||
icon: 'none',
|
||||
})
|
||||
} finally {
|
||||
teardownMessageInbox()
|
||||
clearStoredToken()
|
||||
} catch {
|
||||
// 服务端退出失败仍清本地登录态
|
||||
}
|
||||
clearLocalUserData()
|
||||
uni.reLaunch({ url: '/pages/login/index' })
|
||||
} finally {
|
||||
setTimeout(() => endVoluntaryLogout(), 1500)
|
||||
}
|
||||
})()
|
||||
},
|
||||
@@ -118,7 +144,9 @@ export function usePrivacy() {
|
||||
|
||||
return {
|
||||
sections,
|
||||
cancelAccountDialogVisible,
|
||||
onItemTap,
|
||||
onLogout,
|
||||
onConfirmCancelAccount,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<template>
|
||||
<template>
|
||||
<view class="set-password-page">
|
||||
<app-navbar title="设置新密码" />
|
||||
<view class="set-password-page__body">
|
||||
@@ -9,7 +9,7 @@
|
||||
<base-input v-model="confirmPassword" icon="lock" type="password" placeholder="确认密码" />
|
||||
</view>
|
||||
|
||||
<text class="set-password-page__hint">8-20位字符,须包含字母、数字、符号中的至少2种。</text>
|
||||
<text class="set-password-page__hint">{{ passwordRuleHint }}</text>
|
||||
|
||||
<view class="set-password-page__btn">
|
||||
<primary-button text="确认修改" @click="submit" />
|
||||
@@ -23,8 +23,11 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { PASSWORD_RULE_HINT } from '@/utils/validate'
|
||||
import { useSetPassword } from './use-set-password'
|
||||
|
||||
const passwordRuleHint = `${PASSWORD_RULE_HINT}。`
|
||||
|
||||
const { password, confirmPassword, onForgotPassword, submit } = useSetPassword()
|
||||
</script>
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user