Files
ttstd_family_care_miniapp/pages/device-manager/index.ts
T

64 lines
1.7 KiB
TypeScript

import type { DeviceBrief } from '../../utils/api'
import { getMyDevices, unbindDevice } from '../../utils/api'
import { getDeviceSn, saveDeviceSn } from '../../utils/token'
Page({
data: {
devices: [] as DeviceBrief[],
currentSn: '',
loading: false
},
onShow() {
this.loadDevices()
},
async loadDevices() {
if (this.data.loading) return
this.setData({ loading: true })
try {
const devices = await getMyDevices()
this.setData({ devices, currentSn: getDeviceSn() })
} catch (err) {
this.toast((err as Error).message || '设备列表加载失败')
} finally {
this.setData({ loading: false })
}
},
/** 绑定操作走独立页面,绑定成功返回后由 onShow 刷新已绑定列表 */
onAddDevice() {
wx.navigateTo({ url: '/pages/device-bind/index' })
},
onSelect(e: WechatMiniprogram.TouchEvent) {
const { sn } = e.currentTarget.dataset as { sn: string }
saveDeviceSn(sn)
this.setData({ currentSn: sn })
this.toast('已切换当前设备')
},
onUnbind(e: WechatMiniprogram.TouchEvent) {
const { sn } = e.currentTarget.dataset as { sn: string }
wx.showModal({
title: '解除绑定',
content: `确定解绑设备 ${sn} 吗?`,
confirmColor: '#EF4444',
success: (res) => {
if (!res.confirm) return
void unbindDevice(sn)
.then(() => {
if (this.data.currentSn === sn) saveDeviceSn('')
this.toast('已解绑')
return this.loadDevices()
})
.catch((err: Error) => this.toast(err.message || '解绑失败'))
}
})
},
toast(title: string) {
wx.showToast({ title, icon: 'none', duration: 1800 })
}
})