Compare commits

...

9 Commits

Author SHA1 Message Date
李伊帆
d574565fb3 feat:更新页面内容 2026-11-05 13:54:05 +08:00
李伊帆
2ec91cca26 feat:最新 2026-11-02 08:14:48 +08:00
李伊帆
98402548eb fix:蓝牙bug解决 2026-10-29 10:09:43 +08:00
李伊帆
91bca314ba fix:bug解决 2026-10-28 10:36:39 +08:00
李伊帆
c369127166 fix:蓝牙同步名称报错解决 2026-10-23 11:13:26 +08:00
李伊帆
c288d6914e fix:修改客服报错问题 2026-10-23 11:09:37 +08:00
李伊帆
28531c8120 fix:最新 2026-10-23 10:26:54 +08:00
李伊帆
e4276b0853 fix:最新版本 2026-10-21 17:09:53 +08:00
李伊帆
83a1e961ea fix:客服上传图片及接受问题修复 2026-10-20 14:35:39 +08:00
205 changed files with 10090 additions and 2728 deletions

View File

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

View File

@@ -1,4 +1,5 @@
# 接口根地址(App / 小程序 / H5 直连) # 接口根地址(App / 小程序 / H5 直连)
# 正式打包读 .env.production;未配置时 src/config/app-env.ts 有兜底地址
VITE_API_BASE_URL=http://192.168.0.222:8082 VITE_API_BASE_URL=http://192.168.0.222:8082
# H5 开发:BASE_URL 留空时可走 vite 代理 /app # H5 开发:BASE_URL 留空时可走 vite 代理 /app
@@ -10,6 +11,12 @@ VITE_API_PROXY_TARGET=http://192.168.0.222:8082
# 消息推送 WebSocket(不含 token,连接时自动拼接 ?token=) # 消息推送 WebSocket(不含 token,连接时自动拼接 ?token=)
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message 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 代理,可不配此项) # 在线客服 WebSocket(App/小程序直连;H5 开发默认走 Vite 代理,可不配此项)
# VITE_CS_CHAT_WS_URL=ws://192.168.0.222:8082/app/cs/chat # VITE_CS_CHAT_WS_URL=ws://192.168.0.222:8082/app/cs/chat
# H5 仍要直连内网 IP 时设为 true(如客服 WS 只在 212 上) # 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_NOTIFY_CHAR_UUID=0000fff1-0000-1000-8000-00805f9b34fb
# VITE_BLE_DEBUG=true # VITE_BLE_DEBUG=true
# 腾讯地图 Key(可选,用于拖动地图后逆地理编码显示详细地址) # BLE 广播名前缀(完整格式:Z2_A_<12位MAC>,默认 Z2_A_)
# VITE_BLE_DEVICE_NAME_PREFIX=Z2_A_
# 腾讯地图 Key(可选,旧版逆地理编码)
# VITE_TENCENT_MAP_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
View 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

File diff suppressed because it is too large Load Diff

View File

@@ -37,34 +37,35 @@
"type-check": "vue-tsc --noEmit" "type-check": "vue-tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@dcloudio/uni-app": "3.0.0-5020420260813003", "@dcloudio/uni-app": "3.0.0-5020620260917001",
"@dcloudio/uni-app-harmony": "3.0.0-5020420260813003", "@dcloudio/uni-app-harmony": "3.0.0-5020620260917001",
"@dcloudio/uni-app-plus": "3.0.0-5020420260813003", "@dcloudio/uni-app-plus": "3.0.0-5020620260917001",
"@dcloudio/uni-components": "3.0.0-5020420260813003", "@dcloudio/uni-components": "3.0.0-5020620260917001",
"@dcloudio/uni-h5": "3.0.0-5020420260813003", "@dcloudio/uni-h5": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-alipay": "3.0.0-5020420260813003", "@dcloudio/uni-mp-alipay": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-baidu": "3.0.0-5020420260813003", "@dcloudio/uni-mp-baidu": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-harmony": "3.0.0-5020420260813003", "@dcloudio/uni-mp-harmony": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-jd": "3.0.0-5020420260813003", "@dcloudio/uni-mp-jd": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-kuaishou": "3.0.0-5020420260813003", "@dcloudio/uni-mp-kuaishou": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-lark": "3.0.0-5020420260813003", "@dcloudio/uni-mp-lark": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-qq": "3.0.0-5020420260813003", "@dcloudio/uni-mp-qq": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-toutiao": "3.0.0-5020420260813003", "@dcloudio/uni-mp-toutiao": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003", "@dcloudio/uni-mp-weixin": "3.0.0-5020620260917001",
"@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003", "@dcloudio/uni-mp-xhs": "3.0.0-5020620260917001",
"@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003", "@dcloudio/uni-quickapp-webview": "3.0.0-5020620260917001",
"element-china-area-data": "^6.1.0", "element-china-area-data": "^6.1.0",
"vue": "^3.4.21", "vue": "3.4.21",
"vue-i18n": "^9.1.9" "vue-i18n": "9.14.5"
}, },
"devDependencies": { "devDependencies": {
"@dcloudio/types": "^3.4.8", "@dcloudio/types": "3.4.31",
"@dcloudio/uni-automator": "3.0.0-5020420260813003", "@dcloudio/uni-automator": "3.0.0-5020620260917001",
"@dcloudio/uni-cli-shared": "3.0.0-5020420260813003", "@dcloudio/uni-cli-shared": "3.0.0-5020620260917001",
"@dcloudio/uni-stacktracey": "3.0.0-5020420260813003", "@dcloudio/uni-stacktracey": "3.0.0-5020620260917001",
"@dcloudio/vite-plugin-uni": "3.0.0-5020420260813003", "@dcloudio/vite-plugin-uni": "3.0.0-5020620260917001",
"@vue/runtime-core": "^3.4.21", "@vue/runtime-core": "3.5.44",
"@vue/tsconfig": "^0.1.3", "@vue/tsconfig": "^0.1.3",
"rollup": "4.14.3",
"sass": "^1.105.1", "sass": "^1.105.1",
"typescript": "^4.9.4", "typescript": "^4.9.4",
"vite": "5.2.8", "vite": "5.2.8",

View File

@@ -1,12 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { onLaunch, onShow } from '@dcloudio/uni-app' import { onLaunch, onShow } from '@dcloudio/uni-app'
import { setupMessageInbox } from '@/hooks/use-message-inbox' import { setupMessageInbox } from '@/hooks/use-message-inbox'
import { import { ensureLoggedInOnForeground, LOGIN_ROUTE } from '@/utils/auth-session'
connectMessageSocket,
isMessageSocketConnected,
isMessageSocketConnecting,
} from '@/utils/message-socket'
import { getStoredToken } from '@/utils/auth-token' import { getStoredToken } from '@/utils/auth-token'
import { installLocalizedToast } from '@/utils/localized-toast'
import { staticAssets } from '@/utils/static-assets' import { staticAssets } from '@/utils/static-assets'
function applyH5Favicon() { function applyH5Favicon() {
@@ -25,18 +22,26 @@ function applyH5Favicon() {
// #endif // #endif
} }
onLaunch(() => { function bootstrapAuthRoute() {
applyH5Favicon()
if (getStoredToken()) { if (getStoredToken()) {
setupMessageInbox() setupMessageInbox()
return
} }
uni.reLaunch({ url: LOGIN_ROUTE })
}
onLaunch(() => {
installLocalizedToast()
applyH5Favicon()
bootstrapAuthRoute()
}) })
onShow(() => { onShow(() => {
if (!getStoredToken()) return if (getStoredToken()) {
if (!isMessageSocketConnected() && !isMessageSocketConnecting()) { setupMessageInbox()
connectMessageSocket() return
} }
ensureLoggedInOnForeground()
}) })
</script> </script>
<style lang="scss"> <style lang="scss">

93
src/api/cs-auth.ts Normal file
View 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)
}
}

View File

@@ -1,17 +1,31 @@
import { request } from '@/api/request' import { request } from '@/api/request'
import type { AppHomeVo, UpdateHomeBody } from '@/types/location'
import { parseId, sameId } from '@/utils/device-id' 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 — 查询当前用户的家庭列表 */ /** GET /app/home/list — 查询当前用户的家庭列表 */
export async function fetchHomeList() {
const data = await request<AppHomeVo[] | { rows?: AppHomeVo[] }>({
url: '/app/home/list', url: '/app/home/list',
method: 'GET', method: 'GET',
}) })
return normalizeHomeList(data)
} }
/** POST /app/home/create — 创建家庭(返回 RVoid,需再拉列表取 ID) */ /** POST /app/home/create — 创建家庭(返回 RVoid,需再拉列表取 ID) */
export function createHome(data: UpdateHomeBody) {
return request<void>({ return request<void>({
url: '/app/home/create', url: '/app/home/create',
method: 'POST', 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 { function isDefaultHome(home: AppHomeVo): boolean {
const value = home.isDefault const value = home.isDefault
return value === '1' || value === 1 || value === true 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 { 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) { 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)) let defaultId = getHomeId(pickDefaultHome(list))
if (defaultId) return defaultId if (defaultId) return defaultId
return homes.find(isDefaultHome) ?? homes[0] try {
await createHome(buildUpdateHomeBody('我的家'))
} catch {
// 可能已存在同名家庭,继续拉列表取 ID
}
list = await fetchHomeList() list = await fetchHomeList()
defaultId = getHomeId(pickDefaultHome(list)) defaultId = getHomeId(pickDefaultHome(list))
return defaultId return defaultId

View File

@@ -1,10 +1,5 @@
import { API_CLIENT_ID, request } from '@/api/request' import { request, uploadAppFile } from '@/api/request'
import type { ApiResponse } from '@/types/api'
import type { AppUserProfileVo, AvatarUploadVo, UpdateProfileBo } from '@/types/profile' 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 — 获取当前用户资料 */ /** GET /app/profile — 获取当前用户资料 */
export function fetchProfile() { export function fetchProfile() {
@@ -25,37 +20,5 @@ export function updateProfile(data: UpdateProfileBo) {
/** POST /app/profile/avatar — 上传用户头像 */ /** POST /app/profile/avatar — 上传用户头像 */
export function uploadProfileAvatar(filePath: string): Promise<AvatarUploadVo> { export function uploadProfileAvatar(filePath: string): Promise<AvatarUploadVo> {
return new Promise((resolve, reject) => { return uploadAppFile<AvatarUploadVo>('/app/profile/avatar', filePath, 'file')
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 || '上传失败'))
},
})
})
} }

View File

@@ -1,30 +1,54 @@
import type { ApiResponse } from '@/types/api' import type { ApiResponse } from '@/types/api'
import { extractAuthToken, getStoredToken, saveStoredToken } from '@/utils/auth-token' import {
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error' 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/小程序使用完整后端地址 */ /** RuoYi-Vue-Plus App 端 clientId(登录等 JSON 接口) */
function resolveBaseUrl(): string { export const API_CLIENT_ID = getApiClientId()
const envUrl = import.meta.env.VITE_API_BASE_URL ?? ''
// #ifdef H5
if (import.meta.env.DEV) return ''
// #endif
return envUrl
}
const BASE_URL = resolveBaseUrl() /** 文件上传 clientId(与 Postman /app/cs/upload 一致) */
/** RuoYi-Vue-Plus App 端 clientId(请求头 clientid,与 Postman 一致) */ export const UPLOAD_CLIENT_ID = getUploadClientId()
export const API_CLIENT_ID =
import.meta.env.VITE_API_CLIENT_ID || '428a8310cd442757ae699df5d894f051'
/** 将响应 JSON 中的 int64 主键字段转为字符串,避免 JS 精度丢失 */ /** 将响应 JSON 中的 int64 主键字段转为字符串,避免 JS 精度丢失 */
function parseJsonPreserveIdFields(text: string): unknown { function parseJsonPreserveIdFields(text: string): unknown {
const safe = text.replace( 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"', '"$1":"$2"',
) )
return JSON.parse(safe) 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 { function parseResponseBody(data: unknown): unknown {
if (typeof data === 'string') { if (typeof data === 'string') {
if (!data) return {} if (!data) return {}
@@ -41,37 +65,328 @@ export interface RequestOptions extends Omit<UniApp.RequestOptions, 'url'> {
url: string url: string
} }
/** 构建鉴权请求头:clientid + Authorization */ /** 仅 clientId,不带登录 token(忘记密码 / 重置密码等) */
export function buildAuthHeaders(extra?: Record<string, unknown>): Record<string, string> { export function buildPublicHeaders(extra?: Record<string, unknown>): Record<string, string> {
const token = getStoredToken()
return { return {
'Content-Type': 'application/json;charset=UTF-8', 'Content-Type': 'application/json;charset=UTF-8',
clientId: API_CLIENT_ID, clientId: API_CLIENT_ID,
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(extra as Record<string, string> | undefined), ...(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>( function handleSuccess<T>(
res: UniApp.RequestSuccessCallbackResult, res: UniApp.RequestSuccessCallbackResult,
resolve: (value: T) => void, resolve: (value: T) => void,
reject: (reason: ApiError) => void, reject: (reason: ApiError) => void,
saveTokenFromBody = false, saveTokenFromBody = false,
requestPath = '',
) { ) {
if (res.statusCode < 200 || res.statusCode >= 300) { if (res.statusCode < 200 || res.statusCode >= 300) {
const body = parseResponseBody(res.data) as ApiResponse | undefined const body = parseResponseBody(res.data) as ApiResponse | undefined
reject( rejectRequestError(
new ApiError( new ApiError(
body?.msg || body?.message || `请求失败(${res.statusCode})`, body?.msg || body?.message || `请求失败(${res.statusCode})`,
body?.code ?? res.statusCode, body?.code ?? res.statusCode,
), ),
requestPath,
reject,
) )
return return
} }
const body = parseResponseBody(res.data) as ApiResponse<T> & Record<string, unknown> const body = parseResponseBody(res.data) as ApiResponse<T> & Record<string, unknown>
if (!isApiSuccess(body)) { if (!isApiSuccess(body)) {
reject(new ApiError(body.msg || body.message || '请求失败', body.code)) rejectRequestError(
new ApiError(body.msg || body.message || '请求失败', body.code),
requestPath,
reject,
)
return return
} }
@@ -83,32 +398,78 @@ function handleSuccess<T>(
resolve(unwrapApiData<T>(body)) 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) => { return new Promise((resolve, reject) => {
try {
assertRequestUrl(url)
} catch (err) {
reject(new ApiError(err instanceof Error ? err.message : '接口地址未配置'))
return
}
uni.request({ uni.request({
...options, ...options,
url: `${BASE_URL}${options.url}`, url,
header: buildAuthHeaders(options.header), header: buildHeaders(options.header),
dataType: 'text', dataType: 'text',
success: (res) => handleSuccess<T>(res, resolve, reject), success: (res) => handleSuccess<T>(res, resolve, reject, saveTokenFromBody, requestPath),
fail: (err) => { 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 */ /** 登录类接口:从完整响应体提取并保存 token */
export function requestLogin<T = unknown>(options: RequestOptions): Promise<T> { export function requestLogin<T = unknown>(options: RequestOptions): Promise<T> {
const url = `${getApiBaseUrl()}${options.url}`
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try {
assertRequestUrl(url)
} catch (err) {
reject(new ApiError(err instanceof Error ? err.message : '接口地址未配置'))
return
}
uni.request({ uni.request({
...options, ...options,
url: `${BASE_URL}${options.url}`, url,
header: buildAuthHeaders(options.header), header: buildAuthHeaders(options.header),
dataType: 'text', dataType: 'text',
success: (res) => handleSuccess<T>(res, resolve, reject, true), success: (res) => handleSuccess<T>(res, resolve, reject, true, options.url),
fail: (err) => { fail: (err) => {
reject(new ApiError(err.errMsg || '网络异常')) reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg)))
}, },
}) })
}) })

View File

@@ -25,6 +25,8 @@ import { staticAssets } from '@/utils/static-assets'
const props = defineProps<{ const props = defineProps<{
modelValue: boolean modelValue: boolean
/** 勾选前弹出确认;同意才勾选,不同意保持未勾选 */
confirmBeforeAgree?: boolean
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
@@ -32,6 +34,20 @@ const emit = defineEmits<{
}>() }>()
function toggle() { 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) emit('update:modelValue', !props.modelValue)
} }

View 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
View 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):// 或 / 开头`)
}

View 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 }
}

View 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)
})
}

View File

@@ -1,6 +1,9 @@
import { createSSRApp } from "vue"; import { createSSRApp } from "vue";
import App from "./App.vue"; import App from "./App.vue";
import { registerGlobalComponents } from "./plugins/register-global-components"; import { registerGlobalComponents } from "./plugins/register-global-components";
import { installLocalizedToast } from "./utils/localized-toast";
installLocalizedToast();
export function createApp() { export function createApp() {
const app = createSSRApp(App); const app = createSSRApp(App);

View File

@@ -1,8 +1,8 @@
{ {
"name" : "", "name" : "虫子智家",
"appid" : "", "appid" : "__UNI__925D0CC",
"description" : "", "description" : "",
"versionName" : "1.0.0", "versionName" : "1.2.4",
"versionCode" : "100", "versionCode" : "100",
"transformPx" : false, "transformPx" : false,
/* 5+App特有相关 */ /* 5+App特有相关 */
@@ -18,6 +18,9 @@
}, },
/* 模块配置 */ /* 模块配置 */
"modules" : { "modules" : {
"Bluetooth" : {},
"Camera" : {},
"Push" : {},
"Maps" : {} "Maps" : {}
}, },
/* 应用发布信息 */ /* 应用发布信息 */
@@ -50,9 +53,65 @@
] ]
}, },
/* ios打包配置 */ /* ios打包配置 */
"ios" : {}, "ios" : {
"dSYMs" : false
},
/* SDK配置 */ /* SDK配置 */
"sdkConfigs" : {} "sdkConfigs" : {
"maps" : {
"amap" : {
"name" : "amapxzEnK46i",
"appkey_ios" : "7d9a3ca1ef32775dd5cef9b11962ca49",
"appkey_android" : "6b0279ce51355d222b5023c1124f4581"
}
},
"push" : {
"unipush" : {
"version" : "2",
"offline" : false
}
},
"geolocation" : {
"amap" : {
"name" : "",
"__platform__" : [ "ios", "android" ],
"appkey_ios" : "7d9a3ca1ef32775dd5cef9b11962ca49",
"appkey_android" : "6b0279ce51355d222b5023c1124f4581"
}
}
},
"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 +160,8 @@
} }
} }
}, },
"uniStatistics": { "uniStatistics" : {
"enable": false "enable" : false
}, },
"vueVersion" : "3" "vueVersion" : "3"
} }

View File

