// pages/order/index.js const API = require('../../utils/api.js') const { calcAge } = require('../../utils/format.js') const role = require('../../utils/role.js') // 状态映射配置 const STATUS_MAP = { pending: { label: '待确认', text: '待确认', color: '#D98E04' }, confirmed: { label: '已确认', text: '已确认', color: '#3E6E9E' }, cancel_requested: { label: '待取消', text: '待取消', color: '#C0564A' }, in_progress: { label: '进行中', text: '进行中', color: '#C26A2E' }, completed: { label: '已完成', text: '已完成', color: '#8A7BB5' }, cancelled: { label: '已取消', text: '已取消', color: '#C0564A' } }; // 状态筛选选项 const STATUS_FILTERS = [ { label: '全部', value: '', count: 0 }, { label: '待确认', value: 'pending', count: 0 }, { label: '待取消', value: 'cancel_requested', count: 0 }, { label: '已确认', value: 'confirmed', count: 0 }, { label: '进行中', value: 'in_progress', count: 0 }, { label: '已完成', value: 'completed', count: 0 }, { label: '已取消', value: 'cancelled', count: 0 } ]; // 取消与 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' } // 页签 → 服务端筛选参数:筛选、分页、计数全部交给后端,避免按当前页过滤 function buildTabFilter(status) { switch (status) { case '': return { includeCancelled: 1 } case 'pending': return { status: 'pending', cancelStatus: 'none' } case 'cancel_requested': return { cancelStatus: 'requested' } case 'confirmed': return { status: 'confirmed', cancelStatus: 'none' } case 'in_progress': return { status: 'in_progress', cancelStatus: 'none' } case 'completed': return { status: 'completed', cancelStatus: 'none' } case 'cancelled': return { cancelStatus: 'cancelled' } default: return {} } } Page({ /** * 页面的初始数据 */ data: { // 角色:管理员可新增预约,陪诊员只看订单池/本人订单 role: '', isAdmin: false, // 实习陪诊师:能看到未分配订单,但不能接单 isIntern: false, // 订单分栏:pool=未分配订单,mine=我的订单 currentScope: 'pool', // 统计 stats: { total: 0, pending: 0, cancelRequested: 0, confirmed: 0, inProgress: 0, completed: 0, cancelled: 0 }, // 状态筛选 statusFilters: STATUS_FILTERS, // 状态下拉:picker 只认索引,文案与 statusFilters 保持同序 statusFilterLabels: STATUS_FILTERS.map(filter => filter.label), statusIndex: 0, currentStatus: 'pending', // 订单列表 orderList: [], // 分页 page: 1, pageSize: 10, hasMore: true, // 加载状态 isLoading: false, isLoadingMore: false, isRefreshing: false }, /** * 生命周期函数--监听页面加载 */ onLoad(options) { // 先解析角色:陪诊员走订单池接口,管理员走全量接口 role.ensureRoleSafe().then(({ role: r, attendant }) => { const isAdmin = r === 'admin' // 管理员与陪诊员统一从「未分配订单」进入,两个分栏都可见 const currentStatus = isAdmin ? this.data.currentStatus : '' const statusIndex = Math.max( 0, STATUS_FILTERS.findIndex(filter => filter.value === currentStatus) ) this.setData({ role: r, isAdmin, isIntern: Boolean(attendant && attendant.stage === 'intern'), currentScope: 'pool', currentStatus, statusIndex }) this.loadOrderList(); }) }, /** * 生命周期函数--监听页面显示 */ onShow() { if (this.data.orderList.length > 0) { this.refreshData(); } }, /** * 更新状态下拉的计数(口径由后端聚合,避免按当前页统计) */ updateFilterCounts(counts) { const c = counts || {}; const countMap = { '': c.all, pending: c.pending, cancel_requested: c.cancelRequested, confirmed: c.confirmed, in_progress: c.inProgress, completed: c.completed, cancelled: c.cancelled }; const statusFilters = this.data.statusFilters.map(filter => ({ ...filter, count: Number(countMap[filter.value]) || 0 })); // 下拉项直接带计数,替代原筛选条上的数字 const statusFilterLabels = statusFilters.map(filter => filter.count > 0 ? `${filter.label}(${filter.count})` : filter.label ); this.setData({ statusFilters, statusFilterLabels }); }, /** * 格式化日期 */ formatDate(dateStr) { if (!dateStr) return ''; const date = new Date(dateStr); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); return `${month}月${day}日`; }, /** * 处理订单数据 */ processOrders(orders) { return orders.map(order => { const age = calcAge(order.patient?.birth) const displayStatus = resolveDisplayStatus(order) // 接单/共享标记由服务端按身份计算;未分配 = attendant.id 为空 const isPoolOrder = Boolean(order.isPoolOrder) const assignedToMe = Boolean(order.attendantAssignedToMe) return { ...order, displayStatus, statusText: STATUS_MAP[displayStatus]?.text || displayStatus, patientFirstChar: (order.patient?.name || '?')[0], patientAgeText: age ? `${age}岁` : '', isPoolOrder, assignedToMe, sharedToMe: Boolean(order.attendantSharedToMe), // 取消中/已取消的池订单不给接单入口,避免接完即被取消确认 canAccept: !this.data.isAdmin && !this.data.isIntern && isPoolOrder && order.cancelStatus !== 'requested' && order.cancelStatus !== 'cancelled', // 状态流转只对自己已接的订单开放,管理员保持全量可操作 canOperate: this.data.isAdmin || assignedToMe, schedule: { ...order.schedule, dateText: this.formatDate(order.schedule?.date) } }; }); }, /** * 加载订单列表:筛选、分页与计数全部使用服务端口径 */ loadOrderList(isRefresh = false) { if (this.data.isLoading || this.data.isLoadingMore) return; const { currentStatus, currentScope, page, pageSize } = this.data; this.setData({ isLoading: !isRefresh, isLoadingMore: isRefresh && page > 1 }); const params = { page, pageSize, // 陪诊员:pool=未分配,mine=我的;管理员不传,保持全量口径 ...(currentScope ? { scope: currentScope } : {}), // 未分配订单不做状态筛选,所有可接订单都要能刷到 ...(currentScope === 'pool' ? {} : buildTabFilter(currentStatus)) }; role.queryOrders(params) .then(res => { if (res.code !== 0) { wx.showToast({ title: res.msg || '获取订单失败', icon: 'none' }); this.setData({ isLoading: false, isLoadingMore: false, isRefreshing: false }); return; } const data = res.data || {}; const list = data.records || []; const total = Number(data.total) || 0; const processedOrders = this.processOrders(list); const orderList = isRefresh && page > 1 ? [...this.data.orderList, ...processedOrders] : processedOrders; this.updateFilterCounts(data.counts); this.setData({ orderList, // 头部总数用后端「全部」口径;未分配池与当前筛选完全一致,直接用 total stats: { ...this.data.stats, total: currentScope === 'pool' ? total : Number((data.counts || {}).all) || total }, isLoading: false, isLoadingMore: false, isRefreshing: false, // total 由服务端返回,不能用当前页长度推断 hasMore: page * pageSize < total }); }) .catch(err => { console.error('获取订单列表失败', err); wx.showToast({ title: '网络错误,请重试', icon: 'none' }); this.setData({ isLoading: false, isLoadingMore: false, isRefreshing: false }); }); }, /** * 刷新数据 */ refreshData() { this.setData({ page: 1, hasMore: true }, () => { this.loadOrderList(); }); }, /** * 跳转新增预约(页面内选择健康档案) */ onAddOrder() { wx.navigateTo({ url: '/pages/order/orderEdit' }); }, /** * 空状态刷新 */ onReload() { this.setData({ page: 1, hasMore: true }, () => { this.loadOrderList(); }); }, /** * 状态筛选下拉切换 */ onStatusPick(e) { const index = Number(e.detail.value) || 0; const filter = this.data.statusFilters[index]; if (!filter || filter.value === this.data.currentStatus) return; this.setData({ currentStatus: filter.value, statusIndex: index, page: 1, hasMore: true, orderList: [] }, () => { this.loadOrderList(); }); }, /** * 未分配订单 / 我的订单切换:范围、分页、计数都由服务端按 scope 重算 */ onScopeChange(e) { const scope = e.currentTarget.dataset.scope; if (!scope || scope === this.data.currentScope) return; const statusFilters = this.data.statusFilters.map(filter => ({ ...filter, count: 0 })); this.setData({ currentScope: scope, // 我的订单默认展示全部状态;未分配订单不参与状态筛选 currentStatus: scope === 'mine' ? '' : this.data.currentStatus, statusIndex: scope === 'mine' ? 0 : this.data.statusIndex, statusFilters, // 清空上一分栏的状态计数,等本次请求返回后再写入 statusFilterLabels: statusFilters.map(filter => filter.label), stats: { ...this.data.stats, total: 0 }, page: 1, hasMore: true, orderList: [] }, () => { this.loadOrderList(); }); }, /** * 订单详情 */ onOrderDetail(e) { const id = e.currentTarget.dataset.id; wx.navigateTo({ url: `/pages/order/orderDetail?id=${id}` }); }, /** * 订单操作 */ onOrderAction(e) { const { id, action } = e.currentTarget.dataset; const order = this.data.orderList.find(item => item._id === id); if (!order) return; if (action === 'accept') { wx.showModal({ title: '确认接单', content: '接单后该订单将从其他陪诊师的未分配列表中移除,确认接单?', confirmColor: '#C26A2E', success: (res) => { if (res.confirm) this.acceptOrder(id); } }); return; } const isCancelRequest = action === 'cancel' && order.displayStatus === 'cancel_requested'; const actionMap = { confirm: { title: '确认订单', content: '确认接受此订单?', nextStatus: 'confirmed' }, cancel: isCancelRequest ? { title: '同意取消', content: '同意取消该订单?已收款订单将进入退款流程。', nextStatus: 'cancelled' } : { title: '取消订单', content: '确定要取消此订单?未确认且未收款的订单会被直接删除,已收款订单将进入退款。', nextStatus: 'cancelled' }, start: { title: '开始服务', content: '确认开始陪诊服务?', nextStatus: 'in_progress' }, complete: { title: '完成服务', content: '确认陪诊服务已完成?', nextStatus: 'completed' }, detail: { title: '', content: '', nextStatus: '' } }; const actionConfig = actionMap[action]; if (!actionConfig) return; if (action === 'detail') { wx.navigateTo({ url: `/pages/order/orderDetail?id=${id}` }); return; } wx.showModal({ title: actionConfig.title, content: actionConfig.content, confirmColor: '#C26A2E', success: (res) => { if (res.confirm) { this.updateOrderStatus(id, actionConfig.nextStatus); } } }); }, /** * 接单:服务端会再次校验身份与订单是否已被接走 */ acceptOrder(id) { wx.showLoading({ title: '接单中...' }); API.escort.acceptRecord(id) .then(res => { wx.hideLoading(); if (res.code !== 0) { wx.showToast({ title: res.msg || '接单失败', icon: 'none' }); this.refreshData(); return; } wx.showToast({ title: '接单成功', icon: 'success' }); this.refreshData(); }) .catch(err => { console.error('接单失败', err); wx.hideLoading(); wx.showToast({ title: '网络错误,请重试', icon: 'none' }); }); }, /** * 更新订单状态 */ updateOrderStatus(id, newStatus) { wx.showLoading({ title: '处理中...' }); API.escort.updateStatus(id, { status: newStatus }) .then(res => { wx.hideLoading(); if (res.code !== 0) { wx.showToast({ title: res.msg || '操作失败', icon: 'none' }); return; } wx.showToast({ title: '操作成功', icon: 'success' }); // 取消可能物理删除订单,状态与计数以服务端为准,不做本地推断 this.refreshData(); }) .catch(err => { console.error('更新订单状态失败', err); wx.showToast({ title: '网络错误,请重试', icon: 'none' }); wx.hideLoading(); }); }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh() { this.setData({ isRefreshing: true, page: 1, hasMore: true }, () => { this.loadOrderList(); }); }, /** * 页面上拉触底事件的处理函数 */ onReachBottom() { if (!this.data.hasMore || this.data.isLoadingMore) return; this.setData({ page: this.data.page + 1 }, () => { this.loadOrderList(true); }); }, /** * 用户点击右上角分享 */ onShareAppMessage() { return { title: '订单管理', path: '/pages/order/index' }; } });