Files
wxapp_escort/pages/health/profileedit.js
T
2026-11-03 16:15:41 +08:00

283 lines
8.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const API = require('../../utils/api.js')
const { parseDate, formatDate } = require('../../utils/date.js')
const { setUnsavedGuard } = require('../../utils/form.js')
// 性别选项,与后端 schema 的 male / female 对应
const SEX_OPTIONS = [
{ value: 'male', label: '男' },
{ value: 'female', label: '女' }
]
const MOBILE_REGEX = /^1[3-9]\d{9}$/
const ID_NUMBER_REGEX = /^\d{17}[\dXx]$/
Page({
data: {
id: '',
isEdit: false,
saving: false,
loading: false,
loadError: '',
today: '',
errors: {},
sexOptions: SEX_OPTIONS,
form: {
name: '',
sex: '',
birth: '',
mobile: '',
idnumber: '',
height: '',
weight: '',
remark: ''
}
},
onLoad(options) {
const id = options.id || ''
this.unsavedGuardActive = false
this.initialFormSnapshot = ''
this.setData({
id,
isEdit: !!id,
today: formatDate(new Date())
})
wx.setNavigationBarTitle({
title: id ? '编辑就诊人' : '新增就诊人'
})
if (id) {
this.loadProfile(id)
} else {
this.captureInitialForm()
}
},
onUnload() {
if (this.unsavedGuardActive) setUnsavedGuard(false)
},
captureInitialForm() {
this.initialFormSnapshot = JSON.stringify(this.data.form)
this.syncUnsavedGuard()
},
syncUnsavedGuard() {
const dirty = JSON.stringify(this.data.form) !== this.initialFormSnapshot
if (dirty === this.unsavedGuardActive) return
this.unsavedGuardActive = dirty
setUnsavedGuard(dirty)
},
// 编辑模式:读取档案详情回填表单;失败时不能用空表单冒充已加载。
async loadProfile(id) {
this.setData({ loading: true, loadError: '' })
try {
const res = await API.healthProfile.getMyProfileById(id)
if (res.code !== 0) throw new Error(res.msg || '就诊人信息加载失败')
const detail = (res.data && res.data.profile) || {}
const profile = detail.profile || {}
const health = detail.health || {}
this.setData({
form: {
name: profile.name || '',
sex: profile.sex || '',
birth: formatDate(profile.birth),
mobile: profile.mobile || '',
idnumber: profile.idnumber || '',
// 身高的 schema 默认值是 0,0 视为未填写,回填成空串而不是 "0"
height: health.height ? String(health.height) : '',
weight: health.weight ? String(health.weight) : '',
remark: health.remark || ''
}
})
this.captureInitialForm()
} catch (err) {
console.log('获取就诊人信息失败', err)
this.setData({ loadError: err.message || '网络请求失败,请重试' })
} finally {
this.setData({ loading: false })
}
},
retryLoad() {
if (this.data.id) this.loadProfile(this.data.id)
},
onFieldInput(e) {
const field = e.currentTarget.dataset.field
this.setData({
[`form.${field}`]: e.detail.value,
[`errors.${field}`]: ''
})
this.syncUnsavedGuard()
},
onSexSelect(e) {
const sex = e.currentTarget.dataset.sex
// 再次点击已选中的性别则取消选择
this.setData({
'form.sex': this.data.form.sex === sex ? '' : sex
})
this.syncUnsavedGuard()
},
onBirthChange(e) {
this.setData({
'form.birth': e.detail.value,
'errors.birth': ''
})
this.syncUnsavedGuard()
},
validateOptionalNumber(value, min, max) {
if (!value.trim()) return true
const number = Number(value)
return Number.isFinite(number) && number >= min && number <= max
},
// 返回字段错误表,WXML 在对应字段下展示,保存时同时提示首个错误。
validate() {
const { name, mobile, birth, idnumber, height, weight } = this.data.form
const errors = {}
if (!name.trim()) errors.name = '请输入就诊人姓名'
if (!mobile.trim()) {
errors.mobile = '请输入联系电话'
} else if (!MOBILE_REGEX.test(mobile.trim())) {
errors.mobile = '请输入正确的 11 位手机号'
}
if (birth) {
const birthDate = parseDate(birth)
if (!birthDate) {
errors.birth = '请选择有效的出生日期'
} else if (birthDate < parseDate('1900-01-01') || birthDate > parseDate(this.data.today)) {
errors.birth = '出生日期需在 1900-01-01 至今天之间'
}
}
if (idnumber.trim()) {
const value = idnumber.trim()
if (!ID_NUMBER_REGEX.test(value)) {
errors.idnumber = '请输入 18 位身份证号,末位可为 X'
} else {
const idBirth = `${value.slice(6, 10)}-${value.slice(10, 12)}-${value.slice(12, 14)}`
if (!parseDate(idBirth)) errors.idnumber = '身份证号中的出生日期无效'
}
}
if (!this.validateOptionalNumber(height, 30, 250)) {
errors.height = '身高需为 30–250 cm 的数字'
}
if (!this.validateOptionalNumber(weight, 2, 300)) {
errors.weight = '体重需为 2–300 kg 的数字'
}
return errors
},
async onSave() {
if (this.data.saving) return
const errors = this.validate()
const firstError = Object.values(errors)[0]
this.setData({ errors })
if (firstError) {
wx.showToast({ title: firstError, icon: 'none' })
return
}
const { name, sex, birth, mobile, idnumber, height, weight, remark } = this.data.form
// 可选数值留空才写 0;所有非空值已通过校验,不再用 || 0 吞掉非法输入。
const heightNum = height.trim() ? Number(height) : 0
const weightNum = weight.trim() ? Number(weight) : 0
// 新增用嵌套对象;更新用点号路径,避免与后端 profile.pinyin 的额外写入冲突。
const payload = this.data.isEdit ? {
'profile.name': name.trim(),
'profile.sex': sex,
'profile.birth': birth,
'profile.mobile': mobile.trim(),
'profile.idnumber': idnumber.trim().toUpperCase(),
'health.height': heightNum,
'health.weight': weightNum,
'health.remark': remark.trim()
} : {
profile: {
name: name.trim(),
sex,
birth,
mobile: mobile.trim(),
idnumber: idnumber.trim().toUpperCase()
},
health: {
height: heightNum,
weight: weightNum,
remark: remark.trim()
}
}
this.setData({ saving: true })
wx.showLoading({ title: '保存中...' })
try {
const request = this.data.isEdit
? API.healthProfile.updateMyProfile(this.data.id, payload)
: API.healthProfile.createMyProfile(payload)
const res = await request
if (res.code !== 0) {
wx.showToast({ title: res.msg || '保存失败', icon: 'none' })
return
}
this.captureInitialForm()
wx.showToast({ title: '保存成功', icon: 'success' })
setTimeout(() => wx.navigateBack(), 800)
} catch (err) {
console.log('保存就诊人失败', err)
wx.showToast({ title: '网络请求失败', icon: 'none' })
} finally {
wx.hideLoading()
this.setData({ saving: false })
}
},
// 回首页:首页是 tabBar 页,必须走 switchTab,navigateTo 跳不过去。
// switchTab 不保证被 enableAlertBeforeUnload 拦截,未保存时先自行确认再放行,
// 并主动关掉返回询问,避免同一次离开弹两遍。
onGoHome() {
const goHome = () => {
if (this.unsavedGuardActive) setUnsavedGuard(false)
wx.switchTab({ url: '/pages/home/index' })
}
if (!this.unsavedGuardActive) {
goHome()
return
}
wx.showModal({
title: '放弃未保存的修改?',
content: '返回首页后,当前填写的就诊人信息不会保存。',
confirmText: '返回首页',
cancelText: '继续编辑',
success: (res) => {
if (res.confirm) goHome()
}
})
},
// 转发卡片统一落到首页,避免好友打开需要登录的空表单。
onShareAppMessage() {
return {
title: '暖橙陪诊 · 专业陪诊服务',
path: '/pages/home/index'
}
}
})