544 lines
19 KiB
JavaScript
544 lines
19 KiB
JavaScript
const API = require('../../utils/api.js')
|
||
|
||
const { parseDate, formatDate, formatDateTime, calcAge } = require('../../utils/date.js')
|
||
const { STATUS_MAP, PAYMENT_STATUS_MAP } = require('../../utils/order.js')
|
||
const { maskIdNumber, maskOrderId } = require('../../utils/privacy.js')
|
||
|
||
const SEX_MAP = {
|
||
male: '男',
|
||
female: '女'
|
||
}
|
||
|
||
const SEX_REQUIREMENT_MAP = {
|
||
none: '不限',
|
||
male: '男',
|
||
female: '女'
|
||
}
|
||
|
||
// 支付方式:与 schema 的 payment.method 枚举一一对应
|
||
const PAYMENT_METHOD_MAP = {
|
||
online_wechat: '线上微信',
|
||
offline_cash: '线下现金',
|
||
offline_transfer: '线下转账'
|
||
}
|
||
|
||
const WEEKDAYS = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
|
||
|
||
Page({
|
||
data: {
|
||
recordId: '',
|
||
record: {},
|
||
showAllDetails: false,
|
||
service: null,
|
||
loading: false,
|
||
loadError: '',
|
||
// 编辑全部收进底部弹窗:页面只读,表单只活在弹窗里,两个弹窗各自一个开关
|
||
showNotePopup: false,
|
||
editPatientNote: '',
|
||
// 医院预约规则与下单页一致,均由订单关联的服务目录下发
|
||
showHospitalPopup: false,
|
||
provinces: [],
|
||
minAppointmentDate: '',
|
||
fixedTime: false,
|
||
timeOptions: [],
|
||
timeStart: '',
|
||
timeEnd: '',
|
||
editHospital: {},
|
||
showCancelPopup: false,
|
||
cancelReason: '',
|
||
cancelReasons: [
|
||
{ id: 'schedule', text: '临时有事,无法前往' },
|
||
{ id: 'recovered', text: '病情好转,无需陪诊' },
|
||
{ id: 'hospital', text: '医院停诊/改期' },
|
||
{ id: 'escort', text: '陪诊师无法到达' },
|
||
{ id: 'other', text: '其他原因' }
|
||
]
|
||
},
|
||
|
||
onLoad(options) {
|
||
const id = options.id
|
||
if (!id) {
|
||
wx.showToast({ title: '参数错误', icon: 'none' })
|
||
setTimeout(() => wx.navigateBack(), 1500)
|
||
return
|
||
}
|
||
this.setData({ recordId: id })
|
||
},
|
||
|
||
// onShow 在首次渲染时紧跟 onLoad 触发,加载只放在这里,避免进页面发两次请求
|
||
onShow() {
|
||
if (this.data.recordId) {
|
||
this.loadRecord(this.data.recordId)
|
||
}
|
||
},
|
||
|
||
onPullDownRefresh() {
|
||
if (this.data.recordId) {
|
||
this.loadRecord(this.data.recordId).finally(() => {
|
||
wx.stopPullDownRefresh()
|
||
})
|
||
}
|
||
},
|
||
|
||
async loadRecord(id) {
|
||
this.setData({ loading: true, loadError: '' })
|
||
try {
|
||
const app = getApp()
|
||
await app.waitForAuth()
|
||
if (!app.globalData.user?._id) throw new Error('请先登录后查看订单')
|
||
|
||
const [res, services] = await Promise.all([
|
||
API.escort.getRecordById(id),
|
||
app.loadServices()
|
||
])
|
||
if (res.code !== 0 || !res.data?.record) throw new Error(res.msg || '订单加载失败')
|
||
if (!services) throw new Error('服务规则加载失败,请重试')
|
||
|
||
const item = res.data.record
|
||
const service = services.find(entry => entry.id === item.escort?.serviceId) || null
|
||
const record = this.formatRecord(item)
|
||
// 服务已下架时仍可查看历史订单,但不能再按失效规则修改订单。
|
||
if (!service) {
|
||
record.canEditBooking = false
|
||
record.canEditNote = false
|
||
}
|
||
this.setData({ record, service })
|
||
if (service) this.applyBookingConfig(service)
|
||
if (record.healthProfileId) this.loadProfileSnapshot(record.healthProfileId)
|
||
} catch (err) {
|
||
this.setData({ record: {}, loadError: err.message || '网络请求失败,请重试' })
|
||
} finally {
|
||
this.setData({ loading: false })
|
||
}
|
||
},
|
||
|
||
retryLoad() {
|
||
if (this.data.recordId) this.loadRecord(this.data.recordId)
|
||
},
|
||
|
||
applyBookingConfig(service) {
|
||
const booking = service.booking || {}
|
||
const sessions = booking.sessions || []
|
||
const fixedTime = sessions.length > 0 && sessions.every(item => !item.flexible)
|
||
const firstSession = sessions[0] || {}
|
||
const minDate = new Date()
|
||
minDate.setDate(minDate.getDate() + Number(booking.advanceDays || 0))
|
||
const minAppointmentDate = formatDate(minDate)
|
||
let timeEnd = firstSession.end || ''
|
||
if (!fixedTime && firstSession.end && booking.durationMinutes) {
|
||
const [hour, minute] = firstSession.end.split(':').map(Number)
|
||
const latest = hour * 60 + minute - booking.durationMinutes
|
||
timeEnd = `${String(Math.floor(latest / 60)).padStart(2, '0')}:${String(latest % 60).padStart(2, '0')}`
|
||
}
|
||
this.setData({
|
||
provinces: service.areas || [],
|
||
minAppointmentDate,
|
||
fixedTime,
|
||
timeOptions: sessions.map(item => `${item.start} - ${item.end}`),
|
||
timeStart: firstSession.start || '',
|
||
timeEnd
|
||
})
|
||
},
|
||
|
||
// 用档案最新信息覆盖订单里的 patient 快照:
|
||
// 订单必须关联就诊人,档案才是信息源;读取失败(如档案已删除)时保留快照兜底
|
||
loadProfileSnapshot(profileId) {
|
||
return API.healthProfile.getMyProfileById(profileId)
|
||
.then((res) => {
|
||
if (res.code !== 0 || !res.data) {
|
||
return
|
||
}
|
||
const detail = res.data.profile || {}
|
||
const profile = detail.profile || {}
|
||
const health = detail.health || {}
|
||
// 与 formatRecord 同一批就诊人字段:档案加载完成后覆盖订单快照,
|
||
// 展开区资料因此需要一起重算
|
||
const patient = {
|
||
name: profile.name || '',
|
||
sexText: SEX_MAP[profile.sex] || '',
|
||
age: calcAge(profile.birth),
|
||
weight: health.weight || 0,
|
||
height: health.height || 0,
|
||
mobile: profile.mobile || '',
|
||
idnumber: profile.idnumber || ''
|
||
}
|
||
this.setData({
|
||
'record.patientName': patient.name,
|
||
'record.patientMobile': patient.mobile,
|
||
'record.patientIdnumber': maskIdNumber(patient.idnumber),
|
||
'record.patientMeta': this.buildPatientMeta(patient),
|
||
'record.patientBrief': this.buildPatientBrief(patient)
|
||
})
|
||
})
|
||
.catch((err) => {
|
||
console.log('获取就诊人档案失败,展示订单快照', err)
|
||
})
|
||
},
|
||
|
||
formatRecord(item) {
|
||
const status = item.status
|
||
const paymentStatus = item.payment?.status || 'unpaid'
|
||
const statusInfo = STATUS_MAP[status] || STATUS_MAP.pending
|
||
const paymentInfo = PAYMENT_STATUS_MAP[paymentStatus] || PAYMENT_STATUS_MAP.unpaid
|
||
|
||
// 底栏与「修改」入口的口径在这里算一次,WXML 只读结果,不再重复一串状态判断。
|
||
// 用户只能取消:未确认且未收款的取消后订单即被删除;已确认/已收款的转为取消申请
|
||
const canCancel = status === 'pending' || status === 'confirmed'
|
||
const canRebook = (status === 'completed' || status === 'cancelled') && item.escort?.serviceId > 0
|
||
// 终态单据只读:医院预约与陪诊需求不允许回改(就诊人「档案」跳的是档案页,不在此列)
|
||
// 进行中服务已开始:排期与医院不允许用户单方变更,仅保留就诊人备注(与后端字段白名单一致)
|
||
const canEditBooking = status === 'pending' || status === 'confirmed'
|
||
const canEditNote = canEditBooking || status === 'in_progress'
|
||
|
||
// 就诊人字段先落到局部变量:摘要姓名与展开区资料都从同一批值派生,
|
||
// 口径不在 WXML 与 JS 两处各写一份
|
||
const patient = {
|
||
name: item.patient?.name || '',
|
||
sexText: SEX_MAP[item.patient?.sex] || '',
|
||
age: calcAge(item.patient?.birth),
|
||
weight: item.patient?.weight || 0,
|
||
height: item.patient?.height || 0,
|
||
mobile: item.patient?.mobile || '',
|
||
idnumber: item.patient?.idnumber || ''
|
||
}
|
||
|
||
// 预约时间派生:日期行(带星期)与开始时间同一行
|
||
const scheduleMeta = this.buildScheduleMeta(item.schedule || {})
|
||
|
||
return {
|
||
_id: item._id,
|
||
displayId: maskOrderId(item._id),
|
||
healthProfileId: item.healthProfileId || '',
|
||
serviceId: item.escort?.serviceId || 0,
|
||
patientName: patient.name,
|
||
patientMobile: patient.mobile,
|
||
patientIdnumber: maskIdNumber(patient.idnumber),
|
||
patientMeta: this.buildPatientMeta(patient),
|
||
patientBrief: this.buildPatientBrief(patient),
|
||
// 陪诊师由平台分配:以 id 或 name 任一存在视为已派单,
|
||
// 派单若只写了 id 而没冗余姓名,卡片也不会误报「待分配」
|
||
hasAttendant: Boolean(item.attendant?.id || item.attendant?.name),
|
||
attendantName: item.attendant?.name || '',
|
||
attendantMobile: item.attendant?.mobile || '',
|
||
hospitalProvince: item.hospital?.province || '',
|
||
hospitalName: item.hospital?.name || '',
|
||
hospitalAddress: item.hospital?.address || '',
|
||
// 科室用于摘要展示;医生、病历号与省份只做编辑弹窗的回填源,不再在展开区重复
|
||
hospitalDepartment: item.hospital?.department || '',
|
||
hospitalDoctor: item.hospital?.doctor || '',
|
||
medicalRecordNo: item.hospital?.medicalRecordNo || '',
|
||
// scheduleDate 保留 YYYY-MM-DD 原格式:编辑弹窗的 date picker 直接喂它
|
||
scheduleDate: item.schedule?.date ? formatDate(item.schedule.date) : '',
|
||
scheduleStartTime: item.schedule?.startTime || '',
|
||
scheduleEndTime: item.schedule?.endTime || '',
|
||
scheduleDateText: scheduleMeta.dateText,
|
||
scheduleTimeText: scheduleMeta.timeText,
|
||
escortServiceName: item.escort?.serviceName || '',
|
||
sexRequirementText: SEX_REQUIREMENT_MAP[item.escort?.sexRequirement] || '',
|
||
shippingAddress: item.shippingAddress || null,
|
||
cancelReason: item.cancelReason || '',
|
||
totalFee: (item.payment?.totalFee || 0).toFixed(2),
|
||
paidFee: (item.payment?.paidFee || 0).toFixed(2),
|
||
showPaidFee: Number(item.payment?.paidFee) > 0,
|
||
paymentStatus,
|
||
paymentStatusText: paymentInfo.text,
|
||
paymentStatusColor: paymentInfo.color,
|
||
paymentStatusBg: paymentInfo.bg,
|
||
paymentStatusBorder: paymentInfo.border,
|
||
paymentMethodText: PAYMENT_METHOD_MAP[item.payment?.method] || '',
|
||
patientNote: item.notes?.patientNote || '',
|
||
escortNote: item.notes?.escortNote || '',
|
||
medicalSummary: item.notes?.medicalSummary || '',
|
||
status,
|
||
statusText: statusInfo.text,
|
||
statusColor: statusInfo.color,
|
||
statusBg: statusInfo.bg,
|
||
statusBorder: statusInfo.border,
|
||
statusDesc: statusInfo.desc,
|
||
canCancel,
|
||
canRebook,
|
||
canEditBooking,
|
||
canEditNote,
|
||
// 底栏只在确实有按钮时出现,避免无动作状态空留一条白栏
|
||
showBottomBar: canCancel || canRebook,
|
||
createTime: item.meta?.createtime ? formatDateTime(item.meta.createtime) : '',
|
||
updateTime: item.meta?.updatetime ? formatDateTime(item.meta.updatetime) : ''
|
||
}
|
||
},
|
||
|
||
// 展开区「就诊人资料」的字段序列:只留摘要卡没展示的核对项(身高体重),
|
||
// 性别年龄已在摘要卡的就诊人行给出,此处不再重复;
|
||
// 空值整项剔除,WXML 只负责在项之间插竖线
|
||
buildPatientMeta(patient) {
|
||
const list = []
|
||
if (patient.height) list.push({ id: 'height', text: `身高 ${patient.height}cm` })
|
||
if (patient.weight) list.push({ id: 'weight', text: `体重 ${patient.weight}kg` })
|
||
return list
|
||
},
|
||
|
||
// 摘要卡就诊人行只取性别与年龄:这两项决定陪诊师是否需要额外准备,
|
||
// 身高体重属核对资料,留在展开区(buildPatientMeta 那份)
|
||
buildPatientBrief(patient) {
|
||
const list = []
|
||
if (patient.sexText) list.push({ id: 'sex', text: patient.sexText })
|
||
if (patient.age) list.push({ id: 'age', text: `${patient.age}岁` })
|
||
return list
|
||
},
|
||
|
||
// 预约时间派生:日期行(带星期)与开始时间同一行;
|
||
// 日期无效或缺失时返回空串,由 WXML 走兜底文案
|
||
buildScheduleMeta(schedule) {
|
||
const result = { dateText: '', timeText: '' }
|
||
if (schedule.date) {
|
||
const d = parseDate(schedule.date)
|
||
if (d) {
|
||
result.dateText = `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 ${WEEKDAYS[d.getDay()]}`
|
||
}
|
||
}
|
||
const start = schedule.startTime || ''
|
||
result.timeText = start
|
||
return result
|
||
},
|
||
|
||
onContactSupport() {
|
||
const record = this.data.record
|
||
if (!record._id) return
|
||
wx.navigateTo({
|
||
url: `/pages/mine/contact?orderId=${encodeURIComponent(record._id)}`
|
||
})
|
||
},
|
||
|
||
onToggleDetails() {
|
||
this.setData({ showAllDetails: !this.data.showAllDetails })
|
||
},
|
||
|
||
// ===== 陪诊需求编辑(底部弹窗) =====
|
||
|
||
onEditPatientNote() {
|
||
this.setData({
|
||
showNotePopup: true,
|
||
editPatientNote: this.data.record.patientNote || ''
|
||
})
|
||
},
|
||
|
||
onPatientNoteInput(e) {
|
||
this.setData({ editPatientNote: e.detail.value })
|
||
},
|
||
|
||
onCancelEdit() {
|
||
this.setData({ showNotePopup: false })
|
||
},
|
||
|
||
onSavePatientNote() {
|
||
const note = this.data.editPatientNote.trim()
|
||
wx.showLoading({ title: '保存中...' })
|
||
API.escort.updateRecord(this.data.recordId, {
|
||
'notes.patientNote': note
|
||
})
|
||
.then((res) => {
|
||
wx.hideLoading()
|
||
if (res.code === 0) {
|
||
wx.showToast({ title: '保存成功', icon: 'success' })
|
||
this.setData({
|
||
showNotePopup: false,
|
||
'record.patientNote': note
|
||
})
|
||
} else {
|
||
wx.showToast({ title: res.msg || '保存失败', icon: 'none' })
|
||
}
|
||
})
|
||
.catch(() => {
|
||
wx.hideLoading()
|
||
wx.showToast({ title: '网络请求失败', icon: 'none' })
|
||
})
|
||
},
|
||
|
||
// ===== 医院预约信息编辑(底部弹窗) =====
|
||
|
||
// 打开弹窗:用当前展示值填充表单(scheduleDate 已是 YYYY-MM-DD,可直接喂给 date picker)
|
||
onEditHospital() {
|
||
const r = this.data.record
|
||
const provinceIndex = Math.max(0, this.data.provinces.indexOf(r.hospitalProvince))
|
||
const sessions = this.data.service?.booking?.sessions || []
|
||
const sessionIndex = Math.max(0, sessions.findIndex(item => item.start === r.scheduleStartTime))
|
||
this.setData({
|
||
showHospitalPopup: true,
|
||
editHospital: {
|
||
province: r.hospitalProvince || this.data.provinces[0] || '',
|
||
provinceIndex,
|
||
name: r.hospitalName || '',
|
||
address: r.hospitalAddress || '',
|
||
department: r.hospitalDepartment || '',
|
||
doctor: r.hospitalDoctor || '',
|
||
medicalRecordNo: r.medicalRecordNo || '',
|
||
scheduleDate: r.scheduleDate || '',
|
||
startTime: r.scheduleStartTime || '',
|
||
sessionIndex
|
||
}
|
||
})
|
||
},
|
||
|
||
// 文本字段统一走 data-field 分发,省掉每字段一个 handler
|
||
onHospitalFieldInput(e) {
|
||
const field = e.currentTarget.dataset.field
|
||
this.setData({ [`editHospital.${field}`]: e.detail.value })
|
||
},
|
||
|
||
onProvinceChange(e) {
|
||
const index = Number(e.detail.value)
|
||
this.setData({
|
||
'editHospital.provinceIndex': index,
|
||
'editHospital.province': this.data.provinces[index]
|
||
})
|
||
},
|
||
|
||
onScheduleDateChange(e) {
|
||
this.setData({ 'editHospital.scheduleDate': e.detail.value })
|
||
},
|
||
|
||
onStartTimeChange(e) {
|
||
if (this.data.fixedTime) {
|
||
const sessionIndex = Number(e.detail.value)
|
||
const session = this.data.service.booking.sessions[sessionIndex]
|
||
this.setData({
|
||
'editHospital.sessionIndex': sessionIndex,
|
||
'editHospital.startTime': session.start
|
||
})
|
||
return
|
||
}
|
||
this.setData({ 'editHospital.startTime': e.detail.value })
|
||
},
|
||
|
||
onCancelHospitalEdit() {
|
||
this.setData({ showHospitalPopup: false })
|
||
},
|
||
|
||
onSaveHospital() {
|
||
const form = this.data.editHospital
|
||
if (!form.name || !form.name.trim()) {
|
||
wx.showToast({ title: '请输入就诊医院', icon: 'none' })
|
||
return
|
||
}
|
||
if (!form.scheduleDate) {
|
||
wx.showToast({ title: '请选择预约日期', icon: 'none' })
|
||
return
|
||
}
|
||
if (!form.startTime) {
|
||
wx.showToast({ title: '请选择预约时间', icon: 'none' })
|
||
return
|
||
}
|
||
|
||
const update = {
|
||
'hospital.province': form.province || '',
|
||
'hospital.name': form.name.trim(),
|
||
'hospital.address': (form.address || '').trim(),
|
||
'hospital.department': (form.department || '').trim(),
|
||
'hospital.doctor': (form.doctor || '').trim(),
|
||
'hospital.medicalRecordNo': (form.medicalRecordNo || '').trim(),
|
||
// 时长与结束时间由后端按服务目录重新派生,前端只提交业务输入。
|
||
'schedule.date': form.scheduleDate,
|
||
'schedule.startTime': form.startTime
|
||
}
|
||
|
||
wx.showLoading({ title: '保存中...' })
|
||
API.escort.updateRecord(this.data.recordId, update)
|
||
.then((res) => {
|
||
wx.hideLoading()
|
||
if (res.code === 0) {
|
||
wx.showToast({ title: '保存成功', icon: 'success' })
|
||
this.setData({ showHospitalPopup: false })
|
||
// 重新拉取,保证 formatRecord 出的展示字段(日历牌、时长)与库内一致
|
||
this.loadRecord(this.data.recordId)
|
||
} else {
|
||
wx.showToast({ title: res.msg || '保存失败', icon: 'none' })
|
||
}
|
||
})
|
||
.catch(() => {
|
||
wx.hideLoading()
|
||
wx.showToast({ title: '网络请求失败', icon: 'none' })
|
||
})
|
||
},
|
||
|
||
// 就诊人信息统一在健康档案里维护,这里只负责跳转查看
|
||
onViewProfile() {
|
||
const profileId = this.data.record.healthProfileId
|
||
if (!profileId) {
|
||
return
|
||
}
|
||
wx.navigateTo({
|
||
url: `/pages/health/profileedit?id=${profileId}`
|
||
})
|
||
},
|
||
|
||
onCancelOrder() {
|
||
this.setData({
|
||
showCancelPopup: true,
|
||
cancelReason: ''
|
||
})
|
||
},
|
||
|
||
onCloseCancelPopup() {
|
||
this.setData({ showCancelPopup: false })
|
||
},
|
||
|
||
onSelectCancelReason(e) {
|
||
this.setData({ cancelReason: e.currentTarget.dataset.reason })
|
||
},
|
||
|
||
onConfirmCancel() {
|
||
if (!this.data.cancelReason) {
|
||
wx.showToast({ title: '请选择取消原因', icon: 'none' })
|
||
return
|
||
}
|
||
|
||
wx.showLoading({ title: '处理中...' })
|
||
API.escort.updateStatus(this.data.recordId, {
|
||
status: 'cancelled',
|
||
reason: this.data.cancelReason
|
||
})
|
||
.then((res) => {
|
||
wx.hideLoading()
|
||
if (res.code === 0) {
|
||
this.setData({ showCancelPopup: false })
|
||
wx.showToast({ title: res.msg || '操作成功', icon: 'success' })
|
||
// 未确认且未收款的订单取消后已被删除,直接退回列表;其余刷新展示「待取消」
|
||
if (res.data?.deleted) {
|
||
setTimeout(() => wx.navigateBack(), 1200)
|
||
} else {
|
||
this.loadRecord(this.data.recordId)
|
||
}
|
||
} else {
|
||
wx.showToast({ title: res.msg || '操作失败', icon: 'none' })
|
||
}
|
||
})
|
||
.catch(() => {
|
||
wx.hideLoading()
|
||
wx.showToast({ title: '网络请求失败', icon: 'none' })
|
||
})
|
||
},
|
||
|
||
onRebook() {
|
||
const serviceId = this.data.record.serviceId
|
||
if (!serviceId) return
|
||
wx.navigateTo({
|
||
url: `/pages/escort/itemdetail?id=${serviceId}&book=1`
|
||
})
|
||
},
|
||
|
||
// 回首页:首页是 tabBar 页,必须走 switchTab,navigateTo 跳不过去
|
||
onGoHome() {
|
||
wx.switchTab({
|
||
url: '/pages/home/index'
|
||
})
|
||
},
|
||
|
||
// 本页含就诊人姓名 / 手机号 / 身份证号与订单号,转发卡片不指向本页,统一落到首页;
|
||
// 也不提供朋友圈分享——朋友圈只能分享当前页 URL,会把订单页地址带出去
|
||
onShareAppMessage() {
|
||
return {
|
||
title: '暖橙陪诊 - 专业陪诊服务',
|
||
path: '/pages/home/index'
|
||
}
|
||
}
|
||
})
|