100 lines
2.6 KiB
TypeScript
100 lines
2.6 KiB
TypeScript
import type { ContactItem } from '../../utils/api'
|
|
import { getContactForm, insertContact, updateContact } from '../../utils/api'
|
|
import { getDeviceSn } from '../../utils/token'
|
|
|
|
interface SwitchEvent {
|
|
detail: { value: boolean }
|
|
currentTarget: { dataset: Record<string, unknown> }
|
|
}
|
|
|
|
const emptyForm = (): ContactItem => ({
|
|
name: '',
|
|
nickName: '',
|
|
phoneNumber: '',
|
|
position: 0,
|
|
emergency: false,
|
|
showDesktop: true
|
|
})
|
|
|
|
Page({
|
|
data: {
|
|
form: emptyForm(),
|
|
editing: false,
|
|
loading: false,
|
|
saving: false
|
|
},
|
|
|
|
onLoad(options: Record<string, string | undefined>) {
|
|
const id = Number(options.id)
|
|
if (id > 0) {
|
|
this.setData({ editing: true })
|
|
wx.setNavigationBarTitle({ title: '编辑联系人' })
|
|
void this.loadContact(id)
|
|
}
|
|
},
|
|
|
|
async loadContact(id: number) {
|
|
const sn = getDeviceSn()
|
|
if (!sn) {
|
|
this.toast('请先选择设备')
|
|
return
|
|
}
|
|
this.setData({ loading: true })
|
|
try {
|
|
this.setData({ form: await getContactForm(sn, id) })
|
|
} catch (err) {
|
|
this.toast((err as Error).message || '联系人读取失败')
|
|
} finally {
|
|
this.setData({ loading: false })
|
|
}
|
|
},
|
|
|
|
onInput(e: WechatMiniprogram.Input) {
|
|
const { field } = e.currentTarget.dataset as { field: 'name' | 'nickName' | 'phoneNumber' }
|
|
this.setData({ form: { ...this.data.form, [field]: e.detail.value } })
|
|
},
|
|
|
|
onSwitch(e: SwitchEvent) {
|
|
const { field } = e.currentTarget.dataset as { field: 'emergency' | 'showDesktop' }
|
|
this.setData({ form: { ...this.data.form, [field]: e.detail.value } })
|
|
},
|
|
|
|
async onSave() {
|
|
const form = this.data.form
|
|
if (!form.name?.trim() || !form.phoneNumber?.trim()) {
|
|
this.toast('请填写姓名和手机号')
|
|
return
|
|
}
|
|
const sn = getDeviceSn()
|
|
if (!sn) {
|
|
this.toast('请先选择设备')
|
|
return
|
|
}
|
|
if (this.data.saving) return
|
|
this.setData({ saving: true })
|
|
wx.showLoading({ title: '保存中' })
|
|
try {
|
|
const payload: ContactItem = {
|
|
...form,
|
|
name: form.name.trim(),
|
|
phoneNumber: form.phoneNumber.trim(),
|
|
bindSn: sn
|
|
}
|
|
if (this.data.editing && form.id) await updateContact(sn, payload)
|
|
else await insertContact(sn, payload)
|
|
wx.hideLoading()
|
|
this.toast('已保存')
|
|
wx.navigateBack()
|
|
} catch (err) {
|
|
wx.hideLoading()
|
|
this.toast((err as Error).message || '保存失败')
|
|
} finally {
|
|
this.setData({ saving: false })
|
|
}
|
|
},
|
|
|
|
toast(title: string) {
|
|
wx.showToast({ title, icon: 'none', duration: 1800 })
|
|
}
|
|
})
|