liufumingren 686d4442f5 feat(packaging): 免验改「单击弹窗 + 右键直执行」,去掉真机难摁的长按
- 现场取证:longpress-免验 事件正常到达且能执行(两次成功把 0/2 推到 2/2),痛点是长按需摁住不动
- 单击商品行弹「免验确认」窗(关闭 / 免验);右键(含右键菜单键)直接免验不弹窗
- 抽出 verifyBlockReason(已核实 / 无数量)与 doVerifyItem(弹窗与右键共用),不再按 packStarted / groupVerifyCompleted 整单拦截
- 诊点:免验-open(附整单状态快照)/ 免验-execute(source=dialog|contextmenu)/ 免验-blocked(原因)
- 商品图 @click.stop,避免点图误弹免验窗;提示文案改「单击/右键商品行免验」;renderjs 统一为 #ifndef APP-PLUS 包裹
2026-09-27 03:15:06 +08:00

4689 lines
156 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<view class="page">
<view class="mode-topbar">
<view class="mode-title-wrap">
<image class="mode-logo" src="/static/images/1.png" mode="heightFix" />
<view class="mode-title">
<text v-if="workbenchInfo && workbenchInfo.name" class="mode-title-name">{{ workbenchInfo.name }}</text>
<text v-if="workbenchInfo && workbenchInfo.name" class="mode-title-divider"></text>
<text class="mode-title-label" @click="handleDiagTitleTap">打包模式</text>
</view>
</view>
<view class="topbar-actions">
<button
class="operator-btn"
:class="workbenchMembers.length > 0 ? 'operator-btn--bound' : ''"
@click="handleOperatorClick"
>
<view v-if="workbenchMembers.length > 0" class="operator-user-icon">
<view class="operator-user-icon-head"></view>
<view class="operator-user-icon-body"></view>
</view>
<text>{{ topbarOperatorText }}</text>
</button>
</view>
</view>
<view class="mode-main">
<view v-if="infoLoading" class="mode-card mode-card--center">
<text class="mode-card-desc">正在获取工作台信息...</text>
</view>
<view v-else-if="infoError" class="mode-card mode-card--center">
<text class="mode-card-desc">{{ infoError || '工作台信息加载失败' }}</text>
<button v-if="infoError" class="retry-btn" @click="loadWorkbenchInfo">重试</button>
</view>
<view v-else class="pack-layout">
<!-- 左面板 65% -->
<view class="pack-left">
<view v-if="packStarted && packWaitRemaining > 0" class="pack-countdown-bar">
<text class="pack-countdown-bar-text">大团购打包倒计时 {{ packWaitRemainingText }}</text>
</view>
<view class="pack-search">
<input
class="pack-search-input"
v-model="keyword"
:placeholder="searchPlaceholder"
:focus="searchFocus"
:adjust-position="false"
confirm-type="search"
@input="handleSearchInput"
@confirm="handlePackSearch"
@focus="handleSearchFocus"
@blur="handleSearchBlur"
/>
<view v-if="keyword" class="pack-search-clear" @click="clearKeyword">×</view>
</view>
<view v-if="hasPackRecord" class="pack-card pack-wave">
<view class="pack-wave-head" :class="{ 'pack-wave-head--blocked': orderBlocked }">
<text class="pack-card-title">{{ isSandan === 1 ? '运单' : '波次' }}</text>
<text class="pack-wave-no">{{ isSandan === 1 ? (currentWaybillCode || '暂无运单') : (currentWaveNo || '暂无波次') }}</text>
<text v-if="packStarted" class="pack-wave-status">打包中</text>
<text v-if="isGroupOrder" class="pack-wave-count">共{{ waveTotalOrders || 0 }}单</text>
</view>
<view class="pack-meta-line">
<view class="pack-meta-item">
<text class="pack-meta-label">货主</text>
<text class="pack-meta-value">{{ storeRemark || '—' }}</text>
</view>
<view class="pack-meta-item">
<text class="pack-meta-label">包材</text>
<text class="pack-meta-value">{{ packageMaterialName || '—' }}</text>
</view>
<view class="pack-meta-item">
<text class="pack-meta-label">拣货</text>
<text class="pack-meta-value">{{ pickerName || '—' }}</text>
</view>
<view class="pack-meta-item">
<text class="pack-meta-label">商品总数</text>
<text class="pack-meta-value">{{ productCount }}</text>
</view>
</view>
</view>
<view v-if="showPackDetail" class="pack-card pack-detail">
<view class="pack-detail-title">
<text class="pack-card-title">商品明细</text>
<text
v-if="isSandan !== null"
class="pack-order-type"
:class="isGroupOrder ? 'pack-order-type--group' : 'pack-order-type--single'"
>{{ isGroupOrder ? '团单' : '散单' }}</text>
<text v-if="isGroupOrder" class="pack-verify-hint">单击/右键商品行免验</text>
<button v-if="isGroupOrder && !packStarted" class="pack-verify-cancel-btn" @click="handleCancelGroupVerify">取消核实</button>
<text v-if="isGroupOrder" class="pack-detail-scan-stat">已扫 {{ scannedKindCount }}/{{ totalKindCount }} 种</text>
<text v-if="detailList.length > 0" class="pack-detail-total" :class="{ 'pack-detail-total--auto': !isGroupOrder }">共{{ detailList.length }}项</text>
</view>
<view class="pack-detail-body">
<view v-if="detailList.length === 0" class="pack-empty">暂无商品明细</view>
<scroll-view v-else scroll-y class="pack-detail-scroll">
<view
v-for="(item, index) in detailList"
:key="index"
class="pack-detail-row"
:class="{ 'pack-detail-row--scanned': isGroupOrder && isItemScanned(item) }"
@click="handleDetailRowClick(item)"
@contextmenu.prevent="handleVerifyItemDirect(item)"
>
<text class="pack-detail-col pack-detail-col--index">{{ index + 1 }}</text>
<view class="pack-detail-col pack-detail-col--image">
<view class="pack-item-img-wrap">
<image
v-if="item.image"
class="pack-item-img"
:src="item.image"
mode="aspectFit"
@click.stop="previewItemImage(item)"
/>
<text v-else class="pack-item-img-empty">-</text>
<text v-if="item.imageCount > 1" class="pack-item-img-badge">{{ item.imageCount }}</text>
</view>
</view>
<view class="pack-detail-col pack-detail-col--info">
<text class="pack-detail-info-name">{{ item.name }}</text>
<text class="pack-detail-info-barcode">【{{ item.barcode }}】</text>
<text v-if="item.packingRequirements" class="pack-detail-info-req">{{ item.packingRequirements }}</text>
</view>
<text
class="pack-detail-col pack-detail-col--qty"
:class="{ 'pack-detail-col--qty-done': isGroupOrder && isItemScanned(item) }"
>x{{ item.qty }}</text>
</view>
</scroll-view>
</view>
</view>
<view v-if="orderBlocked" class="pack-card pack-blocked">
<text class="pack-blocked-text">{{ orderBlockReason }}</text>
</view>
<view v-if="!hasPackRecord" class="pack-left-empty">
<text class="pack-left-empty-text">暂无打包记录</text>
<text class="pack-left-empty-sub">扫码运单号开始打包</text>
</view>
</view>
<!-- 右面板:固定 3.8rem(= 380px,≥1280 不再放大),剩余宽度全给左侧 -->
<view class="pack-right">
<view class="pack-card pack-today">
<text class="pack-card-title">今日打包</text>
<view class="pack-today-stats">
<view class="pack-stat">
<text class="pack-stat-label">团购波次</text>
<text class="pack-stat-num">{{ todayWaveCount }}</text>
</view>
<view class="pack-stat">
<text class="pack-stat-label">团购订单</text>
<text class="pack-stat-num">{{ todayGroupOrderCount }}</text>
</view>
<view class="pack-stat">
<text class="pack-stat-label">散单</text>
<text class="pack-stat-num">{{ todaySingleCount }}</text>
</view>
<view v-if="isPersonalWorkbench && todayRatio !== null" class="pack-stat">
<text class="pack-stat-label">团散</text>
<text class="pack-stat-num">{{ todayRatio }}</text>
</view>
<view v-if="isPersonalWorkbench" class="pack-stat">
<text class="pack-stat-label">均件数</text>
<text class="pack-stat-num">{{ todayAvgPiece ?? '—' }}</text>
</view>
</view>
</view>
<view class="pack-card pack-records">
<view class="pack-records-title">
<text class="pack-records-title-text">扫描记录</text>
</view>
<view class="pack-records-body">
<view v-if="scanRecords.length === 0" class="pack-empty">暂无扫描记录</view>
<scroll-view v-else scroll-y class="pack-records-scroll">
<view
v-for="(record, index) in scanRecords"
:key="index"
class="pack-record-item"
:class="{ 'pack-record-item--even': index % 2 === 0 }"
>
<text class="pack-record-text">{{ record.text }}</text>
<text class="pack-record-time">{{ record.time }}</text>
</view>
</scroll-view>
</view>
</view>
</view>
</view>
</view>
<!-- 真机扫码捕获:保持隐藏 input 聚焦,WebView 才会持续派发按键 -->
<input
v-if="enableHiddenInputCapture"
ref="scanHiddenInput"
class="scan-hidden-input"
v-model="scanHiddenValue"
:focus="scanInputFocus"
:adjust-position="false"
confirm-type="done"
@focus="handleHiddenScanFocus"
@input="handleHiddenScanInput"
@confirm="handleHiddenScanConfirm"
@blur="handleHiddenScanBlur"
/>
<!-- 绑定操作员弹窗 -->
<view v-if="operatorDialogVisible" class="op-mask" @click="closeOperatorDialog">
<view class="op-dialog" @click.stop>
<view class="op-dialog-head">
<text class="op-dialog-title">绑定操作员</text>
<text class="op-dialog-close" @click="closeOperatorDialog">×</text>
</view>
<view class="op-dialog-body">
<!-- 在线操作员列表(一个打包台支持多人,仅展示与下线) -->
<view class="op-member-head">
<text class="op-member-head-title">在线操作员</text>
<text class="op-member-head-count">{{ workbenchMembers.length }}人</text>
</view>
<view v-if="workbenchMembers.length > 0" class="op-member-list">
<view
v-for="(member, index) in workbenchMembers"
:key="member.id"
class="op-member-row"
:class="{ 'op-member-row--last': index === workbenchMembers.length - 1 }"
>
<view class="op-member-avatar">{{ (member.user_name || '?').slice(0, 1) }}</view>
<text class="op-member-name">{{ member.user_name || '—' }}</text>
<button
class="op-btn op-btn--danger op-btn--small"
:disabled="operatorRemoving"
@click="handleRemoveOperator(member)"
>下线</button>
</view>
</view>
<view v-else class="op-member-empty">暂无在线操作员</view>
</view>
</view>
</view>
<!-- 操作员下线确认弹窗 -->
<view v-if="removeConfirmVisible" class="op-mask">
<view class="op-dialog op-dialog--confirm" @click.stop>
<view class="op-dialog-head">
<text class="op-dialog-title">操作员下线</text>
<text class="op-dialog-close" @click="closeRemoveConfirm">×</text>
</view>
<view class="op-confirm-content">确认操作员「{{ removeTargetName }}」下线?</view>
<view class="op-confirm-footer op-confirm-footer--equal">
<button class="op-btn op-btn--cancel" @click="closeRemoveConfirm">取消</button>
<button
class="op-btn op-btn--danger"
:disabled="operatorRemoving"
@click="confirmRemoveOperator"
>{{ operatorRemoving ? '下线中...' : '下线' }}</button>
</view>
</view>
</view>
<!-- 商品图片预览弹窗 -->
<view v-if="imagePreviewVisible" class="img-preview-mask" @click="closeImagePreview">
<view class="img-preview-toolbar" @click.stop>
<text v-if="imagePreviewList.length > 1" class="img-preview-count">{{ imagePreviewIndex + 1 }} / {{ imagePreviewList.length }}</text>
<button class="img-preview-btn" @click="previewZoomOut">−</button>
<text class="img-preview-scale">{{ Math.round(previewScale * 100) }}%</text>
<button class="img-preview-btn" @click="previewZoomIn">+</button>
<button class="img-preview-btn" @click="previewResetZoom">重置</button>
<button class="img-preview-btn img-preview-btn--close" @click="closeImagePreview">关闭</button>
</view>
<view
class="img-preview-body"
@click.stop
@touchstart="previewTouchStart"
@touchmove="previewTouchMove"
@touchend="previewTouchEnd"
@touchcancel="previewTouchEnd"
>
<view
v-if="imagePreviewList.length > 1"
class="img-preview-arrow img-preview-arrow--prev"
@click.stop="previewPrev"
>‹</view>
<image
class="img-preview-img"
:src="previewImageUrl"
mode="aspectFit"
:style="previewImageStyle"
/>
<view
v-if="imagePreviewList.length > 1"
class="img-preview-arrow img-preview-arrow--next"
@click.stop="previewNext"
>›</view>
</view>
</view>
<!-- 取消核实确认弹窗 -->
<view v-if="cancelVerifyPopupOpen" class="op-mask">
<view class="op-dialog op-dialog--confirm cancel-verify-popup" @click.stop>
<view class="op-dialog-head">
<text class="op-dialog-title">取消核实</text>
<text class="op-dialog-close" @click="handleCloseCancelVerifyPopup">×</text>
</view>
<view class="op-confirm-content">确认取消本次核实?将放弃当前订单的商品核实,且不会开始打包。</view>
<view class="op-confirm-footer op-confirm-footer--equal">
<button class="op-btn op-btn--cancel" @click="handleCloseCancelVerifyPopup">关闭</button>
<button class="op-btn op-btn--primary" @click="confirmCancelVerify">确定</button>
</view>
</view>
</view>
<!-- 免验确认弹窗(单击商品行触发;右键直接免验不走这里) -->
<view v-if="verifyConfirmVisible" class="op-mask">
<view class="op-dialog op-dialog--confirm" @click.stop>
<view class="op-dialog-head">
<text class="op-dialog-title">免验确认</text>
<text class="op-dialog-close" @click="closeVerifyConfirm">×</text>
</view>
<view class="op-confirm-content">
将「{{ verifyConfirmItem?.name || verifyConfirmItem?.barcode || '-' }}」标记为已核实(免验)?
</view>
<view class="op-confirm-footer op-confirm-footer--equal">
<button class="op-btn op-btn--cancel" @click="closeVerifyConfirm">关闭</button>
<button class="op-btn op-btn--primary" @click="confirmVerifyItem">免验</button>
</view>
</view>
</view>
<!-- 扫码诊断面板(隐藏入口:3 秒内连点标题 5 次) -->
<scan-diag-panel :visible="diagPanelVisible" @close="diagPanelVisible = false" />
</view>
</template>
<script>
import {
getWorkbenchInfo,
getWorkbenchCount,
queryUserByToken,
bindWorkbenchMember,
removeWorkbenchMember,
queryPackOrder,
packOrder,
finishPack,
} from '@/api/index'
import ScanDiagPanel from '@/components/scan-diag-panel.vue'
import {
diagAnomaly,
diagBegin,
diagDrop,
diagFlush,
diagHeal,
diagHeartbeat,
diagKey,
diagNote,
diagPersistNow,
diagSetContext,
diagSetGates,
} from '@/core/scan-diag'
import { probeAppWindow } from '@/core/device-probe'
// 扫码枪识别参数(广播扫描:扫码枪为键盘 HID 设备,按键事件全局广播)
// 无回车结束符时:停止输入超过该毫秒数视为一次完整扫码,自动提交
const SCAN_IDLE_TIMEOUT = 300
// 自动提交所需的最短内容长度
const SCAN_MIN_LENGTH = 2
// 真机 plus 链路的最小码长:运单/商品码都是 8~13 位、工牌 64 位,
// 1~3 字符必然是误触/输入法/枪配置异常,不得当运单提交
const SCAN_CODE_MIN_LENGTH = 4
// "无结束符"异常上报的最小间隔(避免未配置后缀的枪刷爆服务端;本地日志仍逐次记录)
const NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS = 10 * 60 * 1000
// 手动输入识别:相邻按键间隔超过该毫秒数视为手动输入,不自动提交
const SCAN_BURST_MAX_GAP = 100
// Android KeyEvent 符号键映射(KEYCODE_* → 字符)。
// 重要:这些 keyCode 与 ASCII 字母/数字区间重叠,必须优先于 ASCII 分支判断,
// 否则 KEYCODE_EQUALS=70 会被 ASCII 的 [65..90] 分支误读为 'F'。
const ANDROID_PUNCT_MAP = {
55: ',', // KEYCODE_COMMA
56: '.', // KEYCODE_PERIOD
62: ' ', // KEYCODE_SPACE
68: '`', // KEYCODE_GRAVE
69: '-', // KEYCODE_MINUS
70: '=', // KEYCODE_EQUALS
71: '[', // KEYCODE_LEFT_BRACKET
72: ']', // KEYCODE_RIGHT_BRACKET
73: '\\', // KEYCODE_BACKSLASH
74: ';', // KEYCODE_SEMICOLON
75: "'", // KEYCODE_APOSTROPHE
76: '/', // KEYCODE_SLASH
77: '@', // KEYCODE_AT
81: '+', // KEYCODE_PLUS
}
// 已绑定操作员本地缓存 key(后端暂未提供查询成员接口时,刷新后据此恢复显示)
const MEMBER_STORAGE_KEY = 'workbenchMember'
// 扫描记录本地缓存 key(最多 50 条,出入栈:最新在前、超限丢最旧)
const SCAN_RECORDS_STORAGE_KEY = 'packScanRecords'
// 空闲超过该时长后重新锁定 plus.key 实际生效的事件类型(自愈「锁错就永久静默」)
const SCAN_IDLE_LOCK_RESET_MS = 1200
// 长时间(默认 10 分钟)无任何按键到达时强制重挂监听(防桥接回调静默失效)
const SCAN_LISTENER_REARM_IDLE_MS = 10 * 60 * 1000
// 无新打包任务自动退出:超过该时长(毫秒)自动登出所有成员并结束最后打包任务
const IDLE_AUTO_LOGOUT_MS = 30 * 60 * 1000
// 语音播报:HTTP 语音接口(参考 WMS_PDA voice.js,不依赖平板系统中文语音包)
const VOICE_API_URL = 'http://tbdata.gztbyc.com/voice/'
const VOICE_API_PATH = 'http://tbdata.gztbyc.com'
export default {
name: 'PackagingPage',
components: { ScanDiagPanel },
data() {
return {
workbenchInfo: null,
infoLoading: false,
infoError: '',
keyword: '',
currentWaveNo: '',
waveTotalOrders: '',
storeRemark: '',
packageMaterialName: '',
pickerName: '',
productCount: 0,
detailList: [],
todayWaveCount: 0,
todaySingleCount: 0,
todayGroupOrderCount: 0,
todayRatio: null,
todayAvgPiece: null,
scanRecords: [],
// ---- 广播扫描(扫码枪全局键盘监听,移植自 order/index.vue)----
searchFocus: false,
searchFocused: false,
pageActive: true,
scanTimer: null,
lastScanKeyTime: 0,
scanBurstConfirmed: false,
plusKeyListener: null,
plusKeyUpListener: null,
plusKeyBuffer: '',
plusKeyTimer: null,
plusKeyStartedAt: 0,
plusKeyLastAt: 0,
// 本次扫码已处理的按键数(诊断用:区分"只收到 1 个字符"与"整个码都收到了")
plusKeyBurstCount: 0,
// 最近一个原始 keyCode(诊断用)+ 无结束符异常上次上报时间
plusKeyLastCode: 0,
lastNoTerminatorAnomalyAt: 0,
// 字母大小写策略:'auto' 跟踪 Shift 键 / 'upper' 全大写 / 'lower' 全小写
// 注意:plus.key 只给 keyCode、无 Shift 状态;仅当扫码枪会额外上报
// Android Shift 键(KEYCODE_SHIFT_LEFT=59 / SHIFT_RIGHT=60)时 'auto' 才能还原大小写。
plusLetterCase: 'auto',
// Shift 状态滞后字符数(本机实测滞后 1 个字符):
// 只投递 keyup 的设备上,Shift 的 keydown 会比字符更早进入事件流,
// 导致判断时 Shift 状态“超前”一位,用滞后 1 位补偿。0 = 不补偿。
plusLetterCaseLag: 1,
globalKeyListener: null,
globalKeyTargets: [],
globalKeyBuffer: '',
globalKeyTimer: null,
globalKeyStartedAt: 0,
globalKeyLastAt: 0,
scanWatchdogTimer: null,
enableHiddenInputCapture: false,
scanInputFocus: false,
scanHiddenValue: '',
scanHiddenTimer: null,
scanHiddenRefocusTimer: null,
scanFocusResumeTimer: null,
scanKeyboardSuppressTimers: [],
scanHiddenFocused: false,
scanInputIdleTimer: null,
lastSubmittedScan: { code: '', at: 0 },
lastScannedCode: '',
// ---- 长时间运行可追踪/自愈 ----
lastScanKeyArrivedAt: 0, // 最近一次按键到达(任何门控之前)
scanRearmedForIdle: false, // 本次空闲是否已重挂过监听(收到按键后复位)
scanWatchdogStartedAt: 0, // 看门狗启动时刻(从未收到按键时的空闲基线)
diagPanelVisible: false,
diagTitleTapAt: 0,
diagTitleTapCount: 0,
// ---- 绑定操作员(工作台成员)----
operatorDialogVisible: false,
badgeHandling: false,
operatorBinding: false,
operatorRemoving: false,
workbenchMembers: [],
removeTargetMember: null,
operatorSearchTimer: null,
removeConfirmVisible: false,
orderQuerying: false,
// ---- 打包订单类型 / 无条码复核 ----
isSandan: null,
cancelVerifyPopupOpen: false,
// 免验确认弹窗(单击商品行触发;右键直接免验不走这里)
verifyConfirmVisible: false,
verifyConfirmItem: null,
idleLogoutTimer: null,
idleLoggingOut: false,
// ---- 打包流程(预检/上报/完成)----
currentOrderCode: '',
currentWaybillCode: '',
currentDeliveryOrderCode: '',
// 服务端缓存的订单上下文 key(queryOrder 返回,开始打包时回传 packOrder)
currentOrderKey: '',
currentOrderRaw: null,
// 本次查询与正在打包的订单是否一致(团单比波次、散单比运单号),一致时不显示"已打包"
sameOrderQuery: false,
precheckPassed: false,
packStarted: false,
packReporting: false,
packFinishing: false,
// ---- 商品图片预览 ----
imagePreviewVisible: false,
imagePreviewList: [],
imagePreviewIndex: 0,
previewScale: 1,
previewOffsetX: 0,
previewOffsetY: 0,
previewTouchMode: '',
previewTouchStartX: 0,
previewTouchStartY: 0,
previewTouchOriginX: 0,
previewTouchOriginY: 0,
previewPinchStartDistance: 0,
previewPinchStartScale: 1,
// ---- 语音播报(HTTP 接口优先 + Android 原生 TTS + Web Speech 降级)----
ttsEngine: null,
ttsReady: false,
ttsPendingText: '',
voiceAudioContext: null,
// 语音播报串行队列状态
voicePlaying: false,
voicePendingText: '',
voiceNextTimer: null,
// ---- 波次范围 / 大团购打包时长闸门 ----
currentWaveScope: null,
packWaitSeconds: 0,
packStartTime: 0,
packWaitRemaining: 0,
packCountdownTimer: null,
}
},
computed: {
workbenchTypeText() {
const type = this.workbenchInfo?.type
if (type === 'group') {
return '团体工作台'
}
if (type === 'personal') {
return '个人工作台'
}
return type ? String(type) : '未知类型'
},
workbenchStatusText() {
const status = Number(this.workbenchInfo?.status)
if (status === 1) {
return '启用'
}
if (status === 0) {
return '禁用'
}
return this.workbenchInfo?.status !== undefined && this.workbenchInfo?.status !== ''
? '未知'
: '—'
},
workbenchEnabled() {
return Number(this.workbenchInfo?.status) === 1
},
searchPlaceholder() {
return this.workbenchMembers.length > 0 ? '扫描/输入运单号' : '请先扫描工牌登录'
},
topbarOperatorText() {
const count = this.workbenchMembers.length
if (count === 0) {
return '未绑定'
}
const first = this.workbenchMembers[0].user_name || '操作员'
return count === 1 ? first : `${first}等${count}人在线`
},
removeTargetName() {
return this.removeTargetMember?.user_name || '该操作员'
},
previewImageUrl() {
return this.imagePreviewList[this.imagePreviewIndex] || ''
},
previewImageStyle() {
return {
transform: `translate(${this.previewOffsetX}px, ${this.previewOffsetY}px) scale(${this.previewScale})`,
}
},
isGroupOrder() {
return this.isSandan === 0
},
scannedKindCount() {
return this.detailList.filter((item) => this.isItemScanned(item)).length
},
totalKindCount() {
return this.detailList.length
},
groupVerifiedCount() {
return this.scannedKindCount
},
// 团单是否已完全核对(全部商品均已核实)
groupVerifyCompleted() {
return this.totalKindCount > 0 && this.groupVerifiedCount >= this.totalKindCount
},
// 行级拦截已取消(单击/右键都只看这一行);保留它仅供诊断日志显示当时状态
groupVerifyDone() {
return this.groupVerifyCompleted || this.packStarted
},
hasPackRecord() {
return !!(this.currentOrderRaw || this.currentOrderCode || this.detailList.length > 0)
},
// 是否个人工作台(type=personal 展示团散/均件数,group 展示团购订单数)
isPersonalWorkbench() {
return this.workbenchInfo?.type === 'personal'
},
// 订单是否被禁止打包(命中即隐藏商品明细)
orderBlocked() {
return this.checkOrderBlocked().blocked
},
// 商品明细显示条件:已绑定操作员 + 查询成功 + 订单未被禁止打包
showPackDetail() {
return !!(this.workbenchMembers.length > 0 && this.hasPackRecord && !this.orderBlocked)
},
orderBlockReason() {
return this.checkOrderBlocked().reason
},
// 大团购打包倒计时展示文案(mm:ss)
packWaitRemainingText() {
const total = this.packWaitRemaining
if (!total || total <= 0) {
return ''
}
const mins = Math.floor(total / 60)
const secs = total % 60
return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
},
},
watch: {
groupVerifiedCount(val) {
this.maybeAutoSubmitGroupPack()
},
},
onLoad() {
// #ifdef APP-PLUS
plus.android.importClass('android.util.Log').i('WMSPage', 'onLoad')
// #endif
diagBegin('packaging')
diagNote('lifecycle', { hook: 'onLoad' })
// 简单守卫:无 token 时回到登录页
if (!uni.getStorageSync('token')) {
uni.reLaunch({
url: '/pages/login/login',
})
return
}
this.restoreWorkbenchMembers()
this.restoreScanRecords()
this.lockLandscape()
this.loadTodayPackStat()
this.loadWorkbenchInfo()
},
onReady() {
this.lockLandscape()
setTimeout(() => {
this.lockLandscape()
}, 500)
},
onShow() {
// #ifdef APP-PLUS
plus.android.importClass('android.util.Log').i('WMSPage', 'onShow')
// #endif
diagNote('lifecycle', { hook: 'onShow' })
try {
this.pageActive = true
this.lockLandscape()
// 多时间点重试全屏重排:覆盖 WebView 尺寸错乱白屏场景
;[300, 800, 2000].forEach((delay) => {
setTimeout(() => {
if (this.pageActive) {
this.setFullscreenStyle()
}
}, delay)
})
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
this.startScanWatchdog()
this.suppressSoftKeyboardBurst()
this.scheduleIdleAutoLogout()
} catch (e) {
console.error('[packaging] onShow 异常:', e)
}
},
onHide() {
this.pageActive = false
this.stopScanWatchdog()
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.clearScanTimers()
this.clearIdleAutoLogoutTimer()
diagNote('lifecycle', { hook: 'onHide' })
diagSetGates({ pageActive: false })
diagPersistNow()
},
methods: {
// 强制锁定横屏 + 全屏重排:
// 实验:暂时禁用所有 native 调用,验证白屏是否与 lockOrientation/setStyle 相关。
lockLandscape() {
// #ifdef APP-PLUS
try {
const screen = plus && plus.screen
if (screen && typeof screen.lockOrientation === 'function') {
// screen.lockOrientation('landscape')
}
// this.setFullscreenStyle()
return true
} catch (e) {
console.error('[packaging] lockLandscape 异常:', e)
}
// #endif
return false
},
// 仅修正 WebView 全屏边距(不触发方向事件,可安全重复调用)
setFullscreenStyle() {
// 【临时实验】禁用 setStyle native 调用,对照验证白屏元凶
return
// #ifdef APP-PLUS
try {
if (typeof plus !== 'undefined' && plus.webview) {
const wv = plus.webview.currentWebview()
if (wv && typeof wv.setStyle === 'function') {
wv.setStyle({ top: '0px', bottom: '0px', left: '0px', right: '0px' })
console.log('[packaging] webview setStyle fullscreen done')
}
}
} catch (e) {
console.error('[packaging] setFullscreenStyle 异常:', e)
}
// #endif
},
handlePackSearch() {
const kw = this.dedupeRepeatedScan(String(this.keyword || '').trim())
if (!kw) {
return
}
console.log('[packaging][scan] handlePackSearch keyword =', kw)
// 工作台信息未就绪时不处理(加载中/失败态)
if (this.infoLoading || this.infoError) {
console.log('[packaging][scan] handlePackSearch skip: infoLoading =', this.infoLoading, 'infoError =', this.infoError)
return
}
// 连续重复扫码限制:与上一次扫描内容一致时不执行任何操作
if (this.lastScannedCode === kw) {
diagDrop('duplicate-consecutive', { code: kw })
console.log('[packaging][scan] handlePackSearch skip: duplicate consecutive code =', kw)
this.keyword = ''
this.scheduleScanInputFocus(150)
return
}
this.lastScannedCode = kw
// 工牌码(base64 JSON 含 uuid):识别为操作员工牌,走工牌登录/下线切换
const badge = this.parseBadgeCode(kw)
if (badge && badge.uuid) {
console.log('[packaging][scan] handlePackSearch -> badge uuid =', badge.uuid)
this.handleBadgeScan(kw)
return
}
// 无在线成员:非工牌码(非用户码)拦截,不走查询用户,提示先登录
if (!this.workbenchMembers.length) {
diagDrop('no-member-intercept', { code: kw })
console.log('[packaging][scan] handlePackSearch -> 无成员且非工牌码,拦截')
this.keyword = ''
this.lastScannedCode = ''
this.speak('需要先登录')
uni.showToast({ title: '需要先登录', icon: 'none', silentVoice: true })
this.scheduleScanInputFocus(150)
return
}
// 已绑定:团单待核实中,所有条码输入均作为商品条码校验(切换订单请先取消核实)
// 完全核对(自动开始打包)后,扫码恢复为运单查询,用于检查下一个订单
if (
this.isGroupOrder &&
this.precheckPassed &&
this.detailList.length > 0 &&
!this.groupVerifyCompleted
) {
this.matchProductBarcode(kw)
return
}
// 已绑定:扫码运单号查询订单
this.queryPackOrderByCode(kw)
},
queryPackOrderByCode(code) {
console.log('[packaging][query] queryPackOrderByCode code =', code)
// 未绑定操作员时禁止查询订单,避免绕过绑定流程直接查询
if (!this.workbenchMembers.length) {
this.speak('未绑定操作员')
uni.showToast({ title: '请先绑定操作员', icon: 'none', silentVoice: true })
return
}
const token = this.getWorkbenchToken()
if (!token) {
diagDrop('no-workbench-token', { code })
uni.showToast({ title: '工作台登录已失效', icon: 'none' })
return
}
if (this.orderQuerying) {
diagDrop('query-busy', { code })
return
}
this.orderQuerying = true
// 记录搜索的运单号到扫描记录
this.addScanRecord(code)
queryPackOrder(String(token), code)
.then((body) => {
this.applyQueryResult(body, code)
this.keyword = ''
})
.catch(() => {
// 查询失败允许重扫同一码
this.lastScannedCode = ''
diagNote('query-failed', { code })
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
})
.finally(() => {
this.orderQuerying = false
})
},
/**
* 商品明细统一映射(queryOrder.items 与 getWorkbenchInfo.current_orders.items 共用)
*/
mapOrderItems(items) {
return items.map((it) => {
const rawBarcodes = Array.isArray(it?.barcodes) ? it.barcodes : []
// barcodes 元素可能是对象 { id, barcode } 或字符串,兼容两种结构
const firstBarcode =
rawBarcodes.length > 0
? typeof rawBarcodes[0] === 'object' && rawBarcodes[0] !== null
? rawBarcodes[0].barcode || rawBarcodes[0].code || ''
: String(rawBarcodes[0])
: ''
const images = this.extractImages(it)
const barcodeList = rawBarcodes
.map((bc) =>
typeof bc === 'object' && bc !== null ? bc.barcode || bc.code || '' : String(bc)
)
.filter((bc) => bc)
return {
name: it?.item_name || it?.item_code || '',
barcode: firstBarcode || it?.item_code || '',
barcodes: barcodeList.length > 0 ? barcodeList : firstBarcode ? [firstBarcode] : [],
qty: it?.plan_qty ?? '',
scannedQty: 0,
image: images[0] || '',
imageCount: images.length,
images,
// 打包要求(packing_requirements)
packingRequirements: it?.packing_requirements ?? it?.packingRequirements ?? '',
// 是否需要验货(need_recheck=Y 需要核实;N 免验直接标绿;缺失按需要核实处理)
needRecheck: String(it?.need_recheck ?? it?.needRecheck ?? 'Y'),
}
})
},
/**
* 恢复进行中的打包任务(getWorkbenchInfo.current_wave / current_orders)
* - app 中途退出后重进:依据服务端当前任务恢复界面(打包中、商品明细全部标绿)
* - 本地已有订单上下文/打包状态时跳过,避免覆盖
*/
restoreCurrentPackTask(raw) {
if (this.packStarted || this.hasPackRecord) {
return
}
const wave =
raw?.current_wave && typeof raw.current_wave === 'object' ? raw.current_wave : null
const orders = Array.isArray(raw?.current_orders) ? raw.current_orders : []
const order =
orders.length > 0 && typeof orders[0] === 'object' ? orders[0] : null
if (!wave && !order) {
return
}
const isGroup = Number(order?.pack_mode) === 2
this.isSandan = isGroup ? 0 : 1
this.currentWaveScope =
order?.wave_scope !== undefined && order?.wave_scope !== null && order?.wave_scope !== ''
? Number(order?.wave_scope)
: null
this.currentWaveNo = wave?.wave_no || order?.wave_no || ''
this.currentWaybillCode = order?.waybill_code || order?.barcode || ''
this.currentDeliveryOrderCode = order?.delivery_order_code || ''
this.currentOrderKey =
order?.key || order?.order_key || order?.orderKey || wave?.key || wave?.order_key || ''
this.waveTotalOrders = wave?.order_count ?? order?.order_count ?? ''
this.productCount = Number(wave?.items_total) || Number(order?.items_total) || 0
this.currentOrderCode =
order?.waybill_code || this.currentWaveNo || order?.delivery_order_code || ''
const items = Array.isArray(order?.items) ? order.items : []
this.detailList = this.mapOrderItems(items)
// 任务已在进行中:核实已完成,全部标绿;恢复打包中状态
this.detailList.forEach((item) => {
item.scannedQty = Number(item.qty) || 0
})
this.precheckPassed = true
this.packStarted = true
// 留痕:这条一旦出现,说明是「服务端有进行中的任务」把 packStarted 置为 true 的
// (开发库没有进行中任务,所以只会在生产包上复现"长按免验被拦")
diagNote('pack-restore-task', {
packMode: order?.pack_mode ?? wave?.pack_mode ?? '',
wave: this.currentWaveNo,
items: this.detailList.length,
})
// 恢复进行中的大团购打包时长闸门倒计时(若服务端随任务下发倒计时字段)
const restoreWait = Number(
this.pickInfoField(order, {}, ['pack_wait_seconds', 'packWaitSeconds']) ||
this.pickInfoField(wave, {}, ['pack_wait_seconds', 'packWaitSeconds']) ||
0
)
const restoreStart = Number(
this.pickInfoField(order, {}, ['pack_start_time', 'packStartTime']) ||
this.pickInfoField(wave, {}, ['pack_start_time', 'packStartTime']) ||
0
)
if (restoreWait > 0 && restoreStart > 0) {
this.startPackCountdown(restoreWait, restoreStart)
}
console.log(
'[packaging][restore] 恢复进行中的打包任务',
this.currentWaveNo || this.currentWaybillCode || this.currentDeliveryOrderCode
)
},
applyQueryResult(body, code) {
const payload = body?.data || body?.result || body
const raw =
payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
const flag = body?.flag || raw?.flag || ''
if (this.checkWorkbenchAuthExpired(body)) {
this.speak('无记录')
return
}
if (flag === 'failure') {
// 后端失败文案可能含条码等长文本,过长时用简短提示代替
const failMsg = body?.message || body?.msg || '未找到对应订单'
// 大团购打包时长闸门:存在进行中的 wave_scope=1 打包任务且未到时,
// 扫描本波次以外的订单会返回「打包时长不足」;按该文案提示并允许继续扫描本波次订单
if (String(failMsg).indexOf('打包时长不足') >= 0) {
this.lastScannedCode = ''
this.speak('打包时长不足')
uni.showToast({ title: '打包时长不足', icon: 'none', silentVoice: true })
return
}
this.speak('无记录')
uni.showToast({
title: String(failMsg).length > 24 ? '未找到对应订单' : failMsg,
icon: 'none',
silentVoice: true,
})
return
}
const order = raw?.order && typeof raw.order === 'object' ? raw.order : {}
const express = raw?.express && typeof raw.express === 'object' ? raw.express : {}
const batch = raw?.batch && typeof raw.batch === 'object' ? raw.batch : {}
const items = Array.isArray(raw?.items) ? raw.items : []
// 快照:查询前正在打包的订单标识(重复查询同一单时不显示"已打包"、无需重新复核)
const prevIsGroup = this.isGroupOrder
const prevWaybillCode = this.currentWaybillCode
const prevWaveNo = this.currentWaveNo
const prevPackStarted = this.packStarted
// 订单类型:isSandan=1 散单、0 团单(团单需扫码商品条码核验)
const rawSandan = this.pickInfoField(raw, {}, ['isSandan', 'is_sandan'])
const newIsGroup = rawSandan !== '' && Number(rawSandan) === 0
this.isSandan = rawSandan === '' ? null : Number(rawSandan)
// 波次范围:0=未分配 1=大团购 2=散单 3=小团购 4=单品单件
// (服务端在 queryOrder 下发 order.wave_scope,开始打包时回传 packOrder)
let waveScope = null
for (const src of [order, raw, batch]) {
const v = this.pickInfoField(src, {}, ['wave_scope', 'waveScope'])
if (v !== '' && v !== undefined && v !== null) {
waveScope = Number(v)
break
}
}
this.currentWaveScope = waveScope
// 与正在打包的订单对比:团单比波次号、散单比运单号;一致即重复查询同一单
const newWaveNo =
this.pickInfoField(batch, {}, ['wave_no', 'waveNo']) ||
this.pickInfoField(order, {}, ['wave_no', 'waveNo'])
const newWaybill =
this.pickInfoField(raw, {}, ['waybill_code', 'waybillCode']) ||
this.pickInfoField(raw, {}, ['barcode']) ||
''
this.sameOrderQuery =
prevIsGroup === newIsGroup &&
(newIsGroup
? Boolean(prevWaveNo) &&
Boolean(newWaveNo) &&
String(prevWaveNo) === String(newWaveNo)
: Boolean(prevWaybillCode) &&
Boolean(newWaybill) &&
String(prevWaybillCode) === String(newWaybill))
// 记录当前订单上下文(用于预检/上报)
this.currentOrderRaw = raw
// 订单上下文 key(服务端缓存):开始打包时回传 workbench.packOrder
this.currentOrderKey =
this.pickInfoField(raw, {}, ['key', 'order_key', 'orderKey']) ||
this.pickInfoField(order, {}, ['key', 'order_key', 'orderKey']) ||
''
this.currentOrderCode = code || ''
// 重复查询正在打包的同一单:保持打包中状态,不要求重新复核/重复上报
this.packStarted = this.sameOrderQuery && prevPackStarted
this.precheckPassed = this.packStarted
// 运单号(散单展示用:waybill_code 优先,兜底 barcode)
this.currentWaybillCode =
this.pickInfoField(raw, {}, ['waybill_code', 'waybillCode']) ||
this.pickInfoField(raw, {}, ['barcode']) ||
''
// 发货单号(上报用:order.delivery_order_code)
this.currentDeliveryOrderCode = this.pickInfoField(order, {}, [
'delivery_order_code',
'deliveryOrderCode',
])
// 波次号:团购优先 batch.wave_no,散单用 order.wave_no
this.currentWaveNo =
this.pickInfoField(batch, {}, ['wave_no', 'waveNo']) ||
this.pickInfoField(order, {}, ['wave_no', 'waveNo'])
// 波次总订单数(团购 batch.total_orders);散单固定 1 单
this.waveTotalOrders = this.pickInfoField(batch, {}, ['total_orders', 'totalOrders'])
if (!this.isGroupOrder && !this.waveTotalOrders) {
this.waveTotalOrders = 1
}
// 货主备注
this.storeRemark = this.pickInfoField(raw, {}, ['store_remark', 'storeRemark'])
// 包材名称
this.packageMaterialName = this.pickInfoField(express, {}, [
'package_material_name',
'packageMaterialName',
])
// 拣货人
this.pickerName = this.pickInfoField(order, {}, ['picker_name', 'pickerName'])
// 商品数量:优先 order.items_total,兜底 items plan_qty 求和
let productCount = Number(order?.items_total)
if (!productCount) {
productCount = items.reduce((sum, it) => sum + (Number(it?.plan_qty) || 0), 0)
}
this.productCount = productCount
// 商品明细
this.detailList = this.mapOrderItems(items)
// 诊断上下文:“应该接收到的条码”= 本单商品条码;“当前任务”= 波次/运单
diagSetContext({
'期望任务': this.isGroupOrder
? `团单 ${this.currentWaveNo || ''}`
: `散单 ${this.currentWaybillCode || ''}`,
'期望条码': this.expectedBarcodeText(10),
'商品明细数': this.detailList.length,
})
// 免验商品(need_recheck=N)直接标记为已核实(标绿),无需扫码/长按
this.detailList.forEach((item) => {
if (item.needRecheck === 'N') {
item.scannedQty = Number(item.qty) || 0
}
})
// 重复查询正在打包的同一单:全部商品恢复为已核实,不要求重新复核
if (this.sameOrderQuery && this.packStarted) {
this.detailList.forEach((item) => {
item.scannedQty = Number(item.qty) || 0
})
}
// ---- 预检与分流 ----
const precheck = this.packPrecheck()
if (!precheck.ok) {
this.speak(precheck.speakText)
uni.showToast({ title: precheck.reason, icon: 'none', silentVoice: true })
return
}
this.precheckPassed = true
// 重复查询正在打包的同一单:保持打包中,不重复上报、不重新复核
if (this.sameOrderQuery && this.packStarted) {
this.speak('正在打包')
uni.showToast({ title: '正在打包', icon: 'none', silentVoice: true })
return
}
if (this.isGroupOrder) {
// 团单:无商品明细 或 全部商品免验/已完全核对 = 无需核实,直接提交开始打包
if (this.detailList.length === 0 || this.groupVerifyCompleted) {
this.handleSubmitGroupPack()
}
return
}
// 散单:预检通过立即自动上报开始打包
this.startPack()
},
matchProductBarcode(barcode) {
const target = this.detailList.find(
(item) =>
(Array.isArray(item.barcodes) && item.barcodes.includes(barcode)) ||
item.barcode === barcode
)
if (target) {
if (this.isItemScanned(target)) {
diagDrop('barcode-already-verified', { code: barcode })
this.keyword = ''
this.speak('数据一致')
uni.showToast({ title: '数据一致', icon: 'none', silentVoice: true })
return
}
// 按商品种类:扫 1 次即标记为已核实,无需扫满数量
diagNote('barcode-matched', { code: barcode, name: target.name || '' })
target.scannedQty = Number(target.qty) || 0
this.addScanRecord(barcode)
this.keyword = ''
this.speak('数据一致')
uni.showToast({ title: '数据一致', icon: 'none', silentVoice: true })
// 全部核实后自动开始打包
this.maybeAutoSubmitGroupPack()
} else {
// 收到码但业务不匹配:把"收到的码"与"期望的码"同时记下来
diagDrop('barcode-not-matched', { code: barcode, 期望条码: this.expectedBarcodeText(10) })
this.speak('无记录')
uni.showToast({ title: '条码与待核实商品不匹配', icon: 'none', silentVoice: true })
}
},
/** 期望条码文本(诊断日志用):本单商品条码,最多 limit 个 */
expectedBarcodeText(limit = 8) {
return this.detailList
.map((item) => item.barcode)
.filter((code) => !!code)
.slice(0, limit)
.join(',')
},
isItemScanned(item) {
const qty = Number(item?.qty) || 0
const scanned = Number(item?.scannedQty) || 0
return qty > 0 && scanned >= qty
},
// 单击商品行:弹免验确认窗(关闭 / 免验)
// 2026-09-26:长按在真机上"非常难摁"(要挟住不动),改成单击弹窗 + 右键直执行
handleDetailRowClick(item) {
if (!item || !this.isGroupOrder) {
return
}
const reason = this.verifyBlockReason(item)
if (reason) {
diagNote('免验-blocked', { reason, source: 'click', item: item?.name || item?.barcode || '' })
uni.showToast({ title: reason, icon: 'none' })
return
}
diagNote('免验-open', {
source: 'click',
item: item?.name || item?.barcode || '',
// 保留整单状态快照,便于事后判读(不再用它拦截)
done: this.groupVerifyDone,
completed: this.groupVerifyCompleted,
packStarted: this.packStarted,
verified: `${this.scannedKindCount}/${this.totalKindCount}`,
})
this.verifyConfirmItem = item
this.verifyConfirmVisible = true
},
closeVerifyConfirm() {
this.verifyConfirmVisible = false
this.verifyConfirmItem = null
},
confirmVerifyItem() {
const item = this.verifyConfirmItem
this.verifyConfirmVisible = false
this.verifyConfirmItem = null
this.doVerifyItem(item, 'dialog')
},
// 右键(含电脑右键菜单键):不弹窗,直接免验
handleVerifyItemDirect(item) {
if (!item || !this.isGroupOrder) {
return
}
const reason = this.verifyBlockReason(item)
if (reason) {
diagNote('免验-blocked', { reason, source: 'contextmenu', item: item?.name || item?.barcode || '' })
uni.showToast({ title: reason, icon: 'none' })
return
}
this.doVerifyItem(item, 'contextmenu')
},
// 不能免验的原因文案('' = 可以免验):单击弹窗与右键直执行共用
verifyBlockReason(item) {
if (this.isItemScanned(item)) {
return '该商品已核实'
}
if ((Number(item?.qty) || 0) <= 0) {
return '该商品无数量,无法免验'
}
return ''
},
// 免验执行(单击确认窗与右键共用)
doVerifyItem(item, source) {
if (!item) {
return
}
const total = Number(item.qty) || 0
if (total <= 0) {
return
}
diagNote('免验-execute', {
source,
item: item.name || item.barcode || '',
qty: total,
})
// 直接标记为已核实(标绿),无需扫码
item.scannedQty = total
this.addScanRecord(`免验:${item.name || item.barcode || ''}`)
this.speak('免验通过')
uni.showToast({ title: `「${item.name || ''}」免验通过`, icon: 'none', silentVoice: true })
// 全部核实后自动开始打包
this.maybeAutoSubmitGroupPack()
},
/**
* 团单全部商品核实完成后自动开始打包(扫码核实/免验后调用,watcher 兼作兑底)
*/
maybeAutoSubmitGroupPack() {
if (!this.isGroupOrder || !this.precheckPassed || this.packStarted || this.packReporting) {
return
}
if (this.groupVerifyCompleted) {
this.handleSubmitGroupPack()
}
},
handleCancelGroupVerify() {
this.cancelVerifyPopupOpen = true
},
handleCloseCancelVerifyPopup() {
this.cancelVerifyPopupOpen = false
},
confirmCancelVerify() {
// 清空核实与订单,回到可查询态
this.clearPackState()
this.cancelVerifyPopupOpen = false
this.speak('已取消核实')
uni.showToast({ title: '已取消核实', icon: 'none', silentVoice: true })
},
/**
* 打包预检(本地判断,基于 queryOrder 返回字段)
* - 散单:拦截(intercept_flag=1) / 未复核(recheck_status≠fin) / 已打包(pack_flag=1)
* - 团单:未复核 / 已打包(pack_status≠none),不判拦截
*/
packPrecheck() {
const { blocked, reason, speakText } = this.checkOrderBlocked()
return blocked ? { ok: false, reason, speakText } : { ok: true }
},
/**
* 订单禁止打包判断(命中即隐藏商品明细)
* - 未复核:recheck_status 非空且不是 fin/finished/1
* - 已打包:散单 pack_flag===1;团单 pack_status 非空且非 none
* - 拦截:仅散单 intercept_flag===1
* speakText 为语音文案,reason 为界面提示文案(两者可能不同)
*/
checkOrderBlocked() {
const raw = this.currentOrderRaw
if (!raw) {
return { blocked: false, reason: '', speakText: '' }
}
const order =
raw.order && typeof raw.order === 'object' ? raw.order : {}
const batch =
raw.batch && typeof raw.batch === 'object' ? raw.batch : {}
if (this.isGroupOrder) {
// 团单:未复核 → 已打包
const recheckStatus = order?.recheck_status ?? order?.recheckStatus ?? ''
if (recheckStatus && !['fin', 'finished', '1'].includes(String(recheckStatus))) {
return { blocked: true, reason: '订单未复核,禁止打包', speakText: '订单未复核,禁止打包' }
}
const packStatus =
order?.pack_status ?? order?.packStatus ?? batch?.pack_status ?? batch?.packStatus ?? ''
if (packStatus && String(packStatus) !== 'none' && !this.sameOrderQuery) {
return { blocked: true, reason: '订单已打包,禁止打包', speakText: '已打包' }
}
return { blocked: false, reason: '', speakText: '' }
}
// 散单:拦截 → 未复核 → 已打包
if (Number(order?.intercept_flag) === 1) {
return { blocked: true, reason: '订单已拦截,禁止打包', speakText: '订单已拦截,禁止打包' }
}
const recheckStatus = order?.recheck_status ?? order?.recheckStatus ?? ''
if (recheckStatus && !['fin', 'finished', '1'].includes(String(recheckStatus))) {
return { blocked: true, reason: '订单未复核,禁止打包', speakText: '订单未复核,禁止打包' }
}
if (Number(order?.pack_flag) === 1 && !this.sameOrderQuery) {
return { blocked: true, reason: '订单已打包,禁止打包', speakText: '已打包' }
}
return { blocked: false, reason: '', speakText: '' }
},
/**
* 上报开始打包(复用 workbench.packOrder,status=1)
*/
reportPackOrder(status = 1) {
const token = this.getWorkbenchToken()
if (!token) {
return Promise.reject(new Error('工作台登录已失效'))
}
if (!this.currentOrderKey) {
return Promise.reject(new Error('订单上下文缺失,请重新扫码查询'))
}
const payload = {
token: String(token),
// 订单上下文 key(queryOrder 返回,服务端按 key 解析缓存中的订单信息)
key: this.currentOrderKey,
status,
// 打包时间:Unix 秒(后端按秒转 datetime,传毫秒会导致 start_time 年份溢出报错)
pack_time: Math.floor(Date.now() / 1000),
// 波次范围(queryOrder 下发,服务端复查:上报值非法/缺省时兜底订单行值)
wave_scope:
this.currentWaveScope !== null && this.currentWaveScope !== undefined
? Number(this.currentWaveScope)
: undefined,
// 上报当前在线操作员(workbench.packOrder 的 users 参数,支持多人)
users:
this.workbenchMembers.length > 0
? this.workbenchMembers.map((member) => ({
id: member.id ?? null,
real_name: member.user_name || '',
wms_account_id: member.user_id ?? null,
}))
: undefined,
}
return packOrder(payload).then((body) => {
const res = body?.data || body?.result || body
const raw = res && typeof res === 'object' && !Array.isArray(res) ? res : null
const flag = body?.flag || raw?.flag || ''
if (this.checkWorkbenchAuthExpired(body)) {
throw new Error('工作台已解绑')
}
if (flag === 'failure') {
throw new Error(body?.message || body?.msg || '打包上报失败')
}
return body
})
},
startPack() {
if (this.packReporting || this.packStarted) {
return
}
this.packReporting = true
this.reportPackOrder(1)
.then((body) => {
this.packStarted = true
// 大团购:按 packOrder 响应下发的倒计时字段启动「打包时长闸门」倒计时
this.applyPackCountdown(body)
// 新打包提交成功后刷新今日打包统计(服务端为准)
this.loadTodayPackStat()
// 有新打包任务:重置 30 分钟无新任务自动登出计时
this.scheduleIdleAutoLogout()
this.speak('开始打包')
uni.showToast({ title: '开始打包', icon: 'none', silentVoice: true })
})
.catch((err) => {
uni.showToast({ title: err?.message || '打包上报失败', icon: 'none' })
})
.finally(() => {
this.packReporting = false
})
},
/**
* 读取 packOrder 响应下发的倒计时字段(仅大团购 wave_scope=1 非 0):
* - pack_wait_seconds:需等待秒数
* - pack_start_time:开始打包毫秒时间戳
* 其余波次两字段均为 0,不启动倒计时。
*/
applyPackCountdown(body) {
const payload = body?.data || body?.result || body
const raw =
payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
const waitSeconds = Number(
this.pickInfoField(raw, body, ['pack_wait_seconds', 'packWaitSeconds']) || 0
)
const startTime = Number(
this.pickInfoField(raw, body, ['pack_start_time', 'packStartTime']) || 0
)
if (waitSeconds > 0 && startTime > 0) {
this.startPackCountdown(waitSeconds, startTime)
} else {
this.stopPackCountdown()
}
},
/** 启动打包时长闸门倒计时(1 秒刷新一次,到 0 自动停止) */
startPackCountdown(waitSeconds, startTime) {
this.stopPackCountdown()
this.packWaitSeconds = Number(waitSeconds) || 0
this.packStartTime = Number(startTime) || 0
this.updatePackWaitRemaining()
if (this.packWaitRemaining <= 0) {
return
}
this.packCountdownTimer = setInterval(() => {
this.updatePackWaitRemaining()
if (this.packWaitRemaining <= 0) {
this.stopPackCountdown()
}
}, 1000)
},
/** 根据 pack_start_time 与 pack_wait_seconds 重算剩余秒数 */
updatePackWaitRemaining() {
const elapsed =
this.packStartTime > 0 ? Math.floor((Date.now() - this.packStartTime) / 1000) : 0
this.packWaitRemaining = Math.max(0, (this.packWaitSeconds || 0) - elapsed)
},
/** 停止并复位打包时长闸门倒计时 */
stopPackCountdown() {
if (this.packCountdownTimer) {
clearInterval(this.packCountdownTimer)
this.packCountdownTimer = null
}
this.packWaitSeconds = 0
this.packStartTime = 0
this.packWaitRemaining = 0
},
handleSubmitGroupPack() {
this.startPack()
},
async ensurePackFinishedBeforeLeave() {
const token = this.getWorkbenchToken()
if (!token || !this.packStarted || this.packFinishing) {
return
}
this.packFinishing = true
try {
const body = await finishPack(String(token))
if (this.checkWorkbenchAuthExpired(body)) {
return
}
this.packStarted = false
} catch (e) {
// 失败不阻断
} finally {
this.packFinishing = false
}
},
clearPackState() {
this.detailList = []
this.lastScannedCode = ''
this.currentWaveNo = ''
this.waveTotalOrders = ''
this.storeRemark = ''
this.packageMaterialName = ''
this.pickerName = ''
this.productCount = 0
this.isSandan = null
this.currentOrderCode = ''
this.currentWaybillCode = ''
this.currentDeliveryOrderCode = ''
this.currentOrderKey = ''
this.currentOrderRaw = null
this.sameOrderQuery = false
this.precheckPassed = false
this.packStarted = false
// 波次范围与打包时长闸门倒计时复位
this.currentWaveScope = null
this.stopPackCountdown()
// 诊断上下文同步复位(避免日志里残留上一单的期望条码)
diagSetContext({ '期望任务': '', '期望条码': '', '商品明细数': 0 })
},
speak(text) {
const str = this.normalizeSpeakText(text)
if (!str) {
return
}
// 正在播报:不打断当前音频,只保留最新一条待播(快速连扫时合并为最后一条)
if (this.voicePlaying) {
this.voicePendingText = str
console.log('[语音播报] 正在播报,暂存待播文本:', str)
return
}
this.voicePlaying = true
this.playSpeakText(str)
},
normalizeSpeakText(text) {
let str = String(text || '').trim()
if (!str) {
return ''
}
// 长文本缩减:语音播报过长很啰嗦,超过 12 字符截断并以“等”收尾
if (str.length > 12) {
str = str.slice(0, 12) + '等'
}
return str
},
/**
* 播报单条文本(串行队列执行单元)
* APP-PLUS:优先 HTTP 语音接口,失败兜底本地 TTS / Web Speech
* 非 APP:直接走 TTS / Web Speech,按语速估时后取下一条
*/
playSpeakText(str) {
console.log('[语音播报] 开始播报:', str)
// #ifdef APP-PLUS
this.speakViaHttp(str).then((ok) => {
console.log('[语音播报] HTTP 语音接口结果:', ok)
if (!ok) {
this.speakViaTtsOrWebSpeech(str)
// 原生 TTS / Web Speech 无结束回调,按语速估时后再取下一条
this.voiceNextTimer = setTimeout(() => this.scheduleNextSpeak(), this.estimateSpeakMs(str))
return
}
this.scheduleNextSpeak()
})
return
// #endif
// #ifndef APP-PLUS
this.speakViaTtsOrWebSpeech(str)
this.voiceNextTimer = setTimeout(() => this.scheduleNextSpeak(), this.estimateSpeakMs(str))
// #endif
},
scheduleNextSpeak() {
const next = this.voicePendingText
this.voicePendingText = ''
if (next) {
console.log('[语音播报] 播放待播文本:', next)
this.playSpeakText(next)
} else {
this.voicePlaying = false
}
},
estimateSpeakMs(str) {
// 按中文语速粗略估算播放时长:每字约 300ms,下限 500ms,上限 4000ms
return Math.min(4000, Math.max(500, String(str || '').length * 300))
},
speakViaHttp(msg) {
return new Promise((resolve) => {
let settled = false
let timeoutTimer = null
const finish = (ok) => {
if (!settled) {
settled = true
if (timeoutTimer) {
clearTimeout(timeoutTimer)
timeoutTimer = null
}
resolve(ok)
}
}
// 末字补句号(两个以加长停顿):让 TTS 在最后一个字后生成停顿,避免部分 Android 设备
// 播放 HTTP 音频时解码丢尾帧,导致最后一个字(如“包”)被截断
const ttsText = String(msg) + '。。'
uni.request({
url: VOICE_API_URL + encodeURIComponent(ttsText),
method: 'GET',
timeout: 3000,
header: { 'content-type': 'text/xml; charset=utf-8' },
success: (res) => {
try {
const audioPath = res?.data?.audio
if (!audioPath) {
console.warn('[语音播报] HTTP 接口未返回 audio 字段:', JSON.stringify(res?.data || res))
finish(false)
return
}
const src = VOICE_API_PATH + audioPath
console.log('[语音播报] HTTP 音频地址:', src)
// 先整体下载到本地临时文件再播放:避免内网/流式播放缓冲不足时尾帧被截断
this.downloadVoiceAudio(src)
.then((localSrc) => {
this.playVoiceAudio(localSrc, finish)
// 超时兜底:5 秒后仍未播放完成也视为完成,避免一直等待
timeoutTimer = setTimeout(() => finish(true), 5000)
})
.catch(() => {
// 下载失败回退为直接播远程地址
this.playVoiceAudio(src, finish)
timeoutTimer = setTimeout(() => finish(true), 5000)
})
} catch (e) {
console.error('[语音播报] HTTP 接口解析异常:', e)
finish(false)
}
},
fail: (err) => {
console.warn('[语音播报] HTTP 语音接口请求失败:', err)
finish(false)
},
})
})
},
downloadVoiceAudio(src) {
return new Promise((resolve, reject) => {
uni.downloadFile({
url: src,
timeout: 5000,
success: (res) => {
if (res.statusCode === 200 && res.tempFilePath) {
console.log('[语音播报] 音频已下载到本地:', res.tempFilePath)
resolve(res.tempFilePath)
} else {
reject(new Error('下载状态异常: ' + res.statusCode))
}
},
fail: (err) => {
reject(err)
},
})
})
},
playVoiceAudio(src, onEnd) {
try {
if (this.voiceAudioContext) {
try {
this.voiceAudioContext.destroy()
} catch (e) {
// 忽略旧实例销毁异常
}
this.voiceAudioContext = null
}
const audio = uni.createInnerAudioContext()
this.voiceAudioContext = audio
let playStarted = false
let finished = false
const doPlay = () => {
if (playStarted || finished) {
return
}
playStarted = true
try {
audio.play()
console.log('[语音播报] 音频已开始播放')
} catch (e) {
console.error('[语音播报] 音频播放异常:', e)
onEnd(false)
}
}
audio.onError((e) => {
finished = true
console.warn('[语音播报] 音频播放错误:', e)
onEnd(false)
})
audio.onEnded(() => {
finished = true
console.log('[语音播报] 播放结束,总时长:', audio.duration, 's,实际播到:', audio.currentTime, 's')
onEnd(true)
})
// 等缓冲就绪再播放:部分 Android 设备设置 src 后立即 play 会在缓冲不足时
// 截断尾帧(末字丢失);onCanplay 后再播更稳,500ms 兜底防止事件不触发
audio.onCanplay(() => {
console.log('[语音播报] 音频可播放,总时长:', audio.duration, 's,来源:', String(src).startsWith('http') ? '远程' : '本地')
doPlay()
})
audio.src = src
setTimeout(doPlay, 500)
} catch (e) {
console.error('[语音播报] 创建音频上下文异常:', e)
onEnd(false)
}
},
destroyVoiceAudio() {
if (this.voiceNextTimer) {
clearTimeout(this.voiceNextTimer)
this.voiceNextTimer = null
}
this.voicePlaying = false
this.voicePendingText = ''
if (this.voiceAudioContext) {
try {
this.voiceAudioContext.stop()
this.voiceAudioContext.destroy()
} catch (e) {
// 忽略
}
this.voiceAudioContext = null
}
},
speakViaTtsOrWebSpeech(text) {
const str = String(text)
// #ifdef APP-PLUS
console.log(
'[语音播报] APP-PLUS 分支:',
JSON.stringify({ hasEngine: !!this.ttsEngine, ttsReady: this.ttsReady, text: str })
)
if (this.ttsEngine) {
if (this.ttsReady) {
const ok = this.speakNativeTts(str)
console.log('[语音播报] speakNativeTts 返回:', ok)
} else {
// 引擎未就绪:只保留最后一条待播文本
this.ttsPendingText = str
console.log('[语音播报] 引擎未就绪,暂存待播文本:', str)
}
return
}
console.log('[语音播报] 无 TTS 引擎,回退 Web Speech')
// #endif
this.speakViaWebSpeech(str)
},
speakViaWebSpeech(text) {
console.log(
'[语音播报] Web Speech 分支:',
JSON.stringify({
hasWindow: typeof window !== 'undefined',
hasSpeechSynthesis: typeof window !== 'undefined' && !!window.speechSynthesis,
text: String(text),
})
)
try {
if (typeof window !== 'undefined' && window.speechSynthesis) {
window.speechSynthesis.cancel()
const utterance = new SpeechSynthesisUtterance(String(text))
utterance.lang = 'zh-CN'
window.speechSynthesis.speak(utterance)
console.log('[语音播报] Web Speech 已调用 speak')
} else {
console.warn('[语音播报] window.speechSynthesis 不可用,无法用 Web Speech 播报')
}
} catch (e) {
console.error('[语音播报] Web Speech 异常:', e)
}
},
initNativeTts() {
// #ifdef APP-PLUS
console.log(
'[语音播报] initNativeTts 开始:',
JSON.stringify({ hasPlus: typeof plus !== 'undefined', hasAndroid: !!(plus && plus.android) })
)
if (typeof plus === 'undefined' || !plus.android) {
console.warn('[语音播报] plus.android 不可用,无法初始化原生 TTS')
return
}
try {
const vm = this
const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech')
const Locale = plus.android.importClass('java.util.Locale')
console.log('[语音播报] 已导入 TextToSpeech / Locale 类')
const OnInitListener = plus.android.implements(
'android.speech.tts.TextToSpeech$OnInitListener',
{
onInit: function (status) {
console.log('[语音播报] onInit 回调 status:', status)
// status === 0 表示 TTS 初始化成功(TextToSpeech.SUCCESS)
if (status !== 0 || !vm.ttsEngine) {
vm.ttsReady = false
console.warn('[语音播报] TTS 初始化失败或引擎为空:', { status, hasEngine: !!vm.ttsEngine })
return
}
// 设置中文语音;返回值 >= 0 表示该语言可用
const langResult = vm.ttsEngine.setLanguage(Locale.CHINA)
console.log('[语音播报] setLanguage(Locale.CHINA) 返回:', langResult)
if (langResult >= 0) {
vm.ttsReady = true
console.log('[语音播报] TTS 就绪,ttsReady=true')
if (vm.ttsPendingText) {
const pending = vm.ttsPendingText
vm.ttsPendingText = ''
console.log('[语音播报] 补播暂存文本:', pending)
vm.speakNativeTts(pending)
}
} else {
vm.ttsReady = false
console.warn('[语音播报] 中文语音包不可用(-1缺数据/-2不支持),需安装中文 TTS 语音数据')
}
},
}
)
this.ttsEngine = new TextToSpeech(plus.android.runtimeMainActivity(), OnInitListener)
console.log('[语音播报] TextToSpeech 实例已创建:', !!this.ttsEngine)
} catch (e) {
this.ttsEngine = null
this.ttsReady = false
console.error('[语音播报] initNativeTts 异常:', e)
}
// #endif
},
speakNativeTts(text) {
// #ifdef APP-PLUS
console.log(
'[语音播报] speakNativeTts 调用:',
JSON.stringify({ hasEngine: !!this.ttsEngine, ttsReady: this.ttsReady, text: String(text) })
)
if (!this.ttsEngine || !this.ttsReady) {
console.warn('[语音播报] speakNativeTts 跳过:引擎未就绪')
return false
}
try {
const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech')
// QUEUE_FLUSH = 0:清空队列后立即播报当前文本
this.ttsEngine.speak(String(text), TextToSpeech.QUEUE_FLUSH, null)
console.log('[语音播报] 原生 TTS speak 已调用')
return true
} catch (e) {
console.error('[语音播报] 原生 TTS speak 异常:', e)
return false
}
// #endif
return false
},
shutdownNativeTts() {
// #ifdef APP-PLUS
console.log('[语音播报] shutdownNativeTts:', { hasEngine: !!this.ttsEngine })
if (this.ttsEngine) {
try {
this.ttsEngine.stop()
this.ttsEngine.shutdown()
console.log('[语音播报] 原生 TTS 已 stop + shutdown')
} catch (e) {
console.error('[语音播报] 释放 TTS 异常:', e)
}
this.ttsEngine = null
this.ttsReady = false
this.ttsPendingText = ''
}
// #endif
},
previewItemImage(item) {
const urls =
Array.isArray(item?.images) && item.images.length > 0
? item.images
: item?.image
? [item.image]
: []
if (!urls.length) {
return
}
this.imagePreviewList = urls
this.imagePreviewIndex = 0
this.previewScale = 1
this.previewOffsetX = 0
this.previewOffsetY = 0
this.previewTouchMode = ''
this.imagePreviewVisible = true
},
closeImagePreview() {
this.imagePreviewVisible = false
this.previewTouchMode = ''
this.previewScale = 1
this.previewOffsetX = 0
this.previewOffsetY = 0
},
previewZoomIn() {
this.previewScale = Math.min(Number((this.previewScale + 0.2).toFixed(2)), 6)
},
previewZoomOut() {
this.previewScale = Math.max(Number((this.previewScale - 0.2).toFixed(2)), 0.2)
},
previewResetZoom() {
this.previewScale = 1
this.previewOffsetX = 0
this.previewOffsetY = 0
},
previewPrev() {
if (this.imagePreviewList.length <= 1) {
return
}
this.imagePreviewIndex =
(this.imagePreviewIndex - 1 + this.imagePreviewList.length) % this.imagePreviewList.length
this.previewResetZoom()
},
previewNext() {
if (this.imagePreviewList.length <= 1) {
return
}
this.imagePreviewIndex = (this.imagePreviewIndex + 1) % this.imagePreviewList.length
this.previewResetZoom()
},
previewTouchStart(event) {
const touches = this.getPreviewTouches(event)
if (touches.length >= 2) {
// 双指捏合缩放
this.previewTouchMode = 'pinch'
this.previewPinchStartDistance = this.getTouchDistance(touches)
this.previewPinchStartScale = this.previewScale
} else if (touches.length === 1) {
// 单指拖拽平移
this.previewTouchMode = 'drag'
this.previewTouchStartX = this.getTouchX(touches[0])
this.previewTouchStartY = this.getTouchY(touches[0])
this.previewTouchOriginX = this.previewOffsetX
this.previewTouchOriginY = this.previewOffsetY
}
},
previewTouchMove(event) {
const touches = this.getPreviewTouches(event)
if (this.previewTouchMode === 'pinch' && touches.length >= 2) {
const distance = this.getTouchDistance(touches)
if (this.previewPinchStartDistance > 0) {
const next = this.previewPinchStartScale * (distance / this.previewPinchStartDistance)
this.previewScale = Math.min(Math.max(Number(next.toFixed(2)), 0.2), 6)
}
} else if (this.previewTouchMode === 'drag' && touches.length >= 1) {
const x = this.getTouchX(touches[0])
const y = this.getTouchY(touches[0])
this.previewOffsetX = this.previewTouchOriginX + (x - this.previewTouchStartX)
this.previewOffsetY = this.previewTouchOriginY + (y - this.previewTouchStartY)
}
},
previewTouchEnd() {
this.previewTouchMode = ''
},
getPreviewTouches(event) {
const touches = event?.touches
if (touches && typeof touches.length === 'number' && touches.length > 0) {
return touches
}
const changed = event?.changedTouches
if (changed && typeof changed.length === 'number' && changed.length > 0) {
return changed
}
return []
},
getTouchX(touch) {
return touch?.clientX ?? touch?.pageX ?? touch?.x ?? 0
},
getTouchY(touch) {
return touch?.clientY ?? touch?.pageY ?? touch?.y ?? 0
},
getTouchDistance(touches) {
const a = touches[0]
const b = touches[1]
if (!a || !b) {
return 0
}
const dx = this.getTouchX(a) - this.getTouchX(b)
const dy = this.getTouchY(a) - this.getTouchY(b)
return Math.sqrt(dx * dx + dy * dy)
},
handleSearchFocus() {
this.searchFocused = true
// 真机:输入框被聚焦时立即压制软键盘(扫码走 plus.key,不依赖软键盘)
if (this.isAppPlus()) {
this.setWindowSoftInputHidden()
}
},
handleSearchBlur() {
this.searchFocused = false
this.searchFocus = false
if (this.enableHiddenInputCapture) {
this.scheduleScanInputFocus(150)
}
},
handleSearchInput() {
// 真机(APP-PLUS)扫码枪走 IME 注入文本、无 DOM keydown 字符,
// 停止输入 1000ms 视为一次完整扫码自动查询(@confirm 仍可即时查询)。
// plus.key 可用时由原生链路捕获,此处不兜底,避免同一码双触发。
if (!this.isPageActive() || !this.isAppPlus()) {
return
}
if (this.hasPlusKeyboardSupport()) {
return
}
const code = String(this.keyword || '').trim()
this.clearScanInputIdleTimer()
if (!code) {
return
}
this.scanInputIdleTimer = setTimeout(() => {
if (!this.isPageActive()) {
return
}
if (!String(this.keyword || '').trim()) {
return
}
this.handlePackSearch()
}, 1000)
},
clearKeyword() {
this.keyword = ''
this.scanBurstConfirmed = false
// 真机下扫码输入走隐藏输入框,聚焦隐藏框而非可见搜索框,避免弹出软键盘
this.scheduleScanInputFocus(150)
},
/**
* 全局键盘监听:扫码枪广播扫描识别
* 扫码枪本质是模拟键盘的 HID 设备,字符走浏览器标准 keydown 事件广播。
* 非聚焦时对可打印字符 / Tab / Enter 主动抢焦点;
* 可打印字符同时缓冲进 keyword,避免首字符丢失;
* 回车且有内容时立即提交;无回车结束符则静默防抖自动提交。
*/
handleGlobalKeydown(event) {
this.markScanKeyArrived('dom', { key: (event && event.key) || '' })
if (!this.isPageActive()) {
diagDrop('page-inactive', { source: 'dom' })
return
}
const key = event.key || ''
const activeEl = typeof document !== 'undefined' ? document.activeElement : null
const inInput = !!(activeEl && (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA'))
// 焦点在输入框:字符由输入框自身接收(@confirm/@input 处理),这里只记录节奏
if (inInput) {
this.touchScanInput()
return
}
if (this.enableHiddenInputCapture) {
return
}
if (event.ctrlKey || event.altKey || event.metaKey) {
return
}
// 操作员弹窗打开时:弹窗已无输入框,关闭弹窗后按键继续走主扫码流程
if (this.operatorDialogVisible) {
this.closeOperatorDialog()
}
const isPrintable = !!key && key.length === 1
const isEnter = key === 'Enter'
if (!isPrintable && !isEnter) {
return
}
if (event && typeof event.preventDefault === 'function') {
event.preventDefault()
}
if (isPrintable) {
const now = Date.now()
if (!this.globalKeyBuffer) {
this.globalKeyStartedAt = now
}
this.globalKeyLastAt = now
this.globalKeyBuffer += key
this.clearGlobalKeyTimer()
this.globalKeyTimer = setTimeout(() => {
if (!this.isPageActive()) {
return
}
this.flushGlobalScanBuffer()
}, 380)
return
}
// Enter:结束符立即提交
const code = (this.globalKeyBuffer || '').trim()
const durationMs = this.globalKeyStartedAt
? Math.max(0, (this.globalKeyLastAt || Date.now()) - this.globalKeyStartedAt)
: 0
this.globalKeyBuffer = ''
this.globalKeyStartedAt = 0
this.globalKeyLastAt = 0
this.clearGlobalKeyTimer()
if (!code) {
return
}
if (this.isLikelyScannerCode(code, durationMs, true)) {
diagFlush({ trigger: 'enter', source: 'dom', length: code.length, durationMs })
this.submitScanCode(code, 'dom')
} else {
diagDrop('dom-not-scanner-code', { length: code.length, durationMs, trigger: 'enter' })
}
},
touchScanInput() {
const now = Date.now()
const gap = now - this.lastScanKeyTime
if (this.lastScanKeyTime > 0 && gap > SCAN_BURST_MAX_GAP) {
this.scanBurstConfirmed = false
} else if ((this.keyword || '').trim().length >= 2) {
this.scanBurstConfirmed = true
}
this.lastScanKeyTime = now
if (this.scanTimer) {
clearTimeout(this.scanTimer)
}
this.scanTimer = setTimeout(() => this.checkScanIdle(), SCAN_IDLE_TIMEOUT)
},
checkScanIdle() {
this.scanTimer = null
// 绑定操作员弹窗打开时静默防抖不触发主搜索,避免误提交
if (this.operatorDialogVisible) {
this.scanBurstConfirmed = false
return
}
const elapsed = Date.now() - this.lastScanKeyTime
const buffer = (this.keyword || '').trim()
if (this.scanBurstConfirmed && elapsed >= SCAN_IDLE_TIMEOUT && buffer.length >= SCAN_MIN_LENGTH) {
this.handlePackSearch()
}
},
isPageActive() {
return this.pageActive !== false
},
isAppPlus() {
// #ifdef APP-PLUS
return true
// #endif
// #ifndef APP-PLUS
return false
// #endif
},
hasPlusKeyboardSupport() {
// #ifdef APP-PLUS
return typeof plus !== 'undefined' && !!plus?.key?.addEventListener
// #endif
// #ifndef APP-PLUS
return false
// #endif
},
hasDomKeyboardSupport() {
return typeof window !== 'undefined' || typeof document !== 'undefined'
},
setupScanCaptureMode() {
// 真机(APP-PLUS)逻辑层无 DOM:window/document 均为 undefined,
// hasDomKeyboardSupport() 会返回 false,导致 !hasDomKeyboardSupport() 误开启隐藏 input,
// 而看门狗每 2s 反复聚焦隐藏 input → 软键盘反复弹出(闪烁根因)。
// 现在 plus.key 已按 Android 原生 keycode 完整捕获扫码,真机彻底关闭隐藏 input。
if (this.isAppPlus()) {
this.enableHiddenInputCapture = false
return
}
// H5/Electron:有 DOM → 关闭隐藏捕获;小程序等无 DOM 且无 plus.key 平台 → 开启兜底
this.enableHiddenInputCapture = !this.hasDomKeyboardSupport()
},
// 看门狗:即使 onShow 异常未触发也能自愈恢复扫码。
// App/H5 页面隐藏或后台时收不到按键,所以 pageActive=true 不会误处理。
// 长时间运行自愈:
// 1) 空闲超过 10 分钟无任何按键 → 强制重挂 plus/DOM 监听(防桥接回调静默失效);
// 2) 每次心跳刷新门控快照 + 触发 60s 健康心跳,事后可定位「哪一分钟开始收不到按键」。
startScanWatchdog() {
if (this.scanWatchdogTimer) {
return
}
this.scanWatchdogStartedAt = Date.now()
this.scanWatchdogTimer = setInterval(() => {
this.pageActive = true
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
this.ensureScanInputFocus()
this.maybeRearmScanListenersWhenIdle()
diagSetGates(
Object.assign(
{
scope: 'packaging',
pageActive: this.pageActive !== false,
plusListener: !!(this.plusKeyListener || this.plusKeyUpListener),
domListener: !!this.globalKeyListener,
eventTypeLock: this._plusKeyEventType || 'none',
idleSec: this.lastScanKeyArrivedAt
? Math.round((Date.now() - this.lastScanKeyArrivedAt) / 1000)
: 'never',
},
// 真机:Window 焦点 / 输入法状态(决定按键能否到达 WebView),H5 返回空对象
probeAppWindow()
)
)
diagHeartbeat({ intervalMs: 2000 })
}, 2000)
},
stopScanWatchdog() {
if (this.scanWatchdogTimer) {
clearInterval(this.scanWatchdogTimer)
this.scanWatchdogTimer = null
}
},
/** 记录「按键到达 JS」(任何门控之前调用),返回距上次按键的空闲时长 */
markScanKeyArrived(source, extra) {
const now = Date.now()
const gap = this.lastScanKeyArrivedAt ? now - this.lastScanKeyArrivedAt : 0
this.lastScanKeyArrivedAt = now
this.scanRearmedForIdle = false
diagKey(source, extra)
return gap
},
/**
* 空闲(默认 10 分钟无任何按键)时强制重挂监听:
* 只在空闲时执行,不会打断正在进行的扫码;
* 用于兜住「监听器还在、但桥接回调不再投递按键」这类长时间运行才出现的静默失效。
*/
maybeRearmScanListenersWhenIdle() {
if (this.scanRearmedForIdle) {
return
}
// 从未收到过按键时以看门狗启动时刻为基准,否则"一直收不到"永远不会触发重挂
const baseline = this.lastScanKeyArrivedAt || this.scanWatchdogStartedAt || Date.now()
const idleMs = Date.now() - baseline
if (idleMs < SCAN_LISTENER_REARM_IDLE_MS) {
return
}
this.scanRearmedForIdle = true
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
diagHeal('listener-rearmed-idle', { scope: 'packaging', idleMs, hint: '长时间无按键,强制重挂监听' })
console.log('[packaging][scan] 已重挂扫码监听(空闲)', idleMs)
},
/** 诊断面板隐藏入口:3 秒内连点标题 5 次(操作员不会误触) */
handleDiagTitleTap() {
const now = Date.now()
if (now - this.diagTitleTapAt > 3000) {
this.diagTitleTapCount = 0
}
this.diagTitleTapAt = now
this.diagTitleTapCount += 1
if (this.diagTitleTapCount >= 5) {
this.diagTitleTapCount = 0
this.diagPanelVisible = true
diagNote('diag-panel-opened')
}
},
isRealDevice() {
// #ifdef APP-PLUS
return true
// #endif
return this.isMobileBrowser()
},
isMobileBrowser() {
try {
const info =
typeof uni !== 'undefined' && uni.getSystemInfoSync ? uni.getSystemInfoSync() : null
if (info && info.platform) {
const p = String(info.platform).toLowerCase()
if (p === 'android' || p === 'ios') {
return true
}
}
} catch (e) {
// 忽略
}
try {
if (typeof navigator !== 'undefined' && navigator.userAgent) {
return /Android|iPhone|iPad|iPod|Mobile|Tablet/i.test(navigator.userAgent)
}
} catch (e) {
// 忽略
}
return false
},
clearGlobalKeyTimer() {
if (this.globalKeyTimer) {
clearTimeout(this.globalKeyTimer)
this.globalKeyTimer = null
}
},
// 判断是否为扫码枪码(DOM 全局捕获用):
// 回车结束符 / 长度>=8 / 输入总时长与平均间隔足够快 → 视为扫码枪;否则视为手动输入忽略
isLikelyScannerCode(code, durationMs, byEnter) {
const normalizedCode = (code || '').replace(/\s+/g, '')
if (!normalizedCode || normalizedCode.length < 4) {
return false
}
if (byEnter) {
return true
}
if (!durationMs || durationMs <= 0) {
return normalizedCode.length >= 8
}
const avgInterval = durationMs / Math.max(normalizedCode.length - 1, 1)
return normalizedCode.length >= 8 || (durationMs <= 1800 && avgInterval <= 120)
},
flushGlobalScanBuffer() {
if (!this.isPageActive()) {
return
}
const code = (this.globalKeyBuffer || '').trim()
const durationMs = this.globalKeyStartedAt
? Math.max(0, (this.globalKeyLastAt || Date.now()) - this.globalKeyStartedAt)
: 0
this.globalKeyBuffer = ''
this.globalKeyStartedAt = 0
this.globalKeyLastAt = 0
this.clearGlobalKeyTimer()
if (!code) {
return
}
if (this.isLikelyScannerCode(code, durationMs, false)) {
diagFlush({ trigger: 'timer', source: 'dom', length: code.length, durationMs })
this.submitScanCode(code, 'dom')
} else {
diagDrop('dom-not-scanner-code', { length: code.length, durationMs })
}
},
attachGlobalKeyboardListener() {
if (this.globalKeyListener) {
return
}
const hasWindow = typeof window !== 'undefined'
const hasDocument = typeof document !== 'undefined'
const targets = []
if (hasDocument) {
targets.push(document)
} else if (hasWindow) {
targets.push(window)
}
if (!targets.length) {
return
}
this.globalKeyTargets = targets
this.globalKeyListener = this.handleGlobalKeydown
this.globalKeyTargets.forEach((target) => {
target.addEventListener('keydown', this.globalKeyListener, true)
})
},
removeGlobalKeyboardListener() {
this.clearGlobalKeyTimer()
this.globalKeyBuffer = ''
this.globalKeyStartedAt = 0
this.globalKeyLastAt = 0
if (!this.globalKeyTargets || !this.globalKeyListener) {
this.globalKeyTargets = []
this.globalKeyListener = null
return
}
this.globalKeyTargets.forEach((target) => {
target.removeEventListener('keydown', this.globalKeyListener, true)
})
this.globalKeyTargets = []
this.globalKeyListener = null
},
parsePlusKeyCodeToChar(keyCode) {
// Android Enter=66 在 ASCII 里是 'B',必须先排除,交给 isPlusEnterKey 处理
if (keyCode === 66) {
this._plusKeyStyle = this._plusKeyStyle || 'android'
return ''
}
// ---- Android 原生 keycode ----
if (keyCode >= 7 && keyCode <= 16) {
this._plusKeyStyle = this._plusKeyStyle || 'android'
return String(keyCode - 7) // 0-9
}
if (keyCode >= 29 && keyCode <= 54) {
this._plusKeyStyle = this._plusKeyStyle || 'android'
return String.fromCharCode(keyCode - 29 + 65) // A-Z
}
// Android 符号键:必须放在 ASCII 分支之前(防止 70('=') → 'F' 这类误读)
if (this._plusKeyStyle !== 'ascii' && ANDROID_PUNCT_MAP[keyCode] !== undefined) {
this._plusKeyStyle = this._plusKeyStyle || 'android'
return ANDROID_PUNCT_MAP[keyCode]
}
// ---- ASCII/DOM 风格(其它设备兑底)----
if (keyCode >= 48 && keyCode <= 57) {
this._plusKeyStyle = this._plusKeyStyle || 'ascii'
return String.fromCharCode(keyCode)
}
if (keyCode >= 65 && keyCode <= 90) {
this._plusKeyStyle = this._plusKeyStyle || 'ascii'
return String.fromCharCode(keyCode)
}
if (keyCode >= 96 && keyCode <= 105) {
this._plusKeyStyle = this._plusKeyStyle || 'ascii'
return String(keyCode - 96)
}
if (keyCode === 189 || keyCode === 109) {
return '-'
}
if (keyCode === 190 || keyCode === 110) {
return '.'
}
if (keyCode === 191 || keyCode === 111) {
return '/'
}
return ''
},
// 应用字母大小写策略(仅对 A-Z 生效)
applyLetterCase(ch, shifted) {
if (!ch || ch.length !== 1 || ch < 'A' || ch > 'Z') {
return ch
}
const mode = this.plusLetterCase || 'upper'
if (mode === 'lower') {
return ch.toLowerCase()
}
if (mode === 'auto') {
return shifted ? ch : ch.toLowerCase()
}
return ch // 'upper'
},
// 判断是否为 Enter:Android 原生 Enter=66;ASCII 风格为 13
// (13 在 Android 风格下是数字键 '6',所以用 text 能否解析来消歧)
isPlusEnterKey(keyCode, text) {
if (text) {
return false
}
if (keyCode === 66) {
return true
}
if (keyCode === 13) {
return this._plusKeyStyle !== 'android'
}
return false
},
attachPlusKeyboardListener() {
if (!this.hasPlusKeyboardSupport()) {
return
}
if (this.plusKeyListener || this.plusKeyUpListener) {
return
}
this.plusKeyListener = (event) => this.handlePlusKeyEvent(event, 'keydown')
this.plusKeyUpListener = (event) => this.handlePlusKeyEvent(event, 'keyup')
// #ifdef APP-PLUS
// 同时监听 keydown 与 keyup:本机实测只触发 keyup(keydown 不触发),
// 由 handlePlusKeyEvent 里的类型锁定避免两者都触发时重复采集
plus.key.addEventListener('keydown', this.plusKeyListener)
plus.key.addEventListener('keyup', this.plusKeyUpListener)
// #endif
},
// 统一处理 plus.key 按键(keydown / keyup)
handlePlusKeyEvent(event, type) {
// 先记录「按键到达 JS」这一事实(任何门控之前),用于区分「按键根本没到」与「到了被门控丢掉」
const keyCode = Number((event && event.keyCode) || 0)
this.plusKeyLastCode = keyCode
const gap = this.markScanKeyArrived('plus', { keyCode, type })
// 空闲后重新锁定实际生效的事件类型:自愈「锁错就永久静默」
if (this._plusKeyEventType && gap > SCAN_IDLE_LOCK_RESET_MS) {
const locked = this._plusKeyEventType
this._plusKeyEventType = null
diagHeal('event-type-lock-idle-reset', { locked, gapMs: gap })
}
if (!this.isPageActive()) {
diagDrop('page-inactive', { source: 'plus' })
return
}
// 跟踪 Shift 修饰键(Android KEYCODE_SHIFT_LEFT=59 / SHIFT_RIGHT=60)
if (keyCode === 59 || keyCode === 60) {
if (type === 'keydown') {
this._plusShiftDown = true
} else if (type === 'keyup') {
this._plusShiftDown = false
}
return
}
const rawChar = this.parsePlusKeyCodeToChar(keyCode)
// Shift 状态滞后补偿:本机实测 Shift 状态比字符滞后 1 个字符
const lag = Number(this.plusLetterCaseLag) || 0
const isFirstChar = !this.plusKeyBuffer
const shifted = lag > 0 && !isFirstChar ? !!this._plusShiftPrev : !!this._plusShiftDown
const text = this.applyLetterCase(rawChar, shifted)
this._plusShiftPrev = this._plusShiftDown
const isEnter = this.isPlusEnterKey(keyCode, text)
if (!text && !isEnter) {
diagDrop('unmapped-keycode', { keyCode, type })
return
}
// 锁定实际生效的事件类型,避免 keydown/keyup 都触发时把一个键记两次
if (!this._plusKeyEventType) {
this._plusKeyEventType = type
}
if (this._plusKeyEventType !== type) {
// 这一类丢弃最致命(整串码会丢),必须带上已收到的内容
diagDrop('event-type-locked', {
keyCode,
type,
locked: this._plusKeyEventType,
dropped: (this.plusKeyBuffer || '').slice(-40),
})
return
}
if (text) {
const now = Date.now()
if (!this.plusKeyBuffer) {
this.plusKeyStartedAt = now
// 新的一次扫码:按键数重新计数
this.plusKeyBurstCount = 0
}
this.plusKeyBurstCount += 1
this.plusKeyLastAt = now
this.plusKeyBuffer += text
this.clearPlusKeyTimer()
this.plusKeyTimer = setTimeout(() => this.flushPlusKeyBuffer('timer'), 420)
return
}
this.flushPlusKeyBuffer('enter')
},
removePlusKeyboardListener() {
this.clearPlusKeyTimer()
this.plusKeyBuffer = ''
this.plusKeyStartedAt = 0
this.plusKeyLastAt = 0
this._plusKeyEventType = null
if (!this.plusKeyListener && !this.plusKeyUpListener) {
return
}
// #ifdef APP-PLUS
if (this.hasPlusKeyboardSupport()) {
if (this.plusKeyListener) {
plus.key.removeEventListener('keydown', this.plusKeyListener)
}
if (this.plusKeyUpListener) {
plus.key.removeEventListener('keyup', this.plusKeyUpListener)
}
}
// #endif
this.plusKeyListener = null
this.plusKeyUpListener = null
},
flushPlusKeyBuffer(trigger = 'timer') {
if (!this.isPageActive()) {
diagDrop('page-inactive-flush', { source: 'plus', trigger })
return
}
const code = (this.plusKeyBuffer || '').trim()
const keyCount = this.plusKeyBurstCount
const durationMs = this.plusKeyStartedAt
? Math.max(0, (this.plusKeyLastAt || Date.now()) - this.plusKeyStartedAt)
: 0
this.plusKeyBuffer = ''
this.plusKeyBurstCount = 0
this.plusKeyStartedAt = 0
this.plusKeyLastAt = 0
this.clearPlusKeyTimer()
if (!code) {
return
}
// 过短输入(误触/输入法/枪异常)不当运单:记录收到的内容与按键数,便于事后区分
// "本来就只有 1 个字符"与"扫了完整码但按键中途停止投递"
if (code.length < SCAN_CODE_MIN_LENGTH) {
diagDrop('too-short', { source: 'plus', code, length: code.length, keys: keyCount, trigger })
return
}
diagFlush({ trigger, source: 'plus', code, length: code.length, durationMs, keys: keyCount })
console.log('[packaging][scan] plus-buffer trigger =', trigger, 'code =', code, 'keys =', keyCount)
// 扫码枪通常以 Enter 结尾(真机日志 trigger=enter):没有结束符就靠空闲 flush,
// 优先怀疑按键流在结束符前中断(也可能枪未配置后缀,服务端按 10 分钟一条区分)
if (trigger !== 'enter' && keyCount >= 4 && durationMs > 0 && durationMs <= 1500) {
this.reportNoTerminatorScan(code, keyCount, durationMs)
}
this.submitScanCode(code, 'plus')
},
/**
* 扫码没收到结束符就被 flush:记一条 anomaly(本地逐次记录,服务端限流上报)。
* 服务端据此区分"枪无后缀"(常态化)与"按键中途停止投递"(异常)。
*/
reportNoTerminatorScan(code, keys, durationMs) {
const now = Date.now()
const shouldReport = now - (this.lastNoTerminatorAnomalyAt || 0) >= NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS
if (shouldReport) {
this.lastNoTerminatorAnomalyAt = now
}
diagAnomaly(
'partial-code-no-terminator',
{
code,
keys,
length: code.length,
durationMs,
lastKeyCode: this.plusKeyLastCode || 0,
reported: shouldReport ? 1 : 0,
},
{ report: shouldReport }
)
},
handleHiddenScanFocus() {
if (!this.isPageActive() || !this.enableHiddenInputCapture) {
return
}
this.scanHiddenFocused = true
this.scanInputFocus = true
this.clearHiddenRefocusTimer()
this.applyScanInputAttrs()
this.suppressSoftKeyboardBurst()
},
applyScanInputAttrs() {
const input = this.getScanHiddenInputEl()
if (!input || typeof input.setAttribute !== 'function') {
return
}
input.setAttribute('autocapitalize', 'off')
input.setAttribute('autocorrect', 'off')
input.setAttribute('autocomplete', 'off')
input.setAttribute('spellcheck', 'false')
},
handleHiddenScanBlur() {
if (!this.isPageActive() || !this.enableHiddenInputCapture) {
return
}
this.scanHiddenFocused = false
this.scanInputFocus = false
this.clearHiddenRefocusTimer()
this.scanHiddenRefocusTimer = setTimeout(() => {
if (!this.isPageActive() || !this.enableHiddenInputCapture) {
return
}
const activeEl = typeof document !== 'undefined' ? document.activeElement : null
if (activeEl && (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA')) {
return
}
if (!this.scanHiddenFocused) {
this.scheduleScanInputFocus(220)
}
}, 500)
},
handleHiddenScanInput(event) {
if (!this.isPageActive() || !this.enableHiddenInputCapture) {
return
}
const value = event?.detail?.value || ''
// v-model 已同步 scanHiddenValue,这里仅回填可见搜索框并防抖提交
this.keyword = value
this.clearHiddenScanTimer()
this.scanHiddenTimer = setTimeout(() => {
if (!this.isPageActive() || !this.enableHiddenInputCapture) {
return
}
this.processHiddenScanValue('timer')
}, 320)
},
handleHiddenScanConfirm(event) {
if (!this.isPageActive() || !this.enableHiddenInputCapture) {
return
}
const value = event?.detail?.value || this.scanHiddenValue || ''
this.scanHiddenValue = value
this.processHiddenScanValue('confirm')
},
processHiddenScanValue(trigger = 'timer') {
if (!this.isPageActive() || !this.enableHiddenInputCapture) {
return
}
const code = (this.scanHiddenValue || '').trim()
this.clearHiddenScanTimer()
if (!code) {
return
}
this.scanHiddenValue = ''
this.clearScanHiddenInputValue()
this.dismissSoftKeyboard()
this.submitScanCode(code, 'hidden')
this.ensureScanInputFocus()
},
clearScanHiddenInputValue() {
const input = this.getScanHiddenInputEl()
if (input) {
input.value = ''
}
},
getScanHiddenInputEl() {
const ref = this.$refs.scanHiddenInput
if (!ref) {
return null
}
const el = ref.$el || ref
if (!el) {
return null
}
if (el.tagName === 'INPUT') {
return el
}
return typeof el.querySelector === 'function' ? el.querySelector('input') : null
},
ensureScanInputFocus() {
if (!this.isPageActive()) {
return
}
if (!this.enableHiddenInputCapture) {
// 无隐藏捕获:不再抢占/隐藏软键盘,避免点击操作时软键盘反复弹收
this.scanInputFocus = false
return
}
if (!this.scanInputFocus) {
this.scanInputFocus = true
}
// 状态可能已为 true 但原生 input 实际已失焦,直接同步聚焦兜底
this.focusScanHiddenInput()
},
focusScanHiddenInput() {
const input = this.getScanHiddenInputEl()
if (input && typeof input.focus === 'function') {
try {
input.focus()
} catch (e) {
// 忽略聚焦失败
}
}
},
scheduleScanInputFocus(delay = 0) {
if (!this.isPageActive()) {
return
}
this.clearScanFocusResumeTimer()
this.scanFocusResumeTimer = setTimeout(() => {
if (!this.isPageActive()) {
return
}
this.ensureScanInputFocus()
}, delay)
},
// 窗口级软键盘模式设为 ALWAYS_HIDDEN:input 聚焦也不会自动弹软键盘。
// 真机上不要用 uni.hideKeyboard()——它会断开输入框的按键连接,
// 导致“扫一次后就不再接收输入”;用 Android 窗口软键盘模式彻底压制。
setWindowSoftInputHidden() {
// #ifdef APP-PLUS
try {
if (typeof plus !== 'undefined' && plus.android && plus.android.runtimeMainActivity) {
const main = plus.android.runtimeMainActivity()
const win = plus.android.invoke(main, 'getWindow')
// SOFT_INPUT_STATE_ALWAYS_HIDDEN = 3(数值直传,避免静态字段访问失败导致设置无效)
plus.android.invoke(win, 'setSoftInputMode', 3)
console.log('[packaging][kb] setSoftInputMode=ALWAYS_HIDDEN(3)')
} else {
console.log('[packaging][kb] plus.android unavailable')
}
} catch (e) {
console.log('[packaging][kb] setSoftInputMode failed:', e && e.message)
}
// #endif
// 隐藏当前已显示的软键盘;此后窗口级 ALWAYS_HIDDEN 阻止再弹,不会形成闪烁循环
if (typeof uni !== 'undefined' && typeof uni.hideKeyboard === 'function') {
uni.hideKeyboard()
}
},
suppressSoftKeyboardBurst() {
if (!this.isPageActive()) {
return
}
this.clearKeyboardSuppressTimers()
// 真机:窗口级 ALWAYS_HIDDEN,input 聚焦也不会弹软键盘(不打断扫码输入)
if (this.isAppPlus()) {
this.setWindowSoftInputHidden()
// 软键盘可能晚于页面显示弹出,多时间点重设窗口模式 + 收键盘覆盖
;[80, 180, 320].forEach((delay) => {
const timer = setTimeout(() => {
if (!this.isPageActive()) {
return
}
this.setWindowSoftInputHidden()
}, delay)
this.scanKeyboardSuppressTimers.push(timer)
})
return
}
uni.hideKeyboard?.()
},
dismissSoftKeyboard() {
if (!this.isPageActive()) {
return
}
if (this.isAppPlus()) {
this.setWindowSoftInputHidden()
return
}
// 不主动 blur,避免隐藏输入框失焦导致下一次扫码首字符丢失
uni.hideKeyboard?.()
},
/**
* 扫码枪连续读取同一码时,隐藏输入框可能累积为同一内容重复多次(可能带不完整尾段)。
* 检测重复并只保留第一段完整内容;单段长度需 >= 8 才去重,避免误截短码。
*/
dedupeRepeatedScan(value) {
const s = String(value || '').trim()
const n = s.length
if (n < 2) {
return s
}
const minUnit = 8
const maxUnit = Math.floor(n / 2)
// 完整重复:s = p * k(k >= 2)
for (let len = minUnit; len <= maxUnit; len++) {
if (n % len === 0) {
const p = s.slice(0, len)
if (p.repeat(n / len) === s) {
return p
}
}
}
// 不完整尾段:s = p * k + p 的前缀(k >= 2)
for (let len = minUnit; len <= maxUnit; len++) {
const p = s.slice(0, len)
let rest = s
let count = 0
while (rest.length >= len && rest.slice(0, len) === p) {
rest = rest.slice(len)
count++
}
if (
count >= 2 &&
rest.length > 0 &&
rest.length < len &&
p.slice(0, rest.length) === rest
) {
return p
}
}
return s
},
submitScanCode(code, source) {
if (!this.isPageActive()) {
diagDrop('page-inactive-submit', { source })
return
}
const trimmed = this.dedupeRepeatedScan((code || '').trim())
if (!trimmed) {
return
}
const now = Date.now()
if (
this.lastSubmittedScan &&
this.lastSubmittedScan.code === trimmed &&
now - this.lastSubmittedScan.at < 600
) {
diagDrop('dedupe-same-code', { source, length: trimmed.length })
return
}
this.lastSubmittedScan = { code: trimmed, at: now }
diagNote('submit-scan', { source, code: trimmed })
console.log('[packaging][scan] submitScanCode source =', source, 'code =', trimmed)
// 操作员弹窗打开时:弹窗已无输入框,关闭弹窗后扫码内容走主流程
if (this.operatorDialogVisible) {
this.closeOperatorDialog()
this.keyword = trimmed
this.handlePackSearch()
return
}
this.keyword = trimmed
this.handlePackSearch()
},
restoreScanRecords() {
try {
const cached = uni.getStorageSync(SCAN_RECORDS_STORAGE_KEY)
if (Array.isArray(cached)) {
this.scanRecords = cached
.filter((record) => record && record.text)
.slice(0, 50)
}
} catch (e) {
// 忽略:缓存读取失败不影响页面
}
},
addScanRecord(code) {
const date = new Date()
const pad = (n) => String(n).padStart(2, '0')
const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
// 出入栈:最新在最前,超过 50 条丢最旧
this.scanRecords.unshift({ text: code, time })
if (this.scanRecords.length > 50) {
this.scanRecords = this.scanRecords.slice(0, 50)
}
// 持久化到 localStorage(最多 50 条)
try {
uni.setStorageSync(SCAN_RECORDS_STORAGE_KEY, this.scanRecords)
} catch (e) {
// 存储失败不阻断扫描流程
}
},
loadTodayPackStat() {
const token = this.getWorkbenchToken()
if (!token) {
return
}
// 今日打包统计以服务端 workbench.getWorkbenchCount 为准
getWorkbenchCount(String(token))
.then((body) => {
if (this.checkWorkbenchAuthExpired(body)) {
return
}
const payload = body?.data || body?.result || body
const raw =
payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
if (!raw) {
return
}
this.todayWaveCount = Number(raw.group_wave_count) || 0
this.todaySingleCount = Number(raw.single_order_count) || 0
this.todayGroupOrderCount = Number(raw.group_order_count) || 0
this.todayRatio = raw.group_single_ratio ?? null
this.todayAvgPiece = raw.avg_piece_count ?? null
})
.catch(() => {
// 静默:统计失败不影响打包流程
})
},
clearPlusKeyTimer() {
if (this.plusKeyTimer) {
clearTimeout(this.plusKeyTimer)
this.plusKeyTimer = null
}
},
clearHiddenScanTimer() {
if (this.scanHiddenTimer) {
clearTimeout(this.scanHiddenTimer)
this.scanHiddenTimer = null
}
},
clearHiddenRefocusTimer() {
if (this.scanHiddenRefocusTimer) {
clearTimeout(this.scanHiddenRefocusTimer)
this.scanHiddenRefocusTimer = null
}
},
clearScanFocusResumeTimer() {
if (this.scanFocusResumeTimer) {
clearTimeout(this.scanFocusResumeTimer)
this.scanFocusResumeTimer = null
}
},
clearScanInputIdleTimer() {
if (this.scanInputIdleTimer) {
clearTimeout(this.scanInputIdleTimer)
this.scanInputIdleTimer = null
}
},
clearKeyboardSuppressTimers() {
this.scanKeyboardSuppressTimers.forEach((timer) => clearTimeout(timer))
this.scanKeyboardSuppressTimers = []
},
clearScanTimers() {
this.clearScanFocusResumeTimer()
this.clearKeyboardSuppressTimers()
this.clearHiddenScanTimer()
this.clearPlusKeyTimer()
this.clearHiddenRefocusTimer()
this.clearScanInputIdleTimer()
if (this.scanTimer) {
clearTimeout(this.scanTimer)
this.scanTimer = null
}
this.clearOperatorSearchTimer()
},
// ---- 绑定操作员(工作台成员)----
getWorkbenchToken() {
return uni.getStorageSync('token') || uni.getStorageSync('workbench_token') || ''
},
restoreWorkbenchMembers() {
try {
const cached = uni.getStorageSync(MEMBER_STORAGE_KEY)
if (Array.isArray(cached)) {
this.workbenchMembers = cached.filter(
(member) => member && (member.id || member.user_name)
)
} else if (cached && typeof cached === 'object' && (cached.id || cached.user_name)) {
// 兼容旧版单成员缓存
this.workbenchMembers = [cached]
}
} catch (e) {
// 忽略:缓存读取失败不影响页面
}
},
handleOperatorClick() {
this.operatorDialogVisible = true
},
closeOperatorDialog() {
this.operatorDialogVisible = false
this.clearOperatorSearchTimer()
// 关闭弹窗后把焦点还给隐藏扫码输入框,避免下次扫码首字符丢失
this.scheduleScanInputFocus(150)
},
clearOperatorSearchTimer() {
if (this.operatorSearchTimer) {
clearTimeout(this.operatorSearchTimer)
this.operatorSearchTimer = null
}
},
/**
* 解析工牌码:工牌为 base64 编码的 JSON(如 {"uuid":"1e9b11d0-..."})
* - 命中返回解析出的对象;非工牌(普通运单号/临时码)返回 null
*/
parseBadgeCode(code) {
const text = String(code || '').trim()
// 快速预判:长度与字符集需符合 base64,避免每条码都走解码
if (!text || text.length < 16 || !/^[A-Za-z0-9+/=_-]+$/.test(text)) {
return null
}
try {
const b64 = text.replace(/-/g, '+').replace(/_/g, '/')
const binary = typeof atob === 'function' ? atob(b64) : ''
if (!binary) {
return null
}
// UTF-8 安全解码(工牌内可能含中文姓名)
const jsonText = decodeURIComponent(
binary
.split('')
.map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
.join('')
)
const parsed = JSON.parse(jsonText)
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed
}
} catch (e) {
// 非工牌码,忽略
}
return null
},
/**
* 工牌扫码处理:复用 index.queryUserByToken 拉取用户信息
* - 完整工牌码(base64)作为 token 入参,由后端识别/解码提取 uuid
* - 已绑定且为同一用户(名字或 user_id 命中)→ 下线(移除操作员)
* - 未绑定该用户 → 登录(绑定为当前操作员,userId 取 user_id)
*/
handleBadgeScan(code) {
if (this.badgeHandling) {
return
}
const codeStr = String(code || '').trim()
if (!codeStr) {
return
}
// 工号扫码:扫描记录只记「工号」二字,不记录完整工牌码
this.addScanRecord('工号')
const token = this.getWorkbenchToken()
if (!token) {
uni.showToast({ title: '工作台登录已失效', icon: 'none' })
return
}
this.badgeHandling = true
queryUserByToken(codeStr)
.then((body) => {
const payload = body?.data || body?.result || body
const raw =
payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
const flag = body?.flag || raw?.flag || ''
const bizCode = body?.code ?? raw?.code ?? null
if (Number(bizCode) === 401 || Number(bizCode) === 403) {
// 401/403:工作台已解绑或 token 无效,清除状态回登录页
this.handleWorkbenchAuthExpired()
return
}
if (flag === 'failure' || Number(bizCode) === 404) {
this.keyword = ''
this.speak('未绑定操作员')
uni.showToast({ title: '未找到该用户', icon: 'none', silentVoice: true })
return
}
const realName = this.pickInfoField(raw, body, [
'real_name',
'realName',
'user_name',
'userName',
])
const userId = this.pickInfoField(raw, body, [
'user_id',
'userId',
'wms_account_id',
'wmsAccountId',
])
// 在线成员中查找同一用户(名字或 user_id 命中)
const list = Array.isArray(this.workbenchMembers) ? this.workbenchMembers : []
const member = list.find(
(m) =>
m.user_name === realName ||
(userId != null && String(m.user_id) === String(userId))
)
// 同一用户已在线 → 下线该成员
if (member) {
this.keyword = ''
this.doRemoveOperator(member.id)
return
}
// 未在线 → 登录(绑定为在线成员,userId 取 user_id)
this.doBindOperator(realName, userId)
})
.catch(() => {
// 查询失败允许重扫同一码
this.keyword = ''
this.lastScannedCode = ''
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
})
.finally(() => {
this.badgeHandling = false
// 工牌码支持重复扫码切换上线/下线:处理完清空上次扫码缓存,允许下次扫同一码再次触发
this.lastScannedCode = ''
})
},
doBindOperator(realName, wmsAccountId) {
const token = this.getWorkbenchToken()
if (!token) {
uni.showToast({ title: '工作台登录已失效', icon: 'none' })
return
}
if (this.operatorBinding) {
return
}
this.operatorBinding = true
const userId = wmsAccountId ? Number(wmsAccountId) : null
bindWorkbenchMember({
userId,
userName: realName || '',
token: String(token),
})
.then((body) => {
const payload = body?.data || body?.result || body
const raw =
payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
const flag = body?.flag || raw?.flag || ''
if (this.checkWorkbenchAuthExpired(body)) {
return
}
if (flag === 'failure') {
this.speak('绑定失败,请点击绑定重试')
uni.showToast({ title: body?.message || body?.msg || '绑定失败', icon: 'none', silentVoice: true })
return
}
const member = {
id: this.pickInfoField(raw, body, ['id']),
workbench_id: this.pickInfoField(raw, body, ['workbench_id', 'workbenchId']),
user_id: raw?.user_id ?? body?.user_id ?? null,
user_name: this.pickInfoField(raw, body, ['user_name', 'userName', 'name']),
}
// 追加/更新到在线操作员列表,本地缓存刷新后恢复
const list = Array.isArray(this.workbenchMembers) ? this.workbenchMembers.slice() : []
const idx = list.findIndex((m) => m.id === member.id)
if (idx >= 0) {
list[idx] = member
} else {
list.push(member)
}
this.workbenchMembers = list
uni.setStorageSync(MEMBER_STORAGE_KEY, list)
// 清空主搜索框(扫码内容为临时码/工牌,绑定后应清空)
this.keyword = ''
this.speak(`${member.user_name || realName || ''}绑定成功`)
uni.showToast({ title: '绑定成功', icon: 'none', silentVoice: true })
// 主搜索框扫码绑定:关闭弹窗
this.closeOperatorDialog()
// 上线后重新拉取工作台信息,以服务端成员列表为准
this.loadWorkbenchInfo({ silent: true })
// 重新绑定成员后重启无新任务自动登出计时
this.scheduleIdleAutoLogout()
})
.catch(() => {
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
})
.finally(() => {
this.operatorBinding = false
})
},
handleRemoveOperator(member) {
if (!member || !member.id) {
return
}
if (this.operatorRemoving) {
return
}
this.removeTargetMember = member
this.removeConfirmVisible = true
},
closeRemoveConfirm() {
this.removeConfirmVisible = false
},
confirmRemoveOperator() {
if (!this.removeTargetMember || !this.removeTargetMember.id) {
this.removeConfirmVisible = false
return
}
const memberId = this.removeTargetMember.id
this.doRemoveOperator(memberId)
},
/**
* 解绑操作员(统一入口)
* - 移除单个成员不影响进行中的打包任务;移除成功后若已全员下线,再上报当前任务打包完成
* - silent=true:静默解绑(退出流程用),不弹提示、失败不阻断
* - 全员下线后清空订单/核实数据,防止残留给下一批操作员
*/
async doRemoveOperator(memberId, options = {}) {
const { silent = false, toastText = '' } = options
const token = this.getWorkbenchToken()
if (!token) {
if (!silent) {
this.exitToLogin('工作台已解绑,请重新绑定登录')
}
return 'expired'
}
if (this.operatorRemoving) {
return 'failed'
}
this.operatorRemoving = true
if (!silent) {
uni.showLoading({ title: '下线中...', mask: true })
}
try {
const body = await removeWorkbenchMember({
ids: [Number(memberId)],
token: String(token),
})
const payload = body?.data || body?.result || body
const raw =
payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
const flag = body?.flag || raw?.flag || ''
const bizCode = body?.code ?? raw?.code ?? null
if (Number(bizCode) === 401 || Number(bizCode) === 403) {
// 401/403:工作台已解绑或 token 失效,统一清除状态回登录页
if (!silent) {
this.handleWorkbenchAuthExpired()
}
return 'expired'
}
if (flag === 'failure') {
if (!silent) {
this.speak('下线失败')
uni.showToast({ title: body?.message || body?.msg || '下线失败', icon: 'none', silentVoice: true })
}
return 'failed'
}
const removed = Number(raw?.removed ?? body?.removed ?? 0)
if (removed > 0) {
const list = Array.isArray(this.workbenchMembers) ? this.workbenchMembers.slice() : []
const removedMember = list.find((m) => Number(m.id) === Number(memberId))
const removedName = removedMember?.user_name || removedMember?.name || ''
const next = list.filter((m) => Number(m.id) !== Number(memberId))
this.workbenchMembers = next
if (next.length > 0) {
// 仍有成员在线:进行中的打包任务不受影响
uni.setStorageSync(MEMBER_STORAGE_KEY, next)
} else {
uni.removeStorageSync(MEMBER_STORAGE_KEY)
// 全员下线:先提交当前任务打包完成,再清空订单/核实数据,防止残留给下一批操作员
await this.ensurePackFinishedBeforeLeave()
this.clearPackState()
// 全员已下线:停止无新任务自动登出计时(重新绑定后由 doBindOperator 重启)
this.clearIdleAutoLogoutTimer()
}
this.removeConfirmVisible = false
this.removeTargetMember = null
if (!silent) {
this.speak(`${removedName}下线成功`)
uni.showToast({ title: toastText || '操作员已下线', icon: 'none', silentVoice: true })
}
// 下线后重新拉取工作台信息,以服务端成员列表为准
this.loadWorkbenchInfo({ silent: true })
return 'success'
}
if (!silent) {
this.speak('下线失败')
uni.showToast({ title: '未找到该成员', icon: 'none', silentVoice: true })
}
return 'failed'
} catch (e) {
if (!silent) {
this.speak('下线失败')
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none', silentVoice: true })
}
return 'failed'
} finally {
this.operatorRemoving = false
if (!silent) {
uni.hideLoading()
}
}
},
pickInfoField(raw, body, keys) {
const sources = [raw, body]
for (const src of sources) {
if (!src || typeof src !== 'object') {
continue
}
for (const key of keys) {
const value = src[key]
if (value !== undefined && value !== null && value !== '') {
return value
}
}
}
return ''
},
/**
* 提取商品图片 URL 列表
* 兼容 images 数组(元素为字符串或 { url/image_url/path/src } 对象)与单字段 image/image_url/imageUrl
*/
extractImages(item) {
const raw =
item?.images !== undefined && item?.images !== null
? item.images
: item?.image ?? item?.image_url ?? item?.imageUrl
let list = []
if (Array.isArray(raw)) {
list = raw
} else if (raw !== undefined && raw !== null && raw !== '') {
list = [raw]
}
const urls = []
for (const el of list) {
if (typeof el === 'string') {
const v = el.trim()
if (v) {
urls.push(v)
}
} else if (el && typeof el === 'object') {
const v =
el.url || el.image_url || el.imageUrl || el.path || el.src || el.value || ''
if (v) {
urls.push(String(v))
}
}
}
return urls
},
loadWorkbenchInfo(options = {}) {
const { silent = false } = options
if (this.infoLoading) {
return
}
const token = uni.getStorageSync('token')
if (!token) {
this.exitToLogin('登录状态已失效,请重新登录')
return
}
if (!silent) {
this.infoLoading = true
this.infoError = ''
}
getWorkbenchInfo(String(token))
.then((body) => {
const payload = body?.data || body?.result || body
const raw =
payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
const flag = body?.flag || raw?.flag || ''
const bizCode = body?.code ?? raw?.code ?? null
if (Number(bizCode) === 401 || Number(bizCode) === 403) {
this.workbenchInfo = null
this.infoError = '工作台不存在或 token 无效'
// 工作台已解绑/失效:清除本地保存的工作台会话,回到登录页重新绑定
this.exitToLogin('工作台已解绑,请重新绑定登录')
return
}
if (flag === 'failure') {
// 非鉴权类失败:静默刷新保留现有状态不退出,仅初始加载展示错误
if (!silent) {
this.workbenchInfo = null
this.infoError = body?.message || body?.msg || '未获取到工作台信息'
}
return
}
const info = {
id: this.pickInfoField(raw, body, ['id']),
warehouseId: this.pickInfoField(raw, body, ['warehouse_id', 'warehouseId']),
name: this.pickInfoField(raw, body, ['name']),
status: this.pickInfoField(raw, body, ['status']),
type: this.pickInfoField(raw, body, ['type']),
remark: this.pickInfoField(raw, body, ['remark']),
deviceIds: this.pickInfoField(raw, body, ['device_ids', 'deviceIds']),
createdAt: this.pickInfoField(raw, body, ['created_at', 'createdAt']),
updatedAt: this.pickInfoField(raw, body, ['updated_at', 'updatedAt']),
}
if (!Array.isArray(info.deviceIds)) {
info.deviceIds = []
}
if (!info.id && !info.name) {
this.workbenchInfo = null
this.infoError = '未获取到工作台信息'
return
}
this.workbenchInfo = info
// 同步在线成员列表(服务端 members 为准,含绑定/下线后的最新状态)
if (Array.isArray(raw?.members)) {
const members = raw.members
.filter((m) => m && (m.id || m.user_name))
.map((m) => ({
id: m.id,
workbench_id: info.id ?? m.workbench_id ?? m.workbenchId ?? null,
user_id: m.user_id ?? m.userId ?? null,
user_name: m.user_name ?? m.userName ?? m.name ?? '',
}))
this.workbenchMembers = members
uni.setStorageSync(MEMBER_STORAGE_KEY, members)
}
// 恢复进行中的打包任务(app 中途退出后重进)
this.restoreCurrentPackTask(raw)
})
.catch(() => {
if (silent) {
// 静默刷新失败不阻断,保留本地成员列表
return
}
this.workbenchInfo = null
this.infoError = '网络异常,请稍后重试'
})
.finally(() => {
if (!silent) {
this.infoLoading = false
}
})
},
/**
* 带打包台 token 请求的失效守卫:
* - 401(token 为空)/ 403(工作台不存在或 token 无效)→ 清除工作台状态并回登录页
* - 返回 true 表示已失效并已处理
*/
checkWorkbenchAuthExpired(body) {
const payload = body?.data || body?.result || body
const raw =
payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
const bizCode = body?.code ?? raw?.code ?? null
if (Number(bizCode) === 401 || Number(bizCode) === 403) {
this.handleWorkbenchAuthExpired()
return true
}
return false
},
/**
* 工作台已解绑(带打包台 token 请求返回 401/403):清除本地会话与操作员缓存,回到登录页
*/
handleWorkbenchAuthExpired() {
this.exitToLogin('工作台已解绑,请重新绑定登录')
},
exitToLogin(message) {
this.clearIdleAutoLogoutTimer()
if (message) {
uni.showToast({
title: message,
icon: 'none',
})
}
const wbToken = uni.getStorageSync('workbench_token')
const mainToken = uni.getStorageSync('token')
// 清理工作台会话与操作员缓存
uni.removeStorageSync('workbench_token')
uni.removeStorageSync('workbench_id')
uni.removeStorageSync(MEMBER_STORAGE_KEY)
this.workbenchMembers = []
this.removeTargetMember = null
// 主登录态一致性判断:一致(工作台会话即主登录态)→ 清主 token;不一致 → 保留主登录态
if (wbToken && wbToken === mainToken) {
uni.removeStorageSync('token')
}
// 离开前释放全局扫码监听,避免登录页重新注册时被本页残留监听干扰
this.stopScanWatchdog()
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.clearScanTimers()
setTimeout(() => {
uni.reLaunch({
url: '/pages/login/login',
})
}, 400)
},
/**
* 无新打包任务自动登出(超时)计时
* - 每次开始新打包任务、页面重新显示时重置计时
* - 触发后:结束最后打包任务 → 解绑全部成员(不退出工作台模式,留在当前页面)
*/
scheduleIdleAutoLogout() {
this.clearIdleAutoLogoutTimer()
this.idleLogoutTimer = setTimeout(() => {
this.idleLogoutTimer = null
this.autoLogoutForIdle()
}, IDLE_AUTO_LOGOUT_MS)
},
clearIdleAutoLogoutTimer() {
if (this.idleLogoutTimer) {
clearTimeout(this.idleLogoutTimer)
this.idleLogoutTimer = null
}
},
async autoLogoutForIdle() {
if (this.idleLoggingOut) {
return
}
this.idleLoggingOut = true
try {
// 1. 结束最后打包任务(无进行中任务则跳过)
await this.ensurePackFinishedBeforeLeave()
// 2. 解绑全部在线操作员(removeMember 支持 ids 数组),失败不阻断
const list = Array.isArray(this.workbenchMembers) ? this.workbenchMembers : []
const ids = list.map((m) => Number(m.id)).filter((id) => id > 0)
if (ids.length > 0) {
const token = this.getWorkbenchToken()
if (!token) {
this.exitToLogin('工作台已解绑,请重新绑定登录')
return
}
try {
const body = await removeWorkbenchMember({
ids,
token: String(token),
})
const payload = body?.data || body?.result || body
const raw =
payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
const bizCode = body?.code ?? raw?.code ?? null
// 401/403 已解绑:被动退出,提示并回登录页
if (Number(bizCode) === 401 || Number(bizCode) === 403) {
this.exitToLogin('工作台已解绑,请重新绑定登录')
return
}
} catch (e) {
// 失败不阻断
}
}
// 3. 仅清理打包数据与本地成员列表,不退出工作台模式
this.workbenchMembers = []
uni.removeStorageSync(MEMBER_STORAGE_KEY)
this.clearPackState()
// 4. 重拉工作台信息,成员列表以服务端为准
this.loadWorkbenchInfo({ silent: true })
this.speak('已结束打包并下线全部成员')
uni.showToast({ title: '长时间无新打包任务,已自动下线', icon: 'none', silentVoice: true })
} finally {
this.idleLoggingOut = false
}
},
},
mounted() {
// #ifdef APP-PLUS
plus.android.importClass('android.util.Log').i('WMSPage', 'mounted')
// #endif
try {
// 广播扫描:plus.key(Android 原生 keycode)+ DOM 全局 keydown + 隐藏 input(关闭)
this.setupScanCaptureMode()
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
this.startScanWatchdog()
this.suppressSoftKeyboardBurst()
this.scheduleScanInputFocus(260)
this.initNativeTts()
} catch (e) {
console.error('[packaging] mounted 异常:', e)
}
},
beforeUnmount() {
this.pageActive = false
this.stopScanWatchdog()
this.shutdownNativeTts()
this.destroyVoiceAudio()
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.clearScanTimers()
this.stopPackCountdown()
},
}
</script>
<script module="remInject" lang="renderjs">
import { installZeroViewportFix, installConsoleForward } from '../../render-common/viewport-fix.js'
import { applyRemBase } from '../../render-common/rem-base.js'
export default {
mounted() {
// #ifdef APP-PLUS
// 视图层 console 转发到 logcat(tag: UniViewConsole),dev-adb 终端实时可见
installConsoleForward()
// 真机修复(RK3288/Android7 实测):reLaunch 后新页面 WebView 视口可能为 0×0,
// CSS 的 vw/vh 随之计算为 0 → html fontSize=0 → 所有 rem 尺寸归零 → 白屏;
// 检测到 0×0 视口时强制原生 decorView 重排自愈。公共逻辑见 src/render-common/viewport-fix.js。
// 已对照验证:移除自愈白屏复现,此调用必需保留。
installZeroViewportFix()
try {
const Log = plus.android.importClass('android.util.Log')
const computedFont = () => {
let css = 'na'
try {
css = window.getComputedStyle(document.documentElement).fontSize
} catch (e) { /* ignore */ }
return css
}
Log.i('WMSView', 'renderjs mounted, body=' + (document.body ? document.body.clientWidth + 'x' + document.body.clientHeight : 'null') + ', inner=' + window.innerWidth + 'x' + window.innerHeight + ', inlineFont=' + (document.documentElement.style ? document.documentElement.style.fontSize : 'na') + ', computedFont=' + computedFont())
setTimeout(() => {
Log.i('WMSView', 'renderjs t+2s, body=' + (document.body ? document.body.clientWidth + 'x' + document.body.clientHeight : 'null') + ', inner=' + window.innerWidth + 'x' + window.innerHeight + ', inlineFont=' + (document.documentElement.style ? document.documentElement.style.fontSize : 'na') + ', computedFont=' + computedFont())
}, 2000)
} catch (e) {
const Log2 = plus.android.importClass('android.util.Log')
Log2.i('WMSView', 'renderjs err=' + e)
}
// #endif
// #ifndef APP-PLUS
// rem 基准统一走 render-common/rem-base.js(满格 1rem = 100px,>1280 宽不再放大字体),
// 字号偏大靠改 CSS 的 font-size 值(已全局 ×0.85),不动基准
// 各页面不再各算一份,避免系数漂移
// 真机(APP-PLUS)rem 由 App.vue 全局纯 CSS(html { font-size: 7.8125vw !important }=100/1280)承担。
// ⚠️ 这里用 #ifndef,不要写成 `#ifdef APP-PLUS + return`:后者会让 esbuild 报
// “semicolon-after-return”,且以后往 mounted 里补的视图层代码会变成真机永不执行。
this._remResizeHandler = applyRemBase
applyRemBase()
window.addEventListener('resize', this._remResizeHandler)
// #endif
},
beforeDestroy() {
if (this._remResizeHandler) {
window.removeEventListener('resize', this._remResizeHandler)
this._remResizeHandler = null
}
}
}
</script>
<style>
/* 基准(src/styles/base.css 的 .page):box-sizing / display: flex / flex-direction: column /
flex: 1 / min-height: 0 / 页面底色(--wms-page-bg,全站统一 #e8eaed),本页只写差异项 */
.page {
height: 100vh;
min-width: 6.14rem;
align-items: stretch;
justify-content: flex-start;
overflow: hidden;
}
.mode-topbar {
background-color: var(--wms-primary);
display: flex;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
/* 高度对齐全站顶栏(--wms-nav-height):0.7rem = 70px = 内行 50 + 上下内边距各 10px */
height: 0.7rem;
/* 水平内边距与顶栏一致,保证 logo/标题左右对齐 */
padding: 0.1rem var(--wms-page-pad);
}
.mode-title {
display: flex;
align-items: center;
line-height: 1;
min-width: 0;
}
.mode-title-label {
/* “打包模式”:导航菜单字号 0.22rem = 22px */
font-size: 0.22rem;
font-weight: 400;
color: var(--wms-white);
flex-shrink: 0;
}
.mode-title-divider {
width: 0.02rem;
/* 分隔线高度跟文字(0.22rem = 22px) */
height: 0.22rem;
background-color: rgba(255, 255, 255, 0.45);
margin: 0 0.2rem;
flex-shrink: 0;
}
.mode-title-name {
/* 工作台名:页面级标题 0.25rem = 25px(原 34.8px 偏移动端) */
font-size: 0.25rem;
font-weight: 400;
color: var(--wms-white);
white-space: nowrap;
}
.mode-title-wrap {
display: flex;
align-items: center;
min-width: 0;
}
.mode-logo {
/* 与顶栏内行(0.5rem = 50px)齐高,宽度按原宽高比 2.6667 换算(原 73.7px 是移动端口径) */
width: 1.33rem;
height: 0.5rem;
margin-right: 0.55rem;
flex-shrink: 0;
}
.mode-main {
flex: 1;
min-height: 0;
box-sizing: border-box;
display: flex;
flex-direction: column;
/* 与全站主体内间距统一(顶栏无 margin-bottom,上 0.25 就是顶栏到内容的 25px) */
padding: var(--wms-page-pad);
overflow: hidden;
}
.mode-card {
background-color: var(--wms-card-bg);
border-radius: 0.13rem;
padding: 0.45rem 0.35rem;
box-sizing: border-box;
text-align: center;
}
.mode-card-title {
display: block;
font-size: 0.25rem;
color: var(--wms-text);
font-weight: 600;
margin-bottom: 0.15rem;
}
.mode-card-desc {
display: block;
font-size: 0.21rem;
color: #888;
line-height: 1.6;
}
.mode-card--center {
text-align: center;
padding: 0.4rem 0.35rem;
}
.mode-card--info {
text-align: left;
padding: 0.35rem;
}
.mode-card--desc {
margin-top: 0.2rem;
padding: 0.25rem 0.35rem;
text-align: left;
}
.info-stack {
display: flex;
flex-direction: column;
align-items: stretch;
}
.info-head {
text-align: center;
}
.info-name {
display: block;
font-size: 0.3rem;
font-weight: 600;
color: var(--wms-text);
margin-bottom: 0.15rem;
}
.mode-tags {
display: flex;
align-items: center;
justify-content: center;
}
.mode-tag {
display: inline-block;
padding: 0.05rem 0.15rem;
border-radius: 50%;
font-size: 0.2rem;
color: var(--wms-primary);
background-color: var(--wms-bg-tint);
margin: 0 0.05rem;
}
.mode-tag--on {
color: var(--wms-success-alt);
background-color: #e8f8ef;
}
.mode-tag--off {
color: var(--wms-danger-strong);
background-color: #fdeaea;
}
.info-divider {
height: 0.01rem;
background-color: #f0f0f0;
margin: 0.15rem 0 0.05rem;
}
.info-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 0.15rem 0;
border-bottom: 0.01rem solid #f4f4f4;
}
.info-row:last-child {
border-bottom: none;
}
.info-label {
font-size: 0.21rem;
color: #888;
flex-shrink: 0;
}
.info-value {
font-size: 0.21rem;
color: var(--wms-text);
text-align: right;
word-break: break-all;
margin-left: 0.25rem;
}
.retry-btn {
width: 1.64rem;
height: 0.36rem;
line-height: 0.36rem;
font-size: 0.21rem;
margin: 0.25rem auto 0;
padding: 0;
border-radius: 0.07rem;
color: var(--wms-primary);
background-color: var(--wms-bg-tint);
border: 0.01rem solid #bcd7ff;
}
/* ===== 打包工作区:左右面板 ===== */
.pack-layout {
flex: 1;
min-height: 0;
display: flex;
}
.pack-left {
/* 主区:吃掉全部剩余空间(右侧固定宽度后,宽屏多出来的宽度全归左侧) */
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.pack-left-empty {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: var(--wms-card-bg);
border: 0.01rem solid #dfe3e8;
border-radius: 0.13rem;
margin-top: 0.1rem;
}
.pack-left-empty-text {
font-size: 0.3rem;
color: #bbb;
}
.pack-left-empty-sub {
font-size: 0.2rem;
color: #ccc;
margin-top: 0.15rem;
}
.pack-right {
/* 侧区:与订单复核/退件页统一为 380px(3.8rem,约占设计宽 1280 的 30%),避免切页时侧栏宽度跳变——
≥1280 恒为 380px(不随屏幕放大,宽屏不会变宽变怪),窄于 1280 与全站等比缩小 */
flex: 0 0 3.8rem;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
margin-left: var(--wms-panel-gap);
}
.pack-card {
background-color: var(--wms-card-bg);
border-radius: 0.13rem;
border: 0.01rem solid #dfe3e8;
padding: 0.1rem 0.2rem 0.15rem 0.2rem;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
.pack-card-title {
font-size: 0.21rem;
font-weight: 600;
color: var(--wms-text);
margin-bottom: 0.1rem;
}
/* 大团购打包倒计时条(搜索框上方) */
.pack-countdown-bar {
margin-bottom: 0.05rem;
background-color: #fff7e6;
border: 0.01rem solid #ffd591;
border-radius: 0.13rem;
padding: 0.04rem 0.15rem;
box-sizing: border-box;
display: flex;
align-items: center;
}
.pack-countdown-bar-text {
font-size: 0.21rem;
font-weight: 600;
color: #d46b08;
}
/* 搜索输入框 */
.pack-search {
background-color: var(--wms-card-bg);
border-radius: 0.13rem;
border: 0.01rem solid #dfe3e8;
padding: 0.04rem 0.15rem;
box-sizing: border-box;
display: flex;
align-items: center;
}
.pack-search-input {
flex: 1;
min-width: 0;
height: 0.36rem; /* 控件 36px */
line-height: 0.36rem;
font-size: 0.21rem;
color: var(--wms-text);
}
.pack-search-clear {
flex-shrink: 0;
/* 点击热区/灰圆 36px(与搜索框等高);字形要小于圆,原来是 0.25rem(25px) 显得又大又挤 */
width: 0.36rem;
height: 0.36rem;
line-height: 0.36rem;
text-align: center;
margin-left: 0.15rem;
font-size: 0.18rem;
color: var(--wms-text-placeholder);
background-color: #e8eaed;
border-radius: 50%;
}
/* 波次 */
.pack-wave {
flex-direction: column;
margin-top: 0.1rem;
}
.pack-wave-head {
display: flex;
align-items: center;
padding: 0.1rem 0.15rem;
border-radius: 0.13rem;
background-color: var(--wms-success-alt);
}
/* 订单被拦截/未复核/已打包等禁止打包状态:运单/波次横幅标红 */
.pack-wave-head--blocked {
background-color: var(--wms-danger-strong);
}
.pack-wave-head .pack-card-title {
margin-bottom: 0;
color: var(--wms-white);
}
.pack-wave-no {
font-size: 0.45rem;
font-weight: 600;
color: var(--wms-white);
margin-left: 0.1rem;
}
/* 打包中角标(开始打包后的明确反馈) */
.pack-wave-status {
margin-left: auto;
font-size: 0.18rem;
line-height: 1.2;
color: var(--wms-white);
background-color: rgba(255, 255, 255, 0.25);
border-radius: 0.07rem;
padding: 0.04rem 0.1rem;
}
.pack-wave-count {
font-size: 0.3rem;
color: var(--wms-white);
margin-left: 0.15rem;
}
/* 货主 / 包材 / 商品总数 */
.pack-meta-line {
display: flex;
flex-wrap: wrap;
align-items: center;
margin-top: 0.1rem;
/* 用负外边距抵消末行/末项多余间距(与 flex gap 无关,是为换行排版) */
margin-bottom: -0.1rem;
}
.pack-meta-item {
display: flex;
flex-direction: row;
align-items: center;
min-width: 0;
margin-right: 0.4rem;
margin-bottom: 0.1rem;
}
.pack-meta-item:last-child {
margin-right: 0;
}
.pack-meta-label {
font-size: 0.2rem;
color: #888;
line-height: 1;
flex-shrink: 0;
}
.pack-meta-value {
font-size: 0.3rem;
color: var(--wms-text);
font-weight: 600;
word-break: break-all;
margin-left: 0.1rem;
line-height: 1;
}
/* 商品明细 */
.pack-detail {
flex: 1;
min-height: 0;
margin-top: 0.1rem;
}
.pack-blocked {
flex: 1;
min-height: 0;
margin-top: 0.1rem;
align-items: center;
justify-content: center;
}
.pack-blocked-text {
font-size: 0.45rem;
color: var(--wms-danger-strong);
font-weight: 600;
}
.pack-detail-title {
display: flex;
align-items: center;
margin-bottom: 0.1rem;
}
.pack-detail-title .pack-card-title {
margin-bottom: 0;
}
.pack-order-type {
font-size: 0.15rem;
line-height: 1;
padding: 0.05rem 0.15rem;
border-radius: 50%;
color: var(--wms-primary);
background-color: var(--wms-bg-tint);
margin-left: 0.15rem;
}
.pack-order-type--group {
color: var(--wms-success-alt);
background-color: #e8f8ef;
}
.pack-order-type--single {
color: var(--wms-primary);
background-color: var(--wms-bg-tint);
}
.pack-detail-scan-stat {
margin-left: 0.35rem;
font-size: 0.17rem;
color: var(--wms-primary);
}
.pack-verify-hint {
margin-left: 0.2rem;
font-size: 0.15rem;
color: var(--wms-text-placeholder);
}
.pack-verify-cancel-btn {
margin: 0 0 0 auto;
height: 0.36rem; /* 控件 36px */
line-height: 0.36rem;
padding: 0 0.2rem;
font-size: 0.15rem;
border-radius: 0.07rem;
color: var(--wms-white);
background-color: var(--wms-danger-strong);
border: 0.01rem solid var(--wms-danger-strong);
}
.pack-detail-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.pack-empty {
flex: 1;
min-height: 1.64rem;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.21rem;
color: #bbb;
}
.pack-detail-scroll {
flex: 1;
min-height: 0;
}
.pack-detail-row {
display: flex;
align-items: center;
padding: 0.04rem 0;
border-bottom: 0.01rem solid #e0e0e0;
/* 行内文字不允许选中:单击/右键就是免验操作,
免得轻点/长按先弹文字选择把手、右键先弹系统菜单 */
user-select: none;
-webkit-user-select: none;
}
.pack-detail-total {
margin-left: 0.35rem;
font-size: 0.35rem;
color: var(--wms-text);
}
.pack-detail-total--auto {
margin-left: auto;
}
.pack-detail-col {
font-size: 0.3rem;
color: var(--wms-text);
word-break: break-all;
}
.pack-detail-col--index {
flex: 0 0 0.41rem;
text-align: center;
color: var(--wms-text-placeholder);
font-size: 0.25rem;
}
.pack-detail-col--image {
flex: 0 0 1.02rem;
display: flex;
align-items: center;
justify-content: center;
}
/* 商品名称 + 商品条码 上下两行 */
.pack-detail-col--info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
justify-content: center;
}
.pack-detail-info-name {
font-size: 0.3rem;
color: var(--wms-text);
word-break: break-all;
}
.pack-detail-info-barcode {
font-size: 0.3rem;
color: #ff8c00;
word-break: break-all;
margin-top: 0.04rem;
}
/* 打包要求 */
.pack-detail-info-req {
font-size: 0.22rem;
color: var(--wms-primary);
word-break: break-all;
margin-top: 0.04rem;
}
.pack-item-img-wrap {
position: relative;
width: 0.82rem;
height: 0.82rem;
flex-shrink: 0;
}
.pack-item-img {
width: 0.82rem;
height: 0.82rem;
border-radius: 0.07rem;
background-color: #f2f4f8;
display: block;
}
.pack-item-img-empty {
width: 0.82rem;
height: 0.82rem;
display: flex;
align-items: center;
justify-content: center;
color: var(--wms-text-placeholder);
font-size: 0.2rem;
background-color: #f2f4f8;
border-radius: 0.07rem;
}
.pack-item-img-badge {
position: absolute;
right: -0.1rem;
top: -0.1rem;
/* 控件 36px */
min-width: 0.36rem;
height: 0.36rem;
line-height: 0.36rem;
padding: 0 0.1rem;
box-sizing: border-box;
border-radius: 0.13rem;
background-color: var(--wms-danger-strong);
color: var(--wms-white);
font-size: 0.15rem;
text-align: center;
}
.pack-detail-col--qty {
flex: 0 0 auto;
min-width: 0.82rem;
padding: 0 0.15rem;
box-sizing: border-box;
text-align: center;
color: var(--wms-primary);
font-size: 0.35rem;
font-weight: 700;
white-space: nowrap;
}
.pack-detail-col--qty-done {
color: var(--wms-white) !important;
}
.pack-detail-row--scanned {
background-color: var(--wms-success-alt);
}
.pack-detail-row--scanned .pack-detail-info-name {
color: var(--wms-white);
}
.pack-detail-row--scanned .pack-detail-col--index {
color: var(--wms-white);
}
.pack-detail-row--scanned .pack-detail-info-barcode {
color: var(--wms-white);
}
.pack-detail-row--scanned .pack-detail-info-req {
color: var(--wms-white);
}
/* 今日打包 */
.pack-today-stats {
display: flex;
flex-wrap: wrap;
align-items: center;
padding: 0.1rem 0;
}
.pack-stat {
display: flex;
flex-direction: row;
align-items: center;
width: 50%;
min-width: 0;
box-sizing: border-box;
padding: 0.05rem 0.15rem;
}
.pack-stat-num {
font-size: 0.25rem;
font-weight: 700;
color: var(--wms-primary);
white-space: nowrap;
flex-shrink: 0;
}
.pack-stat-label {
font-size: 0.18rem;
color: #888;
margin-right: 0.05rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-shrink: 1;
min-width: 0;
}
/* 扫描记录 */
.pack-records {
flex: 1;
min-height: 0;
margin-top: 0.1rem;
overflow: hidden;
padding-left: 0;
padding-right: 0;
}
.pack-records-title {
background-color: var(--wms-primary);
margin: -0.1rem 0 0.1rem 0;
padding: 0.05rem 0.15rem;
}
.pack-records-title-text {
font-size: 0.22rem;
font-weight: 600;
color: var(--wms-white);
}
.pack-records-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.pack-records-scroll {
flex: 1;
min-height: 0;
}
.pack-record-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.1rem 0.15rem;
border-bottom: 0.01rem solid #f4f4f4;
}
.pack-record-item--even {
background-color: #e6effd;
}
.pack-record-text {
flex: 1;
min-width: 0;
font-size: 0.25rem;
color: var(--wms-text);
text-align: left;
word-break: break-all;
}
.pack-record-time {
flex-shrink: 0;
margin-left: 0.15rem;
font-size: 0.2rem;
color: #aaa;
}
/* 隐藏扫码捕获输入框:基准样式在 src/styles/base.css,本页差异项只有位置 ——
必须留在屏幕内(top: 0)才能保持聚焦、派发按键 */
.scan-hidden-input {
top: 0;
}
/* 顶栏按钮区 */
.topbar-actions {
display: flex;
align-items: center;
}
.operator-btn {
min-width: 1.31rem;
height: 0.36rem;
font-size: 0.21rem;
margin: 0 0.15rem 0 0;
padding: 0 0.2rem;
border-radius: 0.07rem;
color: var(--wms-white);
background-color: var(--wms-text-muted);
border: 0.01rem solid var(--wms-text-muted);
display: flex;
align-items: center;
justify-content: center;
line-height: 1;
}
.operator-btn--bound {
color: var(--wms-white);
background-color: var(--wms-success-alt);
border-color: var(--wms-success-alt);
}
.operator-user-icon {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin-right: 0.05rem;
}
.operator-user-icon-head {
width: 0.11rem;
height: 0.11rem;
background-color: var(--wms-card-bg);
border-radius: 50%;
}
.operator-user-icon-body {
width: 0.18rem;
height: 0.08rem;
margin-top: 0.02rem;
background-color: var(--wms-card-bg);
border-radius: 0.07rem 0.07rem 0 0;
}
/* 绑定操作员弹窗 */
.op-mask {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.45);
display: flex;
align-items: center;
justify-content: center;
z-index: 999;
}
.op-dialog {
width: 5.24rem;
background-color: var(--wms-card-bg);
border-radius: 0.13rem;
padding: 0.25rem;
box-sizing: border-box;
}
.op-dialog-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.2rem;
}
.op-dialog-title {
font-size: 0.25rem;
font-weight: 600;
color: var(--wms-text);
}
.op-dialog-close {
font-size: 0.3rem;
color: #aaa;
line-height: 1;
padding: 0 0.05rem;
}
.op-dialog-body {
display: flex;
flex-direction: column;
}
.op-member-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.15rem;
}
.op-member-head-title {
font-size: 0.25rem;
font-weight: 600;
color: var(--wms-text);
}
.op-member-head-count {
font-size: 0.2rem;
line-height: 1.2;
color: var(--wms-primary);
background-color: var(--wms-bg-tint);
border-radius: 0.07rem;
padding: 0.04rem 0.15rem;
}
.op-member-list {
max-height: 2.79rem;
overflow-y: auto;
border: 1px solid #e6ebf2;
border-radius: 0.13rem;
}
.op-member-row {
display: flex;
align-items: center;
padding: 0.15rem 0.2rem;
border-bottom: 1px solid #eef1f6;
}
.op-member-row--last {
border-bottom: none;
}
.op-member-avatar {
width: 0.43rem;
height: 0.43rem;
line-height: 0.43rem;
text-align: center;
border-radius: 50%;
background: linear-gradient(135deg, #4d8dff, var(--wms-primary));
color: var(--wms-white);
font-size: 0.2rem;
flex-shrink: 0;
margin-right: 0.15rem;
}
.op-member-name {
flex: 1;
min-width: 0;
font-size: 0.25rem;
font-weight: 500;
color: var(--wms-text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.op-member-empty {
padding: 0.35rem 0.2rem;
text-align: center;
font-size: 0.21rem;
color: var(--wms-text-placeholder);
background-color: #f7f9fc;
border-radius: 0.13rem;
}
.op-btn--small {
height: 0.36rem;
line-height: 0.36rem;
padding: 0 0.2rem;
font-size: 0.2rem;
flex-shrink: 0;
}
.op-btn {
height: 0.36rem;
line-height: 0.36rem;
font-size: 0.21rem;
padding: 0 0.35rem;
margin: 0;
border-radius: 0.07rem;
border: none;
}
.op-btn--primary {
color: var(--wms-white);
background-color: var(--wms-primary);
}
.op-btn--danger {
color: var(--wms-white);
background-color: var(--wms-danger-strong);
}
.op-btn--cancel {
color: var(--wms-text-secondary);
background-color: #f2f2f2;
}
.op-btn[disabled] {
opacity: 0.5;
}
/* 操作员下线确认弹窗 */
.op-dialog--confirm {
width: 5.57rem;
}
.op-confirm-content {
font-size: 0.3rem;
color: var(--wms-text);
line-height: 1.6;
padding: 0.15rem 0.05rem;
text-align: center;
}
.op-confirm-footer {
margin-top: 0.25rem;
display: flex;
justify-content: flex-end;
}
.op-confirm-footer > .op-btn + .op-btn {
margin-left: 0.15rem;
}
.op-confirm-footer--equal {
justify-content: stretch;
}
.op-confirm-footer--equal .op-btn {
flex: 1;
}
/* 商品图片预览弹窗 */
.img-preview-mask {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.85);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 1200;
}
.img-preview-toolbar {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 0.82rem;
display: flex;
align-items: center;
justify-content: center;
z-index: 2;
}
.img-preview-count {
font-size: 0.21rem;
color: var(--wms-white);
margin-right: 0.1rem;
}
.img-preview-scale {
font-size: 0.2rem;
color: var(--wms-white);
min-width: 0.82rem;
text-align: center;
}
.img-preview-btn {
width: 0.66rem;
height: 0.36rem; /* 控件 36px */
line-height: 0.36rem;
padding: 0;
margin: 0;
font-size: 0.22rem;
border-radius: 0.07rem;
color: var(--wms-white);
background-color: rgba(255, 255, 255, 0.16);
}
.img-preview-btn--close {
width: 0.98rem;
}
/* 工具栏按钮间距:用相邻兄弟外边距(不用 flex gap,避免与其他回退写法混用) */
.img-preview-toolbar > * + * {
margin-left: 0.15rem;
}
.img-preview-body {
position: relative;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
touch-action: none;
user-select: none;
}
.img-preview-img {
width: 90%;
height: 90%;
user-select: none;
-webkit-user-drag: none;
}
.img-preview-arrow {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 0.66rem;
height: 0.66rem;
line-height: 0.66rem;
text-align: center;
font-size: 0.45rem;
color: var(--wms-white);
background-color: rgba(0, 0, 0, 0.4);
border-radius: 50%;
z-index: 2;
user-select: none;
}
.img-preview-arrow--prev {
left: 0.2rem;
}
.img-preview-arrow--next {
right: 0.2rem;
}
</style>