Files
ttstd_family_care_miniapp/pages/usage-records/index.ts
T

244 lines
7.0 KiB
TypeScript

import type { UsageApp, UsageDaily, UsageSession } from '../../utils/api'
import {
getUsageApps,
getUsageDays,
getUsageSessionsPage,
syncUsageIcons
} from '../../utils/api'
import { getDeviceSn } from '../../utils/token'
interface SessionRow {
key: string
appName: string
iconUrl: string
timeText: string
/** 组头日期,仅每天第一条有值;为空表示组内后续项 */
dayHeader: string
}
interface AppRow {
key: string
appName: string
iconUrl: string
duration: string
percent: number
}
interface TrendBar {
key: string
label: string
height: number
duration: string
}
Page({
data: {
tab: 'timeline' as 'timeline' | 'byApp',
sessions: [] as SessionRow[],
apps: [] as AppRow[],
trend: [] as TrendBar[],
hasMore: true,
loading: true,
loadingMore: false,
requested: {} as Record<string, boolean>
},
beforeTs: 0,
onShow() {
void this.reload()
},
toast(title: string) {
wx.showToast({ title, icon: 'none' })
},
onTab(e: WechatMiniprogram.TouchEvent) {
const tab = e.currentTarget.dataset.tab as 'timeline' | 'byApp'
if (tab === this.data.tab) return
this.setData({ tab })
if (tab === 'byApp') void this.loadApps()
},
async reload() {
const sn = getDeviceSn()
if (!sn) {
this.toast('请先选择设备')
this.setData({ loading: false })
return
}
this.beforeTs = 0
this.setData({ loading: true, hasMore: true })
try {
await Promise.all([this.loadTrend(sn), this.loadPage(sn, true)])
if (this.data.tab === 'byApp') await this.loadApps()
} catch (err) {
this.toast((err as Error).message || '加载失败')
} finally {
this.setData({ loading: false })
}
},
async loadTrend(sn: string) {
// 固定 7 根柱子:以今天为最后一天向前推 6 天,无数据的日期补 0
const dates: string[] = []
const now = new Date()
for (let i = 6; i >= 0; i--) {
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i)
dates.push(dayKey(d))
}
const byDate: Record<string, number> = {}
try {
const days = await getUsageDays(sn, 7)
for (const d of days as UsageDaily[]) {
byDate[d.statDate] = Number(d.totalMs) || 0
}
} catch {
// 拉取失败也渲染 7 根 0 柱子
}
const max = dates.reduce((m, date) => Math.max(m, byDate[date] || 0), 0)
const trend: TrendBar[] = dates.map((date) => {
const total = byDate[date] || 0
return {
key: date,
label: date.slice(5),
height: max > 0 ? Math.max(6, Math.round((total / max) * 80)) : 6,
duration: formatDuration(total)
}
})
this.setData({ trend })
},
async loadPage(sn: string, reset: boolean) {
const result = await getUsageSessionsPage(sn, reset ? undefined : this.beforeTs)
const items = (result.items || []).filter((i) => (Number(i.durationMs) || 0) >= 1000)
const base = reset ? 0 : this.data.sessions.length
// 按天分组:记录与上一条不同日期时生成组头
let lastDay = reset ? '' : this.lastRenderedDay()
const rows: SessionRow[] = items.map((item, index) => {
const start = new Date(Number(item.startTs) || 0)
const day = dayText(start)
const header = day !== lastDay ? day : ''
lastDay = day
return toSessionRow(item, base + index, header)
})
this.beforeTs = Number(result.nextBeforeTs) || 0
this.setData({
sessions: reset ? rows : this.data.sessions.concat(rows),
hasMore: !!result.hasMore
})
void this.syncMissing(items)
},
/** 已渲染的最后一条记录的日期(分页追加时用于判断是否需要新组头) */
lastRenderedDay(): string {
const list = this.data.sessions
if (!list.length) return ''
// 回溯找到最近一个带组头的行,反推日期
for (let i = list.length - 1; i >= 0; i--) {
if (list[i].dayHeader) return list[i].dayHeader
}
return ''
},
async loadMore() {
if (this.data.loadingMore || !this.data.hasMore) return
const sn = getDeviceSn()
if (!sn) return
this.setData({ loadingMore: true })
try {
await this.loadPage(sn, false)
} catch {
// 忽略,允许再次触发
} finally {
this.setData({ loadingMore: false })
}
},
onReachBottom() {
if (this.data.tab === 'timeline') void this.loadMore()
},
async loadApps() {
const sn = getDeviceSn()
if (!sn) return
try {
const apps = await getUsageApps(sn)
const max = apps.reduce((m, a) => Math.max(m, Number(a.totalMs) || 0), 0)
const rows: AppRow[] = apps.map((a: UsageApp) => ({
key: a.packageName,
appName: a.appName || a.packageName,
iconUrl: a.iconUrl || '',
duration: formatDuration(Number(a.totalMs) || 0),
percent: max > 0 ? Math.round(((Number(a.totalMs) || 0) * 100) / max) : 0
}))
this.setData({ apps: rows })
} catch {
this.setData({ apps: [] })
}
},
/** 缺图标的应用包名请求设备补传,图标就绪后刷新 */
async syncMissing(list: UsageSession[]) {
const requested = this.data.requested
const missing: string[] = []
for (const item of list) {
const pkg = item.packageName || ''
if (!item.iconUrl && pkg && !requested[pkg]) {
requested[pkg] = true
missing.push(pkg)
}
}
if (!missing.length) return
this.setData({ requested })
const sn = getDeviceSn()
if (!sn) return
try {
const result = await syncUsageIcons(sn, missing)
if (result && result.iconUrls && Object.keys(result.iconUrls).length > 0) {
await this.reload()
}
} catch {
// 长轮询失败保留占位图标
}
}
})
function toSessionRow(item: UsageSession, index: number, dayHeader: string): SessionRow {
const start = new Date(Number(item.startTs) || 0)
const end = new Date(Number(item.endTs) || 0)
const range = item.open
? `${clock(start)} 起 · 使用中 ${formatDuration(Number(item.durationMs) || 0)}`
: `${clock(start)} - ${clock(end)} · 用时 ${formatDuration(Number(item.durationMs) || 0)}`
return {
key: `${index}_${item.startTs}`,
appName: item.appName || item.packageName || '未知应用',
iconUrl: item.iconUrl || '',
timeText: range,
dayHeader
}
}
function pad(n: number): string {
return String(n).padStart(2, '0')
}
function clock(time: Date): string {
return `${pad(time.getHours())}:${pad(time.getMinutes())}:${pad(time.getSeconds())}`
}
function dayText(time: Date): string {
return `${time.getFullYear()}-${pad(time.getMonth() + 1)}-${pad(time.getDate())}`
}
function formatDuration(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${seconds % 60}s`
return `${seconds}s`
}
function dayKey(time: Date): string {
return `${time.getFullYear()}-${pad(time.getMonth() + 1)}-${pad(time.getDate())}`
}