Files
ttstd_family_care_miniapp/pages/home/index.ts
T
tongtong 9f55e142fa fix(usage): 首页使用时长应用行顶部对齐并固定三行高度
- usage-body 改 flex-start,应用行与左侧环形同高起排(单行不再居中)
- 条列固定 3 行高度,不足 3 行补占位行,卡片高度与首行位置稳定
2026-12-03 01:20:55 +08:00

592 lines
19 KiB
TypeScript

import type { DeviceBrief, DeviceLocation, Screenshot } from '../../utils/api'
import {
getDeviceLocation,
getMyDevices,
getScreenshots,
getUsageDay,
captureScreenshot,
refreshDevice,
locateDevice,
transferFile,
takeDevicePhoto,
syncMessages,
cleanDevice,
mirrorScreen,
lockScreen,
toggleDeveloperMode
} from '../../utils/api'
import { ensureLogin } from '../../utils/auth'
import { getDeviceSn, saveDeviceSn, saveUsageTodayCache, getUsageTodayCache } from '../../utils/token'
import { toGcj02 } from '../../utils/coord'
import { showTodo } from '../../utils/todo'
import { syncTabBar } from '../../utils/tab-bar'
import { DeviceStatusSseClient } from '../../utils/sse'
import type { DeviceOnlineStatus } from '../../utils/sse'
interface MapMarker {
id: number
latitude: number
longitude: number
iconPath: string
width: number
height: number
}
interface UsageItem {
key: string
label: string
percent: number
color: string
}
interface TileItem {
key: string
emoji: string
color: string
label: string
}
interface ScreenshotItem {
key: string
url: string
time: string
}
/** 系统设置 / 壁纸 / 图标包等完整编辑入口已拆分为独立页面 */
const SHOT_SLOT_COUNT = 3
let statusSse: DeviceStatusSseClient | null = null
let onlinePollTimer: number | null = null
let usagePollTimer: number | null = null
const emptyShot = (index: number): ScreenshotItem => ({
key: `placeholder-${index}`,
url: '',
time: ''
})
/** 固定 3 个槽位,数据未到或不足时用占位撑住高度,避免页面跳动 */
const withShotPlaceholders = (items: ScreenshotItem[]): ScreenshotItem[] => {
const result = items.slice(0, 5)
while (result.length < SHOT_SLOT_COUNT) result.push(emptyShot(result.length))
return result
}
const pad = (value: number): string => (value < 10 ? `0${value}` : String(value))
/** 当天显示 HH:mm,跨天显示 MM-dd HH:mm */
function formatClock(value?: string): string {
if (!value) return ''
const text = value.replace('T', ' ')
const time = text.slice(11, 16)
const date = text.slice(5, 10)
const now = new Date()
const today = `${pad(now.getMonth() + 1)}-${pad(now.getDate())}`
return !time ? text : date === today ? time : `${date} ${time}`
}
/** 设备上报失败时会保留一条只有 mapError、没有坐标的记录,不能当成有效定位 */
function hasValidLocation(location?: DeviceLocation | null): boolean {
if (!location) return false
const latitude = Number(location.latitude)
const longitude = Number(location.longitude)
return (
Number.isFinite(latitude) &&
Number.isFinite(longitude) &&
(latitude !== 0 || longitude !== 0)
)
}
/** 后端回传的是设备端原始错误(如「未知定位错误: 162」),不直接展示给用户 */
function friendlyLocationError(mapError?: string): string {
if (!mapError || mapError === '-') return '设备暂未上报有效定位'
if (mapError.includes('162')) return '定位暂不可用,请检查设备定位权限与网络'
return '定位暂不可用'
}
Page({
data: {
loading: false,
deviceName: '未绑定设备',
online: false,
deviceStatus: '',
located: false,
address: '暂无定位',
locationError: '',
mapLatitude: 0,
mapLongitude: 0,
markers: [] as MapMarker[],
screenshots: withShotPlaceholders([]),
// 使用时长来自 /v1/client/sn/usage/day(设备端上报后展示真实数据)
usageTotal: '—',
usageRingPercent: 0,
usageItems: [] as UsageItem[],
placeholderCount: [1, 2, 3] as number[],
usageLoading: true,
deviceOps: [
{ key: 'screenshot', emoji: '📸', color: '#07C160', label: '屏幕截图' },
{ key: 'camera', emoji: '📷', color: '#0EA5E9', label: '远程相机' },
{ key: 'locate', emoji: '📍', color: '#764BA2', label: '定位' },
{ key: 'refresh', emoji: '🔃', color: '#F5A623', label: '刷新' }
] as TileItem[],
commonActions: [
{ key: 'file', emoji: '📁', color: '#5B8DEF', label: '文件传输' },
{ key: 'msg', emoji: '💬', color: '#F5A623', label: '消息同步' },
{ key: 'clean', emoji: '🧹', color: '#764BA2', label: '清理加速' },
{ key: 'mirror', emoji: '📺', color: '#EF4444', label: '屏幕镜像' },
{ key: 'lost', emoji: '🔔', color: '#0EA5E9', label: '丢失模式' },
{ key: 'screen-lock', emoji: '🔐', color: '#5B8DEF', label: '屏幕锁定' },
{ key: 'app-lock', emoji: '🔒', color: '#22C55E', label: '应用锁' },
{ key: 'developer', emoji: '🛠️', color: '#5B8DEF', label: '开发者模式' },
{ key: 'settings', emoji: '⚙️', color: '#94A3B8', label: '系统设置' },
{ key: 'wallpaper', emoji: '🖼️', color: '#0EA5E9', label: '壁纸设置' },
{ key: 'home-layout', emoji: '🏠', color: '#5B8DEF', label: '首页布局' },
{ key: 'icon-pack', emoji: '🎨', color: '#F5A623', label: '图标包管理' },
{ key: 'more', emoji: '⋯', color: '#94A3B8', label: '更多' }
] as TileItem[]
},
onLoad() {
const page = this
statusSse = new DeviceStatusSseClient((status) => page.applySseStatus(status))
},
onShow() {
syncTabBar(this, 0)
if (!ensureLogin()) return
statusSse?.start()
this.startOnlinePoll()
this.startUsagePoll()
this.loadHome()
},
onHide() {
statusSse?.stop()
this.stopOnlinePoll()
this.stopUsagePoll()
},
onUnload() {
statusSse?.stop()
this.stopOnlinePoll()
this.stopUsagePoll()
},
/** 下拉刷新:重新加载设备列表、定位与截图状态 */
async onPullDownRefresh() {
try {
await this.loadHome()
} finally {
wx.stopPullDownRefresh()
}
},
/** SSE 推送只更新当前选中设备的在线徽标,不触发整页重载 */
applySseStatus(status: DeviceOnlineStatus) {
if (status.serialno !== getDeviceSn()) return
this.setData({ online: status.online === 1 })
},
/** SSE 断线时的兜底:每分钟轻量刷新一次在线状态 */
startOnlinePoll() {
if (onlinePollTimer !== null) return
onlinePollTimer = setInterval(() => {
void this.pollOnlineStatus()
}, 60000) as unknown as number
},
/** 停留在首页时每 60 秒轻量刷新一次今日使用时长 */
startUsagePoll() {
if (usagePollTimer !== null) return
usagePollTimer = setInterval(() => {
const sn = getDeviceSn()
if (sn) void this.loadUsage(sn)
}, 60000) as unknown as number
},
stopUsagePoll() {
if (usagePollTimer === null) return
clearInterval(usagePollTimer)
usagePollTimer = null
},
stopOnlinePoll() {
if (onlinePollTimer === null) return
clearInterval(onlinePollTimer)
onlinePollTimer = null
},
async pollOnlineStatus() {
const sn = getDeviceSn()
if (!sn) return
try {
const devices = await getMyDevices()
const current = devices.find((device) => device.serialno === sn)
if (current) this.setData({ online: current.online === 1 })
} catch {
// 轮询失败不影响页面,等待 SSE 或下次轮询
}
},
/**
* 设备列表 → 优先选「在线且有有效定位」的设备 → 加载截图。
* 最多探测前 5 台,避免绑定设备较多时请求过多。
*/
async loadHome() {
if (this.data.loading) return
this.setData({ loading: true })
try {
const devices = await getMyDevices()
if (!devices.length) {
this.setData({
deviceName: '未绑定设备',
online: false,
deviceStatus: '',
located: false,
address: '暂无定位',
locationError: '',
markers: [],
screenshots: [],
usageTotal: '—',
usageRingPercent: 0,
usageItems: [],
usageLoading: false
})
return
}
const preferred = getDeviceSn()
const inspected = await Promise.all(
devices.slice(0, 5).map(async (device) => {
try {
return { device, location: await getDeviceLocation(device.serialno) }
} catch {
// 单台定位失败不影响其它设备
return { device, location: null }
}
})
)
// 在线优先、有有效坐标优先,其次沿用上次选中的设备
const score = (item: { device: DeviceBrief; location: DeviceLocation | null }): number =>
(item.device.online === 1 ? 4 : 0) +
(hasValidLocation(item.location) ? 2 : 0) +
(item.device.serialno === preferred ? 1 : 0)
const best = inspected.reduce((a, b) => (score(b) > score(a) ? b : a))
saveDeviceSn(best.device.serialno)
this.setData({
deviceName: best.device.snName || best.device.serialno,
online: best.device.online === 1,
// 状态只由徽标显示「在线/离线」,这里展示设备型号或 SN
deviceStatus: best.device.snModel || best.device.serialno
})
this.applyLocation(best.location)
await this.loadScreenshots(best.device.serialno)
await this.loadUsage(best.device.serialno)
} catch (err) {
this.toast((err as Error).message || '加载失败,请稍后重试')
} finally {
this.setData({ loading: false })
}
},
/** 只在坐标有效时落图;失败时给友好提示,不把后端原始错误码展示给用户 */
applyLocation(location: DeviceLocation | null) {
if (!hasValidLocation(location)) {
this.setData({
located: false,
address: friendlyLocationError(location?.mapError),
locationError: location?.mapError || '',
markers: []
})
return
}
this.applyDeviceLocation({
latitude: Number(location?.latitude),
longitude: Number(location?.longitude),
coordType: location?.coordType
})
this.setData({
located: true,
address: location?.address || location?.locationDescribe || '位置已更新',
locationError: ''
})
},
/** 今日使用时长:总时长 + 应用占比(取 Top3)。先渲染本地缓存,再拉网络覆盖。 */
async loadUsage(sn: string) {
const today = dayKey(new Date())
const cached = getUsageTodayCache<{ total: number; items: UsageItem[] }>(sn, today)
if (cached) {
this.setData({
usageTotal: formatUsageDuration(cached.total),
usageRingPercent: cached.items.length ? cached.items[0].percent : 0,
usageItems: cached.items,
placeholderCount: placeholderRows(cached.items.length),
usageLoading: false
})
}
try {
const day = await getUsageDay(sn)
// 当天无数据时后端返回 null(如跨天后设备尚未上报):按 0 处理,不能卡在骨架
if (!day) {
this.setData({
usageTotal: '0s',
usageRingPercent: 0,
usageItems: [],
usageLoading: false
})
saveUsageTodayCache(sn, today, { total: 0, items: [] })
return
}
const total = Number(day.totalMs) || 0
const colors = ['#07C160', '#5B8DEF', '#F5A623']
const items: UsageItem[] = (day.apps || []).slice(0, 3).map((app, index) => ({
key: String(index),
label: app.appName || app.packageName || '',
percent: total > 0 ? Math.round(((Number(app.totalMs) || 0) * 100) / total) : 0,
color: colors[index] || '#94A3B8'
}))
this.setData({
usageTotal: formatUsageDuration(total),
usageRingPercent: items.length ? items[0].percent : 0,
usageItems: items,
placeholderCount: placeholderRows(items.length),
usageLoading: false
})
saveUsageTodayCache(sn, today, { total, items })
} catch {
// 请求失败结束骨架,避免一直显示占位
const items = cached ? this.data.usageItems : []
this.setData({
usageTotal: cached ? this.data.usageTotal : '0s',
usageRingPercent: cached ? this.data.usageRingPercent : 0,
usageItems: items,
placeholderCount: placeholderRows(items.length),
usageLoading: false
})
}
},
/** 进入使用记录页(近 7 天 + 每日打开/关闭明细) */
goUsageRecords() {
wx.navigateTo({ url: '/pages/usage-records/index' })
},
async loadScreenshots(sn: string) {
const list: Screenshot[] = await getScreenshots(sn)
const items: ScreenshotItem[] = list
.filter((item) => !!item.url)
.slice(0, 5)
.map((item) => ({
key: String(item.id),
url: item.url || '',
time: formatClock(item.uploadTime)
}))
this.setData({ screenshots: withShotPlaceholders(items) })
},
/** 后端主坐标为 GCJ-02,微信 map 直通;老后端 BD-09 由 toGcj02 兼容。 */
applyDeviceLocation(coord: { latitude: number; longitude: number; coordType?: string }) {
const gcj = toGcj02(coord.longitude, coord.latitude, coord.coordType)
const markers: MapMarker[] = [
{
id: 1,
latitude: gcj.latitude,
longitude: gcj.longitude,
iconPath: '/assets/marker.png',
width: 24,
height: 24
}
]
this.setData({
mapLatitude: gcj.latitude,
mapLongitude: gcj.longitude,
markers
})
},
/** 设备切换:进入设备管理页选择或绑定设备。 */
onSwitchDevice() {
wx.navigateTo({ url: '/pages/device-manager/index' })
},
/** 地图详情:定位无效时说明原因,有效时进入可缩放的地图页。 */
onOpenMap() {
if (!this.data.located) {
this.toast(
this.data.locationError
? '定位暂不可用,请检查设备定位权限与网络'
: '设备暂未上报有效定位'
)
return
}
wx.navigateTo({ url: '/pages/map/index' })
},
/** 截图列表:进入设备截图页。 */
onViewAllScreenshots() {
wx.navigateTo({ url: '/pages/screenshot/index' })
},
onScreenshotTap(e: WechatMiniprogram.TouchEvent) {
const { url } = e.currentTarget.dataset as { url?: string }
if (!url) {
showTodo('截图预览')
return
}
wx.previewImage({ urls: [url], current: url })
},
/** 统一调用设备类接口:注入当前 SN、处理加载态与错误提示 */
async runDeviceApi(
label: string,
action: (sn: string) => Promise<unknown>,
successText = `${label}指令已下发`
): Promise<boolean> {
const sn = getDeviceSn()
if (!sn) {
this.toast('请先在首页选择设备')
return false
}
wx.showLoading({ title: '处理中' })
try {
await action(sn)
wx.hideLoading()
this.toast(successText)
return true
} catch (err) {
wx.hideLoading()
this.toast((err as Error).message || `${label}失败`)
return false
}
},
/** 高危操作二次确认 */
confirmAction(content: string, onConfirm: () => void) {
wx.showModal({
title: '确认操作',
content,
confirmText: '确定',
confirmColor: '#07C160',
cancelText: '取消',
success: (res) => {
if (res.confirm) onConfirm()
}
})
},
/** 设备操作:屏幕截图/远程相机/定位/刷新,全部走 /client/sn/ops/* */
onDeviceOp(e: WechatMiniprogram.TouchEvent) {
const { key, label } = e.currentTarget.dataset as { key: string; label: string }
switch (key) {
case 'screenshot':
void this.runDeviceApi(label, captureScreenshot, '屏幕截图指令已下发').then((ok) => {
if (!ok) return
const sn = getDeviceSn()
if (sn) setTimeout(() => void this.loadScreenshots(sn), 1500)
})
break
case 'camera':
wx.showActionSheet({
itemList: ['后置摄像头', '前置摄像头'],
success: (res) => {
const camera = res.tapIndex === 1 ? 1 : 0
void this.runDeviceApi(label, (sn) => takeDevicePhoto(sn, camera), '拍照指令已下发')
}
})
break
case 'refresh':
void this.runDeviceApi(label, refreshDevice, '已请求设备刷新').then((ok) => {
if (ok) this.loadHome()
})
break
case 'locate':
void this.runDeviceApi(label, locateDevice, '定位指令已下发').then((ok) => {
if (ok) this.loadHome()
})
break
default:
showTodo(label)
}
},
/** 常用功能:有后端端点的逐项调用,无端点的保持 showTodo */
onAction(e: WechatMiniprogram.TouchEvent) {
const { key, label } = e.currentTarget.dataset as { key: string; label: string }
switch (key) {
case 'file':
void this.runDeviceApi(label, transferFile)
break
case 'msg':
void this.runDeviceApi(label, syncMessages, '消息同步指令已下发')
break
case 'clean':
void this.runDeviceApi(label, cleanDevice, '清理指令已下发')
break
case 'mirror':
void this.runDeviceApi(label, mirrorScreen, '镜像指令已下发,实时画面请使用支持 WebRTC 的端')
break
case 'screen-lock':
void this.runDeviceApi(label, lockScreen, '锁屏指令已下发')
break
case 'developer':
void this.runDeviceApi(label, toggleDeveloperMode, '开发者模式指令已下发')
break
case 'settings':
this.openDevicePage('/pages/system-settings/index')
break
case 'wallpaper':
this.openDevicePage('/pages/wallpaper/index')
break
case 'home-layout':
this.openDevicePage('/pages/home-layout/index')
break
case 'icon-pack':
this.openDevicePage('/pages/icon-packs/index')
break
case 'more':
this.openDevicePage('/pages/more/index')
break
default:
showTodo(label)
}
},
/** 需要设备上下文的独立页面:未选设备时先提示 */
openDevicePage(url: string) {
const sn = getDeviceSn()
if (!sn) {
this.toast('请先在首页选择设备')
return
}
wx.navigateTo({ url })
},
toast(title: string) {
wx.showToast({ title, icon: 'none', duration: 1800 })
}
})
/** 毫秒时长格式化为 2h34m / 34m / 12s */
function formatUsageDuration(ms: number): string {
const seconds = Math.max(0, Math.floor(ms / 1000))
if (seconds >= 3600) return `${Math.floor(seconds / 3600)}h${Math.floor((seconds % 3600) / 60)}m`
if (seconds >= 60) return `${Math.floor(seconds / 60)}m`
return `${seconds}s`
}
/** 本地日期键 yyyy-MM-dd */
function dayKey(time: Date): string {
const pad = (n: number) => String(n).padStart(2, '0')
return `${time.getFullYear()}-${pad(time.getMonth() + 1)}-${pad(time.getDate())}`
}
/** 补足到 3 行所需的占位行数量 */
function placeholderRows(count: number): number[] {
const need = Math.max(0, 3 - count)
return Array.from({ length: need }, (_, i) => i)
}