@@ -6,13 +6,6 @@
} }
}, },
"pages": [ "pages": [
{
"path": "pages/login/index",
"style": {
"navigationStyle": "custom",
"navigationBarTitleText": "登录"
}
},
{ {
"path": "pages/device/index", "path": "pages/device/index",
"style": { "style": {
@@ -20,6 +13,13 @@
"navigationBarTitleText": "设备" "navigationBarTitleText": "设备"
} }
}, },
{
"path": "pages/login/index",
"style": {
"navigationStyle": "custom",
"navigationBarTitleText": "登录"
}
},
{ {
"path": "pages/device/detail/index", "path": "pages/device/detail/index",
"style": { "style": {
@@ -108,7 +108,10 @@
"path": "pages/mine/support/index", "path": "pages/mine/support/index",
"style": { "style": {
"navigationStyle": "custom", "navigationStyle": "custom",
"navigationBarTitleText": "在线客服" "navigationBarTitleText": "在线客服",
"app-plus": {
"softinputMode": "adjustResize"
}
} }
}, },
{ {

View File

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

View File

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

View File

@@ -1,11 +1,22 @@
import { request } from '@/api/request' import { request } from '@/api/request'
import type { ProductOption } from './complete.types' 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() { export function fetchProductOptions() {
return request<ProductOption[]>({ return request<ProductOption[]>({
url: '/app/device/productOptions', url: '/app/device/productOptions',
method: 'POST', method: 'GET',
data: {}, }).then((rows) => (Array.isArray(rows) ? rows.map(normalizeProductOption) : []))
})
} }

View File

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

View File

@@ -1,11 +1,6 @@
/** POST /app/device/productOptions 返回项 */ /** GET /app/device/productOptions — 启用状态产品型号(AppProductOptionVo) */
export interface ProductOption { export interface ProductOption {
productId?: string | number productId?: string | number
model?: string model?: string
name?: string name?: string
category?: string
connectTypes?: string
filterEnabled?: boolean
filterTotalDays?: number
capabilities?: string[]
} }

View File

@@ -1,7 +1,9 @@
<template> <template>
<view class="complete-page"> <view class="complete-page">
<view class="complete-page__top">
<app-navbar title="设备配置" /> <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"> <view class="complete-page__body">
<bind-steps :steps="BIND_STEPS" :current="currentStep" /> <bind-steps :steps="BIND_STEPS" :current="currentStep" />
<complete-success-hero /> <complete-success-hero />
@@ -55,15 +57,11 @@
</view> </view>
<view class="complete-page__field"> <view class="complete-page__field">
<text class="complete-page__label">产品型号</text> <text class="complete-page__label">产品型号</text>
<picker <view
mode="selector" class="complete-page__select-row"
:range="productOptions" hover-class="complete-page__select-row--hover"
range-key="model" @tap.stop="onPickProduct"
:value="productIndex"
:disabled="productOptionsLoading || !productOptions.length"
@change="onProductChange"
> >
<view class="complete-page__select-row">
<text <text
class="complete-page__select-text" class="complete-page__select-text"
:class="{ 'complete-page__select-text--placeholder': !productSelected }" :class="{ 'complete-page__select-text--placeholder': !productSelected }"
@@ -76,7 +74,6 @@
mode="aspectFit" mode="aspectFit"
/> />
</view> </view>
</picker>
</view> </view>
<view class="complete-page__field"> <view class="complete-page__field">
<text class="complete-page__label">所在房间</text> <text class="complete-page__label">所在房间</text>
@@ -112,7 +109,7 @@
</text> </text>
</view> </view>
</view> </view>
</scroll-view> </page-scroll-view>
<view class="complete-page__footer"> <view class="complete-page__footer">
<view <view
class="complete-page__submit" class="complete-page__submit"
@@ -129,7 +126,15 @@
<script setup lang="ts"> <script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
import { staticAssets } from '@/utils/static-assets' 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 BindSteps from '../components/bind-steps/index.vue'
import { BIND_STEPS } from '../use-add-device' import { BIND_STEPS } from '../use-add-device'
import CompleteSuccessHero from './components/complete-success-hero/index.vue' import CompleteSuccessHero from './components/complete-success-hero/index.vue'
@@ -139,8 +144,6 @@ const {
currentStep, currentStep,
deviceName, deviceName,
serialMasked, serialMasked,
productOptions,
productIndex,
productDisplayText, productDisplayText,
productSelected, productSelected,
productOptionsLoading, productOptionsLoading,
@@ -151,7 +154,7 @@ const {
bluetoothConnected, bluetoothConnected,
bluetoothStatusText, bluetoothStatusText,
initPage, initPage,
onProductChange, onPickProduct,
onPickRoom, onPickRoom,
onFinishAdd, onFinishAdd,
} = useCompleteDevice() } = useCompleteDevice()

View File

@@ -1,13 +1,18 @@
import { onShow } from '@dcloudio/uni-app' import { onShow, onUnload } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { resolveValidHomeId } from '@/api/home' import { resolveValidHomeId } from '@/api/home'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { fetchRoomList } from '@/api/location' import { fetchRoomList } from '@/api/location'
import type { RoomOption } from '@/types/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 { 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 { bindDevice } from '../add-device.api'
import { parseId, sameId } from '@/utils/device-id' import { parseId, sameId } from '@/utils/device-id'
import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home'
import { readBindDeviceContext } from '../add-device.types' import { readBindDeviceContext } from '../add-device.types'
import { fetchProductOptions } from './complete.api' import { fetchProductOptions } from './complete.api'
import type { ProductOption } from './complete.types' import type { ProductOption } from './complete.types'
@@ -16,6 +21,8 @@ export function useCompleteDevice() {
const currentStep = 4 const currentStep = 4
const deviceNo = ref('') const deviceNo = ref('')
const deviceName = ref('Z2 空气净化器') const deviceName = ref('Z2 空气净化器')
/** 配对时读到的 BLE 广播名,与用户可改的云端显示名无关 */
const pairedBleName = ref('')
const serialMasked = ref('****A3B2') const serialMasked = ref('****A3B2')
const productId = ref('') const productId = ref('')
const model = ref('') const model = ref('')
@@ -32,6 +39,7 @@ export function useCompleteDevice() {
const loading = ref(false) const loading = ref(false)
const initialized = ref(false) const initialized = ref(false)
const bluetoothConnected = ref(false) const bluetoothConnected = ref(false)
const bleDeviceId = ref('')
const roomSelected = computed(() => !!locationId.value && roomName.value !== '请选择所在房间') const roomSelected = computed(() => !!locationId.value && roomName.value !== '请选择所在房间')
const productSelected = computed(() => !!productId.value && !!model.value) const productSelected = computed(() => !!productId.value && !!model.value)
@@ -135,7 +143,10 @@ export function useCompleteDevice() {
function applyQuery(query: Record<string, string | undefined>) { function applyQuery(query: Record<string, string | undefined>) {
const ctx = readBindDeviceContext(query) const ctx = readBindDeviceContext(query)
if (ctx.deviceNo) deviceNo.value = ctx.deviceNo 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 if (ctx.serialMasked) serialMasked.value = ctx.serialMasked
const parsedProductId = parseId(ctx.productId) const parsedProductId = parseId(ctx.productId)
if (parsedProductId) productId.value = parsedProductId if (parsedProductId) productId.value = parsedProductId
@@ -145,7 +156,10 @@ export function useCompleteDevice() {
} }
if (ctx.imei) imei.value = ctx.imei if (ctx.imei) imei.value = ctx.imei
if (ctx.mac) mac.value = ctx.mac if (ctx.mac) mac.value = ctx.mac
const parsedHomeId = parseId(ctx.homeId)
if (parsedHomeId) homeId.value = parsedHomeId
bluetoothConnected.value = ctx.bluetoothConnected === '1' bluetoothConnected.value = ctx.bluetoothConnected === '1'
if (ctx.bleDeviceId) bleDeviceId.value = ctx.bleDeviceId
if (roomOptions.value.length) { if (roomOptions.value.length) {
syncRoomFromOptions() syncRoomFromOptions()
} }
@@ -153,15 +167,36 @@ export function useCompleteDevice() {
async function initPage(query: Record<string, string | undefined>) { async function initPage(query: Record<string, string | undefined>) {
applyQuery(query) applyQuery(query)
if (!homeId.value) {
homeId.value = readStoredHomeId()
}
await Promise.all([loadRoomOptionList(), loadProductOptions()]) await Promise.all([loadRoomOptionList(), loadProductOptions()])
if (homeId.value) {
saveSelectedHomeId(homeId.value)
}
initialized.value = true initialized.value = true
} }
function onProductChange(event: { detail: { value: number } }) { function onPickProduct() {
const index = Number(event.detail.value) if (productOptionsLoading.value) {
const option = productOptions.value[index] uni.showToast({ title: '产品型号加载中', icon: 'none' })
if (!option) return return
applyProduct(option) }
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() { function onPickRoom() {
@@ -213,8 +248,24 @@ export function useCompleteDevice() {
loading.value = true loading.value = true
try { 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) const validHomeId = await resolveValidHomeId(homeId.value)
homeId.value = validHomeId homeId.value = validHomeId
if (validHomeId) saveSelectedHomeId(validHomeId)
await bindDevice({ await bindDevice({
deviceNo: deviceNo.value.trim(), deviceNo: deviceNo.value.trim(),
name, name,
@@ -226,9 +277,16 @@ export function useCompleteDevice() {
...(locationId.value ? { locationId: locationId.value } : {}), ...(locationId.value ? { locationId: locationId.value } : {}),
}) })
const list = await fetchDeviceList() const list = await fetchAllDeviceList()
const bound = list?.find((item) => item.deviceNo === deviceNo.value.trim()) const bound = list?.find((item) => item.deviceNo === deviceNo.value.trim())
if (bound?.deviceId != null) { if (bound?.deviceId != null) {
const boundName = bound.name?.trim()
if (boundName !== name) {
await updateDeviceSettings({
deviceId: bound.deviceId,
name,
})
}
await updateDeviceRuntime({ await updateDeviceRuntime({
deviceId: bound.deviceId, deviceId: bound.deviceId,
status: bluetoothConnected.value ? '1' : '2', status: bluetoothConnected.value ? '1' : '2',
@@ -248,10 +306,19 @@ export function useCompleteDevice() {
} }
onShow(() => { onShow(() => {
uni.hideLoading()
if (!initialized.value || !homeId.value) return if (!initialized.value || !homeId.value) return
void loadRoomOptionList() void loadRoomOptionList()
}) })
onUnload(() => {
uni.hideLoading()
if (bleDeviceId.value) {
clearZ2BleHandleCache(bleDeviceId.value)
void releaseBleDevice(bleDeviceId.value)
}
})
return { return {
currentStep, currentStep,
deviceName, deviceName,
@@ -268,7 +335,7 @@ export function useCompleteDevice() {
bluetoothConnected, bluetoothConnected,
bluetoothStatusText, bluetoothStatusText,
initPage, initPage,
onProductChange, onPickProduct,
onPickRoom, onPickRoom,
onFinishAdd, onFinishAdd,
} }

View File

@@ -1,7 +1,10 @@
<template> <template>
<view class="add-device-page"> <view class="add-device-page">
<app-navbar title="添加设备" /> <app-navbar title="添加设备" />
<scroll-view class="add-device-page__scroll" scroll-y> <view v-if="checkingBluetooth" class="add-device-page__checking">
<text class="add-device-page__checking-text">正在检测蓝牙…</text>
</view>
<page-scroll-view v-else class="add-device-page__scroll">
<view class="add-device-page__body"> <view class="add-device-page__body">
<bind-steps :steps="BIND_STEPS" :current="currentStep" /> <bind-steps :steps="BIND_STEPS" :current="currentStep" />
<bind-bluetooth-hero /> <bind-bluetooth-hero />
@@ -25,17 +28,41 @@
</view> </view>
</view> </view>
</view> </view>
</scroll-view> </page-scroll-view>
</view> </view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import BindBluetoothHero from './components/bind-bluetooth-hero/index.vue' import BindBluetoothHero from './components/bind-bluetooth-hero/index.vue'
import BindFeatureList from './components/bind-feature-list/index.vue' import BindFeatureList from './components/bind-feature-list/index.vue'
import BindSteps from './components/bind-steps/index.vue' import BindSteps from './components/bind-steps/index.vue'
import { BIND_FEATURES, BIND_STEPS, useAddDevice } from './use-add-device' import { BIND_FEATURES, BIND_STEPS, useAddDevice } from './use-add-device'
const { currentStep, opening, onOpenBluetooth, onBindLater } = useAddDevice() const {
currentStep,
opening,
checkingBluetooth,
applyBindHomeId,
checkBluetoothAndRoute,
onPageShowAfterSettings,
onPageUnload,
onOpenBluetooth,
onBindLater,
} = useAddDevice()
onLoad((query) => {
applyBindHomeId(query?.homeId)
void checkBluetoothAndRoute()
})
onShow(() => {
onPageShowAfterSettings()
})
onUnload(() => {
onPageUnload()
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -1,7 +1,9 @@
<template> <template>
<view class="pair-page"> <view class="pair-page">
<view class="pair-page__top">
<app-navbar title="设备配置" /> <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"> <view class="pair-page__body">
<bind-steps :steps="BIND_STEPS" :current="currentStep" /> <bind-steps :steps="BIND_STEPS" :current="currentStep" />
<pair-hero /> <pair-hero />
@@ -32,8 +34,6 @@
<pair-check-list :items="checkItems" /> <pair-check-list :items="checkItems" />
<pair-device-summary :device="device" :connect-status="connectStatus" /> <pair-device-summary :device="device" :connect-status="connectStatus" />
</view>
</scroll-view>
<view class="pair-page__footer"> <view class="pair-page__footer">
<view <view
v-if="connectStatus === 'failed'" v-if="connectStatus === 'failed'"
@@ -49,11 +49,14 @@
</view> </view>
</view> </view>
</view> </view>
</page-scroll-view>
</view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue' import { computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
import BindSteps from '../components/bind-steps/index.vue' import BindSteps from '../components/bind-steps/index.vue'
import { BIND_STEPS } from '../use-add-device' import { BIND_STEPS } from '../use-add-device'
import { readBindDeviceContext } from '../add-device.types' 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 PairHero from './components/pair-hero/index.vue'
import { usePairDevice } from './use-pair-device' import { usePairDevice } from './use-pair-device'
const { scrollStyle } = usePageScrollHeight({ topSelector: '.pair-page__top' })
const { const {
currentStep, currentStep,
device, device,
@@ -69,6 +74,7 @@ const {
progress, progress,
errorMessage, errorMessage,
checkItems, checkItems,
applyBindHomeId,
applyDevice, applyDevice,
startPairing, startPairing,
onCancelPair, onCancelPair,
@@ -108,6 +114,7 @@ function onFooterCancel() {
onLoad((query) => { onLoad((query) => {
const ctx = readBindDeviceContext(query ?? {}) const ctx = readBindDeviceContext(query ?? {})
applyBindHomeId(ctx.homeId)
applyDevice({ applyDevice({
name: ctx.name ?? '', name: ctx.name ?? '',
serialMasked: ctx.serialMasked ?? '', serialMasked: ctx.serialMasked ?? '',

View File

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

View File

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

View File

@@ -1,13 +1,13 @@
<template> <template>
<view class="scan-page"> <view class="scan-page">
<app-navbar title="扫描设备" /> <app-navbar title="扫描设备" />
<scroll-view class="scan-page__scroll" scroll-y> <page-scroll-view class="scan-page__scroll">
<view class="scan-page__body"> <view class="scan-page__body">
<bind-steps :steps="BIND_STEPS" :current="currentStep" /> <bind-steps :steps="BIND_STEPS" :current="currentStep" />
<scan-hero /> <scan-hero />
<view class="scan-page__status"> <view class="scan-page__status">
<text class="scan-page__title">正在扫描附近设备...</text> <text class="scan-page__title">{{ pageTitle }}</text>
<view class="scan-page__hint"> <view v-if="!bluetoothDisabled" class="scan-page__hint">
<view class="scan-page__hint-dot" /> <view class="scan-page__hint-dot" />
<text class="scan-page__hint-text">{{ statusHint }}</text> <text class="scan-page__hint-text">{{ statusHint }}</text>
</view> </view>
@@ -20,7 +20,18 @@
</text> </text>
</view> </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> <text class="scan-page__empty-text">{{ scanError }}</text>
</view> </view>
<view v-else-if="devices.length === 0" class="scan-page__empty"> <view v-else-if="devices.length === 0" class="scan-page__empty">
@@ -41,12 +52,13 @@
<scan-help-tip /> <scan-help-tip />
</view> </view>
</scroll-view> </page-scroll-view>
</view> </view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue' import { computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import BindSteps from '../components/bind-steps/index.vue' import BindSteps from '../components/bind-steps/index.vue'
import { BIND_STEPS } from '../use-add-device' import { BIND_STEPS } from '../use-add-device'
import ScanDeviceItem from './components/scan-device-item/index.vue' import ScanDeviceItem from './components/scan-device-item/index.vue'
@@ -61,10 +73,22 @@ const {
secondsLeft, secondsLeft,
scanning, scanning,
scanError, scanError,
bluetoothDisabled,
applyBindHomeId,
onRetryScan,
onOpenBluetoothSettings,
onSelectDevice, onSelectDevice,
onDeviceAction, onDeviceAction,
} = useScanDevice() } = useScanDevice()
onLoad((query) => {
applyBindHomeId(query?.homeId)
})
const pageTitle = computed(() =>
bluetoothDisabled.value ? '蓝牙未开启' : '正在扫描附近设备...',
)
const statusHint = computed(() => { const statusHint = computed(() => {
const count = devices.value.length const count = devices.value.length
if (scanning.value) { if (scanning.value) {

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,15 @@
import { ref } from 'vue' import { ref } from 'vue'
import { ensureBluetoothReady, getBluetoothErrorMessage } from '@/utils/bluetooth' import {
assertBluetoothEnabledForScan,
getBluetoothErrorMessage,
isBluetoothApiSupported,
isBluetoothPermissionError,
probeBluetoothEnabledForBind,
promptEnableBluetooth,
subscribeBluetoothAdapterStateChange,
} from '@/utils/bluetooth'
import { parseId } from '@/utils/device-id'
import { readStoredHomeId } from '@/utils/selected-home'
import { staticAssets } from '@/utils/static-assets' import { staticAssets } from '@/utils/static-assets'
import type { BindFeatureItem, BindStepItem } from './add-device.types' import type { BindFeatureItem, BindStepItem } from './add-device.types'
@@ -34,32 +44,147 @@ export const BIND_FEATURES: BindFeatureItem[] = [
export function useAddDevice() { export function useAddDevice() {
const currentStep = 1 const currentStep = 1
const opening = ref(false) const opening = ref(false)
/** 进入页时检测蓝牙,未完成前不闪引导内容 */
const checkingBluetooth = ref(true)
const bindHomeId = ref('')
let routingToScan = false
/** 仅用户去系统设置开启蓝牙后,回页才复检;避免系统弹窗触发 onShow 误跳扫描 */
let awaitingBluetoothSettings = false
let unsubscribeAdapterState: (() => void) | undefined
function applyBindHomeId(homeId?: string | number) {
const parsed = parseId(homeId)
if (parsed) {
bindHomeId.value = parsed
return
}
if (!bindHomeId.value) {
bindHomeId.value = readStoredHomeId()
}
}
function scanPageUrl() {
const q = bindHomeId.value ? `?homeId=${bindHomeId.value}` : ''
return `/pages/add-device/scan/index${q}`
}
function goScanPage(replace = false) {
if (routingToScan) return
routingToScan = true
awaitingBluetoothSettings = false
stopWatchBluetoothOn()
const url = scanPageUrl()
if (replace) {
uni.redirectTo({
url,
fail: () => {
routingToScan = false
uni.navigateTo({ url })
},
})
return
}
uni.navigateTo({
url,
complete: () => {
routingToScan = false
},
})
}
function stopWatchBluetoothOn() {
unsubscribeAdapterState?.()
unsubscribeAdapterState = undefined
}
/** 停留在引导页时监听:用户一开蓝牙立即进扫描 */
function startWatchBluetoothOn() {
if (unsubscribeAdapterState || routingToScan || !isBluetoothApiSupported()) return
unsubscribeAdapterState = subscribeBluetoothAdapterStateChange((res) => {
if (!res.available || routingToScan) return
goScanPage(true)
})
}
/**
* 蓝牙已开则直进扫描页;未开则展示本页引导并开始监听开启事件。
* @param silent 从设置返回时静默复检,不闪「正在检测」
*/
async function checkBluetoothAndRoute(options?: { silent?: boolean }) {
if (routingToScan) return
const silent = Boolean(options?.silent)
if (!silent) checkingBluetooth.value = true
try {
if (!isBluetoothApiSupported()) {
return
}
await probeBluetoothEnabledForBind()
goScanPage(true)
} catch {
// 未开启 / 无权限:停留在引导页,并监听随后开启
startWatchBluetoothOn()
} finally {
if (!silent) checkingBluetooth.value = false
}
}
/** 从系统设置返回时调用:仅在主动去开启后复检;平时靠适配器状态监听即时跳转 */
function onPageShowAfterSettings() {
if (!awaitingBluetoothSettings || checkingBluetooth.value || routingToScan) return
awaitingBluetoothSettings = false
void checkBluetoothAndRoute({ silent: true })
}
async function onOpenBluetooth() { async function onOpenBluetooth() {
if (opening.value) return if (opening.value || routingToScan) return
opening.value = true opening.value = true
try { try {
await ensureBluetoothReady() if (!isBluetoothApiSupported()) {
uni.navigateTo({ url: '/pages/add-device/scan/index' })
} catch (err) {
uni.showModal({ uni.showModal({
title: '无法开启蓝牙', title: '无法使用蓝牙',
content: '当前环境不支持蓝牙,请使用 App 或微信小程序',
showCancel: false,
confirmText: '知道了',
})
return
}
await assertBluetoothEnabledForScan()
goScanPage(false)
} catch (err) {
if (isBluetoothPermissionError(err)) {
uni.showModal({
title: '需要相关权限',
content: getBluetoothErrorMessage(err), content: getBluetoothErrorMessage(err),
showCancel: false, showCancel: false,
confirmText: '知道了', confirmText: '知道了',
}) })
return
}
awaitingBluetoothSettings = true
startWatchBluetoothOn()
promptEnableBluetooth()
} finally { } finally {
opening.value = false opening.value = false
} }
} }
function onBindLater() { function onBindLater() {
stopWatchBluetoothOn()
uni.navigateBack() uni.navigateBack()
} }
function onPageUnload() {
stopWatchBluetoothOn()
}
return { return {
currentStep, currentStep,
opening, opening,
checkingBluetooth,
applyBindHomeId,
checkBluetoothAndRoute,
onPageShowAfterSettings,
onPageUnload,
onOpenBluetooth, onOpenBluetooth,
onBindLater, onBindLater,
} }

View File

@@ -1,14 +1,14 @@
<template> <template>
<view class="agreement-page"> <view class="agreement-page">
<app-navbar :title="title" /> <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 class="agreement-page__content">
<view v-if="loading" class="agreement-page__loading"> <view v-if="loading" class="agreement-page__loading">
<text>加载中...</text> <text>加载中...</text>
</view> </view>
<text v-else class="agreement-page__text">{{ content }}</text> <text v-else class="agreement-page__text">{{ content }}</text>
</view> </view>
</scroll-view> </page-scroll-view>
</view> </view>
</template> </template>
@@ -27,8 +27,7 @@ const { title, content, loading } = useAgreement()
} }
.agreement-page__scroll { .agreement-page__scroll {
flex: 1; width: 100%;
height: calc(100vh - 88rpx);
} }
.agreement-page__content { .agreement-page__content {

View File

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

View File

@@ -7,7 +7,7 @@
<base-input v-model="password" icon="lock" type="password" placeholder="请输入密码" /> <base-input v-model="password" icon="lock" type="password" placeholder="请输入密码" />
<base-input v-model="confirmPassword" 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"> <view class="auth-form-page__btn">
<primary-button text="确认修改" @click="submit" /> <primary-button text="确认修改" @click="submit" />
@@ -17,8 +17,11 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { PASSWORD_RULE_HINT } from '@/utils/validate'
import { useChangePassword } from './use-change-password' import { useChangePassword } from './use-change-password'
const passwordRuleHint = `${PASSWORD_RULE_HINT}。`
const { password, confirmPassword, submit } = useChangePassword() const { password, confirmPassword, submit } = useChangePassword()
</script> </script>

View File

@@ -1,20 +1,39 @@
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error' 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' 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() { export function useChangePassword() {
const password = ref('') const password = ref('')
const confirmPassword = ref('') const confirmPassword = ref('')
const resetToken = ref('') const resetToken = ref('')
const fromPrivacy = ref(false) const boundPhone = ref('')
const loading = ref(false) const loading = ref(false)
onLoad((query) => { onLoad((query) => {
const raw = (query?.resetToken as string) || '' const raw = (query?.resetToken as string) || ''
resetToken.value = raw ? decodeURIComponent(raw) : '' resetToken.value = raw ? decodeURIComponent(raw) : ''
fromPrivacy.value = query?.from === 'privacy' const phoneRaw = (query?.phone as string) || ''
boundPhone.value = phoneRaw ? decodeURIComponent(phoneRaw) : ''
if (!resetToken.value) { if (!resetToken.value) {
uni.showToast({ title: '请先完成验证码校验', icon: 'none' }) uni.showToast({ title: '请先完成验证码校验', icon: 'none' })
setTimeout(() => uni.navigateBack(), 1500) setTimeout(() => uni.navigateBack(), 1500)
@@ -27,10 +46,7 @@ export function useChangePassword() {
return return
} }
if (!isValidStrongPassword(password.value)) { if (!isValidStrongPassword(password.value)) {
uni.showToast({ uni.showToast({ title: PASSWORD_INVALID_TOAST, icon: 'none' })
title: '密码需8-20位,且包含字母、数字、符号中至少2种',
icon: 'none',
})
return return
} }
if (password.value !== confirmPassword.value) { if (password.value !== confirmPassword.value) {
@@ -45,15 +61,14 @@ export function useChangePassword() {
newPassword: password.value, newPassword: password.value,
confirmPassword: confirmPassword.value, confirmPassword: confirmPassword.value,
}) })
uni.showToast({ title: '密码修改成功', icon: 'success' }) recordPasswordModifiedAfterReset(boundPhone.value)
setTimeout(() => { redirectToLoginAfterPasswordChange()
if (fromPrivacy.value) { } catch (err) {
uni.navigateBack({ delta: 2 }) if (isAuthSessionExpiredError(err)) {
recordPasswordModifiedAfterReset(boundPhone.value)
redirectToLoginAfterPasswordChange('登录状态已失效,请使用新密码重新登录')
return return
} }
uni.reLaunch({ url: '/pages/login/index' })
}, 800)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '修改失败,请重试'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '修改失败,请重试'), icon: 'none' })
} finally { } finally {
loading.value = false loading.value = false

View File

@@ -79,8 +79,8 @@ defineEmits<{
.device-empty__btn { .device-empty__btn {
width: 100%; width: 100%;
width: 335px; max-width: 670rpx;
height: 48px; height: 96rpx;
border-radius: 15rpx; border-radius: 15rpx;
display: flex; display: flex;
align-items: center; align-items: center;
@@ -88,7 +88,7 @@ defineEmits<{
position: relative; position: relative;
flex-shrink: 0; flex-shrink: 0;
background: linear-gradient(98deg, #45d685 0%, #21c25e 100%); 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 { .device-empty__btn-text {

View File

@@ -21,22 +21,37 @@
v-if="pickerOpen" v-if="pickerOpen"
class="device-header__mask" class="device-header__mask"
@tap="closePicker" @tap="closePicker"
@touchmove.stop.prevent="preventTouchMove"
/> />
<view v-if="pickerOpen" class="device-header__dropdown"> <view v-if="pickerOpen" class="device-header__dropdown">
<view <scroll-view
class="device-header__option device-header__option--active" class="device-header__dropdown-scroll"
@tap.stop="selectHome" scroll-y
:show-scrollbar="false"
:style="dropdownScrollStyle"
> >
<text class="device-header__option-text device-header__option-text--active"> <view
{{ homeName }} 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> </text>
<image <image
v-if="isActiveHome(home)"
class="device-header__check-icon" class="device-header__check-icon"
:src="staticAssets.iconHomeSelected" :src="staticAssets.iconHomeSelected"
mode="aspectFit" mode="aspectFit"
/> />
</view> </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> <text class="device-header__option-text">家庭管理</text>
</view> </view>
</view> </view>
@@ -72,12 +87,16 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { computed, ref, watch } from 'vue'
import { hasUnreadMessages } from '@/hooks/use-message-inbox' 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' import { staticAssets } from '@/utils/static-assets'
defineProps<{ const props = defineProps<{
homeName: string homeName: string
homeId: string
homes: AppHomeVo[]
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
@@ -85,12 +104,30 @@ const emit = defineEmits<{
'add-device': [] 'add-device': []
scan: [] scan: []
manage: [] 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 pickerOpen = ref(false)
const addMenuOpen = ref(false) const addMenuOpen = ref(false)
const hasUnreadNotify = hasUnreadMessages const hasUnreadNotify = hasUnreadMessages
watch(pickerOpen, (open) => {
emit('picker-open-change', open)
})
function preventTouchMove() {}
const sys = uni.getSystemInfoSync() const sys = uni.getSystemInfoSync()
const statusBarHeight = sys.statusBarHeight ?? 0 const statusBarHeight = sys.statusBarHeight ?? 0
const headerPaddingTop = const headerPaddingTop =
@@ -107,8 +144,14 @@ function closePicker() {
pickerOpen.value = false 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() closePicker()
emit('select-home', home)
} }
function selectManage() { function selectManage() {
@@ -207,6 +250,13 @@ function onScan() {
background: #fff; background: #fff;
box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1); box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
z-index: 300; z-index: 300;
display: flex;
flex-direction: column;
}
.device-header__dropdown-scroll {
flex-shrink: 0;
width: 100%;
} }
.device-header__option { .device-header__option {
@@ -221,6 +271,10 @@ function onScan() {
background: linear-gradient(98deg, #45d685 0%, #21c25e 100%); background: linear-gradient(98deg, #45d685 0%, #21c25e 100%);
} }
.device-header__option--manage {
border-top: 1rpx solid #f0f0f0;
}
.device-header__option-text { .device-header__option-text {
font-size: 30rpx; font-size: 30rpx;
font-weight: 500; font-weight: 500;

View File

@@ -7,7 +7,6 @@
<text class="device-list__badge-text">{{ onlineCount }} 台在线</text> <text class="device-list__badge-text">{{ onlineCount }} 台在线</text>
</view> </view>
</view> </view>
<text class="device-list__manage" @tap="$emit('manage')">管理 &gt;</text>
</view> </view>
<view class="device-list__grid"> <view class="device-list__grid">
@@ -31,7 +30,6 @@ defineProps<{
}>() }>()
defineEmits<{ defineEmits<{
manage: []
select: [device: DeviceListItem] select: [device: DeviceListItem]
}>() }>()
</script> </script>
@@ -44,7 +42,6 @@ defineEmits<{
.device-list__head { .device-list__head {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between;
margin-bottom: 24rpx; margin-bottom: 24rpx;
} }
@@ -72,11 +69,6 @@ defineEmits<{
line-height: 1; line-height: 1;
} }
.device-list__manage {
font-size: 26rpx;
color: $color-text-secondary;
}
.device-list__grid { .device-list__grid {
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));

View File

@@ -1,97 +0,0 @@
<template>
<view class="hot-devices">
<view class="hot-devices__head">
<text class="hot-devices__title">热门设备</text>
<text class="hot-devices__link" @tap="$emit('mall')">去商城看看 &gt;</text>
</view>
<scroll-view class="hot-devices__scroll" scroll-x :show-scrollbar="false">
<view class="hot-devices__list">
<view v-for="item in items" :key="item.id" class="hot-devices__card">
<view class="hot-devices__img" />
<text class="hot-devices__name">{{ item.name }}</text>
<text class="hot-devices__desc">{{ item.desc }}</text>
</view>
</view>
</scroll-view>
</view>
</template>
<script setup lang="ts">
import type { HotDeviceItem } from '../../device.types'
defineProps<{
items: HotDeviceItem[]
}>()
defineEmits<{
mall: []
}>()
</script>
<style lang="scss" scoped>
.hot-devices {
padding: 0 32rpx 32rpx;
}
.hot-devices__head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 24rpx;
}
.hot-devices__title {
font-size: 32rpx;
font-weight: 600;
color: $color-text;
}
.hot-devices__link {
font-size: 26rpx;
color: $color-text-secondary;
}
.hot-devices__scroll {
width: 100%;
white-space: nowrap;
}
.hot-devices__list {
display: inline-flex;
gap: 24rpx;
padding-bottom: 8rpx;
}
.hot-devices__card {
display: inline-flex;
flex-direction: column;
width: 300rpx;
padding: 24rpx;
background: #fff;
border-radius: 24rpx;
box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.04);
vertical-align: top;
white-space: normal;
}
.hot-devices__img {
width: 100%;
height: 200rpx;
background: linear-gradient(145deg, #f0f2f5 0%, #e8eaed 100%);
border-radius: 16rpx;
margin-bottom: 20rpx;
}
.hot-devices__name {
font-size: 28rpx;
font-weight: 600;
color: $color-text;
margin-bottom: 8rpx;
}
.hot-devices__desc {
font-size: 22rpx;
color: $color-text-secondary;
line-height: 1.4;
}
</style>

View File

@@ -1,5 +1,11 @@
<template> <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 class="room-tabs__inner">
<view <view
v-for="room in rooms" v-for="room in rooms"
@@ -15,6 +21,7 @@
</view> </view>
</view> </view>
</scroll-view> </scroll-view>
</view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -32,22 +39,37 @@ defineEmits<{
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.room-tabs-wrap {
padding: 8rpx 32rpx 24rpx;
box-sizing: border-box;
}
.room-tabs { .room-tabs {
width: 100%; width: 100%;
white-space: nowrap; white-space: nowrap;
padding: 8rpx 32rpx 24rpx;
/* #ifdef APP-PLUS */
::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
/* #endif */
} }
.room-tabs__inner { .room-tabs__inner {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 16rpx; gap: 16rpx;
min-width: 100%;
box-sizing: border-box;
} }
.room-tabs__item { .room-tabs__item {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
flex-shrink: 0;
padding: 16rpx 36rpx; padding: 16rpx 36rpx;
border-radius: 40rpx; border-radius: 40rpx;
background: transparent; background: transparent;

View File

@@ -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>

View File

@@ -1,8 +1,9 @@
import { import {
mapZ2StateToRuntimePatch, mapZ2StateToRuntimePatch,
Z2_BLE_CMD,
type Z2AirQuality, type Z2AirQuality,
} from '@/utils/z2-ble-protocol' } 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' import type { UpdateDeviceRuntimeBody } from './device-detail.types'
export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & { export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & {
@@ -11,12 +12,61 @@ export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & {
airQuality?: Z2AirQuality 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( export async function readRuntimeFromBle(
bleDeviceId: string, bleDeviceId: string,
): Promise<BleRuntimePatch> { ): Promise<BleRuntimePatch> {
if (typeof uni.readBLECharacteristicValue !== 'function') return {} if (typeof uni.readBLECharacteristicValue !== 'function') return {}
const state = await queryZ2BleState(bleDeviceId) 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 } : {}),
}
} }

View File

@@ -34,7 +34,8 @@
.device-detail-hero__bar { .device-detail-hero__bar {
position: relative; position: relative;
z-index: 1; /* 高于连接遮罩,保证加载中返回/设置可点 */
z-index: 10001;
height: 88rpx; height: 88rpx;
display: flex; display: flex;
align-items: center; 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 { .device-detail-hero__status-text {
font-size: 24rpx; font-size: 24rpx;
color: rgba(255, 255, 255, 0.92); color: rgba(255, 255, 255, 0.92);
} }
@keyframes device-detail-status-spin {
to {
transform: rotate(360deg);
}
}
.device-detail-hero__metric-row { .device-detail-hero__metric-row {
position: relative; position: relative;
z-index: 1; z-index: 1;
@@ -163,8 +179,7 @@
.device-detail-page__scroll { .device-detail-page__scroll {
position: relative; position: relative;
z-index: 2; z-index: 2;
flex: 1; width: 100%;
height: 0;
margin-top: -40rpx; margin-top: -40rpx;
} }
@@ -237,6 +252,12 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
box-sizing: border-box; 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 { .device-detail-mode-item--active {
@@ -267,6 +288,12 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: 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 { .device-detail-fan-item--active {

View File

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

View File

@@ -1,4 +1,4 @@
<template> <template>
<view class="device-detail-page"> <view class="device-detail-page">
<view class="device-detail-hero" :style="{ paddingTop: statusBarHeight + 'px' }"> <view class="device-detail-hero" :style="{ paddingTop: statusBarHeight + 'px' }">
<image <image
@@ -22,6 +22,12 @@
<view class="device-detail-hero__status"> <view class="device-detail-hero__status">
<view <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"
:class="{ 'device-detail-hero__status-dot--offline': !isOnline }" :class="{ 'device-detail-hero__status-dot--offline': !isOnline }"
/> />
@@ -41,7 +47,7 @@
<text class="device-detail-hero__sync">{{ syncText }}</text> <text class="device-detail-hero__sync">{{ syncText }}</text>
</view> </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">
<view class="device-detail-panel__dash" aria-hidden="true" /> <view class="device-detail-panel__dash" aria-hidden="true" />
@@ -65,6 +71,8 @@
:key="item.value" :key="item.value"
class="device-detail-mode-item" class="device-detail-mode-item"
:class="{ 'device-detail-mode-item--active': runMode === item.value }" :class="{ 'device-detail-mode-item--active': runMode === item.value }"
hover-class="device-detail-mode-item--pressed"
hover-stay-time="80"
@tap="onSelectRunMode(item.value)" @tap="onSelectRunMode(item.value)"
> >
<text class="device-detail-mode-item__text">{{ item.label }}</text> <text class="device-detail-mode-item__text">{{ item.label }}</text>
@@ -84,6 +92,8 @@
:key="item.value" :key="item.value"
class="device-detail-fan-item" class="device-detail-fan-item"
:class="{ 'device-detail-fan-item--active': fanLevel === item.value }" :class="{ 'device-detail-fan-item--active': fanLevel === item.value }"
hover-class="device-detail-fan-item--pressed"
hover-stay-time="80"
@tap="onSelectFanLevel(item.value)" @tap="onSelectFanLevel(item.value)"
> >
<text class="device-detail-fan-item__text">{{ item.label }}</text> <text class="device-detail-fan-item__text">{{ item.label }}</text>
@@ -140,34 +150,48 @@
</view> </view>
</view> </view>
</view> </view>
</scroll-view> </page-scroll-view>
<filter-replace-dialog <filter-replace-dialog
v-model:visible="filterReplaceDialogVisible" v-model:visible="filterReplaceDialogVisible"
@confirm="onConfirmFilterReplace" @confirm="onConfirmFilterReplace"
/> />
<run-mode-explain-dialog v-model:visible="runModeExplainVisible" /> <run-mode-explain-dialog v-model:visible="runModeExplainVisible" />
<!-- 页面居中加载,挡住下方操作区;顶栏返回/设置仍可点 -->
<ble-reconnect-loading
:visible="showReconnectLoading"
:title="reconnectLoadingTitle"
:desc="reconnectLoadingDesc"
:top-offset-px="statusBarHeight + navBarHeightPx"
/>
</view> </view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { ref } from 'vue'
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
import { staticAssets } from '@/utils/static-assets' 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 FilterReplaceDialog from './components/filter-replace-dialog/index.vue'
import RunModeExplainDialog from './components/run-mode-explain-dialog/index.vue' import RunModeExplainDialog from './components/run-mode-explain-dialog/index.vue'
import { useDeviceDetail } from './use-device-detail' import { useDeviceDetail } from './use-device-detail'
const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight ?? 0) 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) const runModeExplainVisible = ref(false)
function onOpenRunModeExplain() {
runModeExplainVisible.value = true
}
const { const {
deviceName, deviceName,
connectionText, connectionText,
isOnline, isOnline,
showReconnectLoading,
reconnectLoadingTitle,
reconnectLoadingDesc,
tvocDisplay, tvocDisplay,
tvocLevel, tvocLevel,
syncText, syncText,
@@ -191,6 +215,11 @@ const {
onConfirmFilterReplace, onConfirmFilterReplace,
} = useDeviceDetail() } = useDeviceDetail()
function onOpenRunModeExplain() {
if (showReconnectLoading.value) return
runModeExplainVisible.value = true
}
function onBack() { function onBack() {
const pages = getCurrentPages() const pages = getCurrentPages()
if (pages.length > 1) { if (pages.length > 1) {

View File

@@ -1,12 +1,15 @@
import { onUnload } from '@dcloudio/uni-app' import { onShow, onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { buildBleDeviceName } from '@/utils/ble-device-name'
import { recallBleDeviceId, rememberBleDeviceId } from '@/utils/ble-device-id-cache'
import { import {
closeBleConnection, closeBleConnection,
ensureBleConnection, ensureBleConnection,
ensureBluetoothReady, ensureBluetoothReady,
getBluetoothErrorMessage, getBluetoothErrorMessage,
getDiscoveredBluetoothDevices, getConnectedBleDeviceByMac,
isBleDeviceConnected,
isBluetoothApiSupported, isBluetoothApiSupported,
rssiToSignalLevel, rssiToSignalLevel,
scanForBleDeviceByMac, scanForBleDeviceByMac,
@@ -19,7 +22,10 @@ import { readRuntimeFromBle, type BleRuntimePatch } from './device-bluetooth-rea
import type { UpdateDeviceRuntimeBody } from './device-detail.types' import type { UpdateDeviceRuntimeBody } from './device-detail.types'
const SYNC_INTERVAL_MS = 15000 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 { export interface DeviceBluetoothSyncContext {
getDeviceId: () => string | number getDeviceId: () => string | number
@@ -34,31 +40,35 @@ export interface DeviceBluetoothSyncContext {
export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) { export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
const syncing = ref(false) const syncing = ref(false)
const connecting = ref(false)
const bleDeviceId = ref<string>() const bleDeviceId = ref<string>()
let syncTimer: ReturnType<typeof setInterval> | undefined let syncTimer: ReturnType<typeof setInterval> | undefined
let disconnectTimer: ReturnType<typeof setTimeout> | undefined
let unsubscribeConnection: (() => void) | undefined let unsubscribeConnection: (() => void) | undefined
let active = false let active = false
let tearingDown = false
let hadSuccessfulSync = false
/** 正在主动建连,忽略期间的断连回调 */
let linking = false
function setSyncText(text: string) { function setSyncText(text: string) {
context.onSyncTextChange(text) context.onSyncTextChange(text)
} }
async function reportBleDisconnected() { function resolveBleBroadcastName(mac: string): string | undefined {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
try { try {
await updateDeviceRuntime({ return buildBleDeviceName(mac)
deviceId,
bluetoothConnected: '0',
signalLevel: '0',
})
} catch { } 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() const deviceId = context.getDeviceId()
if (!deviceId) return if (!deviceId) return
context.onBluetoothConnectedChange(false) 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> { async function connectAndSync(): Promise<boolean> {
const deviceId = context.getDeviceId() const deviceId = context.getDeviceId()
const mac = context.getMac() const mac = context.getMac()
@@ -91,86 +241,111 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (syncing.value) return false if (syncing.value) return false
syncing.value = true syncing.value = true
connecting.value = !hadSuccessfulSync
let connected = false let targetBleId = bleDeviceId.value || recallBleDeviceId(mac)
let targetBleId = bleDeviceId.value
try { try {
setSyncText('正在连接蓝牙…') if (connecting.value) {
setSyncText('正在搜索并连接设备…')
}
await ensureBluetoothReady() await ensureBluetoothReady()
let foundDevice: UniApp.BluetoothDeviceInfo | null = null // 周期同步 / 回前台:链路还在就只读数据,避免反复建连闪断
const quiet = await syncIfAlreadyConnected(mac)
if (quiet != null) return quiet
if (!targetBleId) { const foundDevice = await resolveBleTarget(mac)
const deviceName = context.getDeviceName?.()
foundDevice = await scanForBleDeviceByMac(mac ?? '', {
timeoutMs: SCAN_TIMEOUT_MS,
name: deviceName,
})
if (!foundDevice) { if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机') setSyncText('未找到设备,请确认已开机并靠近手机')
await reportDeviceOffline() if (!tearingDown) {
if (hadSuccessfulSync) {
hadSuccessfulSync = false
void reportBleDisconnected()
} else {
reportBleLinkLostLocal()
}
}
return false return false
} }
targetBleId = foundDevice.deviceId targetBleId = foundDevice.deviceId
bleDeviceId.value = targetBleId persistBleId(mac, targetBleId)
} else {
const discovered = await getDiscoveredBluetoothDevices() const alreadyLinked = await isBleDeviceConnected(targetBleId)
foundDevice = discovered.find((item) => item.deviceId === targetBleId) ?? null if (!alreadyLinked) {
if (!hadSuccessfulSync) {
connecting.value = true
setSyncText('正在连接蓝牙…')
} }
linking = true
await ensureBleConnection(targetBleId)
connected = true
context.onBluetoothConnectedChange(true)
setSyncText('正在同步设备数据…')
const blePayload = await readRuntimeFromBle(targetBleId)
if (Object.keys(blePayload).length) {
context.onBleRuntimeRead?.(blePayload)
}
const runtimePatch = context.getRuntimePatch()
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
const hasBleData = Object.keys(blePayload).length > 0
try { try {
await updateDeviceRuntime({ await ensureBleConnection(targetBleId)
deviceId, } finally {
...runtimePatch, linking = false
...blePayload,
status: '1',
bluetoothConnected: '1',
signalLevel,
})
if (!hasBleData) {
setSyncText('蓝牙已连接,等待设备上报数据…')
} else {
setSyncText('刚刚更新 · 数据实时同步中')
}
await context.onSynced?.()
} catch (apiErr) {
if (hasBleData) {
setSyncText('蓝牙已连接 · 本地数据已更新,云端同步失败')
} else {
setSyncText(
`蓝牙已连接 · 云端同步失败:${getErrorMessage(apiErr, '请检查网络')}`,
)
} }
} }
return true
return await syncBleData(targetBleId, foundDevice)
} catch (err) { } 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)) setSyncText(getBluetoothErrorMessage(err))
if (!connected) { if (!tearingDown) {
bleDeviceId.value = undefined
clearZ2BleHandleCache(targetBleId) clearZ2BleHandleCache(targetBleId)
await reportDeviceOffline() if (hadSuccessfulSync) {
hadSuccessfulSync = false
void reportBleDisconnected()
} else {
reportBleLinkLostLocal()
}
} }
return false return false
} finally { } finally {
syncing.value = false 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> { async function sendBleCommand(command: string): Promise<boolean> {
if (!bleDeviceId.value) { if (!bleDeviceId.value) {
const ok = await connectAndSync() const ok = await connectAndSync()
@@ -183,39 +358,73 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
context.onBleRuntimeRead?.(runtimePatch) context.onBleRuntimeRead?.(runtimePatch)
} }
return true 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 { } catch {
return false return false
} }
} }
}
function startSyncLoop() { function startSyncLoop() {
if (active) return if (active) return
if (!isBluetoothApiSupported()) { if (!isBluetoothApiSupported()) {
connecting.value = false
setSyncText('云端数据已加载 · 实时同步请使用 App 或微信小程序') setSyncText('云端数据已加载 · 实时同步请使用 App 或微信小程序')
return return
} }
active = true active = true
connecting.value = true
setSyncText('正在搜索并连接设备…')
const mac = context.getMac()
if (mac) {
const cached = recallBleDeviceId(mac)
if (cached) bleDeviceId.value = cached
}
unsubscribeConnection = subscribeBleConnectionStateChange((res) => { unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
if (tearingDown || !active) return
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
if (!res.connected) { if (res.connected) {
bleDeviceId.value = undefined clearDisconnectTimer()
void reportBleDisconnected() return
setSyncText('蓝牙已断开,正在尝试重连…')
} }
// 主动建连 / 同步中的瞬时断连忽略,等结束后再判定
if (linking || syncing.value) return
clearDisconnectTimer()
disconnectTimer = setTimeout(() => {
disconnectTimer = undefined
void handleConfirmedDisconnect(res.deviceId)
}, DISCONNECT_CONFIRM_MS)
}) })
void connectAndSync() void connectAndSync()
syncTimer = setInterval(() => { syncTimer = setInterval(() => {
if (syncing.value || tearingDown || linking) return
void connectAndSync() void connectAndSync()
}, SYNC_INTERVAL_MS) }, SYNC_INTERVAL_MS)
} }
async function stopSync() { async function stopSync() {
tearingDown = true
active = false active = false
hadSuccessfulSync = false
connecting.value = false
linking = false
clearDisconnectTimer()
if (syncTimer) { if (syncTimer) {
clearInterval(syncTimer) clearInterval(syncTimer)
syncTimer = undefined syncTimer = undefined
@@ -229,16 +438,27 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (currentBleId) { if (currentBleId) {
clearZ2BleHandleCache(currentBleId) clearZ2BleHandleCache(currentBleId)
await closeBleConnection(currentBleId).catch(() => {}) await closeBleConnection(currentBleId).catch(() => {})
await reportBleDisconnected()
} }
tearingDown = false
} }
onShow(() => {
try {
uni.hideLoading()
} catch {
// ignore
}
if (!active || tearingDown) return
void connectAndSync()
})
onUnload(() => { onUnload(() => {
void stopSync() void stopSync()
}) })
return { return {
syncing, syncing,
connecting,
startSyncLoop, startSyncLoop,
stopSync, stopSync,
connectAndSync, connectAndSync,

View File

@@ -1,10 +1,12 @@
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { usePageShowRefresh } from '@/hooks/use-page-show-refresh'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { fetchRoomList } from '@/api/location' import { fetchRoomList } from '@/api/location'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { parseDeviceId, parseId, sameId } from '@/utils/device-id' import { parseDeviceId, parseId, sameId } from '@/utils/device-id'
import { fetchProductOptions } from '@/pages/add-device/complete/complete.api' 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 { fetchDeviceRuntime, updateDeviceRuntime } from './device-detail.api'
import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types' import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types'
import { import {
@@ -33,6 +35,8 @@ import {
import type { BleRuntimePatch } from './device-bluetooth-read' import type { BleRuntimePatch } from './device-bluetooth-read'
import { useDeviceBluetoothSync } from './use-device-bluetooth-sync' import { useDeviceBluetoothSync } from './use-device-bluetooth-sync'
const DEVICE_CONTROL_WAIT_TOAST = '设备连接中,请稍候'
export function useDeviceDetail() { export function useDeviceDetail() {
const deviceId = ref('') const deviceId = ref('')
const deviceNo = ref('') const deviceNo = ref('')
@@ -45,9 +49,10 @@ export function useDeviceDetail() {
const deviceStatus = ref<string>() const deviceStatus = ref<string>()
const bluetoothConnected = ref(false) const bluetoothConnected = ref(false)
const charging = ref(false) const charging = ref(false)
const isOnline = ref(false)
const loading = 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 runMode = ref<RunMode>('0')
const fanLevel = ref<FanLevel>('0') const fanLevel = ref<FanLevel>('0')
@@ -61,6 +66,8 @@ export function useDeviceDetail() {
const filterReplaceDialogVisible = ref(false) const filterReplaceDialogVisible = ref(false)
const batteryLevel = ref<number | null>(null) const batteryLevel = ref<number | null>(null)
let pendingBatteryReading: number | null = null let pendingBatteryReading: number | null = null
/** 本页已从蓝牙读到滤芯后,避免云端旧值盖住实时衰减 */
let filterLifeFromBle = false
const syncText = ref('数据实时同步中') const syncText = ref('数据实时同步中')
const tvocDisplay = computed(() => formatTvocValue(tvoc.value ?? undefined)) const tvocDisplay = computed(() => formatTvocValue(tvoc.value ?? undefined))
@@ -72,13 +79,6 @@ export function useDeviceDetail() {
const batteryDisplay = computed(() => const batteryDisplay = computed(() =>
batteryLevel.value != null ? `${batteryLevel.value}%` : '--', 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 showFanLevelControl = computed(() => isAutoRunMode(runMode.value))
const fanLevelOptions = computed(() => const fanLevelOptions = computed(() =>
showFanLevelControl.value ? AUTO_FAN_LEVEL_OPTIONS : [], showFanLevelControl.value ? AUTO_FAN_LEVEL_OPTIONS : [],
@@ -132,6 +132,7 @@ export function useDeviceDetail() {
if (patch.powerMode != null) powerMode.value = patch.powerMode if (patch.powerMode != null) powerMode.value = patch.powerMode
if (patch.filterLife != null) { if (patch.filterLife != null) {
filterLife.value = patch.filterLife filterLife.value = patch.filterLife
filterLifeFromBle = true
updateFilterRemainText() updateFilterRemainText()
} }
if (patch.deviceBattery != null) applyBatteryLevel(patch.deviceBattery, true) if (patch.deviceBattery != null) applyBatteryLevel(patch.deviceBattery, true)
@@ -145,36 +146,66 @@ export function useDeviceDetail() {
fanLevel.value = view.fanLevel fanLevel.value = view.fanLevel
if (view.tvoc != null) tvoc.value = view.tvoc if (view.tvoc != null) tvoc.value = view.tvoc
powerMode.value = view.powerMode powerMode.value = view.powerMode
// 蓝牙已读到实时滤芯时,不以云端缓存覆盖(否则 15 分钟衰减看不到)
if (!filterLifeFromBle) {
filterLife.value = view.filterLife filterLife.value = view.filterLife
filterRemainText.value = view.filterRemainText filterRemainText.value = view.filterRemainText
} else {
updateFilterRemainText()
}
filterReplaced.value = view.filterReplaced filterReplaced.value = view.filterReplaced
isOnline.value = view.isOnline
if (data.deviceBattery != null) applyBatteryLevel(data.deviceBattery, false) 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() { async function refreshDeviceMeta() {
if (!deviceId.value) return 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 { try {
const list = await fetchDeviceList() const list = await fetchAllDeviceList()
const device = list?.find((item) => String(item.deviceId) === deviceId.value) const device = list?.find((item) => String(item.deviceId) === deviceId.value)
if (!device) return if (!device) return
if (device.deviceId != null) deviceId.value = String(device.deviceId) if (device.deviceId != null) deviceId.value = String(device.deviceId)
if (device.deviceNo) deviceNo.value = device.deviceNo if (device.deviceNo) deviceNo.value = device.deviceNo
if (device.mac) deviceMac.value = device.mac if (device.mac) deviceMac.value = device.mac
const parsedLocationId = parseId(device.locationId) // 本地刚改名优先,避免 onShow 刷新用接口旧名称盖回去
if (parsedLocationId) locationId.value = parsedLocationId if (patchedName && device.name !== patchedName) {
deviceName.value = patchedName
} else if (device.name) {
deviceName.value = device.name
}
const parsedHomeId = parseId(device.homeId) const parsedHomeId = parseId(device.homeId)
if (parsedHomeId) homeId.value = parsedHomeId if (parsedHomeId) homeId.value = parsedHomeId
if (patchedLocation) {
// 本地刚切换的房间优先,避免接口短暂延迟把展示盖回旧房间
} else {
const parsedLocationId = parseId(device.locationId)
if (parsedLocationId) locationId.value = parsedLocationId
if (parsedHomeId && parsedLocationId) { if (parsedHomeId && parsedLocationId) {
const locations = await fetchRoomList(parsedHomeId) const locations = await fetchRoomList(parsedHomeId)
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId)) const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
if (matched) locationName.value = matched.name if (matched) locationName.value = matched.name
} }
bluetoothConnected.value = isBluetoothConnected(device.bluetoothConnected) }
charging.value = device.charging === '1' charging.value = device.charging === '1'
if (device.status !== undefined) deviceStatus.value = device.status // 详情页连接态以本地 BLE 为准:云端不能把状态打成「已连接」,
isOnline.value = device.status === '1' // 否则会提前关掉重连加载遮罩(列表/接口常有脏在线态)
if (!bleConnectedLocally) {
const apiConnected = isBluetoothConnected(device.bluetoothConnected)
if (!apiConnected) {
bluetoothConnected.value = false
deviceStatus.value = device.status === '0' ? '0' : '2'
}
}
} catch { } 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 }) { async function patchRuntime(patch: { runMode?: RunMode; fanLevel?: FanLevel }) {
if (!deviceId.value || updating.value) return if (!deviceId.value) return
updating.value = true if (patch.runMode != null && runMode.value === patch.runMode) return
try { 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 const bleCmd = patch.runMode != null
? encodeRunModeBleCommand(patch.runMode) ? encodeRunModeBleCommand(patch.runMode)
: patch.fanLevel != null : patch.fanLevel != null
? encodeFanLevelBleCommand(patch.fanLevel) ? encodeFanLevelBleCommand(patch.fanLevel)
: undefined : undefined
if (bleCmd) {
await sendBleCommand(bleCmd) try {
} const apiTask = updateDeviceRuntime({
await updateDeviceRuntime({
deviceId: deviceId.value, deviceId: deviceId.value,
...patch, ...patch,
}) })
const data = await fetchDeviceRuntime({ deviceId: deviceId.value }) if (bleCmd) {
applyRuntime(data) const [bleOk] = await Promise.all([sendBleCommand(bleCmd), apiTask])
await refreshDeviceMeta() if (!bleOk) {
throw new Error('蓝牙指令发送失败')
}
} else {
await apiTask
}
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '设置失败'), icon: 'none' }) runMode.value = snapshot.runMode
} finally { fanLevel.value = snapshot.fanLevel
updating.value = false 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) { function onSelectRunMode(mode: RunMode) {
if (showReconnectLoading.value) return
if (runMode.value === mode) return if (runMode.value === mode) return
void patchRuntime({ runMode: mode }) void patchRuntime({ runMode: mode })
} }
function onSelectFanLevel(level: FanLevel) { function onSelectFanLevel(level: FanLevel) {
if (showReconnectLoading.value) return
if (!isAutoRunMode(runMode.value)) return if (!isAutoRunMode(runMode.value)) return
if (fanLevel.value === level) return if (fanLevel.value === level) return
void patchRuntime({ fanLevel: level }) void patchRuntime({ fanLevel: level })
@@ -253,19 +306,33 @@ export function useDeviceDetail() {
} }
function onFilterReplace() { function onFilterReplace() {
if (showReconnectLoading.value) return
if (filterReplaced.value) return if (filterReplaced.value) return
filterReplaceDialogVisible.value = true filterReplaceDialogVisible.value = true
} }
async function onConfirmFilterReplace() { 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 filterReplaced.value = true
filterLife.value = 100 filterLife.value = 100
filterLifeFromBle = true
updateFilterRemainText() updateFilterRemainText()
uni.showToast({ title: '操作成功', icon: 'success' }) uni.showToast({ title: '操作成功', icon: 'success' })
} }
const { startSyncLoop, sendBleCommand } = useDeviceBluetoothSync({ const {
connecting: bleConnecting,
startSyncLoop,
sendBleCommand,
} = useDeviceBluetoothSync({
getDeviceId: () => deviceId.value, getDeviceId: () => deviceId.value,
getMac: () => deviceMac.value, getMac: () => deviceMac.value,
getDeviceName: () => deviceName.value, getDeviceName: () => deviceName.value,
@@ -278,10 +345,7 @@ export function useDeviceDetail() {
}), }),
onBluetoothConnectedChange: (connected) => { onBluetoothConnectedChange: (connected) => {
bluetoothConnected.value = connected bluetoothConnected.value = connected
if (connected) { deviceStatus.value = connected ? '1' : '2'
isOnline.value = true
deviceStatus.value = '1'
}
}, },
onSyncTextChange: (text) => { onSyncTextChange: (text) => {
syncText.value = 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) => { onLoad((query?: DeviceDetailRouteQuery) => {
deviceId.value = parseDeviceId(query?.deviceId) deviceId.value = parseDeviceId(query?.deviceId)
if (query?.deviceNo) { if (query?.deviceNo) {
@@ -309,22 +400,31 @@ export function useDeviceDetail() {
const parsedHomeId = parseId(query?.homeId) const parsedHomeId = parseId(query?.homeId)
if (parsedHomeId) homeId.value = parsedHomeId if (parsedHomeId) homeId.value = parsedHomeId
if (query?.model) productModel.value = decodeURIComponent(String(query.model)) 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)) 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' charging.value = query?.charging === '1'
void loadRuntime().then(() => { void loadRuntime()
.catch(() => {})
.finally(() => {
startSyncLoop() startSyncLoop()
awaitingBleStart.value = false
}) })
}) })
usePageShowRefresh(() => refreshDeviceMeta(), { skipInitialShow: true })
return { return {
deviceName, deviceName,
connectionText, connectionText,
isOnline, isOnline,
showReconnectLoading,
reconnectLoadingTitle,
reconnectLoadingDesc,
tvocDisplay, tvocDisplay,
tvocLevel, tvocLevel,
syncText, syncText,

View 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))
}

View File

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

View File

@@ -0,0 +1,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
}

View File

@@ -1,14 +1,26 @@
import { buildBleDeviceName } from '@/utils/ble-device-name'
import { import {
findDeviceInBleScan, findDeviceInBleScan,
getConnectedBleDeviceByMac,
isBluetoothApiSupported, isBluetoothApiSupported,
scanBluetoothDevices, scanBluetoothDevices,
} from '@/utils/bluetooth' } from '@/utils/bluetooth'
import { sameId } from '@/utils/device-id' import { sameId } from '@/utils/device-id'
import {
markPresenceOfflineReportedToCloud,
recordPresenceHit,
recordPresenceMiss,
shouldMarkDeviceOffline,
shouldReportPresenceOfflineToCloud,
} from './device-presence-state'
import { updateDeviceRuntime } from './detail/device-detail.api' import { updateDeviceRuntime } from './detail/device-detail.api'
import type { DeviceListItem } from './device.types' import type { DeviceListItem } from './device.types'
let syncing = false let syncing = false
/** 关机后广播马上消失,缩短扫描窗口以便更快判定离线 */
const PRESENCE_SCAN_MS = 4500
const PRESENCE_DEBUG = import.meta.env.DEV const PRESENCE_DEBUG = import.meta.env.DEV
|| import.meta.env.VITE_BLE_DEBUG === 'true' || import.meta.env.VITE_BLE_DEBUG === 'true'
@@ -21,29 +33,108 @@ function logPresence(message: string, payload?: unknown) {
console.log(`[Device Presence] ${message}`) console.log(`[Device Presence] ${message}`)
} }
function applyPresence( function wasDeviceOnlineInCloud(device: DeviceListItem): boolean {
device: DeviceListItem, return device.status === '1' && device.bluetoothConnected === '1'
present: boolean, }
): DeviceListItem {
const nextStatus = present ? '1' : '2' function resolveBleName(mac?: string): string | undefined {
const nextBluetooth = present ? '1' : '0' if (!mac) return undefined
return { try {
...device, return buildBleDeviceName(mac)
status: nextStatus, } catch {
bluetoothConnected: nextBluetooth, return undefined
isOnline: present,
} }
} }
/** 通过 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( export async function refreshDevicePresence(
devices: DeviceListItem[], devices: DeviceListItem[],
): Promise<DeviceListItem[]> { ): Promise<DeviceListItem[]> {
if (!isBluetoothApiSupported()) return devices 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) { if (!targets.length) {
logPresence('skip: no mac/name on devices') logPresence('skip: no mac on devices')
return devices return devices
} }
@@ -51,57 +142,59 @@ export async function refreshDevicePresence(
syncing = true syncing = true
try { 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', { logPresence('scan result', {
count: scanned.length, count: scanned.length,
names: scanned.map((item) => item.name || item.localName || item.deviceId), names: scanned.map((item) => item.name || item.localName || item.deviceId),
}) })
const offlineReports: DeviceListItem[] = []
const nextDevices = devices.map((device) => { const nextDevices = devices.map((device) => {
if (!device.deviceId) return device if (!device.deviceId) return device
const isTarget = targets.some((item) => sameId(item.deviceId, device.deviceId)) const targetIndex = targets.findIndex((item) => sameId(item.deviceId, device.deviceId))
if (!isTarget) return device if (targetIndex < 0) return device
const found = findDeviceInBleScan( const found = findDeviceInPresenceScan(device, scanned)
{ mac: device.mac, name: device.name }, const gattConnected = connectedFlags[targetIndex]
scanned, const present = !!found || gattConnected
{ strictName: true },
)
const present = !!found
logPresence('device presence', { logPresence('device presence', {
name: device.name, name: device.name,
mac: device.mac, mac: device.mac,
present, 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( void Promise.allSettled(
targets.map(async (device) => { targets.map(async (device) => {
const found = findDeviceInBleScan( const found = findDeviceInPresenceScan(device, scanned)
{ mac: device.mac, name: device.name }, if (found) {
scanned, await reportPresenceOnlineToCloud(device)
{ 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)
} }
}), }),
) )
void Promise.allSettled(offlineReports.map((device) => reportPresenceOfflineToCloud(device)))
return nextDevices return nextDevices
} catch (err) { } catch (err) {
logPresence('scan failed', err) logPresence('scan failed', err)

View File

@@ -1,7 +1,7 @@
import { request } from '@/api/request' import { request } from '@/api/request'
import type { AppDeviceVo, DeviceQueryBody } from './device.types' import type { AppDeviceVo, DeviceQueryBody } from './device.types'
/** POST /app/device/list — 查询当前用户的设备列表 */ /** POST /app/device/list — 按家庭/房间查询设备(首页设备 Tab 等) */
export function fetchDeviceList(query: DeviceQueryBody = {}) { export function fetchDeviceList(query: DeviceQueryBody = {}) {
return request<AppDeviceVo[]>({ return request<AppDeviceVo[]>({
url: '/app/device/list', url: '/app/device/list',
@@ -9,3 +9,12 @@ export function fetchDeviceList(query: DeviceQueryBody = {}) {
data: query, data: query,
}) })
} }
/** POST /app/device/listAll — 当前用户绑定的全部设备(选择设备、我的设备等跨家庭场景) */
export function fetchAllDeviceList() {
return request<AppDeviceVo[]>({
url: '/app/device/listAll',
method: 'GET',
data: {},
})
}

View File

@@ -3,4 +3,23 @@
background: $color-bg-page; background: $color-bg-page;
padding-bottom: calc(120rpx + env(safe-area-inset-bottom)); padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
box-sizing: border-box; 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;
} }

View File

@@ -4,18 +4,14 @@ export interface RoomTab {
locationId?: string | number locationId?: string | number
} }
export interface HotDeviceItem { /** POST /app/device/list 查询参数(按家庭/房间筛选) */
id: string
name: string
desc: string
}
/** POST /app/device/list 查询参数 */
export interface DeviceQueryBody { export interface DeviceQueryBody {
homeId?: string | number homeId?: string | number
locationId?: string | number locationId?: string | number
} }
/** POST /app/device/listAll — 无筛选参数,返回当前用户全部绑定设备 */
/** 设备状态:0未激活 1在线 2离线 */ /** 设备状态:0未激活 1在线 2离线 */
export type DeviceStatus = '0' | '1' | '2' export type DeviceStatus = '0' | '1' | '2'
@@ -26,6 +22,12 @@ export interface AppDeviceVo {
name?: string name?: string
imei?: string imei?: string
mac?: string mac?: string
sn?: string
/** 产品主键(绑定时常写入;列表若返回则可据此解析型号) */
productId?: string | number
/** 产品型号,如 CZ-Z2023(OpenAPI 可能未声明,后端可能仍返回) */
model?: string
productName?: string
homeId?: string | number homeId?: string | number
locationId?: string | number locationId?: string | number
status?: DeviceStatus | string status?: DeviceStatus | string

View File

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

View File

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

View File

@@ -1,8 +1,8 @@
<template> <template>
<view class="home-manage-page"> <view class="home-manage-page">
<app-navbar title="家庭管理" /> <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"> <view class="home-manage-page__body">
<text class="home-manage-page__summary">{{ summaryText }}</text> <text class="home-manage-page__summary">{{ summaryText }}</text>
@@ -31,7 +31,7 @@
</view> </view>
</view> </view>
</view> </view>
</scroll-view> </page-scroll-view>
<home-name-dialog <home-name-dialog
v-model:visible="nameDialogVisible" v-model:visible="nameDialogVisible"

View File

@@ -5,9 +5,33 @@
flex-direction: column; 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 { .home-manage-page__scroll {
flex: 1; width: 100%;
height: 0;
} }
.home-manage-page__body { .home-manage-page__body {
@@ -73,11 +97,18 @@
margin-left: 32rpx; margin-left: 32rpx;
} }
.home-manage-page__loading,
.home-manage-page__empty { .home-manage-page__empty {
padding: 120rpx 32rpx; padding: 120rpx 32rpx;
text-align: center; text-align: center;
} }
.home-manage-page__loading-text {
font-size: 28rpx;
color: #999;
line-height: 1.5;
}
.home-manage-page__empty-text { .home-manage-page__empty-text {
font-size: 28rpx; font-size: 28rpx;
color: #999; color: #999;

View File

@@ -1,8 +1,18 @@
<template> <template>
<view class="home-manage-page"> <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 class="home-manage-page__body">
<view v-if="homes.length" class="home-manage-page__list"> <view v-if="homes.length" class="home-manage-page__list">
<view <view
@@ -20,19 +30,41 @@
</view> </view>
</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> <text class="home-manage-page__empty-text">暂无家庭</text>
</view> </view>
</view> </view>
</scroll-view> </page-scroll-view>
<home-name-dialog
v-model:visible="createDialogVisible"
:value="createHomeName"
title="新增家庭"
placeholder="请输入新家庭名称"
confirm-text="创建"
@confirm="onConfirmCreateHome"
/>
</view> </view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { staticAssets } from '@/utils/static-assets' import { staticAssets } from '@/utils/static-assets'
import HomeNameDialog from './components/home-name-dialog/index.vue'
import { useHomeList } from './use-home-list' import { useHomeList } from './use-home-list'
const { homes, loading, onSelectHome } = useHomeList() const {
homes,
loading,
creating,
createDialogVisible,
createHomeName,
onSelectHome,
onAddHome,
onConfirmCreateHome,
} = useHomeList()
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -1,118 +1,315 @@
<template> <template>
<!-- #ifdef H5 -->
<view class="location-map"> <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 <map
class="location-map" id="home-location-map"
:latitude="latitude" class="location-map__canvas"
:longitude="longitude" provider="amap"
:latitude="mapLatitude"
:longitude="mapLongitude"
:scale="16" :scale="16"
:show-location="true" :show-location="true"
:enable-3d="false" :enable-3d="false"
:show-compass="false" :show-compass="false"
:enable-scroll="true"
:enable-zoom="true"
@regionchange="onRegionChange" @regionchange="onRegionChange"
/> @updated="onMapUpdated"
>
<!-- #ifdef APP-PLUS || MP-WEIXIN -->
<cover-view class="location-map__pin">
<cover-image class="location-map__pin-img" src="/static/icon-map-pin.png" />
</cover-view>
<cover-view
class="location-map__locate"
:class="{ 'location-map__locate--loading': locating }"
@tap="emit('locate')"
>
<cover-view class="location-map__locate-icon">◎</cover-view>
</cover-view>
<!-- #endif --> <!-- #endif -->
</map>
<!-- #ifdef H5 -->
<view class="location-map__pin" aria-hidden="true">
<image class="location-map__pin-img" :src="pinIcon" mode="aspectFit" />
</view>
<view
class="location-map__locate location-map__locate--web"
:class="{ 'location-map__locate--loading': locating }"
@tap="emit('locate')"
>
<text class="location-map__locate-icon">◎</text>
</view>
<!-- #endif -->
</view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue' import { getCurrentInstance, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { getTencentMapKey, loadTencentMapGl, type TencentMapInstance } from '@/utils/tencent-map-loader' import { staticAssets } from '@/utils/static-assets'
const props = defineProps<{ const props = withDefaults(
defineProps<{
latitude: number latitude: number
longitude: number longitude: number
}>() locating?: boolean
}>(),
{ locating: false },
)
const emit = defineEmits<{ const emit = defineEmits<{
'center-change': [center: { latitude: number; longitude: number }] ready: []
regionchange: [event: UniHelper.MapRegionChangeEvent] locate: []
pick: [point: { latitude: number; longitude: number }]
}>() }>()
// #ifdef H5 const MAP_ID = 'home-location-map'
const mapDomId = `location-map-${Math.random().toString(36).slice(2, 10)}` const instance = getCurrentInstance()
const hintText = ref('') const pinIcon = staticAssets.iconMapPin
let mapInstance: TencentMapInstance | null = null
let syncingFromDrag = false
async function initH5Map() { const mapLatitude = ref(props.latitude)
const key = getTencentMapKey() const mapLongitude = ref(props.longitude)
if (!key) {
hintText.value = '请在 .env 中配置 VITE_TENCENT_MAP_KEY(腾讯地图 Web 端 Key)'
return
}
try { let destroyed = false
await loadTencentMapGl() let mapReady = false
await nextTick() let dragging = false
const container = document.getElementById(mapDomId) /** 本次手势开始时的绑定中心,用于拦截「瞬移到北京」 */
if (!container || !window.TMap) { let dragOrigin = { latitude: props.latitude, longitude: props.longitude }
hintText.value = '地图容器初始化失败' let ignoreRegionUntil = 0
return let lastEmitKey = ''
} let mapCtx: UniApp.MapContext | null = null
hintText.value = '' type NativeMap = {
mapInstance = new window.TMap.Map(container, { getCenter?: () => {
center: new window.TMap.LatLng(props.latitude, props.longitude), getLng?: () => number
zoom: 16, getLat?: () => number
pitch: 0, longitude?: number
rotation: 0, latitude?: number
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 pointKey(lat: number, lng: number) {
return `${lat.toFixed(6)},${lng.toFixed(6)}`
}
/** 常见地图默认中心(天安门附近),不能只用 39.9042/116.4074 一个点 */
function isBeijingCore(lat: number, lng: number) {
return lat > 39.85 && lat < 40.05 && lng > 116.28 && lng < 116.55
}
function ensureMapContext(): UniApp.MapContext | null {
if (mapCtx) return mapCtx
const proxy = instance?.proxy
if (!proxy) return null
mapCtx = uni.createMapContext(MAP_ID, proxy as never)
return mapCtx
}
function getNativeMap(): NativeMap | null {
// #ifdef APP-PLUS
try {
const ctx = ensureMapContext() as UniApp.MapContext & { $getAppMap?: () => NativeMap }
if (typeof ctx?.$getAppMap === 'function') {
return ctx.$getAppMap() || null
}
} catch {
return null
}
// #endif
return null
}
/** 同步读取原生可视中心(App 唯一可靠来源) */
function readNativeCenterSync(): { latitude: number; longitude: number } | null {
const nativeMap = getNativeMap()
if (!nativeMap?.getCenter) return null
try {
const center = nativeMap.getCenter()
if (!center) return null
const lng = typeof center.getLng === 'function' ? center.getLng() : Number(center.longitude)
const lat = typeof center.getLat === 'function' ? center.getLat() : Number(center.latitude)
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null
return { latitude: lat, longitude: lng }
} catch {
return null
}
}
function readEventCenter(detail: Record<string, unknown>): { latitude: number; longitude: number } | null {
const nested = detail.centerLocation as { latitude?: number; longitude?: number } | undefined
const lat = Number(detail.latitude ?? nested?.latitude)
const lng = Number(detail.longitude ?? nested?.longitude)
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null
return { latitude: lat, longitude: lng }
}
/**
* 丢弃错误中心:从非北京「瞬移」进北京城区核心(地图未就绪时的默认点)
* 小范围拖动(< ~5km)即使进北京也允许
*/
function isBogusBeijingTeleport(
from: { latitude: number; longitude: number },
to: { latitude: number; longitude: number },
) {
const jump = Math.hypot(to.latitude - from.latitude, to.longitude - from.longitude)
if (jump < 0.05) return false
return isBeijingCore(to.latitude, to.longitude) && !isBeijingCore(from.latitude, from.longitude)
}
function applyCenter(lat: number, lng: number, emitPick: boolean) {
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return false
if (isBogusBeijingTeleport(
{ latitude: mapLatitude.value, longitude: mapLongitude.value },
{ latitude: lat, longitude: lng },
)) {
return false
}
mapLatitude.value = lat
mapLongitude.value = lng
if (!emitPick) return true
const key = pointKey(lat, lng)
if (key === lastEmitKey) return true
lastEmitKey = key
emit('pick', { latitude: lat, longitude: lng })
return true
}
function pickFromDetailOrNative(detail: Record<string, unknown>) {
const fromEvent = readEventCenter(detail)
if (fromEvent && !isBogusBeijingTeleport(dragOrigin, fromEvent)) {
applyCenter(fromEvent.latitude, fromEvent.longitude, true)
return
}
// #ifdef APP-PLUS
// 必须在 end 回调里同步读原生中心,抢在框架用旧绑定重绘之前
const fromNative = readNativeCenterSync()
if (fromNative && !isBogusBeijingTeleport(dragOrigin, fromNative)) {
applyCenter(fromNative.latitude, fromNative.longitude, true)
}
// 禁止 getCenterLocation:App 常返回绑定值或默认北京
return
// #endif
// #ifndef APP-PLUS
const fromNative = readNativeCenterSync()
if (fromNative && !isBogusBeijingTeleport(dragOrigin, fromNative)) {
applyCenter(fromNative.latitude, fromNative.longitude, true)
return
}
ensureMapContext()?.getCenterLocation({
success: (res) => {
if (destroyed) return
const lat = Number(res?.latitude)
const lng = Number(res?.longitude)
const point = { latitude: lat, longitude: lng }
if (!isBogusBeijingTeleport(dragOrigin, point)) {
applyCenter(lat, lng, true)
}
},
})
// #endif
}
function onRegionChange(event: Record<string, unknown>) {
if (Date.now() < ignoreRegionUntil) return
const detail = (event.detail || {}) as Record<string, unknown>
const type = String(event.type || detail.type || '')
if (type === 'begin') {
dragging = true
dragOrigin = { latitude: mapLatitude.value, longitude: mapLongitude.value }
ensureMapContext()
return
}
// end,或 App 上偶发无 type
if (type === 'end' || type === '') {
dragging = false
pickFromDetailOrNative(detail)
}
}
function onMapUpdated() {
if (!mapReady) {
mapReady = true
emit('ready')
}
ensureMapContext()
}
watch( watch(
() => [props.latitude, props.longitude], () => [props.latitude, props.longitude] as const,
([lat, lng]) => { ([lat, lng]) => {
if (!mapInstance || syncingFromDrag || !window.TMap) return if (dragging) return
mapInstance.setCenter(new window.TMap.LatLng(lat, lng)) if (!Number.isFinite(lat) || !Number.isFinite(lng)) return
if (
Math.abs(mapLatitude.value - lat) < 1e-7
&& Math.abs(mapLongitude.value - lng) < 1e-7
) {
return
}
// 父级(搜索/定位)写入时也拦截异常北京瞬移
if (isBogusBeijingTeleport(
{ latitude: mapLatitude.value, longitude: mapLongitude.value },
{ latitude: lat, longitude: lng },
)) {
return
}
mapLatitude.value = lat
mapLongitude.value = lng
}, },
) )
onMounted(() => { onMounted(() => {
void initH5Map() mapLatitude.value = props.latitude
mapLongitude.value = props.longitude
dragOrigin = { latitude: props.latitude, longitude: props.longitude }
void nextTick(() => {
ensureMapContext()
setTimeout(() => {
if (!mapReady && !destroyed) {
mapReady = true
emit('ready')
}
ensureMapContext()
}, 400)
})
}) })
onUnmounted(() => { onUnmounted(() => {
mapInstance?.destroy?.() destroyed = true
mapInstance = null mapCtx = null
}) })
// #endif
// #ifndef H5 defineExpose({
function onRegionChange(event: UniHelper.MapRegionChangeEvent) { /** 页面 onReady 时再取一次 context,App 上更稳 */
emit('regionchange', event) onPageReady() {
} ensureMapContext()
// #endif },
moveTo(lng: number, lat: number) {
ignoreRegionUntil = Date.now() + 800
dragging = false
lastEmitKey = ''
mapLatitude.value = lat
mapLongitude.value = lng
dragOrigin = { latitude: lat, longitude: lng }
},
moveToUserLocation() {
if (destroyed) return
ignoreRegionUntil = Date.now() + 1000
dragging = false
lastEmitKey = ''
void nextTick(() => {
if (destroyed) return
ensureMapContext()?.moveToLocation({
latitude: mapLatitude.value,
longitude: mapLongitude.value,
})
})
},
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@@ -120,6 +317,7 @@ function onRegionChange(event: UniHelper.MapRegionChangeEvent) {
position: relative; position: relative;
width: 100%; width: 100%;
height: 100%; height: 100%;
overflow: hidden;
} }
.location-map__canvas { .location-map__canvas {
@@ -127,21 +325,49 @@ function onRegionChange(event: UniHelper.MapRegionChangeEvent) {
height: 100%; height: 100%;
} }
.location-map__hint { .location-map__pin {
position: absolute; position: absolute;
inset: 0; left: 50%;
top: 50%;
width: 56rpx;
height: 76rpx;
margin-left: -28rpx;
margin-top: -76rpx;
pointer-events: none;
z-index: 3;
}
.location-map__pin-img {
width: 56rpx;
height: 76rpx;
}
.location-map__locate {
position: absolute;
right: 24rpx;
bottom: 32rpx;
width: 80rpx;
height: 80rpx;
border-radius: 40rpx;
background-color: #ffffff;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
padding: 48rpx; z-index: 2;
background: #eef1f5;
z-index: 1;
} }
.location-map__hint-text { .location-map__locate--web {
font-size: 28rpx; box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.12);
color: #667085; }
line-height: 1.6;
.location-map__locate--loading {
opacity: 0.6;
}
.location-map__locate-icon {
font-size: 40rpx;
line-height: 80rpx;
text-align: center; text-align: center;
color: #1ec671;
} }
</style> </style>

View File

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

View File

@@ -6,6 +6,12 @@
overflow: hidden; overflow: hidden;
} }
.home-location-page__header {
flex-shrink: 0;
z-index: 100;
background: #f5f6f8;
}
.home-location-page__confirm { .home-location-page__confirm {
width: 56rpx; width: 56rpx;
height: 56rpx; height: 56rpx;
@@ -61,58 +67,47 @@
height: 100%; 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 { .home-location-page__locate {
position: absolute; position: absolute;
right: 24rpx; right: 24rpx;
bottom: 32rpx; bottom: 32rpx;
width: 80rpx; width: 80rpx;
height: 80rpx; height: 80rpx;
border-radius: 50%; border-radius: 40rpx;
background: #fff; background-color: #ffffff;
box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.12);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
z-index: 2; z-index: 2;
} }
.home-location-page__locate--web {
box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.12);
}
.home-location-page__locate--loading { .home-location-page__locate--loading {
opacity: 0.6; opacity: 0.6;
} }
.home-location-page__locate-icon { .home-location-page__locate-icon {
font-size: 40rpx; font-size: 40rpx;
line-height: 1; line-height: 80rpx;
color: $color-primary; text-align: center;
color: #1ec671;
}
.home-location-page__map-loading {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #eef1f4;
}
.home-location-page__map-loading-text {
font-size: 28rpx;
color: #98a2b3;
} }
.home-location-page__footer { .home-location-page__footer {
@@ -137,3 +132,23 @@
line-height: 1.5; line-height: 1.5;
word-break: break-all; word-break: break-all;
} }
.home-location-page__pick-btn {
margin-top: 24rpx;
height: 88rpx;
border-radius: 16rpx;
background: $color-primary;
display: flex;
align-items: center;
justify-content: center;
}
.home-location-page__pick-btn--disabled {
opacity: 0.6;
}
.home-location-page__pick-btn-text {
font-size: 30rpx;
color: #fff;
font-weight: 600;
}

View File

@@ -1,5 +1,6 @@
<template> <template>
<view class="home-location-page"> <view class="home-location-page">
<view class="home-location-page__header">
<app-navbar title="家庭位置"> <app-navbar title="家庭位置">
<template #right> <template #right>
<view class="home-location-page__confirm" @tap="onConfirm"> <view class="home-location-page__confirm" @tap="onConfirm">
@@ -7,63 +8,125 @@
</view> </view>
</template> </template>
</app-navbar> </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-icon">⌕</text>
<text class="home-location-page__search-text"> <text class="home-location-page__search-text">
{{ searchKeyword || '搜索地点' }} {{ searchKeyword || '搜索地点' }}
</text> </text>
</view> </view>
<view class="home-location-page__map-wrap"> <view v-show="!searchVisible" class="home-location-page__map-wrap">
<location-map <view v-if="!mapCenterReady" class="home-location-page__map-loading">
<text class="home-location-page__map-loading-text">正在定位…</text>
</view>
<map
v-else
:id="MAP_ID"
class="home-location-page__map" class="home-location-page__map"
provider="amap"
:latitude="latitude" :latitude="latitude"
:longitude="longitude" :longitude="longitude"
@center-change="onMapCenterChange" :scale="16"
@regionchange="onRegionChange" :markers="markers"
/> :show-location="true"
:enable-3d="false"
<view class="home-location-page__pin" aria-hidden="true"> :show-compass="false"
<view class="home-location-page__pin-head" /> :enable-scroll="true"
<view class="home-location-page__pin-tail" /> :enable-zoom="true"
</view> @tap="onMapTap"
@updated="onMapReady"
<view >
<!-- #ifdef APP-PLUS || MP-WEIXIN -->
<cover-view
class="home-location-page__locate" class="home-location-page__locate"
:class="{ 'home-location-page__locate--loading': locating }" :class="{ 'home-location-page__locate--loading': locating }"
@tap="onLocate" @tap.stop="onLocate"
>
<cover-view class="home-location-page__locate-icon">◎</cover-view>
</cover-view>
<!-- #endif -->
</map>
<!-- #ifdef H5 -->
<view
v-if="mapCenterReady"
class="home-location-page__locate home-location-page__locate--web"
:class="{ 'home-location-page__locate--loading': locating }"
@tap.stop="onLocate"
> >
<text class="home-location-page__locate-icon">◎</text> <text class="home-location-page__locate-icon">◎</text>
</view> </view>
<!-- #endif -->
</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-label">当前位置</text>
<text class="home-location-page__address-text"> <text class="home-location-page__address-text">
{{ resolvingAddress ? '正在解析地址…' : (addressText || '拖动地图选择家庭位置') }} {{ resolvingAddress ? '正在解析地址…' : (addressText || '请选择家庭位置') }}
</text>
<view
class="home-location-page__pick-btn"
:class="{ 'home-location-page__pick-btn--disabled': choosingLocation }"
@tap="openChooseLocation"
>
<text class="home-location-page__pick-btn-text">
{{ choosingLocation ? '打开选点…' : '选择位置' }}
</text> </text>
</view> </view>
</view> </view>
<location-search
v-if="searchVisible"
:latitude="latitude"
:longitude="longitude"
:city="searchCity"
:top-offset="searchPanelTop"
@select="onSelectSearchPlace"
@close="onCloseSearch"
/>
</view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import LocationMap from './components/location-map/index.vue' import { onReady } from '@dcloudio/uni-app'
import { getCurrentInstance } from 'vue'
import LocationSearch from './components/location-search/index.vue'
import { useHomeLocation } from './use-home-location' import { useHomeLocation } from './use-home-location'
const sys = uni.getSystemInfoSync()
const searchPanelTop = (sys.statusBarHeight ?? 0) + uni.upx2px(88)
const pageInstance = getCurrentInstance()
const { const {
MAP_ID,
latitude, latitude,
longitude, longitude,
markers,
mapCenterReady,
searchKeyword, searchKeyword,
addressText, addressText,
locating, locating,
resolvingAddress, resolvingAddress,
onRegionChange, choosingLocation,
onMapCenterChange, searchVisible,
onChooseLocation, searchCity,
onMapReady,
onMapTap,
openChooseLocation,
onOpenSearch,
onCloseSearch,
onSelectSearchPlace,
onLocate, onLocate,
onConfirm, onConfirm,
} = useHomeLocation() } = useHomeLocation({
pageInstance,
})
onReady(() => {
onMapReady()
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -1,51 +1,194 @@
import { onLoad } from '@dcloudio/uni-app' import { onLoad, onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue' import type { ComponentInternalInstance } from 'vue'
import { computed, ref } from 'vue'
import {
buildUpdateHomeBody,
isValidHomeName,
updateHome,
} from '@/api/home'
import { getErrorMessage } from '@/utils/api-error'
import { parseId } from '@/utils/device-id' 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 { staticAssets } from '@/utils/static-assets'
import { loadHomeGeo, saveHomeGeo } from '../use-home-manage' import { loadHomeGeo, saveHomeGeo } from '../use-home-manage'
import type { HomeGeoInfo } from '../home-manage.types' import type { HomeGeoInfo } from '../home-manage.types'
const DEFAULT_LATITUDE = 39.9042 const DEFAULT_LATITUDE = 39.9042
const DEFAULT_LONGITUDE = 116.4074 const DEFAULT_LONGITUDE = 116.4074
const MAP_ID = 'home-location-map'
function requestUserLocation(): Promise<UniApp.GetLocationSuccess> { interface UseHomeLocationOptions {
pageInstance?: ComponentInternalInstance | null
}
async function requestUserLocation(): Promise<UniApp.GetLocationSuccess> {
const permitted = await ensureLocationPermission()
if (!permitted) {
throw new Error('location permission denied')
}
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.getLocation({ uni.getLocation({
type: 'gcj02', type: 'gcj02',
isHighAccuracy: true, isHighAccuracy: true,
highAccuracyExpireTime: 10000,
geocode: false,
success: resolve, success: resolve,
fail: reject, fail: reject,
}) })
}) })
} }
export function useHomeLocation() { export function useHomeLocation(options: UseHomeLocationOptions = {}) {
const homeId = ref('') const homeId = ref('')
const homeName = ref('我的家')
const saving = ref(false)
const latitude = ref(DEFAULT_LATITUDE) const latitude = ref(DEFAULT_LATITUDE)
const longitude = ref(DEFAULT_LONGITUDE) const longitude = ref(DEFAULT_LONGITUDE)
const mapCenterReady = ref(false)
const searchKeyword = ref('') const searchKeyword = ref('')
const addressText = ref('') const addressText = ref('')
const locating = ref(false) const locating = ref(false)
const resolvingAddress = ref(false) const resolvingAddress = ref(false)
let geocodeTimer: ReturnType<typeof setTimeout> | null = null const choosingLocation = ref(false)
const searchVisible = ref(false)
const searchCity = ref('')
function setMapCenter(lat: number, lng: number) { let geocodeTimer: ReturnType<typeof setTimeout> | null = null
latitude.value = lat let disposed = false
longitude.value = lng let mapCtx: UniApp.MapContext | null = null
/**
* 根因:App-vue 的 <map @tap> 官方不返回经纬度(仅 App-nvue / 微信小程序支持),
* detail 常为 {},因此点击/拖动选点在 App-vue 上本身不可用。
* 正确做法:用 uni.chooseLocation 系统选点。
*/
const markers = computed(() => {
let iconPath = '/static/icon-map-pin.png'
// #ifdef H5
iconPath = staticAssets.iconMapPin
// #endif
return [
{
id: 1,
latitude: latitude.value,
longitude: longitude.value,
iconPath,
width: 28,
height: 38,
anchor: { x: 0.5, y: 1 },
},
]
})
function clearGeocodeTimer() {
if (geocodeTimer) {
clearTimeout(geocodeTimer)
geocodeTimer = null
}
} }
function scheduleAddressResolve() { function scheduleAddressResolve() {
if (geocodeTimer) clearTimeout(geocodeTimer) clearGeocodeTimer()
geocodeTimer = setTimeout(() => { geocodeTimer = setTimeout(() => {
geocodeTimer = null
void resolveAddressFromCoords() void resolveAddressFromCoords()
}, 400) }, 350)
}
function ensureMapContext(): UniApp.MapContext | null {
if (mapCtx) return mapCtx
const proxy = options.pageInstance?.proxy
mapCtx = uni.createMapContext(MAP_ID, proxy as never)
return mapCtx
}
function onMapReady() {
ensureMapContext()
}
function setLocation(lat: number, lng: number, address?: string) {
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return
latitude.value = lat
longitude.value = lng
if (address) {
addressText.value = address
return
}
addressText.value = formatCoordinateAddress(lat, lng)
scheduleAddressResolve()
}
/** 系统地图选点(App-vue 唯一可靠方案) */
function openChooseLocation() {
if (disposed || choosingLocation.value) return
choosingLocation.value = true
uni.chooseLocation({
latitude: latitude.value,
longitude: longitude.value,
success: (res) => {
if (disposed) return
const lat = Number(res.latitude)
const lng = Number(res.longitude)
if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
uni.showToast({ title: '未获取到位置', icon: 'none' })
return
}
const address = [res.name, res.address].filter(Boolean).join(' ')
|| formatCoordinateAddress(lat, lng)
setLocation(lat, lng, address)
if (res.name) searchKeyword.value = res.name
if (!res.address && !res.name) scheduleAddressResolve()
},
fail: (err) => {
const msg = String((err as { errMsg?: string })?.errMsg || '')
// 用户取消不提示
if (/cancel|取消/i.test(msg)) return
uni.showToast({ title: '选点失败,请重试', icon: 'none' })
},
complete: () => {
choosingLocation.value = false
},
})
}
/**
* 点击地图:
* - 小程序等能返回经纬度时直接落点
* - App-vue detail 为空时改走 chooseLocation
*/
function onMapTap(event: { detail?: { latitude?: number; longitude?: number } }) {
if (disposed) return
const lat = Number(event.detail?.latitude)
const lng = Number(event.detail?.longitude)
if (Number.isFinite(lat) && Number.isFinite(lng)) {
setLocation(lat, lng)
return
}
openChooseLocation()
}
function applyMapLocation(point: MapLocationPoint) {
setLocation(
point.latitude,
point.longitude,
formatMapLocation(point) || formatCoordinateAddress(point.latitude, point.longitude),
)
searchKeyword.value = point.name || point.address || ''
} }
async function resolveAddressFromCoords() { async function resolveAddressFromCoords() {
if (disposed) return
resolvingAddress.value = true resolvingAddress.value = true
try { try {
const address = await reverseGeocode(latitude.value, longitude.value) const detail = await reverseGeocodeAmapDetail(latitude.value, longitude.value)
addressText.value = address if (detail?.city) searchCity.value = detail.city
addressText.value = detail?.address
|| formatCoordinateAddress(latitude.value, longitude.value) || formatCoordinateAddress(latitude.value, longitude.value)
} finally { } finally {
resolvingAddress.value = false resolvingAddress.value = false
@@ -53,14 +196,17 @@ export function useHomeLocation() {
} }
async function initMapCenter(saved?: HomeGeoInfo) { async function initMapCenter(saved?: HomeGeoInfo) {
locating.value = true
mapCenterReady.value = false
try {
if (saved?.latitude != null && saved.longitude != null) { if (saved?.latitude != null && saved.longitude != null) {
latitude.value = saved.latitude latitude.value = saved.latitude
longitude.value = saved.longitude longitude.value = saved.longitude
addressText.value = saved.address addressText.value = saved.address || ''
if (!addressText.value) await resolveAddressFromCoords()
return return
} }
locating.value = true
try { try {
const location = await requestUserLocation() const location = await requestUserLocation()
latitude.value = location.latitude latitude.value = location.latitude
@@ -70,77 +216,63 @@ export function useHomeLocation() {
} else { } else {
await resolveAddressFromCoords() await resolveAddressFromCoords()
} }
} catch { } catch (err) {
latitude.value = DEFAULT_LATITUDE latitude.value = DEFAULT_LATITUDE
longitude.value = DEFAULT_LONGITUDE longitude.value = DEFAULT_LONGITUDE
addressText.value = formatCoordinateAddress(latitude.value, longitude.value) addressText.value = formatCoordinateAddress(latitude.value, longitude.value)
uni.showToast({ title: getLocationFailHint(err), icon: 'none' })
}
} finally { } finally {
locating.value = false locating.value = false
mapCenterReady.value = true
} }
} }
function applyMapCenter(center: { latitude: number; longitude: number }) { function onOpenSearch() {
latitude.value = center.latitude searchVisible.value = true
longitude.value = center.longitude
scheduleAddressResolve()
} }
function onRegionChange(e: UniHelper.MapRegionChangeEvent) { function onCloseSearch() {
if (e.type !== 'end') return searchVisible.value = false
const center = e.detail?.centerLocation
if (!center) return
applyMapCenter(center)
} }
function onMapCenterChange(center: { latitude: number; longitude: number }) { function onSelectSearchPlace(point: MapLocationPoint) {
applyMapCenter(center) applyMapLocation(point)
} searchVisible.value = false
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' })
},
})
} }
async function onLocate() { async function onLocate() {
locating.value = true locating.value = true
try { try {
const location = await requestUserLocation() const location = await requestUserLocation()
latitude.value = location.latitude setLocation(
longitude.value = location.longitude location.latitude,
setMapCenter(location.latitude, location.longitude) location.longitude,
if (location.address) { location.address || undefined,
addressText.value = location.address )
} else { ensureMapContext()?.moveToLocation({
await resolveAddressFromCoords() latitude: location.latitude,
} longitude: location.longitude,
} catch { })
uni.showToast({ title: '定位失败,请检查定位权限', icon: 'none' }) if (!location.address) await resolveAddressFromCoords()
} catch (err) {
uni.showToast({ title: getLocationFailHint(err), icon: 'none' })
} finally { } finally {
locating.value = false locating.value = false
} }
} }
function onConfirm() { async function onConfirm() {
if (!homeId.value) { if (!homeId.value) {
uni.navigateBack() uni.navigateBack()
return return
} }
if (!isValidHomeName(homeName.value)) {
uni.showToast({ title: '家庭名称需 2-10 个字符', icon: 'none' })
return
}
if (saving.value) return
const address = addressText.value.trim() const address = addressText.value.trim()
|| formatCoordinateAddress(latitude.value, longitude.value) || formatCoordinateAddress(latitude.value, longitude.value)
const geo: HomeGeoInfo = { const geo: HomeGeoInfo = {
@@ -148,15 +280,36 @@ export function useHomeLocation() {
latitude: latitude.value, latitude: latitude.value,
longitude: longitude.value, longitude: longitude.value,
} }
saving.value = true
try {
await updateHome(
homeId.value,
buildUpdateHomeBody(homeName.value, { geo }),
)
saveHomeGeo(homeId.value, geo) saveHomeGeo(homeId.value, geo)
uni.showToast({ title: '保存成功', icon: 'success' }) uni.showToast({ title: '保存成功', icon: 'success' })
setTimeout(() => { setTimeout(() => {
uni.navigateBack() uni.navigateBack()
}, 300) }, 300)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '保存家庭位置失败'), icon: 'none' })
} finally {
saving.value = false
} }
}
onUnload(() => {
disposed = true
clearGeocodeTimer()
mapCtx = null
})
onLoad((query?: Record<string, string | undefined>) => { onLoad((query?: Record<string, string | undefined>) => {
homeId.value = parseId(query?.homeId) homeId.value = parseId(query?.homeId)
if (query?.homeName) {
homeName.value = decodeURIComponent(String(query.homeName))
}
const saved = homeId.value ? loadHomeGeo(homeId.value) : undefined const saved = homeId.value ? loadHomeGeo(homeId.value) : undefined
if (query?.address) { if (query?.address) {
addressText.value = decodeURIComponent(String(query.address)) addressText.value = decodeURIComponent(String(query.address))
@@ -167,15 +320,24 @@ export function useHomeLocation() {
}) })
return { return {
MAP_ID,
latitude, latitude,
longitude, longitude,
markers,
mapCenterReady,
searchKeyword, searchKeyword,
addressText, addressText,
locating, locating,
resolvingAddress, resolvingAddress,
onRegionChange, choosingLocation,
onMapCenterChange, searchVisible,
onChooseLocation, searchCity,
onMapReady,
onMapTap,
openChooseLocation,
onOpenSearch,
onCloseSearch,
onSelectSearchPlace,
onLocate, onLocate,
onConfirm, onConfirm,
} }

View File

@@ -1,6 +1,11 @@
import { onShow } from '@dcloudio/uni-app' import { onShow } from '@dcloudio/uni-app'
import { ref } from 'vue' import { nextTick, ref } from 'vue'
import { fetchHomeList } from '@/api/home' import {
buildUpdateHomeBody,
createHome,
fetchHomeList,
isValidHomeName,
} from '@/api/home'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { parseId } from '@/utils/device-id' import { parseId } from '@/utils/device-id'
import type { AppHomeVo } from '@/types/location' import type { AppHomeVo } from '@/types/location'
@@ -8,6 +13,9 @@ import type { AppHomeVo } from '@/types/location'
export function useHomeList() { export function useHomeList() {
const homes = ref<AppHomeVo[]>([]) const homes = ref<AppHomeVo[]>([])
const loading = ref(false) const loading = ref(false)
const creating = ref(false)
const createDialogVisible = ref(false)
const createHomeName = ref('')
async function loadHomes() { async function loadHomes() {
loading.value = true 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(() => { onShow(() => {
void loadHomes() void loadHomes()
}) })
@@ -42,7 +81,12 @@ export function useHomeList() {
return { return {
homes, homes,
loading, loading,
creating,
createDialogVisible,
createHomeName,
onSelectHome, onSelectHome,
onAddHome,
onConfirmCreateHome,
loadHomes, loadHomes,
} }
} }

View File

@@ -1,6 +1,12 @@
import { onLoad, onShow } from '@dcloudio/uni-app' import { onLoad, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' 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 { fetchRoomList } from '@/api/location'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { fetchHomeManageStats } from './home-manage.api' import { fetchHomeManageStats } from './home-manage.api'
@@ -31,6 +37,8 @@ export function useHomeManage() {
const homeAddress = ref('') const homeAddress = ref('')
const loading = ref(false) const loading = ref(false)
const nameDialogVisible = ref(false) const nameDialogVisible = ref(false)
const currentHome = ref<AppHomeVo>()
const savingName = ref(false)
const summaryText = computed( const summaryText = computed(
() => `共${roomCount.value}个房间,${deviceCount.value}个设备`, () => `共${roomCount.value}个房间,${deviceCount.value}个设备`,
@@ -44,11 +52,22 @@ export function useHomeManage() {
fetchHomeManageStats(homeId.value), fetchHomeManageStats(homeId.value),
fetchRoomList(homeId.value), fetchRoomList(homeId.value),
]) ])
currentHome.value = stats.home
if (stats.home?.homeName) homeName.value = stats.home.homeName if (stats.home?.homeName) homeName.value = stats.home.homeName
roomCount.value = rooms.length || stats.roomCount roomCount.value = rooms.length || stats.roomCount
deviceCount.value = stats.deviceCount deviceCount.value = stats.deviceCount
const geo = loadHomeGeo(homeId.value) 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) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载家庭信息失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '加载家庭信息失败'), icon: 'none' })
} finally { } finally {
@@ -68,14 +87,31 @@ export function useHomeManage() {
nameDialogVisible.value = true nameDialogVisible.value = true
} }
function onConfirmHomeName(name: string) { async function onConfirmHomeName(name: string) {
const trimmed = name.trim() const trimmed = name.trim()
if (!trimmed) { if (!isValidHomeName(trimmed)) {
uni.showToast({ title: '请输入家庭名称', icon: 'none' }) uni.showToast({ title: '家庭名称需 2-10 个字符', icon: 'none' })
return 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 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() { function onOpenLocation() {

View File

@@ -1,11 +1,15 @@
<template> <template>
<view class="device-page"> <view class="device-page" :class="{ 'device-page--scroll-lock': homePickerOpen }">
<device-header <device-header
:home-name="homeName" :home-name="homeName"
:home-id="homeId"
:homes="homes"
@select-home="onSelectHome"
@manage="onHomeManage" @manage="onHomeManage"
@notify="onNotify" @notify="onNotify"
@add-device="onStartBind" @add-device="onStartBind"
@scan="onScan" @scan="onScan"
@picker-open-change="homePickerOpen = $event"
/> />
<room-tabs <room-tabs
:rooms="rooms" :rooms="rooms"
@@ -18,13 +22,16 @@
v-if="hasDevices" v-if="hasDevices"
:devices="devices" :devices="devices"
:online-count="onlineCount" :online-count="onlineCount"
@manage="onManageDevices"
@select="onSelectDevice" @select="onSelectDevice"
/> />
<template v-else-if="!loading"> <view v-else-if="loading" class="device-page__loading">
<device-empty :step-hint="bindStepHint" @bind="onStartBind" /> <text class="device-page__loading-text">加载中...</text>
<hot-devices :items="hotDevices" @mall="onGoMall" /> </view>
</template> <device-empty
v-else
:step-hint="bindStepHint"
@bind="onStartBind"
/>
<room-location-dialog <room-location-dialog
v-model:visible="roomDialogVisible" v-model:visible="roomDialogVisible"
@@ -37,27 +44,29 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'
import { useTabPage } from '@/hooks/use-tab-page' import { useTabPage } from '@/hooks/use-tab-page'
import DeviceEmpty from './components/device-empty/index.vue' import DeviceEmpty from './components/device-empty/index.vue'
import DeviceHeader from './components/device-header/index.vue' import DeviceHeader from './components/device-header/index.vue'
import DeviceList from './components/device-list/index.vue' import DeviceList from './components/device-list/index.vue'
import HotDevices from './components/hot-devices/index.vue'
import OperationSuccessToast from './components/operation-success-toast/index.vue' import OperationSuccessToast from './components/operation-success-toast/index.vue'
import RoomLocationDialog from './components/room-location-dialog/index.vue' import RoomLocationDialog from './components/room-location-dialog/index.vue'
import RoomTabs from './components/room-tabs/index.vue' import RoomTabs from './components/room-tabs/index.vue'
import { useDevice } from './use-device' import { useDevice } from './use-device'
const { tabCurrent } = useTabPage('device') const { tabCurrent } = useTabPage('device')
const homePickerOpen = ref(false)
const { const {
homeName, homeName,
homeId,
homes,
rooms, rooms,
activeRoomId, activeRoomId,
devices, devices,
onlineCount, onlineCount,
hasDevices, hasDevices,
loading, loading,
hotDevices,
bindStepHint, bindStepHint,
roomDialogVisible, roomDialogVisible,
successToastVisible, successToastVisible,
@@ -66,10 +75,9 @@ const {
onConfirmAddRoom, onConfirmAddRoom,
onStartBind, onStartBind,
onScan, onScan,
onGoMall,
onNotify, onNotify,
onHomeManage, onHomeManage,
onManageDevices, onSelectHome,
onSelectDevice, onSelectDevice,
} = useDevice() } = useDevice()
</script> </script>

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,22 @@
.device-room-page { .device-room-page {
min-height: 100vh; height: 100vh;
overflow: hidden;
background: #fff; 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 { .device-room-page__add-btn {

View File

@@ -5,12 +5,14 @@ import { createLocation, fetchRoomList } from '@/api/location'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { parseId, sameId } from '@/utils/device-id' import { parseId, sameId } from '@/utils/device-id'
import type { RoomOption } from '@/types/location' import type { RoomOption } from '@/types/location'
import { stashRoomSelection } from '../../device-list-patch'
import type { DeviceRoomRouteQuery } from './room.types' import type { DeviceRoomRouteQuery } from './room.types'
let openerEventChannel: UniApp.EventChannel | undefined let openerEventChannel: UniApp.EventChannel | undefined
export function useDeviceRoom() { export function useDeviceRoom() {
const homeId = ref('') const homeId = ref('')
const deviceId = ref('')
const selectedLocationId = ref('') const selectedLocationId = ref('')
const pendingLocationName = ref<string>() const pendingLocationName = ref<string>()
const roomOptions = ref<RoomOption[]>([]) const roomOptions = ref<RoomOption[]>([])
@@ -20,6 +22,7 @@ export function useDeviceRoom() {
const initialized = ref(false) const initialized = ref(false)
function applyQuery(query?: DeviceRoomRouteQuery) { function applyQuery(query?: DeviceRoomRouteQuery) {
if (query?.deviceId) deviceId.value = String(query.deviceId)
const locationId = parseId(query?.locationId) const locationId = parseId(query?.locationId)
if (locationId) { if (locationId) {
selectedLocationId.value = locationId selectedLocationId.value = locationId
@@ -124,10 +127,16 @@ export function useDeviceRoom() {
selectedLocationId.value = String(room.locationId) selectedLocationId.value = String(room.locationId)
pendingLocationName.value = room.name pendingLocationName.value = room.name
openerEventChannel?.emit('roomSelected', { const payload = {
locationId: room.locationId, locationId: room.locationId,
name: room.name, name: room.name,
}
stashRoomSelection({
deviceId: deviceId.value,
locationId: payload.locationId,
name: payload.name,
}) })
openerEventChannel?.emit('roomSelected', payload)
uni.navigateBack() uni.navigateBack()
} }

View File

@@ -2,15 +2,22 @@ import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { usePageShowRefresh } from '@/hooks/use-page-show-refresh'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { resolveValidHomeId } from '@/api/home' import { resolveValidHomeId } from '@/api/home'
import { isValidDeviceId, parseDeviceId, parseId } from '@/utils/device-id' import { fetchRoomList } from '@/api/location'
import { isValidDeviceId, parseDeviceId, parseId, sameId } from '@/utils/device-id'
import { fetchDeviceList } from '../device.api'
import { fetchAllDeviceList } from '../device.api'
import {
consumeRoomSelection,
findPatchedDeviceLocation,
findPatchedDeviceName,
rememberDeviceLocationPatch,
rememberDeviceNamePatch,
} from '../device-list-patch'
import { isBluetoothConnected } from '../detail/device-detail.utils' import { isBluetoothConnected } from '../detail/device-detail.utils'
import { unbindDevice, updateDeviceSettings } from './device-settings.api' import { unbindDevice, updateDeviceSettings } from './device-settings.api'
import type { DeviceSettingsRouteQuery } from './device-settings.types' import type { DeviceSettingsRouteQuery } from './device-settings.types'
@@ -87,7 +94,7 @@ export function useDeviceSettings() {
async function syncDeviceFromList() { async function syncDeviceFromList() {
const list = await fetchDeviceList() const list = await fetchAllDeviceList()
const device = list?.find((item) => { const device = list?.find((item) => {
@@ -113,14 +120,35 @@ export function useDeviceSettings() {
if (device.deviceNo) deviceNo.value = device.deviceNo 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) const parsedHomeId = parseId(device.homeId)
if (parsedHomeId) homeId.value = parsedHomeId 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) const parsedLocationId = parseId(device.locationId)
if (parsedLocationId) locationId.value = parsedLocationId 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 return true
} }
@@ -178,11 +206,21 @@ export function useDeviceSettings() {
async function onConfirmRoom(data: { locationId: string | number; name: string }) { async function onConfirmRoom(data: { locationId: string | number; name: string }) {
if (!isValidDeviceId(deviceId.value)) { const nextLocationId = String(data.locationId)
locationId.value = String(data.locationId) const nextLocationName = data.name?.trim() || ''
locationName.value = data.name if (!nextLocationId || !nextLocationName) return
if (sameId(locationId.value, nextLocationId) && locationName.value === nextLocationName) {
return 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 if (saving.value) return
saving.value = true saving.value = true
@@ -192,10 +230,8 @@ export function useDeviceSettings() {
await updateDeviceSettings({ await updateDeviceSettings({
deviceId: deviceId.value, deviceId: deviceId.value,
homeId: validHomeId, homeId: validHomeId,
locationId: data.locationId, locationId: nextLocationId,
}) })
locationId.value = String(data.locationId)
locationName.value = data.name
uni.showToast({ title: '修改成功', icon: 'success' }) uni.showToast({ title: '修改成功', icon: 'success' })
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '修改房间失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '修改房间失败'), icon: 'none' })
@@ -233,6 +269,7 @@ export function useDeviceSettings() {
await updateDeviceSettings({ deviceId: deviceId.value, name: trimmed }) await updateDeviceSettings({ deviceId: deviceId.value, name: trimmed })
deviceName.value = trimmed deviceName.value = trimmed
rememberDeviceNamePatch(deviceId.value, trimmed)
uni.showToast({ title: '修改成功', icon: 'success' }) uni.showToast({ title: '修改成功', icon: 'success' })
@@ -302,18 +339,22 @@ export function useDeviceSettings() {
onLoad((query?: DeviceSettingsRouteQuery) => { async function reloadFromServer() {
const pendingRoom = consumeRoomSelection(deviceId.value)
applyQuery(query) if (pendingRoom) {
// 仅消费房间选择结果;已与当前一致则不再请求/弹 toast
void (async () => { await onConfirmRoom(pendingRoom)
}
await syncDeviceFromList() await syncDeviceFromList()
homeId.value = await resolveValidHomeId(homeId.value) homeId.value = await resolveValidHomeId(homeId.value)
})() }
onLoad((query?: DeviceSettingsRouteQuery) => {
applyQuery(query)
void reloadFromServer()
}) })
usePageShowRefresh(() => reloadFromServer(), { skipInitialShow: true })
return { return {

View File

@@ -1,15 +1,28 @@
import { onShow } from '@dcloudio/uni-app' import { onHide, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox' 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 { parseId, sameId } from '@/utils/device-id'
import type { AppHomeVo } from '@/types/location'
import { createLocation } from '@/api/location' import { createLocation } from '@/api/location'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { fetchRoomList } from '@/api/location' import { fetchRoomList } from '@/api/location'
import { fetchDeviceList } from './device.api' import { fetchDeviceList } from './device.api'
import type { DeviceListItem, HotDeviceItem, RoomTab } from './device.types' import type { DeviceListItem, RoomTab } from './device.types'
import type { LocationMap } from './device.utils' import type { LocationMap } from './device.utils'
import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home'
import { refreshDevicePresence } from './device-presence' import { refreshDevicePresence } from './device-presence'
import {
applyDeviceListPatches,
mergeDevicePresenceFields,
} from './device-list-patch'
import { import {
buildRoomTabs, buildRoomTabs,
countOnlineDevices, countOnlineDevices,
@@ -17,31 +30,23 @@ import {
mapDeviceItem, mapDeviceItem,
} from './device.utils' } from './device.utils'
const DEFAULT_HOT_DEVICES: HotDeviceItem[] = [ /** 在线态轮询:缩短以便关机后尽快变为离线 */
{ const PRESENCE_INTERVAL_MS = 8000
id: 'z2',
name: 'Z2 空气净化器',
desc: '高效除醛 · 智能检测',
},
{
id: 'lamp',
name: '智能护眼台灯',
desc: '无频闪 · 多场景模式',
},
]
export function useDevice() { export function useDevice() {
const homeName = ref('我的家') const homeName = ref('我的家')
const homeId = ref('') const homeId = ref('')
const homes = ref<AppHomeVo[]>([])
const rooms = ref<RoomTab[]>([{ id: 'all', name: '全部' }]) const rooms = ref<RoomTab[]>([{ id: 'all', name: '全部' }])
const activeRoomId = ref('all') const activeRoomId = ref('all')
const devices = ref<DeviceListItem[]>([]) const devices = ref<DeviceListItem[]>([])
const loading = ref(false) const loading = ref(false)
const hotDevices = ref<HotDeviceItem[]>(DEFAULT_HOT_DEVICES)
const bindStepHint = ref(3) const bindStepHint = ref(3)
const roomDialogVisible = ref(false) const roomDialogVisible = ref(false)
const successToastVisible = ref(false) const successToastVisible = ref(false)
let presenceTimer: ReturnType<typeof setInterval> | undefined
const hasDevices = computed(() => devices.value.length > 0) const hasDevices = computed(() => devices.value.length > 0)
const filteredDevices = computed(() => const filteredDevices = computed(() =>
@@ -76,43 +81,130 @@ export function useDevice() {
} }
} }
async function loadDevices() { function applyCurrentHome(homeList: AppHomeVo[]) {
if (loading.value) return const currentHome = findHomeById(homeList, homeId.value) ?? pickDefaultHome(homeList)
loading.value = true const currentId = getHomeId(currentHome)
try { if (currentId) {
const list = await fetchDeviceList() ?? [] homeId.value = currentId
const homeIds = [ saveSelectedHomeId(currentId)
...new Set(
list
.map((item) => parseId(item.homeId))
.filter((id) => id !== ''),
),
]
if (!homeIds.length) {
const defaultHomeId = await resolveValidHomeId()
if (defaultHomeId) homeIds.push(defaultHomeId)
} }
const locationMap = await buildLocationMap(homeIds) homeName.value = currentHome?.homeName?.trim() || '我的家'
const deviceHomeId = parseId(list.find((item) => item.homeId != null)?.homeId) }
homeId.value = await resolveValidHomeId(deviceHomeId || homeIds[0])
const homes = await fetchHomeList() async function loadHomeList() {
const currentHome = homes?.find((item) => sameId(item.id, homeId.value)) homes.value = await fetchHomeList() ?? []
if (currentHome?.homeName) homeName.value = currentHome.homeName 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) applyRoomTabs(locationMap)
devices.value = list.map((item) => mapDeviceItem(item, locationMap)) const mapped = list.map((item) => mapDeviceItem(item, locationMap))
devices.value = await refreshDevicePresence(devices.value) // 先写入接口数据(含最新名称),再异步合并在线状态,避免 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) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载设备失败'), icon: 'none' }) 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 { } finally {
loading.value = false 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(() => { 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() void refreshUnreadMessageCount()
startPresencePolling()
}) })
onHide(stopPresencePolling)
function showOperationSuccess() { function showOperationSuccess() {
successToastVisible.value = true successToastVisible.value = true
} }
@@ -148,17 +240,14 @@ export function useDevice() {
} }
function onStartBind() { 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() { function onScan() {
uni.showToast({ title: '扫一扫功能开发中', icon: 'none' }) uni.showToast({ title: '扫一扫功能开发中', icon: 'none' })
} }
function onGoMall() {
uni.showToast({ title: '商城功能开发中', icon: 'none' })
}
function onNotify() { function onNotify() {
uni.navigateTo({ url: '/pages/mine/notify/index' }) uni.navigateTo({ url: '/pages/mine/notify/index' })
} }
@@ -167,10 +256,6 @@ export function useDevice() {
uni.navigateTo({ url: '/pages/device/home-manage/index' }) uni.navigateTo({ url: '/pages/device/home-manage/index' })
} }
function onManageDevices() {
uni.showToast({ title: '设备管理功能开发中', icon: 'none' })
}
function onSelectDevice(device: DeviceListItem) { function onSelectDevice(device: DeviceListItem) {
if (!device.deviceId) { if (!device.deviceId) {
uni.showToast({ title: '设备信息不完整', icon: 'none' }) uni.showToast({ title: '设备信息不完整', icon: 'none' })
@@ -193,13 +278,14 @@ export function useDevice() {
return { return {
homeName, homeName,
homeId,
homes,
rooms, rooms,
activeRoomId, activeRoomId,
devices: filteredDevices, devices: filteredDevices,
onlineCount, onlineCount,
hasDevices, hasDevices,
loading, loading,
hotDevices,
bindStepHint, bindStepHint,
roomDialogVisible, roomDialogVisible,
successToastVisible, successToastVisible,
@@ -208,10 +294,9 @@ export function useDevice() {
onConfirmAddRoom, onConfirmAddRoom,
onStartBind, onStartBind,
onScan, onScan,
onGoMall,
onNotify, onNotify,
onHomeManage, onHomeManage,
onManageDevices, onSelectHome,
onSelectDevice, onSelectDevice,
loadDevices, loadDevices,
} }

View File

@@ -57,7 +57,7 @@ export function useForgotPassword() {
return return
} }
uni.navigateTo({ 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) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' })

View File

@@ -8,7 +8,16 @@
</view> </view>
</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="phone" icon="phone" type="number" placeholder="请输入手机号" :maxlength="11" />
<base-input v-model="code" icon="shield" type="number" placeholder="请输入验证码" :maxlength="6"> <base-input v-model="code" icon="shield" type="number" placeholder="请输入验证码" :maxlength="6">
<template #suffix> <template #suffix>
@@ -20,18 +29,9 @@
</view> </view>
</template> </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__footer">
<view class="login-page__agreement"> <view class="login-page__agreement">
<agreement-checkbox v-model="agreed" /> <agreement-checkbox v-model="agreed" confirm-before-agree />
</view> </view>
<primary-button text="登录" @click="submit" /> <primary-button text="登录" @click="submit" />
<view class="login-page__register"> <view class="login-page__register">

View File

@@ -1,16 +1,24 @@
import { onShow } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { useSmsCode } from '@/hooks/use-sms-code' 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 { getErrorMessage } from '@/utils/api-error'
import { setupMessageInbox } from '@/hooks/use-message-inbox' import { setupMessageInbox } from '@/hooks/use-message-inbox'
import { getStoredToken } from '@/utils/auth-token' import { getStoredToken } from '@/utils/auth-token'
import { clearLocalUserDataPreservingAuth } from '@/utils/clear-local-user-data'
import { SMS_CODE_SCENE } from '@/types/api' import { SMS_CODE_SCENE } from '@/types/api'
import { syncCsAuthByPassword, syncCsAuthBySms } from '@/api/cs-auth'
import { loginByPassword, loginBySms } from './login.api' import { loginByPassword, loginBySms } from './login.api'
import type { LoginMode } from './login.types' import type { LoginMode } from './login.types'
export function useLogin() { export function useLogin() {
const mode = ref<LoginMode>('code') const mode = ref<LoginMode>('password')
const agreed = ref(true) const agreed = ref(false)
const phone = ref('') const phone = ref('')
const code = ref('') const code = ref('')
const account = ref('') const account = ref('')
@@ -46,11 +54,16 @@ export function useLogin() {
return return
} }
await loginBySms({ phone: phone.value, code: code.value }) await loginBySms({ phone: phone.value, code: code.value })
await syncCsAuthBySms(phone.value, code.value)
} else { } else {
if (!account.value.trim()) { if (!account.value.trim()) {
uni.showToast({ title: '请输入账号', icon: 'none' }) uni.showToast({ title: '请输入账号', icon: 'none' })
return return
} }
if (!password.value.trim()) {
uni.showToast({ title: LOGIN_PASSWORD_EMPTY_TOAST, icon: 'none' })
return
}
if (!isValidPassword(password.value)) { if (!isValidPassword(password.value)) {
uni.showToast({ title: '密码至少 6 位', icon: 'none' }) uni.showToast({ title: '密码至少 6 位', icon: 'none' })
return return
@@ -59,11 +72,13 @@ export function useLogin() {
account: account.value, account: account.value,
password: password.value, password: password.value,
}) })
await syncCsAuthByPassword(account.value, password.value)
} }
if (!getStoredToken()) { if (!getStoredToken()) {
uni.showToast({ title: '登录失败,未获取到令牌', icon: 'none' }) uni.showToast({ title: '登录失败,未获取到令牌', icon: 'none' })
return return
} }
clearLocalUserDataPreservingAuth()
setupMessageInbox() setupMessageInbox()
uni.showToast({ title: '登录成功', icon: 'success' }) uni.showToast({ title: '登录成功', icon: 'success' })
uni.reLaunch({ url: '/pages/device/index' }) uni.reLaunch({ url: '/pages/device/index' })
@@ -82,6 +97,12 @@ export function useLogin() {
uni.navigateTo({ url: '/pages/forgot-password/index' }) uni.navigateTo({ url: '/pages/forgot-password/index' })
} }
onShow(() => {
if (!getStoredToken()) return
setupMessageInbox()
uni.reLaunch({ url: '/pages/device/index' })
})
return { return {
mode, mode,
agreed, agreed,

View File

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

View File

@@ -1,15 +1,17 @@
import { onLoad } from '@dcloudio/uni-app' import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { fetchProfile } from '@/api/profile'
import { useSmsCode } from '@/hooks/use-sms-code' import { useSmsCode } from '@/hooks/use-sms-code'
import { SMS_CODE_SCENE } from '@/types/api' import { SMS_CODE_SCENE } from '@/types/api'
import { getErrorMessage } from '@/utils/api-error' 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' import { verifyNewPhone } from '../change-phone.api'
export function useChangePhoneBind() { export function useChangePhoneBind() {
const phone = ref('') const phone = ref('')
const code = ref('') const code = ref('')
const changeToken = ref('') const changeToken = ref('')
const boundPhone = ref('')
const loading = ref(false) const loading = ref(false)
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.changePhoneNew, { 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() { function onSendCode() {
if (!ensureNewPhoneDiffersFromBound()) return
sendCode(phone.value) sendCode(phone.value)
} }
@@ -37,10 +62,7 @@ export function useChangePhoneBind() {
uni.showToast({ title: '换绑令牌无效,请重新验证', icon: 'none' }) uni.showToast({ title: '换绑令牌无效,请重新验证', icon: 'none' })
return return
} }
if (!isValidPhone(phone.value)) { if (!ensureNewPhoneDiffersFromBound()) return
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
return
}
if (!isValidSmsCode(code.value)) { if (!isValidSmsCode(code.value)) {
uni.showToast({ title: '请输入验证码', icon: 'none' }) uni.showToast({ title: '请输入验证码', icon: 'none' })
return return
@@ -61,6 +83,10 @@ export function useChangePhoneBind() {
} }
} }
onShow(() => {
void loadBoundPhone()
})
return { return {
phone, phone,
code, code,

View File

@@ -33,17 +33,6 @@
margin-top: 16rpx; 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) { .change-phone-page__form :deep(.base-input) {
border: none; border: none;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04); box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

View File

@@ -1,4 +1,4 @@
<template> <template>
<view class="change-phone-page"> <view class="change-phone-page">
<app-navbar title="手机号换绑" /> <app-navbar title="手机号换绑" />
<view class="change-phone-page__body"> <view class="change-phone-page__body">
@@ -17,10 +17,6 @@
<view class="change-phone-page__btn"> <view class="change-phone-page__btn">
<primary-button text="下一步" @click="nextStep" /> <primary-button text="下一步" @click="nextStep" />
</view> </view>
<view class="change-phone-page__link-row">
<text class="change-phone-page__link" @tap="onUnavailablePhone">原手机号码已不可用?</text>
</view>
</view> </view>
</view> </view>
</template> </template>
@@ -28,8 +24,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { useChangePhoneVerify } from './use-change-phone-verify' import { useChangePhoneVerify } from './use-change-phone-verify'
const { phone, code, counting, seconds, subtitle, onSendCode, onUnavailablePhone, nextStep } = const { phone, code, counting, seconds, subtitle, onSendCode, nextStep } = useChangePhoneVerify()
useChangePhoneVerify()
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -4,11 +4,11 @@ import { fetchProfile } from '@/api/profile'
import { useSmsCode } from '@/hooks/use-sms-code' import { useSmsCode } from '@/hooks/use-sms-code'
import { SMS_CODE_SCENE } from '@/types/api' import { SMS_CODE_SCENE } from '@/types/api'
import { getErrorMessage } from '@/utils/api-error' 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' import { verifyOldPhone } from './change-phone.api'
function maskPhone(phone: string): string { function maskPhone(phone: string): string {
const digits = phone.replace(/\D/g, '') const digits = normalizePhoneDigits(phone)
if (digits.length < 7) return phone if (digits.length < 7) return phone
return digits.replace(/(\d{3})\d{4}(\d+)/, '$1****$2') 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() { function onSendCode() {
if (!ensureInputMatchesBoundPhone()) return
sendCode(phone.value) 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() { async function nextStep() {
if (!isValidPhone(phone.value)) { if (!ensureInputMatchesBoundPhone()) return
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
return
}
if (!isValidSmsCode(code.value)) { if (!isValidSmsCode(code.value)) {
uni.showToast({ title: '请输入验证码', icon: 'none' }) uni.showToast({ title: '请输入验证码', icon: 'none' })
return return
@@ -93,7 +97,6 @@ export function useChangePhoneVerify() {
seconds, seconds,
subtitle, subtitle,
onSendCode, onSendCode,
onUnavailablePhone,
nextStep, nextStep,
} }
} }

View File

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

View File

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

View File

@@ -1,10 +1,10 @@
<template> <template>
<view class="edit-profile-page"> <view class="edit-profile-page">
<view class="edit-profile-page__navbar"> <view class="edit-profile-page__navbar">
<app-navbar title="编辑资料" /> <app-navbar title="编辑资料" />
</view> </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__body">
<view class="edit-profile-page__avatar-section"> <view class="edit-profile-page__avatar-section">
<view class="edit-profile-page__avatar-wrap"> <view class="edit-profile-page__avatar-wrap">
@@ -102,23 +102,9 @@
/> />
</view> </view>
</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>
</view> </page-scroll-view>
</view>
</scroll-view>
<view class="edit-profile-page__footer"> <view class="edit-profile-page__footer">
<view <view
@@ -166,7 +152,6 @@ const {
saving, saving,
uploadingAvatar, uploadingAvatar,
form, form,
maskedPhone,
genderText, genderText,
locationText, locationText,
regionPickerVisible, regionPickerVisible,
@@ -182,7 +167,6 @@ const {
onBirthdayChange, onBirthdayChange,
onOpenRegionPicker, onOpenRegionPicker,
onConfirmRegion, onConfirmRegion,
onChangePhone,
onSave, onSave,
} = useEditProfile() } = useEditProfile()
</script> </script>

View File

@@ -1,4 +1,4 @@
import { onShow } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { fetchProfile, updateProfile, uploadProfileAvatar } from '@/api/profile' import { fetchProfile, updateProfile, uploadProfileAvatar } from '@/api/profile'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
@@ -16,16 +16,16 @@ const GENDER_OPTIONS = [
{ value: '0', label: '未知' }, { 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 { function formatLocation(province: string, city: string, district: string): string {
const primary = province || city const parts: string[] = []
if (primary && district) return `${primary} · ${district}` for (const part of [province, city, district]) {
return primary || district || '未设置' const text = part.trim()
if (!text) continue
if (parts[parts.length - 1] === text) continue
parts.push(text)
}
return parts.length ? parts.join(' ') : '未设置'
} }
function createEmptyForm(): ProfileFormState { function createEmptyForm(): ProfileFormState {
@@ -36,7 +36,6 @@ function createEmptyForm(): ProfileFormState {
province: '', province: '',
city: '', city: '',
district: '', district: '',
phonenumber: '',
avatarUrl: '', avatarUrl: '',
avatarOssId: '', avatarOssId: '',
} }
@@ -51,16 +50,11 @@ export function useEditProfile() {
const nicknameDialogVisible = ref(false) const nicknameDialogVisible = ref(false)
const regionPickerVisible = ref(false) const regionPickerVisible = ref(false)
const maskedPhone = computed(() => maskPhone(form.value.phonenumber))
const genderText = computed(() => GENDER_LABELS[form.value.gender] || '未知') const genderText = computed(() => GENDER_LABELS[form.value.gender] || '未知')
const locationText = computed(() => const locationText = computed(() =>
formatLocation(form.value.province, form.value.city, form.value.district), formatLocation(form.value.province, form.value.city, form.value.district),
) )
async function loadProfile() { function applyProfile(profile: Awaited<ReturnType<typeof fetchProfile>>) {
if (loading.value) return
loading.value = true
try {
const profile = await fetchProfile()
form.value = { form.value = {
nickName: profile.nickName || profile.userName || '', nickName: profile.nickName || profile.userName || '',
gender: profile.gender || '0', gender: profile.gender || '0',
@@ -68,10 +62,16 @@ export function useEditProfile() {
province: profile.province || '', province: profile.province || '',
city: profile.city || '', city: profile.city || '',
district: profile.district || '', district: profile.district || '',
phonenumber: profile.phonenumber || profile.userName || '',
avatarUrl: profile.avatarUrl || '', avatarUrl: profile.avatarUrl || '',
avatarOssId: profile.avatarOssId ? String(profile.avatarOssId) : '', avatarOssId: profile.avatarOssId ? String(profile.avatarOssId) : '',
} }
}
async function loadProfile() {
if (loading.value) return
loading.value = true
try {
applyProfile(await fetchProfile())
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载资料失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '加载资料失败'), icon: 'none' })
} finally { } finally {
@@ -79,6 +79,16 @@ export function useEditProfile() {
} }
} }
/** 从换绑手机号等子页返回时只刷新手机号,避免覆盖未保存的头像等编辑 */
async function refreshPhoneFromServer() {
try {
const profile = await fetchProfile()
form.value.phonenumber = profile.phonenumber || profile.userName || ''
} catch {
// 静默失败,保留当前表单
}
}
function onOpenAvatarSheet() { function onOpenAvatarSheet() {
avatarSheetVisible.value = true avatarSheetVisible.value = true
} }
@@ -105,6 +115,7 @@ export function useEditProfile() {
const filePath = res.tempFilePaths[0] const filePath = res.tempFilePaths[0]
if (!filePath) return if (!filePath) return
form.value.avatarUrl = filePath
uploadingAvatar.value = true uploadingAvatar.value = true
uni.showLoading({ title: '上传中...', mask: true }) uni.showLoading({ title: '上传中...', mask: true })
const uploaded = await uploadProfileAvatar(filePath) const uploaded = await uploadProfileAvatar(filePath)
@@ -163,10 +174,6 @@ export function useEditProfile() {
form.value.district = value.district form.value.district = value.district
} }
function onChangePhone() {
uni.navigateTo({ url: '/pages/mine/change-phone/index' })
}
async function onSave() { async function onSave() {
const nickName = form.value.nickName.trim() const nickName = form.value.nickName.trim()
if (!nickName) { if (!nickName) {
@@ -200,7 +207,7 @@ export function useEditProfile() {
} }
} }
onShow(() => { onLoad(() => {
void loadProfile() void loadProfile()
}) })
@@ -209,7 +216,6 @@ export function useEditProfile() {
saving, saving,
uploadingAvatar, uploadingAvatar,
form, form,
maskedPhone,
genderText, genderText,
locationText, locationText,
regionPickerVisible, regionPickerVisible,
@@ -225,7 +231,6 @@ export function useEditProfile() {
onBirthdayChange, onBirthdayChange,
onOpenRegionPicker, onOpenRegionPicker,
onConfirmRegion, onConfirmRegion,
onChangePhone,
onSave, onSave,
} }
} }

View File

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

View File

@@ -1,13 +1,29 @@
import { resolveValidHomeId } from '@/api/home'
import { fetchProfile } from '@/api/profile' import { fetchProfile } from '@/api/profile'
import { fetchDeviceList } from '../device/device.api' import { fetchAllDeviceList, fetchDeviceList } from '../device/device.api'
export async function fetchMineOverview() { async function fetchDeviceCountForMine(): Promise<number> {
const [profile, devices] = await Promise.all([ try {
fetchProfile(), const devices = await fetchAllDeviceList()
fetchDeviceList(), return devices?.length ?? 0
]) } catch {
return { try {
profile, const homeId = await resolveValidHomeId()
deviceCount: devices?.length ?? 0, 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,
} }
} }

View File

@@ -1,39 +1,91 @@
<template> <template>
<view class="notify-page"> <view class="notify-page">
<app-navbar title="通知"> <view class="notify-page__top">
<template #right> <app-navbar title="通知" />
<view class="notify-page__mark-all" @tap="onMarkAllRead">
<text class="notify-page__mark-all-text">全部已读</text>
</view>
</template>
</app-navbar>
<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" class="notify-page__scroll"
scroll-y top-selector=".notify-page__top"
refresher-enabled refresher-enabled
:refresher-triggered="loading" :refresher-triggered="refreshing"
:lower-threshold="120"
@refresherrefresh="onRefresh" @refresherrefresh="onRefresh"
@scrolltolower="onLoadMore" @scrolltolower="onLoadMore"
> >
<view class="notify-page__body"> <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 <view
v-for="item in messages" v-for="row in messageRows"
:key="normalizeId(item)" :key="row.id"
class="notify-page__item" 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__item-head">
<view class="notify-page__title-wrap"> <view class="notify-page__title-wrap">
<view v-if="isUnreadMessage(item)" class="notify-page__dot" /> <text class="notify-page__title">{{ row.title }}</text>
<text class="notify-page__title">{{ item.title || '系统通知' }}</text>
</view> </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> </view>
<text class="notify-page__content">{{ item.content || '暂无详情' }}</text>
</view> </view>
</view> </view>
@@ -41,38 +93,44 @@
暂无通知消息 暂无通知消息
</view> </view>
<view v-if="loading && !messages.length" class="notify-page__loading"> <view v-if="loading && !messageRows.length" class="notify-page__loading">
加载中... 加载中...
</view> </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>
</view> </view>
</scroll-view> </view>
</page-scroll-view>
</view> </view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type { AppMessageVo } from '@/types/message' import { staticAssets } from '@/utils/static-assets'
import { formatNotifyTime, isUnreadMessage, normalizeMessageId } from './notify.utils'
import { useNotify } from './use-notify' import { useNotify } from './use-notify'
const { const {
messages, messageRows,
homes,
selectedHomeId,
selectedHomeLabel,
homePickerOpen,
unreadCountText,
loading, loading,
refreshing,
hasMore, hasMore,
sectionTitle, toggleHomePicker,
closeHomePicker,
onSelectHome,
isHomeOptionActive,
onRefresh, onRefresh,
onLoadMore, onLoadMore,
onItemTap, onItemTap,
onMarkAllRead, onMarkAllRead,
allHomesId,
parseHomeId,
} = useNotify() } = useNotify()
function normalizeId(item: AppMessageVo) {
return normalizeMessageId(item) || `${item.title}-${item.timestamp}`
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -1,25 +1,111 @@
.notify-page { .notify-page {
min-height: 100vh; height: 100vh;
background: #fff; background: #f7f8fa;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
overflow: hidden;
}
.notify-page__top {
flex-shrink: 0;
} }
.notify-page__scroll { .notify-page__scroll {
width: 100%;
flex: 1; flex: 1;
height: 0; min-height: 0;
} }
.notify-page__body { .notify-page__body {
min-height: 100%; min-height: 100%;
padding: 0 24rpx 32rpx;
} }
.notify-page__section { .notify-page__filter-wrap {
display: block; position: relative;
padding: 16rpx 32rpx 8rpx; 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; font-size: 26rpx;
color: #98a2b3; color: #667085;
line-height: 1.4;
} }
.notify-page__list { .notify-page__list {
@@ -27,34 +113,65 @@
} }
.notify-page__item { .notify-page__item {
padding: 28rpx 32rpx; display: flex;
gap: 20rpx;
padding: 28rpx;
border-bottom: 1rpx solid #f2f4f7; 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 { .notify-page__item-head {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
justify-content: space-between; justify-content: space-between;
gap: 24rpx; gap: 16rpx;
width: 100%;
min-width: 0;
} }
.notify-page__title-wrap { .notify-page__title-wrap {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
display: flex; overflow: hidden;
align-items: center;
gap: 12rpx;
}
.notify-page__dot {
width: 12rpx;
height: 12rpx;
border-radius: 50%;
background: #1ec671;
flex-shrink: 0;
} }
.notify-page__title { .notify-page__title {
display: block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 30rpx; font-size: 30rpx;
font-weight: 600; font-weight: 600;
color: #1a1a1a; color: #1a1a1a;
@@ -62,7 +179,16 @@
} }
.notify-page__time { .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; font-size: 24rpx;
color: #98a2b3; color: #98a2b3;
line-height: 1.4; line-height: 1.4;
@@ -72,36 +198,37 @@
display: block; display: block;
margin-top: 12rpx; margin-top: 12rpx;
font-size: 26rpx; font-size: 26rpx;
color: #98a2b3; color: #667085;
line-height: 1.55; line-height: 1.55;
} }
.notify-page__empty, .notify-page__empty,
.notify-page__loading { .notify-page__loading {
margin: 32rpx; margin: 32rpx 28rpx;
padding: 24rpx; padding: 24rpx;
border-radius: 16rpx; border-radius: 16rpx;
background: #f7f8fa; background: #f7f8fa;
text-align: center; text-align: center;
font-size: 26rpx;
color: #98a2b3;
} }
.notify-page__footer-tip { .notify-page__footer-tip {
padding: 80rpx 32rpx; padding: 48rpx 32rpx;
text-align: center; text-align: center;
font-size: 26rpx; font-size: 26rpx;
color: #98a2b3; color: #98a2b3;
} }
.notify-page__mark-all { .notify-page__mark-all {
display: flex; padding: 8rpx 20rpx;
align-items: center; border: 1rpx solid #93c5fd;
justify-content: flex-end; border-radius: 28rpx;
padding: 8rpx 0;
} }
.notify-page__mark-all-text { .notify-page__mark-all-text {
font-size: 26rpx; font-size: 24rpx;
color: #1ec671; color: #3b82f6;
white-space: nowrap; white-space: nowrap;
line-height: 1; line-height: 1;
} }

View File

@@ -1,13 +1,45 @@
import type { AppMessageVo } from '@/types/message' 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 { 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 { export function isUnreadMessage(message: AppMessageVo): boolean {
const flag = message.readFlag const flag = message.readFlag
return flag === 0 || flag === '0' 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 { export function formatNotifyTime(message: AppMessageVo): string {
const raw = message.timestamp || message.createTime const raw = message.timestamp || message.createTime
if (!raw) return '' 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) const date = /^\d{13,}$/.test(text) ? new Date(Number(text)) : new Date(text)
if (Number.isNaN(date.getTime())) return 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)
} }

View File

@@ -1,5 +1,6 @@
import { onShow, onUnload } from '@dcloudio/uni-app' import { onShow, onUnload } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { fetchHomeList, getHomeId } from '@/api/home'
import { import {
fetchMessagePage, fetchMessagePage,
markAllMessagesRead, markAllMessagesRead,
@@ -7,6 +8,7 @@ import {
} from '@/api/message' } from '@/api/message'
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox' import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { sameId } from '@/utils/device-id'
import { onMessagePush } from '@/utils/message-socket' import { onMessagePush } from '@/utils/message-socket'
import { import {
clearPushCache, clearPushCache,
@@ -15,42 +17,108 @@ import {
rememberPushPayload, rememberPushPayload,
} from '@/utils/message-push-cache' } from '@/utils/message-push-cache'
import type { AppMessageVo } from '@/types/message' import type { AppMessageVo } from '@/types/message'
import type { AppHomeVo } from '@/types/location'
import { import {
formatNotifyContent,
formatNotifyLocation,
formatNotifyTime, formatNotifyTime,
isUnreadMessage, isUnreadMessage,
messageMatchesHome,
normalizeMessageId, normalizeMessageId,
} from './notify.utils' } 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 PAGE_SIZE = 20
const ALL_HOMES_ID = ''
export function useNotify() { export function useNotify() {
const messages = ref<AppMessageVo[]>([]) const messages = ref<AppMessageVo[]>([])
const homes = ref<AppHomeVo[]>([])
const selectedHomeId = ref(ALL_HOMES_ID)
const homePickerOpen = ref(false)
const loading = ref(false) const loading = ref(false)
const refreshing = ref(false)
const loadingMore = ref(false) const loadingMore = ref(false)
const pageNum = ref(1) const pageNum = ref(1)
const total = ref(0) const total = ref(0)
const sectionTitle = ref('全部家庭')
const hasMore = computed(() => messages.value.length < total.value) 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 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) { async function loadMessages(reset = false) {
if (loading.value || loadingMore.value) return if (loading.value || loadingMore.value) return
if (reset) { if (reset) {
pageNum.value = 1 pageNum.value = 1
if (!messages.value.length) {
loading.value = true loading.value = true
}
} else { } else {
if (!hasMore.value && messages.value.length > 0) return if (!hasMore.value && messages.value.length > 0) return
loadingMore.value = true loadingMore.value = true
} }
try { try {
const { rows, total: nextTotal } = await fetchMessagePage({ const query = {
pageNum: pageNum.value, pageNum: pageNum.value,
pageSize: PAGE_SIZE, pageSize: PAGE_SIZE,
}) ...(selectedHomeId.value ? { homeId: selectedHomeId.value } : {}),
const mergedRows = mergeCachedMessages(rows) }
const { rows, total: nextTotal } = await fetchMessagePage(query)
const mergedRows = filterMessagesForHome(mergeCachedMessages(rows))
if (reset) { if (reset) {
messages.value = mergedRows messages.value = mergedRows
} else { } else {
@@ -62,8 +130,6 @@ export function useNotify() {
messages.value = Array.from(map.values()) messages.value = Array.from(map.values())
} }
total.value = Math.max(nextTotal, messages.value.length) 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) { if (rows.length > 0) {
pageNum.value += 1 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 loadMessages(true)
await refreshUnreadMessageCount() 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() { async function onLoadMore() {
if (loadingMore.value || !hasMore.value) return
await loadMessages(false) await loadMessages(false)
} }
@@ -125,6 +217,9 @@ export function useNotify() {
const incoming = rememberPushPayload(payload) const incoming = rememberPushPayload(payload)
if (!incoming) return if (!incoming) return
const homeName = selectedHome.value?.homeName?.trim() || ''
if (!messageMatchesHome(incoming, selectedHomeId.value, homeName)) return
const incomingId = normalizeMessageId(incoming) const incomingId = normalizeMessageId(incoming)
const exists = messages.value.some((item) => normalizeMessageId(item) === incomingId) const exists = messages.value.some((item) => normalizeMessageId(item) === incomingId)
if (exists) return if (exists) return
@@ -133,12 +228,20 @@ export function useNotify() {
total.value = messages.value.length total.value = messages.value.length
} }
function isHomeOptionActive(home: AppHomeVo): boolean {
return sameId(getHomeId(home), selectedHomeId.value)
}
onShow(() => { onShow(() => {
unsubscribePush?.() unsubscribePush?.()
unsubscribePush = onMessagePush((payload) => { unsubscribePush = onMessagePush((payload) => {
prependPushMessage(payload) prependPushMessage(payload)
}) })
void onRefresh() void loadHomes()
void (async () => {
await loadMessages(true)
await refreshUnreadMessageCount()
})()
}) })
onUnload(() => { onUnload(() => {
@@ -148,15 +251,25 @@ export function useNotify() {
return { return {
messages, messages,
messageRows,
homes,
selectedHomeId,
selectedHomeLabel,
homePickerOpen,
unreadCountText,
loading, loading,
refreshing,
loadingMore, loadingMore,
hasMore, hasMore,
sectionTitle, toggleHomePicker,
formatNotifyTime, closeHomePicker,
isUnreadMessage, onSelectHome,
isHomeOptionActive,
onRefresh, onRefresh,
onLoadMore, onLoadMore,
onItemTap, onItemTap,
onMarkAllRead, onMarkAllRead,
allHomesId: ALL_HOMES_ID,
parseHomeId: getHomeId,
} }
} }

View File

@@ -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>

View File

@@ -1,8 +1,8 @@
<template> <template>
<view class="privacy-page"> <view class="privacy-page">
<app-navbar title="账号与安全" /> <app-navbar title="隐私与安全" />
<scroll-view class="privacy-page__scroll" scroll-y> <page-scroll-view class="privacy-page__scroll">
<view class="privacy-page__body"> <view class="privacy-page__body">
<view <view
v-for="section in sections" v-for="section in sections"
@@ -54,15 +54,27 @@
</view> </view>
</view> </view>
</view> </view>
</scroll-view> </page-scroll-view>
<cancel-account-dialog
v-model:visible="cancelAccountDialogVisible"
@confirm="onConfirmCancelAccount"
/>
</view> </view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { staticAssets } from '@/utils/static-assets' import { staticAssets } from '@/utils/static-assets'
import CancelAccountDialog from './components/cancel-account-dialog/index.vue'
import { usePrivacy } from './use-privacy' import { usePrivacy } from './use-privacy'
const { sections, onItemTap, onLogout } = usePrivacy() const {
sections,
cancelAccountDialogVisible,
onItemTap,
onLogout,
onConfirmCancelAccount,
} = usePrivacy()
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -6,8 +6,7 @@
} }
.privacy-page__scroll { .privacy-page__scroll {
flex: 1; width: 100%;
height: 0;
} }
.privacy-page__body { .privacy-page__body {

View File

@@ -3,8 +3,18 @@ import { computed, ref } from 'vue'
import { cancelAccount, logout } from '@/api/auth' import { cancelAccount, logout } from '@/api/auth'
import { fetchProfile } from '@/api/profile' import { fetchProfile } from '@/api/profile'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import {
beginVoluntaryLogout,
endVoluntaryLogout,
} from '@/utils/auth-session'
import { teardownMessageInbox } from '@/hooks/use-message-inbox' 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' import type { PrivacySection } from './privacy.types'
function maskPhone(phone?: string): string { function maskPhone(phone?: string): string {
@@ -15,6 +25,9 @@ function maskPhone(phone?: string): string {
export function usePrivacy() { export function usePrivacy() {
const phone = ref('') const phone = ref('')
const passwordModifiedAt = ref<number | null>(null)
const cancelAccountDialogVisible = ref(false)
const cancelingAccount = ref(false)
const sections = computed<PrivacySection[]>(() => [ const sections = computed<PrivacySection[]>(() => [
{ {
@@ -24,7 +37,7 @@ export function usePrivacy() {
{ {
id: 'password', id: 'password',
title: '登录密码', title: '登录密码',
desc: '上次修改:30天前', desc: formatPasswordModifiedDesc(passwordModifiedAt.value),
}, },
{ {
id: 'phone', id: 'phone',
@@ -51,8 +64,12 @@ export function usePrivacy() {
try { try {
const profile = await fetchProfile() const profile = await fetchProfile()
phone.value = profile?.phonenumber || profile?.userName || '' phone.value = profile?.phonenumber || profile?.userName || ''
const boundPhone = profile?.phonenumber || profile?.userName || ''
passwordModifiedAt.value = getPasswordModifiedAt(profile?.userId)
?? adoptPendingPasswordModifiedForUser(profile?.userId ?? '', boundPhone)
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载账号信息失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '加载账号信息失败'), icon: 'none' })
passwordModifiedAt.value = null
} }
} }
@@ -66,26 +83,33 @@ export function usePrivacy() {
return return
} }
if (itemId === 'delete-account') { if (itemId === 'delete-account') {
uni.showModal({ cancelAccountDialogVisible.value = true
title: '注销账号', }
content: '注销后账号及所有数据将被永久删除,且无法恢复。确定继续吗?', }
confirmColor: '#f04438',
success: (res) => { async function onConfirmCancelAccount() {
if (!res.confirm) return if (cancelingAccount.value) return
void (async () => { cancelingAccount.value = true
beginVoluntaryLogout()
try { try {
await cancelAccount()
teardownMessageInbox() teardownMessageInbox()
clearStoredToken() await cancelAccount()
clearLocalUserData()
try {
await clearAppFileCacheOnDevice()
} catch {
// 非 App 或清理失败不阻断注销流程
}
uni.showToast({ title: '账号已注销', icon: 'success' }) uni.showToast({ title: '账号已注销', icon: 'success' })
uni.reLaunch({ url: '/pages/login/index' }) uni.reLaunch({ url: '/pages/login/index' })
} catch (err) { } catch (err) {
endVoluntaryLogout()
uni.showToast({ title: getErrorMessage(err, '注销失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '注销失败'), icon: 'none' })
} finally {
cancelingAccount.value = false
} }
})() // 成功跳转后稍后再关,避免在途 401 仍弹「登录状态异常」
}, setTimeout(() => endVoluntaryLogout(), 1500)
})
}
} }
function onLogout() { function onLogout() {
@@ -95,17 +119,19 @@ export function usePrivacy() {
success: (res) => { success: (res) => {
if (!res.confirm) return if (!res.confirm) return
void (async () => { void (async () => {
beginVoluntaryLogout()
try {
// 先停消息通道,避免 logout 后在途请求 401 误报
teardownMessageInbox()
try { try {
await logout() await logout()
} catch (err) { } catch {
uni.showToast({ // 服务端退出失败仍清本地登录态
title: getErrorMessage(err, '退出登录失败'), }
icon: 'none', clearLocalUserData()
})
} finally {
teardownMessageInbox()
clearStoredToken()
uni.reLaunch({ url: '/pages/login/index' }) uni.reLaunch({ url: '/pages/login/index' })
} finally {
setTimeout(() => endVoluntaryLogout(), 1500)
} }
})() })()
}, },
@@ -118,7 +144,9 @@ export function usePrivacy() {
return { return {
sections, sections,
cancelAccountDialogVisible,
onItemTap, onItemTap,
onLogout, onLogout,
onConfirmCancelAccount,
} }
} }

View File

@@ -1,4 +1,4 @@
<template> <template>
<view class="set-password-page"> <view class="set-password-page">
<app-navbar title="设置新密码" /> <app-navbar title="设置新密码" />
<view class="set-password-page__body"> <view class="set-password-page__body">
@@ -9,7 +9,7 @@
<base-input v-model="confirmPassword" icon="lock" type="password" placeholder="确认密码" /> <base-input v-model="confirmPassword" icon="lock" type="password" placeholder="确认密码" />
</view> </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"> <view class="set-password-page__btn">
<primary-button text="确认修改" @click="submit" /> <primary-button text="确认修改" @click="submit" />
@@ -23,8 +23,11 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { PASSWORD_RULE_HINT } from '@/utils/validate'
import { useSetPassword } from './use-set-password' import { useSetPassword } from './use-set-password'
const passwordRuleHint = `${PASSWORD_RULE_HINT}。`
const { password, confirmPassword, onForgotPassword, submit } = useSetPassword() const { password, confirmPassword, onForgotPassword, submit } = useSetPassword()
</script> </script>

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