Files

518 lines
17 KiB
JavaScript

// pages/order/orderDetail.js
const API = require('../../utils/api.js')
const role = require('../../utils/role.js')
const STATUS_MAP = {
pending: '待确认',
confirmed: '已确认',
cancel_requested: '待取消',
in_progress: '进行中',
completed: '已完成',
cancelled: '已取消'
}
const STATUS_DESC_MAP = {
pending: '订单已创建,等待确认',
confirmed: '订单已确认,等待服务',
cancel_requested: '用户已申请取消,待确认',
in_progress: '陪诊服务正在进行',
completed: '陪诊服务已完成',
cancelled: '订单已取消'
}
// 取消与 status 解耦:展示状态优先取 cancelStatus
function resolveDisplayStatus(order) {
const cancelStatus = order?.cancelStatus || 'none'
if (cancelStatus === 'cancelled') return 'cancelled'
if (cancelStatus === 'requested') return 'cancel_requested'
return order?.status || 'pending'
}
const PAYMENT_STATUS_MAP = {
unpaid: '未支付',
partial: '部分支付',
paid: '已支付',
refunding: '退款中',
refunded: '已退款'
}
// 支付方式:与 schema 的 payment.method 枚举一一对应
const PAYMENT_METHOD_MAP = {
online_wechat: '线上微信',
offline_cash: '线下现金',
offline_transfer: '线下转账'
}
// 支付渠道:用户下单时的选择,历史订单缺失按线下解释
const PAY_CHANNEL_MAP = {
online_wechat: '微信支付',
offline: '线下支付'
}
function formatDate(timestamp) {
if (!timestamp) return ''
const date = new Date(timestamp)
const y = date.getFullYear()
const m = String(date.getMonth() + 1).padStart(2, '0')
const d = String(date.getDate()).padStart(2, '0')
return y + '-' + m + '-' + d
}
function formatTime(timestamp) {
if (!timestamp) return ''
const date = new Date(timestamp)
const h = String(date.getHours()).padStart(2, '0')
const min = String(date.getMinutes()).padStart(2, '0')
return h + ':' + min
}
function formatDateTime(timestamp) {
if (!timestamp) return ''
return formatDate(timestamp) + ' ' + formatTime(timestamp)
}
Page({
data: {
orderId: '',
loaded: false,
// 角色:管理员可查看档案与退款操作,陪诊员按接单/共享关系展示操作
isAdmin: false,
isIntern: false,
canAcceptOrder: false,
// 订单数据
order: null,
// 格式化后的显示字段
statusText: '',
statusDesc: '',
attendantFirstChar: '',
scheduleDateText: '',
scheduleStartTimeText: '',
scheduleEndTimeText: '',
createtimeText: '',
updatetimeText: '',
paymentStatusText: '',
paymentMethodText: '',
payChannelText: '',
showQueryRefundBtn: false,
showManualRefundBtn: false,
queryingRefund: false,
completingRefund: false,
attendantSexText: '',
sexRequirementText: '',
// 接单 / 共享状态:未分配订单可从详情页接单,已接订单可共享给其他陪诊师
isPoolOrder: false,
assignedToMe: false,
sharedToMe: false,
desensitized: false,
showAcceptBtn: false,
showShareBtn: false,
// 共享弹窗
showSharePanel: false,
shareCandidates: [],
selectedShareIds: [],
sharing: false,
// 操作按钮配置
showConfirmBtn: false,
showCancelBtn: false,
cancelBtnText: '取消订单',
showStartBtn: false,
showCompleteBtn: false
},
onLoad(options) {
const id = options.id || ''
this.setData({ orderId: id })
// 先解析角色:详情页按角色决定是否读取档案、是否展示退款与接单/共享操作
role.ensureRoleSafe().then(({ role: r, attendant }) => {
this.setData({
isAdmin: r === 'admin',
isIntern: Boolean(attendant && attendant.stage === 'intern'),
canAcceptOrder: Boolean(attendant && attendant.canAcceptOrder)
})
if (id) this.loadOrderDetail(id)
})
},
onPullDownRefresh() {
if (this.data.orderId) {
this.loadOrderDetail(this.data.orderId).then(() => {
wx.stopPullDownRefresh()
})
} else {
wx.stopPullDownRefresh()
}
},
async loadOrderDetail(id) {
wx.showLoading({ title: '加载中...' })
try {
const res = await API.escort.getRecordById(id)
wx.hideLoading()
if (res.code !== 0) {
wx.showToast({ title: res.msg || '加载失败', icon: 'none' })
return
}
const order = res.data?.record || {}
this.applyOrderData(order)
} catch (err) {
wx.hideLoading()
console.error('加载订单详情失败', err)
wx.showToast({ title: '网络错误', icon: 'none' })
}
},
applyOrderData(order) {
const cancelStatus = order.cancelStatus || 'none'
const status = resolveDisplayStatus(order)
const attendant = order.attendant || {}
const schedule = order.schedule || {}
const payment = order.payment || {}
const escort = order.escort || {}
const meta = order.meta || {}
const isPoolOrder = !attendant.id
const assignedToMe = Boolean(order.attendantAssignedToMe)
const sharedToMe = Boolean(order.attendantSharedToMe)
// 管理员保持全量操作;陪诊师只能操作自己已接的订单
const canOperate = this.data.isAdmin || assignedToMe
this.setData({
loaded: true,
order: order,
// 有关联档案时交由 patient-info 按 ID 加载(不读缓存,以档案最新数据为准)
healthProfileId: order.healthProfileId || '',
statusText: STATUS_MAP[status] || status,
statusDesc: STATUS_DESC_MAP[status] || '',
statusClass: status,
attendantFirstChar: (attendant.name || '?')[0],
scheduleDateText: formatDate(schedule.date),
scheduleStartTimeText: schedule.startTime || '',
scheduleEndTimeText: schedule.endTime || '',
createtimeText: formatDateTime(meta.createtime),
updatetimeText: formatDateTime(meta.updatetime),
paymentStatusText: PAYMENT_STATUS_MAP[payment.status] || payment.status || '未支付',
paymentMethodText: PAYMENT_METHOD_MAP[payment.method] || '',
payChannelText: PAY_CHANNEL_MAP[payment.payChannel || 'offline'] || '',
// 线上退款:回调丢失时由管理端主动查退款补写终态;
// 人工核销:线下退款、或历史手工标记「线上微信」但无退款单的订单;
// 后端在存在处理中的线上退款时会拒绝,避免误把微信退款标成已完成。
// 退款属管理员能力,陪诊员不展示
showQueryRefundBtn: this.data.isAdmin
&& payment.status === 'refunding' && payment.method === 'online_wechat',
showManualRefundBtn: this.data.isAdmin && payment.status === 'refunding',
queryingRefund: false,
completingRefund: false,
attendantSexText: attendant.sex === 'male' ? '男' : attendant.sex === 'female' ? '女' : '',
sexRequirementText: escort.sexRequirement === 'male' ? '要求男陪诊' : escort.sexRequirement === 'female' ? '要求女陪诊' : '不限',
// 接单 / 共享:未分配订单正式陪诊师可接(取消中/已取消除外),已接订单仅接单本人可共享
isPoolOrder,
assignedToMe,
sharedToMe,
desensitized: Boolean(order.desensitized),
showAcceptBtn: !this.data.isAdmin && this.data.canAcceptOrder && isPoolOrder
&& order.cancelStatus !== 'requested' && order.cancelStatus !== 'cancelled',
showShareBtn: !this.data.isAdmin && assignedToMe,
// 操作按钮:支付/状态流转仍只对已接订单开放
showEditBtn: this.data.isAdmin
|| (assignedToMe && status !== 'pending' && status !== 'cancelled'),
showConfirmBtn: canOperate && cancelStatus === 'none' && status === 'pending',
showCancelBtn: canOperate && (cancelStatus === 'requested'
|| (cancelStatus === 'none' && (status === 'pending' || status === 'confirmed'))),
cancelBtnText: cancelStatus === 'requested' ? '同意取消' : '取消订单',
showStartBtn: canOperate && cancelStatus === 'none' && status === 'confirmed',
showCompleteBtn: canOperate && cancelStatus === 'none' && status === 'in_progress'
})
},
// 拨打电话
callPhone(e) {
// 兼容 patient-info 组件的 call 事件与 data-phone 用法
const phone = (e.detail && e.detail.mobile) || e.currentTarget.dataset.phone
if (!phone) {
wx.showToast({ title: '暂无电话', icon: 'none' })
return
}
wx.makePhoneCall({ phoneNumber: phone })
},
// 点击患者信息,进入健康档案详情(仅管理员有档案权限)
onProfileTap() {
if (!this.data.isAdmin) {
wx.showToast({ title: '仅管理员可查看档案', icon: 'none' })
return
}
if (!this.data.healthProfileId) {
wx.showToast({ title: '该订单未关联健康档案', icon: 'none' })
return
}
wx.navigateTo({
url: `/pages/healthprofile/profileInfo?id=${this.data.healthProfileId}`
})
},
// 接单:正式陪诊师把未分配订单接到自己名下
onAccept() {
wx.showModal({
title: '确认接单',
content: '接单后该订单将从其他陪诊师的未分配列表中移除,确认接单?',
confirmColor: '#C26A2E',
success: (res) => {
if (!res.confirm) return
wx.showLoading({ title: '接单中...' })
API.escort.acceptRecord(this.data.orderId)
.then(result => {
wx.hideLoading()
if (result.code !== 0) {
wx.showToast({ title: result.msg || '接单失败', icon: 'none' })
return
}
wx.showToast({ title: '接单成功', icon: 'success' })
this.loadOrderDetail(this.data.orderId)
})
.catch(err => {
wx.hideLoading()
console.error('接单失败', err)
wx.showToast({ title: '网络错误,请重试', icon: 'none' })
})
}
})
},
// 打开共享弹窗:候选为所有在职陪诊师(含实习),已共享的默认勾选
onShare() {
if (this.data.showSharePanel) return
wx.showLoading({ title: '加载中...' })
API.employee.getShareableAttendants()
.then(res => {
wx.hideLoading()
if (res.code !== 0) {
wx.showToast({ title: res.msg || '加载失败', icon: 'none' })
return
}
const sharedIds = this.data.order?.attendantSharedEmployeeIds || []
const candidates = (res.data?.attendants || []).map(item => ({
...item,
selected: sharedIds.indexOf(item.employeeId) > -1
}))
this.setData({
showSharePanel: true,
shareCandidates: candidates,
selectedShareIds: sharedIds.slice()
})
})
.catch(err => {
wx.hideLoading()
console.error('加载共享名单失败', err)
wx.showToast({ title: '网络错误,请重试', icon: 'none' })
})
},
onToggleShareTarget(e) {
const employeeId = e.currentTarget.dataset.id
const selected = this.data.selectedShareIds.slice()
const index = selected.indexOf(employeeId)
if (index > -1) selected.splice(index, 1)
else selected.push(employeeId)
this.setData({
selectedShareIds: selected,
shareCandidates: this.data.shareCandidates.map(item => ({
...item,
selected: selected.indexOf(item.employeeId) > -1
}))
})
},
onCloseShare() {
if (this.data.sharing) return
this.setData({ showSharePanel: false })
},
// 保存共享关系:新增调用 share,取消调用 unshare,最后刷新详情
onConfirmShare() {
if (this.data.sharing) return
const current = this.data.order?.attendantSharedEmployeeIds || []
const selected = this.data.selectedShareIds
const toAdd = selected.filter(id => current.indexOf(id) === -1)
const toRemove = current.filter(id => selected.indexOf(id) === -1)
if (toAdd.length === 0 && toRemove.length === 0) {
this.setData({ showSharePanel: false })
return
}
this.setData({ sharing: true })
wx.showLoading({ title: '保存中...' })
const tasks = []
if (toAdd.length) tasks.push(API.escort.shareRecord(this.data.orderId, { employeeIds: toAdd }))
if (toRemove.length) tasks.push(API.escort.unshareRecord(this.data.orderId, { employeeIds: toRemove }))
Promise.all(tasks)
.then(results => {
wx.hideLoading()
const failed = results.find(res => res.code !== 0)
if (failed) {
// 部分失败也要关面板并刷新:以服务端最新共享状态为准,避免勾选态错位
wx.showToast({ title: failed.msg || '部分保存失败,已刷新最新状态', icon: 'none' })
} else {
wx.showToast({ title: '共享已更新', icon: 'success' })
}
this.setData({ showSharePanel: false })
this.loadOrderDetail(this.data.orderId)
})
.catch(err => {
wx.hideLoading()
console.error('更新共享失败', err)
wx.showToast({ title: '网络错误,请重试', icon: 'none' })
})
.finally(() => {
this.setData({ sharing: false })
})
},
noop() {},
// 编辑订单
onEdit() {
wx.navigateTo({
url: `/pages/order/orderEdit?orderId=${this.data.orderId}`
})
},
// 确认订单
onConfirm() {
wx.showModal({
title: '确认订单',
content: '确认接受此订单?',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
this.updateStatus('confirmed')
}
}
})
},
// 取消订单
onCancel() {
wx.showModal({
title: '取消订单',
content: '确定要取消此订单?',
confirmColor: '#C0564A',
success: (res) => {
if (res.confirm) {
this.updateStatus('cancelled')
}
}
})
},
// 开始服务
onStart() {
wx.showModal({
title: '开始服务',
content: '确认开始陪诊服务?',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
this.updateStatus('in_progress')
}
}
})
},
// 完成服务
onComplete() {
wx.showModal({
title: '完成服务',
content: '确认陪诊服务已完成?',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
this.updateStatus('completed')
}
}
})
},
// 主动查询退款结果:退款回调丢失时补写终态
async onQueryRefund() {
if (this.data.queryingRefund) return
this.setData({ queryingRefund: true })
wx.showLoading({ title: '查询中...' })
try {
const res = await API.escort.queryRefund(this.data.orderId)
wx.hideLoading()
if (res.code !== 0) {
wx.showToast({ title: res.msg || '查询失败', icon: 'none' })
return
}
const status = res.data?.refund?.status
wx.showToast({
title: status === 'success' ? '退款已成功' : '查询完成',
icon: status === 'success' ? 'success' : 'none'
})
this.loadOrderDetail(this.data.orderId)
} catch (err) {
wx.hideLoading()
console.error('查询退款结果失败', err)
wx.showToast({ title: '网络错误', icon: 'none' })
} finally {
this.setData({ queryingRefund: false })
}
},
// 线下/人工退款:平台确认已退款后核销,避免订单永远停在「退款中」
onCompleteManualRefund() {
if (this.data.completingRefund) return
wx.showModal({
title: '确认退款完成',
content: '请确认已通过现金/转账等方式将款项退还给用户,操作后订单将显示「已退款」。',
success: (modal) => {
if (modal.confirm) this.doCompleteManualRefund()
}
})
},
async doCompleteManualRefund() {
this.setData({ completingRefund: true })
wx.showLoading({ title: '处理中...' })
try {
const res = await API.escort.completeManualRefund(this.data.orderId)
wx.hideLoading()
if (res.code !== 0) {
wx.showToast({ title: res.msg || '操作失败', icon: 'none' })
return
}
wx.showToast({ title: '已标记退款完成', icon: 'success' })
this.loadOrderDetail(this.data.orderId)
} catch (err) {
wx.hideLoading()
console.error('人工核销退款失败', err)
wx.showToast({ title: '网络错误', icon: 'none' })
} finally {
this.setData({ completingRefund: false })
}
},
async updateStatus(newStatus) {
wx.showLoading({ title: '处理中...' })
try {
const res = await API.escort.updateStatus(this.data.orderId, { status: newStatus })
wx.hideLoading()
if (res.code !== 0) {
wx.showToast({ title: res.msg || '操作失败', icon: 'none' })
return
}
wx.showToast({ title: '操作成功', icon: 'success' })
this.loadOrderDetail(this.data.orderId)
} catch (err) {
wx.hideLoading()
console.error('更新状态失败', err)
wx.showToast({ title: '网络错误', icon: 'none' })
}
}
})