Files
wxapp_escort/pages/escort/itemorder.js
T
lik 3755e1283b style(order): 预约下单页兜底与项目切换入口强化
初始化拆出 loadPageContent,协议、医院列表与登录状态失败各自降级,不再挡整页;
陪诊项目「更换」改为品牌橙胶囊并改名「更换服务」,箭头同步换色;
就诊人胶囊补同名提示,导航栏统一为浅色纸面。
2026-11-16 19:30:44 +08:00

589 lines
20 KiB
JavaScript

const API = require('../../utils/api.js')
const { restoreLightNavigation } = require('../../utils/navigation.js')
const { withDuplicateNameHints } = require('../../utils/booking-profiles.js')
const { formatDate, LATEST_APPOINTMENT_TIME, buildTimeSlots } = require('../../utils/date.js')
const { ensureLogin } = require('../../utils/auth.js')
// 陪诊项目下拉单行高度:图标 72rpx + 单行文字 + 上下留白
const SERVICE_OPTION_HEIGHT = 108
// 下拉面板最多占用的屏高:扣掉底部固定操作栏与页面留白,项目再多也能整屏看到
const SERVICE_PANEL_RESERVED = 200
// 免责协议标题兜底:接口未返回时也能在勾选行展示协议名称
const DEFAULT_DISCLAIMER_TITLE = '陪诊服务免责协议'
Page({
data: {
services: [],
serviceIndex: 0,
service: {},
serviceIconClass: 'assist-icon-1',
servicePanelOpen: false,
serviceOptionsHeight: 0,
totalPrice: '0.00',
pageLoading: true,
pageError: '',
submitting: false,
profiles: [],
selectedProfileId: '',
patientName: '',
patientPhone: '',
selectedPatient: null,
province: '',
provinceIndex: 0,
provinces: [],
hospital: '',
hospitalOptions: [],
hospitalCustom: false,
appointmentDate: '',
appointmentTime: '',
minAppointmentDate: '',
// 预约时间:从服务起始时刻到 23:30,每半小时一档
timeSlots: [],
timeSlotIndex: 0,
remark: '',
shippingAddress: '',
requiresAddress: false,
payChannel: 'offline',
// 点击「提交预约」后弹出支付方式选择,默认线下支付
showPayPopup: false,
gender: '不限',
genderIndex: 0,
genderOptions: ['不限', '男', '女'],
// 下单前必须勾选确认《陪诊服务免责协议》
agreementAgreed: false,
agreementHint: false,
agreementTitle: DEFAULT_DISCLAIMER_TITLE,
showAgreementPopup: false,
disclaimer: null,
disclaimerLoading: false,
disclaimerError: false
},
onLoad(options) {
this.requestedServiceId = Number(options.id)
this.idempotencyKey = this.createIdempotencyKey()
this.initializePage()
},
onShow() {
restoreLightNavigation()
// 从新增/编辑就诊人页返回时刷新档案,首次进入由 initializePage 加载。
if (this.pageReady && getApp().globalData.user?._id) this.loadProfiles()
},
/**
* 免责协议:与表单并行预加载,用户点开弹层或直接提交时都能立即展示
*/
loadDisclaimer() {
if (this.data.disclaimer || this.data.disclaimerLoading) return
this.setData({ disclaimerLoading: true, disclaimerError: false })
getApp().loadDisclaimer().then((disclaimer) => {
this.setData({
disclaimer,
agreementTitle: disclaimer?.title || DEFAULT_DISCLAIMER_TITLE,
disclaimerLoading: false,
disclaimerError: !disclaimer
})
}).catch((err) => {
console.error('免责协议加载失败', err)
this.setData({ disclaimerLoading: false, disclaimerError: true })
})
},
onToggleAgreement() {
if (this.data.submitting) return
this.setData({
agreementAgreed: !this.data.agreementAgreed,
agreementHint: false
})
},
onOpenAgreement() {
this.setData({ showAgreementPopup: true })
this.loadDisclaimer()
},
onCloseAgreementPopup() {
this.setData({ showAgreementPopup: false })
},
onAgreeFromPopup() {
this.setData({
agreementAgreed: true,
agreementHint: false,
showAgreementPopup: false
})
},
retryLoadDisclaimer() {
this.loadDisclaimer()
},
async initializePage() {
this.pageReady = false
this.setData({ pageLoading: true, pageError: '' })
try {
await this.loadPageContent()
} catch (err) {
console.error('预约页面初始化失败', err)
this.setData({ pageError: '服务加载失败,请重试' })
} finally {
this.setData({ pageLoading: false })
}
},
async loadPageContent() {
// 免责协议与表单并行加载,避免用户点开协议时再空等
this.loadDisclaimer()
const services = await getApp().loadServices()
if (!services || services.length === 0) {
this.setData({ pageLoading: false, pageError: '服务加载失败,请重试' })
return
}
const requestedIndex = services.findIndex((item) => item.id === this.requestedServiceId)
const consultationIndex = services.findIndex((item) => item.title.includes('问诊'))
const serviceIndex = requestedIndex >= 0 ? requestedIndex : (consultationIndex >= 0 ? consultationIndex : 0)
// 每个项目带上图标类名,供下拉列表逐项渲染(与首页宫格同一套图形)
const serviceList = services.map((item) => ({ ...item, iconClass: this.getServiceIconClass(item) }))
this.setData({
services: serviceList,
serviceOptionsHeight: this.getServiceOptionsHeight(serviceList.length)
})
this.applyService(serviceList[serviceIndex], serviceIndex)
this.setData({ pageLoading: false })
this.pageReady = true
const app = getApp()
// 启动时 app 已在预取,这里只等它落定后用最新列表刷新下拉;
// 列表为空时组件内的「其他医院」入口仍可手填,不会阻断下单
app.loadHospitals().then(() => {
this.refreshHospitalOptions()
}).catch((err) => {
console.error('医院列表加载失败', err)
})
// 登录失败不应隐藏已加载的预约表单,提交时仍会经过登录守卫。
try {
await app.waitForAuth()
if (app.globalData.user?._id) this.loadProfiles()
} catch (err) {
console.error('预约页面登录状态加载失败', err)
}
},
retryLoad() {
this.initializePage()
},
// 按屏高算下拉可见高度:项目少时整列铺开,多时撑到屏高上限后在面板内滚动
getServiceOptionsHeight(count) {
const { windowWidth, windowHeight } = wx.getSystemInfoSync()
const availableRpx = (windowHeight * 750) / windowWidth - SERVICE_PANEL_RESERVED
const maxRows = Math.max(1, Math.floor(availableRpx / SERVICE_OPTION_HEIGHT))
return Math.min(count, maxRows) * SERVICE_OPTION_HEIGHT
},
createIdempotencyKey() {
return `order_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`
},
applyService(service, serviceIndex) {
const booking = service.booking || {}
const sessions = booking.sessions || []
const firstSession = sessions[0] || {}
const minDate = new Date()
minDate.setDate(minDate.getDate() + Number(booking.advanceDays || 0))
const provinces = service.areas || []
this.selectedHospitalId = ''
this.setData({
service,
serviceIndex,
serviceIconClass: service.iconClass || this.getServiceIconClass(service),
servicePanelOpen: false,
totalPrice: service.price,
minAppointmentDate: formatDate(minDate),
// 所有服务统一提供到 23:30 的开始时间档位(夜间陪诊也需覆盖晚间时段)
timeSlots: buildTimeSlots(firstSession.start || '', LATEST_APPOINTMENT_TIME),
timeSlotIndex: 0,
provinces,
province: provinces[0] || '',
provinceIndex: 0,
hospital: '',
hospitalCustom: false,
appointmentDate: '',
appointmentTime: '',
shippingAddress: '',
requiresAddress: !!booking.requiresAddress
}, () => this.refreshHospitalOptions(provinces[0] || ''))
},
// 展开/收起陪诊项目下拉面板
onToggleServicePanel() {
if (this.data.submitting) return
const open = !this.data.servicePanelOpen
this.setData({ servicePanelOpen: open })
if (open) wx.nextTick(() => this.scrollServicePanelIntoView())
},
// 面板展开后若被底部固定操作栏遮挡,自动上滚页面,保证列表完整可见
scrollServicePanelIntoView() {
const query = this.createSelectorQuery()
query.select('.service-panel').boundingClientRect()
query.selectViewport().scrollOffset()
query.exec((res) => {
const panelRect = res && res[0]
const scroll = res && res[1]
if (!panelRect || !scroll) return
const rpx = wx.getSystemInfoSync().windowWidth / 750
// 底部操作栏 152rpx + 留白,避免面板最后一行被压住
const reserved = 180 * rpx
const delta = panelRect.bottom + reserved - wx.getSystemInfoSync().windowHeight
if (delta < 1) return
wx.pageScrollTo({ scrollTop: scroll.scrollTop + delta, duration: 300 })
})
},
onServiceOptionTap(e) {
if (this.data.submitting) return
const index = Number(e.currentTarget.dataset.index)
if (index === this.data.serviceIndex) {
this.setData({ servicePanelOpen: false })
return
}
const service = this.data.services[index]
if (!service) return
this.applyService(service, index)
},
// 图标与首页宫格共用 styles/service-icons.wxss,按后端服务 id 取图;
// id 超出 1~8 时按名称兜底,避免新增服务落到没有图形的空类名上
getServiceIconClass(service) {
const id = Number(service && service.id)
if (Number.isInteger(id) && id >= 1 && id <= 8) return 'assist-icon-' + id
const title = (service && service.title) || ''
if (title.includes('夜间')) return 'assist-icon-7'
if (title.includes('陪诊')) return 'assist-icon-1'
return 'assist-icon-3'
},
loadProfiles() {
return API.healthProfile.getMyProfiles({ page: 1, pageSize: 50 })
.then((res) => {
if (res.code !== 0) throw new Error(res.msg || '就诊人加载失败')
const profiles = withDuplicateNameHints((res.data?.list || []).map((item) => ({
_id: item._id,
name: item.profile?.name || '',
mobile: item.profile?.mobile || '',
sex: item.profile?.sex || '',
birth: item.profile?.birth || ''
})))
// 默认选中第一个就诊人,信息随档案一键带入
const first = profiles[0]
if (first && !this.data.selectedProfileId) {
this.setData({
profiles,
selectedProfileId: first._id,
patientName: first.name,
patientPhone: first.mobile,
selectedPatient: first
})
} else {
this.setData({ profiles })
}
})
.catch((err) => {
console.log('获取就诊人列表失败', err)
wx.showToast({ title: '就诊人加载失败,请重试', icon: 'none' })
})
},
onSelectProfile(e) {
const id = e.currentTarget.dataset.id
const profile = this.data.profiles.find((item) => item._id === id)
if (!profile) return
this.setData({
selectedProfileId: id,
patientName: profile.name,
patientPhone: profile.mobile,
selectedPatient: profile
})
},
goToAddProfile() {
wx.navigateTo({ url: '/pages/health/profileedit' })
},
onProvinceChange(e) {
const index = Number(e.detail.value)
const province = this.data.provinces[index]
// 省份变了,已选医院可能不在新省份内,先清空再按新省份重建列表
this.selectedHospitalId = ''
this.setData({
provinceIndex: index,
province,
hospital: '',
hospitalCustom: false
}, () => this.refreshHospitalOptions(province))
},
// 按当前省份重建医院列表;已选医院按 _id 保留,避免网络刷新后选中值丢失
refreshHospitalOptions(province = this.data.province) {
const hospitalOptions = getApp().getHospitalsByProvince(province)
let hospital = ''
if (this.data.hospitalCustom) {
// 「其他医院」手填的名称不在库内,刷新列表时原样保留
hospital = this.data.hospital
} else {
const selected = hospitalOptions.find((item) => item._id === this.selectedHospitalId)
if (selected) {
hospital = selected.name
} else if (this.selectedHospitalId) {
// 已选医院在刷新后已不存在,退回未选状态
this.selectedHospitalId = ''
}
}
this.setData({ hospitalOptions, hospital })
},
// 医院选择组件回传:name 为最终值,manual 表示是否为「其他医院」手填,hospital 为库内记录
onHospitalChange(e) {
const { name, manual, hospital } = e.detail
this.selectedHospitalId = hospital?._id || ''
this.setData({ hospital: name, hospitalCustom: manual })
},
onDateChange(e) {
this.setData({ appointmentDate: e.detail.value })
},
onTimeChange(e) {
const index = Number(e.detail.value)
this.setData({ timeSlotIndex: index, appointmentTime: this.data.timeSlots[index] || '' })
},
onGenderChange(e) {
const index = Number(e.detail.value)
this.setData({ genderIndex: index, gender: this.data.genderOptions[index] })
},
onRemarkChange(e) {
this.setData({ remark: e.detail.value })
},
onPayChannelChange(e) {
const channel = e.currentTarget.dataset.channel
if (!['online_wechat', 'offline'].includes(channel)) return
if (this.data.submitting) return
this.setData({ payChannel: channel })
},
onShippingAddressChange(e) {
this.setData({ shippingAddress: e.detail.value })
},
validateOrder() {
const data = this.data
if (!data.selectedProfileId || !data.selectedPatient) return '请选择就诊人'
if (!data.hospital.trim()) {
return data.hospitalOptions.length ? '请选择就诊医院' : '请填写就诊医院名称'
}
if (!data.appointmentDate) return '请选择预约日期'
if (!data.appointmentTime) return '请选择预约时间'
// 收货地址选填:跑腿/买药未填地址时由客服线下确认
if (!/^1[3-9]\d{9}$/.test(data.selectedPatient.mobile.trim())) {
return '就诊人手机号有误,请到就诊人档案修改'
}
return ''
},
async submitOrder() {
if (this.data.submitting) return
// 先做一次表单校验,避免用户选完支付方式才发现信息没填全
const error = this.validateOrder()
if (error) {
wx.showToast({ title: error, icon: 'none' })
return
}
// 免责协议是下单前置条件:未勾选时直接拉起协议弹层,读完即可勾选
if (!this.data.agreementAgreed) {
this.setData({ agreementHint: true, showAgreementPopup: true })
this.loadDisclaimer()
return
}
this.setData({ showPayPopup: true, payChannel: 'offline' })
},
onClosePayPopup() {
if (this.data.submitting) return
this.setData({ showPayPopup: false })
},
/**
* 确认支付方式后真正提交订单
*/
async onConfirmPay() {
if (this.data.submitting) return
this.setData({ submitting: true, showPayPopup: false })
try {
// 登录守卫统一走 utils/auth.js:取消静默返回,失败由守卫内 toast
const loggedIn = await ensureLogin({
title: '登录后预约',
content: '登录成功后将继续预约'
})
if (!loggedIn) return
if (this.data.profiles.length === 0) await this.loadProfiles()
const error = this.validateOrder()
if (error) {
wx.showToast({ title: error, icon: 'none' })
return
}
const payChannel = this.data.payChannel
const orderData = this.buildOrderData()
// 网络重试沿用同一幂等键,服务端只创建一笔订单。
const res = await API.escort.createRecord(orderData)
if (res.code !== 0) throw new Error(res.msg || '下单失败')
const record = res.data?.record
this.resetForm()
if (payChannel === 'offline') {
wx.showToast({ title: '线下支付,请联系平台收款', icon: 'none' })
wx.navigateTo({ url: '/pages/escort/recordlist?tab=ongoing' })
return
}
// 选微信支付:下单成功后立即拉起收银台,支付结果以后端查单为准
if (record?._id) await this.startWechatPay(record._id)
else wx.navigateTo({ url: '/pages/escort/recordlist?tab=ongoing' })
} catch (err) {
console.log('下单失败', err)
// 服务端判定协议版本不一致:作废本地缓存、重新拉取并弹出协议要求重新确认
if ((err.message || '').includes('协议已更新')) {
getApp().invalidateDisclaimer()
this.setData({ disclaimer: null, agreementAgreed: false, showAgreementPopup: true })
this.loadDisclaimer()
}
wx.showToast({ title: err.message || '网络请求失败,请重试', icon: 'none' })
} finally {
this.setData({ submitting: false })
}
},
buildOrderData() {
const data = this.data
const sexMap = { 男: 'male', 女: 'female' }
return {
idempotencyKey: this.idempotencyKey,
healthProfileId: data.selectedProfileId,
escort: {
serviceId: data.service.id,
sexRequirement: sexMap[data.gender] || 'none'
},
hospital: {
province: data.province,
name: data.hospital.trim()
},
schedule: {
date: data.appointmentDate,
startTime: data.appointmentTime
},
shippingAddress: { address: data.shippingAddress.trim() },
notes: { patientNote: data.remark.trim() },
payment: { payChannel: data.payChannel },
// 协议确认快照:回传用户实际阅读的协议版本,服务端与当前版本比对,不一致则拒绝
agreement: { accepted: true, version: data.disclaimer?.version || '' }
}
},
/**
* 发起微信支付:payOrder → requestPayment → 查单确认
* 支付按钮防抖(this.paying),前端回调只作提示,最终状态以 getPayStatus 为准
*/
async startWechatPay(recordId) {
if (this.paying) return
this.paying = true
let paid = false
try {
const res = await API.escort.payOrder(recordId)
if (res.code !== 0 || !res.data?.payParams) {
wx.showToast({ title: res.msg || '支付发起失败,请稍后重试', icon: 'none' })
return
}
const payResult = await new Promise((resolve) => {
wx.requestPayment({
...res.data.payParams,
success: () => resolve({ ok: true }),
fail: (err) => resolve({ ok: false, err })
})
})
if (!payResult.ok) {
const errMsg = payResult.err?.errMsg || ''
if (/cancel/i.test(errMsg)) {
wx.showToast({ title: '已取消支付', icon: 'none' })
return
}
// 非取消失败可能是网络中断但支付已成功:先查单兜底
}
const statusRes = await API.escort.getPayStatus(recordId).catch(() => null)
paid = statusRes?.code === 0 && statusRes.data?.paymentStatus === 'paid'
wx.showToast({
title: paid ? '支付成功' : '支付结果确认中',
icon: paid ? 'success' : 'none'
})
} catch (err) {
console.log('发起支付失败', err)
wx.showToast({ title: '支付发起失败,请稍后重试', icon: 'none' })
} finally {
this.paying = false
setTimeout(() => {
wx.navigateTo({ url: `/pages/escort/recorddetail?id=${recordId}` })
}, paid ? 600 : 0)
}
},
resetForm() {
const provinces = this.data.provinces
this.selectedHospitalId = ''
this.setData({
selectedProfileId: '',
patientName: '',
patientPhone: '',
selectedPatient: null,
servicePanelOpen: false,
province: provinces[0] || '',
provinceIndex: 0,
hospital: '',
hospitalCustom: false,
appointmentDate: '',
appointmentTime: '',
timeSlotIndex: 0,
gender: '不限',
genderIndex: 0,
remark: '',
shippingAddress: '',
// 协议按单次服务确认,重置表单后需重新勾选
agreementAgreed: false,
agreementHint: false,
showAgreementPopup: false
}, () => this.refreshHospitalOptions(provinces[0] || ''))
// 重置后仍默认选中第一个就诊人,方便连续预约
const first = this.data.profiles[0]
if (first) {
this.setData({
selectedProfileId: first._id,
patientName: first.name,
patientPhone: first.mobile,
selectedPatient: first
})
}
this.idempotencyKey = this.createIdempotencyKey()
}
})