const { fetchOrdersManagement, fetchOrderManageDetail, advanceOrderManage, confirmRetailOrder, } = require('../../utils/request'); const { ensureMobileRole } = require('../../utils/roleGuard'); const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate'); const { resolveOrderStatusLabel, ORDER_COMPLETED_STATUS } = require('../../utils/constants'); const { chinaTodayYmd, shiftChinaYmd } = require('../../utils/chinaDate'); const { exportDeliveryNoteImage, buildDeliveryNotePayload, } = require('../../utils/deliveryNoteImage'); const ADMIN_ROLES = ['admin', 'operator']; function presetBounds(preset) { const today = chinaTodayYmd(); if (preset === 'today') return { from: today, to: today }; if (preset === 'month') { return { from: `${today.slice(0, 7)}-01`, to: today }; } const weekday = new Date(`${today}T12:00:00+08:00`).getUTCDay(); const diffToMonday = weekday === 0 ? 6 : weekday - 1; const weekStart = shiftChinaYmd(today, -diffToMonday); return { from: weekStart, to: shiftChinaYmd(weekStart, 6) }; } function formatRangeChip(from, to) { if (!from || !to) return '选择起止日期'; return `${from.slice(5)} ~ ${to.slice(5)}`; } Component({ options: { addGlobalClass: true }, properties: { embedded: { type: Boolean, value: false }, homeStatusGroup: { type: String, value: '' }, }, data: { loading: true, error: '', rows: [], /** 正在出图的订单号(在途锁;空 = 无) */ noteImageOrderCode: '', total: 0, totalAmountText: '0.00', statusGroup: '', dateField: 'delivery_date', dateRange: 'today', dateFrom: '', dateTo: '', customRangeLabel: '选择起止日期', search: '', stats: { pending: 0, processing: 0, completed: 0 }, statusGroups: [ { value: '', label: '全部', count: -1 }, { value: 'pending', label: '待处理', count: 0 }, { value: 'processing', label: '履约中', count: 0 }, { value: 'completed', label: '已完成', count: 0 }, ], dateRanges: [ { value: 'today', label: '今天' }, { value: 'week', label: '本周' }, { value: 'month', label: '本月' }, ], advancingOrderCode: '', }, observers: { homeStatusGroup(next) { if (!this.properties.embedded) return; const value = String(next || 'pending'); if (value === this.data.statusGroup) return; this.setData({ statusGroup: value }, () => { if (this._panelReady) this.loadRows(); }); }, }, lifetimes: { attached() { this.onPanelShow(); }, }, pageLifetimes: { show() { this.onPanelShow(); }, }, methods: { async onPanelShow() { if (!beginPanelShow(this)) return; try { const ok = await ensureMobileRole(ADMIN_ROLES); if (!ok) return; if (this.properties.embedded) { const fromHome = String(this.properties.homeStatusGroup || 'pending'); if (fromHome !== this.data.statusGroup) { this.setData({ statusGroup: fromHome }); } } await this.loadRows(); this._panelReady = true; } finally { endPanelShow(this); } }, onStatusGroup(e) { this.setData({ statusGroup: e.currentTarget.dataset.value || '' }, () => this.loadRows()); }, setDateField(e) { const field = e.currentTarget.dataset.field; if (!field || field === this.data.dateField) return; this.setData({ dateField: field }, () => this.loadRows()); }, onDateRange(e) { const value = e.currentTarget.dataset.value || 'today'; this.setData( { dateRange: value, dateFrom: '', dateTo: '', customRangeLabel: '选择起止日期', }, () => this.loadRows() ); }, onOpenCustomRange() { const seeded = this.data.dateRange === 'custom' && this.data.dateFrom && this.data.dateTo ? { from: this.data.dateFrom, to: this.data.dateTo } : presetBounds(this.data.dateRange === 'custom' ? 'week' : this.data.dateRange); this.setData( { dateRange: 'custom', dateFrom: seeded.from, dateTo: seeded.to, customRangeLabel: formatRangeChip(seeded.from, seeded.to), }, () => this.loadRows() ); }, onCustomFromChange(e) { const dateFrom = String(e.detail.value || '').slice(0, 10); let dateTo = this.data.dateTo || dateFrom; if (dateFrom && dateTo && dateFrom > dateTo) dateTo = dateFrom; this.setData( { dateRange: 'custom', dateFrom, dateTo, customRangeLabel: formatRangeChip(dateFrom, dateTo), }, () => this.loadRows() ); }, onCustomToChange(e) { const dateTo = String(e.detail.value || '').slice(0, 10); let dateFrom = this.data.dateFrom || dateTo; if (dateFrom && dateTo && dateFrom > dateTo) dateFrom = dateTo; this.setData( { dateRange: 'custom', dateFrom, dateTo, customRangeLabel: formatRangeChip(dateFrom, dateTo), }, () => this.loadRows() ); }, onSearchInput(e) { this.setData({ search: e.detail.value || '' }); }, onSearch() { this.loadRows(); }, async loadRows() { this.setData({ loading: true, error: '' }); try { const query = { page: 1, page_size: 50, status_group: this.data.statusGroup || undefined, search: this.data.search || undefined, date_field: this.data.dateField || 'delivery_date', }; if (this.data.dateRange === 'custom' && this.data.dateFrom && this.data.dateTo) { query.date_range = 'custom'; query.date_from = this.data.dateFrom; query.date_to = this.data.dateTo; } else { query.date_range = this.data.dateRange || 'today'; } const result = await fetchOrdersManagement(query); const stats = result.stats || { pending: 0, processing: 0, completed: 0 }; const rows = (result.data || []).map((row) => ({ ...row, isRetail: row.is_retail === true, isRetailAwaitingConfirm: row.is_retail === true && Number(row.order_status) < ORDER_COMPLETED_STATUS, statusLabel: resolveOrderStatusLabel(row.order_status, row.is_retail === true), amountText: Number(row.total_amount || 0).toFixed(2), })); this.setData({ rows, total: Number(result.total) || 0, totalAmountText: Number(result.total_amount || 0).toFixed(2), stats, statusGroups: [ { value: '', label: '全部', count: -1 }, { value: 'pending', label: '待处理', count: Number(stats.pending) || 0 }, { value: 'processing', label: '履约中', count: Number(stats.processing) || 0 }, { value: 'completed', label: '已完成', count: Number(stats.completed) || 0 }, ], }); this.triggerEvent('progresschange', { pendingCount: Number(stats.pending) || 0, processingCount: Number(stats.processing) || 0, completedCount: Number(stats.completed) || 0, }); this.triggerEvent('badgechange'); } catch (error) { this.setData({ rows: [], total: 0, totalAmountText: '0.00', error: error.message || '加载失败', }); wx.showToast({ title: error.message || '加载失败', icon: 'none' }); } finally { this.setData({ loading: false }); } }, openDetail(e) { const code = String(e.currentTarget.dataset.code || '').trim(); if (!code) { wx.showToast({ title: '订单号缺失', icon: 'none' }); return; } const q = String(this.data.search || '').trim(); const qPart = q ? `&q=${encodeURIComponent(q)}` : ''; wx.navigateTo({ url: `/pages/order-manage-detail/order-manage-detail?orderCode=${encodeURIComponent(code)}${qPart}`, fail: (err) => { wx.showToast({ title: (err && err.errMsg) || '打开详情失败,请重新上传小程序', icon: 'none', }); }, }); }, /** * 送货单**图片**(2026-10-15 开发者:入口放**订单列表卡片**,不进详情页): * 列表只有摘要 ⇒ 先取该单详情(含明细)→ canvas 出图 → 预览/存相册/分享给好友。 */ async onDeliveryNoteImage(e) { const code = String(e.currentTarget.dataset.code || '').trim(); if (!code || this.data.noteImageOrderCode) return; this.setData({ noteImageOrderCode: code }); try { const result = await fetchOrderManageDetail(code); const order = (result && (result.data || result)) || {}; const items = Array.isArray(order.items) ? order.items : []; const filePath = await exportDeliveryNoteImage( this, '#deliveryNoteCanvas', buildDeliveryNotePayload(order, items) ); this._deliveryNoteImagePath = filePath; this.setData({ noteImageOrderCode: '' }); wx.showActionSheet({ itemList: ['预览', '保存到相册', '分享给好友'], success: (res) => { if (res.tapIndex === 0) wx.previewImage({ urls: [filePath] }); else if (res.tapIndex === 1) this.saveDeliveryNoteImage(); else if (res.tapIndex === 2) this.shareDeliveryNoteImage(); }, }); } catch (error) { this.setData({ noteImageOrderCode: '' }); wx.showToast({ title: (error && error.message) || '生成送货单图片失败', icon: 'none' }); } }, /** 保存送货单图片到相册(无权限时引导去设置,不静默失败) */ saveDeliveryNoteImage() { const filePath = this._deliveryNoteImagePath; if (!filePath) return; wx.saveImageToPhotosAlbum({ filePath, success: () => wx.showToast({ title: '已保存到相册', icon: 'success' }), fail: (err) => { const message = String((err && err.errMsg) || ''); if (message.indexOf('auth') >= 0 || message.indexOf('deny') >= 0) { wx.showModal({ title: '需要相册权限', content: '请在设置里允许「保存到相册」后再试', confirmText: '去设置', success: (res) => { if (res.confirm) wx.openSetting(); }, }); return; } wx.showToast({ title: '保存失败', icon: 'none' }); }, }); }, /** 分享送货单图片给好友(不支持「图片分享菜单」时降级为预览 + 长按保存/转发) */ shareDeliveryNoteImage() { const path = this._deliveryNoteImagePath; if (!path) return; if (typeof wx.showShareImageMenu === 'function') { wx.showShareImageMenu({ path, fail: () => wx.showToast({ title: '长按图片可保存或转发', icon: 'none' }), }); return; } wx.previewImage({ urls: [path] }); wx.showToast({ title: '长按图片可保存或转发', icon: 'none' }); }, onAdvance(e) { const code = String(e.currentTarget.dataset.code || '').trim(); const status = Number(e.currentTarget.dataset.status); const label = e.currentTarget.dataset.label || '推进'; if (!code || !status || this.data.advancingOrderCode) return; wx.showModal({ title: label, content: `确认将订单 ${code} ${label}?`, success: async (res) => { if (!res.confirm) return; this.setData({ advancingOrderCode: code }); wx.showLoading({ title: '处理中', mask: true }); try { await advanceOrderManage(code, status); wx.hideLoading(); wx.showToast({ title: '已推进', icon: 'success' }); await this.loadRows(); } catch (error) { wx.hideLoading(); wx.showToast({ title: error.message || '推进失败', icon: 'none', duration: 2500 }); } finally { this.setData({ advancingOrderCode: '' }); } }, }); }, /** * 散客录单:一键「确认扣除并完结」(30 → 90,后端硬扣 `retail_out`)。 * 二次确认沿用本面板既有句式(`确认将订单 X Y?`),不新增文案。 */ onRetailConfirm(e) { const code = String(e.currentTarget.dataset.code || '').trim(); if (!code || this.data.advancingOrderCode) return; const label = '确认扣除并完结'; wx.showModal({ title: label, content: `确认将订单 ${code} ${label}?`, success: async (res) => { if (!res.confirm) return; this.setData({ advancingOrderCode: code }); wx.showLoading({ title: '处理中', mask: true }); try { await confirmRetailOrder(code); wx.hideLoading(); wx.showToast({ title: '已完成', icon: 'success' }); await this.loadRows(); } catch (error) { wx.hideLoading(); wx.showToast({ title: error.message || '确认失败', icon: 'none', duration: 2500 }); } finally { this.setData({ advancingOrderCode: '' }); } }, }); }, }, });