feat(usage): 首页使用时长接入真实数据并新增使用记录页

- utils/api 新增 getUsageDay/getUsageDays 与类型
- 首页使用时长卡:真实总时长、Top3 应用占比、环形进度,入口改为「使用记录」
- 新增 pages/usage-records:近 7 天汇总 + 展开每日会话时间线
This commit is contained in:
tongtong committed 2026-12-02 01:09:39 +08:00
1 parent 968bdd1c12
commit f03ab6bc03
8 files changed
+325 -11

No files matched your search

+1
View File
@@ -17,6 +17,7 @@
"pages/screenshot/index",
"pages/files/index",
"pages/calls/index",
"pages/usage-records/index",
"pages/sms/index",
"pages/apps/index",
"pages/alarm/index",
+45 -8
View File
@@ -3,6 +3,7 @@ import {
getDeviceLocation,
getMyDevices,
getScreenshots,
getUsageDay,
captureScreenshot,
refreshDevice,
locateDevice,
@@ -115,13 +116,10 @@ Page({
mapLongitude: 0,
markers: [] as MapMarker[],
screenshots: withShotPlaceholders([]),
// 演示数据:后端暂无使用时长接口,等设备端上报后再替换
usageTotal: '3.4h',
usageItems: [
{ key: 'read', label: '阅读', percent: 55, color: '#07C160' },
{ key: 'video', label: '视频', percent: 30, color: '#5B8DEF' },
{ key: 'work', label: '办公', percent: 15, color: '#F5A623' }
] as UsageItem[],
// 使用时长来自 /v1/client/sn/usage/day(设备端上报后展示真实数据)
usageTotal: '—',
usageRingPercent: 0,
usageItems: [] as UsageItem[],
deviceOps: [
{ key: 'screenshot', emoji: '📸', color: '#07C160', label: '屏幕截图' },
{ key: 'camera', emoji: '📷', color: '#0EA5E9', label: '远程相机' },
@@ -227,7 +225,10 @@ Page({
address: '暂无定位',
locationError: '',
markers: [],
screenshots: []
screenshots: [],
usageTotal: '—',
usageRingPercent: 0,
usageItems: []
})
return
}
@@ -261,6 +262,7 @@ Page({
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 {
@@ -291,6 +293,33 @@ Page({
})
},
/** 今日使用时长:总时长 + 应用占比(取 Top3) */
async loadUsage(sn: string) {
try {
const day = await getUsageDay(sn)
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 || '').slice(0, 4),
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
})
} catch {
this.setData({ usageTotal: '—', usageRingPercent: 0, usageItems: [] })
}
},
/** 进入使用记录页(近 7 天 + 每日打开/关闭明细) */
goUsageRecords() {
wx.navigateTo({ url: '/pages/usage-records/index' })
},
async loadScreenshots(sn: string) {
const list: Screenshot[] = await getScreenshots(sn)
const items: ScreenshotItem[] = list
@@ -485,3 +514,11 @@ Page({
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`
}
+3 -3
View File
@@ -82,10 +82,10 @@
<view class="head-icon" style="background: #f5a623">⏱️</view>
<text class="head-title">今日使用时长</text>
<view class="spacer"></view>
<text class="head-link">较昨日 ↓ 12%</text>
<text class="head-link" bindtap="goUsageRecords">使用记录</text>
</view>
<view class="usage-body">
<view class="usage-ring">
<view class="usage-ring" style="background: conic-gradient(#07C160 0%, #07C160 {{usageRingPercent}}%, var(--track) {{usageRingPercent}}%, var(--track) 100%)">
<view class="usage-ring-inner">
<text class="usage-total">{{usageTotal}}</text>
<text class="usage-total-label">今日</text>
@@ -95,7 +95,7 @@
<view class="usage-bar" wx:for="{{usageItems}}" wx:key="key">
<text class="usage-bar-label">{{item.label}}</text>
<view class="usage-bar-track">
<view class="usage-bar-fill {{item.key}}"></view>
<view class="usage-bar-fill" style="width: {{item.percent}}%; background: {{item.color}};"></view>
</view>
</view>
</view>
+5
View File
@@ -0,0 +1,5 @@
{
"navigationBarTitleText": "使用记录",
"navigationBarBackgroundColor": "#ffffff",
"backgroundColor": "#f5f7fa"
}
+113
View File
@@ -0,0 +1,113 @@
import type { UsageDaily, UsageDay, UsageSession } from '../../utils/api'
import { getUsageDay, getUsageDays } from '../../utils/api'
import { getDeviceSn } from '../../utils/token'
interface SessionRow {
key: string
time: string
appName: string
duration: string
open: boolean
}
interface DayRow {
date: string
total: string
summary: string
expanded: boolean
loaded: boolean
sessions: SessionRow[]
}
Page({
data: {
days: [] as DayRow[],
loading: false
},
onShow() {
void this.loadDays()
},
toast(title: string) {
wx.showToast({ title, icon: 'none' })
},
async loadDays() {
const sn = getDeviceSn()
if (!sn) {
this.toast('请先选择设备')
return
}
this.setData({ loading: true })
try {
const list: UsageDaily[] = await getUsageDays(sn, 7)
this.setData({
days: list.map((item) => ({
date: item.statDate,
total: formatDuration(Number(item.totalMs) || 0),
summary: `${Number(item.appCount) || 0} 个应用 · ${Number(item.sessionCount) || 0} 条记录`,
expanded: false,
loaded: false,
sessions: []
}))
})
} catch (err) {
this.toast((err as Error).message || '加载失败')
} finally {
this.setData({ loading: false })
}
},
async onToggle(e: WechatMiniprogram.TouchEvent) {
const index = Number(e.currentTarget.dataset.index)
const days = this.data.days
const row = days[index]
if (!row) return
if (row.expanded) {
this.setData({ [`days[${index}].expanded`]: false })
return
}
if (row.loaded) {
this.setData({ [`days[${index}].expanded`]: true })
return
}
const sn = getDeviceSn()
if (!sn) return
try {
const day: UsageDay = await getUsageDay(sn, row.date)
const sessions = (day.sessions || []).map((item, i) => toSessionRow(item, i))
this.setData({
[`days[${index}].sessions`]: sessions,
[`days[${index}].loaded`]: true,
[`days[${index}].expanded`]: true
})
} catch (err) {
this.toast((err as Error).message || '加载失败')
}
}
})
function toSessionRow(item: UsageSession, index: number): SessionRow {
const start = new Date(Number(item.startTs) || 0)
const end = new Date(Number(item.endTs) || 0)
return {
key: String(index),
time: `${clock(start)} - ${item.open ? '使用中' : clock(end)}`,
appName: item.appName || item.packageName || '未知应用',
duration: formatDuration(Number(item.durationMs) || 0),
open: !!item.open
}
}
function clock(time: Date): string {
const pad = (n: number) => String(n).padStart(2, '0')
return `${pad(time.getHours())}:${pad(time.getMinutes())}`
}
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`
return `${seconds}s`
}
+21
View File
@@ -0,0 +1,21 @@
<view class="page">
<view wx:if="{{!days.length && !loading}}" class="empty">暂无使用记录</view>
<view wx:for="{{days}}" wx:key="date" class="card day-card">
<view class="day-head" bindtap="onToggle" data-index="{{index}}">
<text class="day-date">{{item.date}}</text>
<view class="spacer"></view>
<text class="day-total">{{item.total}}</text>
<text class="chevron">{{item.expanded ? '▾' : '▸'}}</text>
</view>
<view class="day-summary">{{item.summary}}</view>
<block wx:if="{{item.expanded}}">
<view class="divider"></view>
<view wx:if="{{!item.sessions.length}}" class="empty small">暂无记录</view>
<view wx:for="{{item.sessions}}" wx:for-item="session" wx:key="key" class="session-row">
<text class="session-time">{{session.time}}</text>
<text class="session-app">{{session.appName}}</text>
<text class="session-duration">{{session.duration}}</text>
</view>
</block>
</view>
</view>
+84
View File
@@ -0,0 +1,84 @@
.page {
padding: 16rpx 0 32rpx;
}
.day-card {
margin-bottom: 16rpx;
}
.day-head {
display: flex;
align-items: center;
}
.day-date {
font-size: 30rpx;
font-weight: 600;
color: var(--ink);
}
.spacer {
flex: 1;
}
.day-total {
font-size: 28rpx;
font-weight: 600;
color: #07c160;
}
.chevron {
margin-left: 12rpx;
font-size: 24rpx;
color: var(--sub);
}
.day-summary {
margin-top: 8rpx;
font-size: 22rpx;
color: var(--sub);
}
.divider {
height: 1rpx;
margin: 16rpx 0 8rpx;
background: var(--track);
}
.session-row {
display: flex;
align-items: center;
padding: 10rpx 0;
}
.session-time {
width: 220rpx;
font-size: 24rpx;
color: var(--ink);
}
.session-app {
flex: 1;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
font-size: 24rpx;
color: var(--ink);
}
.session-duration {
margin-left: 12rpx;
font-size: 22rpx;
color: var(--sub);
}
.empty {
padding: 80rpx 0;
text-align: center;
font-size: 26rpx;
color: var(--sub);
}
.empty.small {
padding: 24rpx 0;
}
+53
View File
@@ -536,3 +536,56 @@ export const deleteAlarm = (sn: string, id: number) =>
url: `/v1/client/sn/alarm?${query({ sn, id })}`,
method: 'DELETE'
})
/** 应用使用时长明细项(后端 Long 以字符串下发) */
export interface UsageApp {
packageName: string
appName?: string
totalMs: number | string
}
/** 应用打开/关闭会话;open=true 表示快照时仍在使用 */
export interface UsageSession {
packageName: string
appName?: string
startTs: number | string
endTs: number | string
durationMs: number | string
open?: boolean
}
/** 某天使用时长明细 */
export interface UsageDay {
serialno: string
statDate: string
totalMs: number | string
appCount: number | string
sessionCount: number | string
timeZone?: string
updateTime?: string
apps?: UsageApp[]
sessions?: UsageSession[]
}
/** 每日使用时长汇总 */
export interface UsageDaily {
serialno: string
statDate: string
totalMs: number | string
appCount: number | string
sessionCount: number | string
timeZone?: string
updateTime?: string
}
/** 设备某天使用时长明细(date 缺省为今天) */
export const getUsageDay = (sn: string, date?: string) =>
request<UsageDay>({
url: `/v1/client/sn/usage/day?${query({ sn, date })}`
})
/** 设备最近 N 天使用时长汇总(倒序) */
export const getUsageDays = (sn: string, days = 7) =>
request<UsageDaily[]>({
url: `/v1/client/sn/usage/days?${query({ sn, days })}`
})