3434 lines
100 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">{{ modeTitle }}</view>
</view>
<view class="topbar-actions">
<button
class="operator-btn"
:class="workbenchMember ? 'operator-btn--bound' : ''"
@click="handleOperatorClick"
>
<view v-if="workbenchMember" class="operator-user-icon">
<view class="operator-user-icon-head"></view>
<view class="operator-user-icon-body"></view>
</view>
<text>{{ topbarOperatorText }}</text>
</button>
<button class="logout-btn" type="warn" @click="handleLogout">退出</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">
<!-- 左面板 70% -->
<view class="pack-left">
<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">
<text class="pack-card-title">{{ isSandan === 1 ? '运单' : '波次' }}</text>
<text class="pack-wave-no">{{ isSandan === 1 ? (currentWaybillCode || '暂无运单') : (currentWaveNo || '暂无波次') }}</text>
<text 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">{{ 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-detail-scan-stat">已扫 {{ scannedKindCount }}/{{ totalKindCount }} 种</text>
<button v-if="isGroupOrder" class="pack-verify-cancel-btn" @click="handleCancelGroupVerify">取消核实</button>
</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) }"
@longpress="handleLongPressProduct(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="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>
</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>
<!-- 右面板 30% -->
<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-num">{{ todayOrderCount }}</text>
<text class="pack-stat-label">单数</text>
</view>
<view class="pack-stat">
<text class="pack-stat-num">{{ todayProductCount }}</text>
<text class="pack-stat-label">商品数</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">
<!-- 已绑定:显示操作员 + 移除 -->
<template v-if="workbenchMember">
<view class="op-bound-row">
<text class="op-bound-label">当前操作员</text>
<text class="op-bound-name">{{ workbenchMember.user_name || '—' }}</text>
</view>
<button
class="op-btn op-btn--danger"
:disabled="operatorRemoving"
@click="handleRemoveOperator"
>{{ operatorRemoving ? '移除中...' : '移除操作员' }}</button>
</template>
<!-- 未绑定:扫码/输入临时码 → 查询 → 绑定 -->
<template v-else>
<view class="op-scan-row">
<input
class="op-scan-input"
v-model="operatorCode"
placeholder="扫描/输入操作员登录临时码"
:focus="operatorInputFocus"
:adjust-position="false"
confirm-type="search"
@confirm="handleOperatorSearch"
@input="handleOperatorInput"
/>
</view>
<view v-if="operatorResult" class="op-result">
<text class="op-result-label">查询到用户</text>
<text class="op-result-name">{{ operatorResult.real_name || '未知用户' }}</text>
</view>
<view v-else-if="operatorSearched && !operatorSearching" class="op-result op-result--empty">
<text class="op-result-name">未找到该用户,请重新扫描</text>
</view>
<button
class="op-btn op-btn--primary"
:disabled="!operatorResult || operatorBinding"
@click="handleBindOperator"
>{{ operatorBinding ? '绑定中...' : '绑定' }}</button>
</template>
</view>
<view class="op-dialog-footer">
<button class="op-btn op-btn--cancel" @click="closeOperatorDialog">关闭</button>
</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="noBarcodeReviewVisible" 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="closeNoBarcodeReview">×</text>
</view>
<view class="op-confirm-content">将「{{ (noBarcodeReviewTarget && noBarcodeReviewTarget.name) || '' }}」标记为已扫?</view>
<view class="op-confirm-footer op-confirm-footer--equal">
<button class="op-btn op-btn--cancel" @click="closeNoBarcodeReview">取消</button>
<button class="op-btn op-btn--primary" @click="confirmNoBarcodeReview">确认</button>
</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="logoutConfirmVisible" class="op-mask">
<view class="op-dialog op-dialog--confirm logout-dialog" @click.stop>
<view class="op-dialog-head">
<text class="op-dialog-title">退出工作台模式</text>
<text class="op-dialog-close" @click="closeLogoutConfirm">×</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="closeLogoutConfirm">取消</button>
<button class="op-btn op-btn--danger" @click="confirmLogout">退出</button>
</view>
</view>
</view>
</view>
</template>
<script>
import {
getWorkbenchInfo,
queryUserByToken,
bindWorkbenchMember,
removeWorkbenchMember,
queryPackOrder,
packOrder,
finishPack,
} from '@/api/index'
// 扫码枪识别参数(广播扫描:扫码枪为键盘 HID 设备,按键事件全局广播)
// 无回车结束符时:停止输入超过该毫秒数视为一次完整扫码,自动提交
const SCAN_IDLE_TIMEOUT = 300
// 自动提交所需的最短内容长度
const SCAN_MIN_LENGTH = 2
// 手动输入识别:相邻按键间隔超过该毫秒数视为手动输入,不自动提交
const SCAN_BURST_MAX_GAP = 100
// 已绑定操作员本地缓存 key(后端暂未提供查询成员接口时,刷新后据此恢复显示)
const MEMBER_STORAGE_KEY = 'workbenchMember'
// 今日打包统计本地缓存 key(前端自行记录,按天存储,跨天重置)
const TODAY_PACK_STORAGE_KEY = 'todayPackStat'
// 语音播报: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',
data() {
return {
workbenchInfo: null,
infoLoading: false,
infoError: '',
keyword: '',
currentWaveNo: '',
waveTotalOrders: '',
storeRemark: '',
packageMaterialName: '',
productCount: 0,
detailList: [],
todayOrderCount: 0,
todayProductCount: 0,
scanRecords: [],
// ---- 广播扫描(扫码枪全局键盘监听,移植自 order/index.vue)----
searchFocus: false,
searchFocused: false,
pageActive: true,
scanTimer: null,
lastScanKeyTime: 0,
scanBurstConfirmed: false,
plusKeyListener: null,
plusKeyBuffer: '',
plusKeyTimer: null,
plusKeyStartedAt: 0,
plusKeyLastAt: 0,
globalKeyListener: null,
globalKeyTargets: [],
enableHiddenInputCapture: false,
scanInputFocus: false,
scanHiddenValue: '',
scanHiddenTimer: null,
scanHiddenRefocusTimer: null,
scanFocusResumeTimer: null,
scanKeyboardSuppressTimers: [],
scanHiddenFocused: false,
scanInputIdleTimer: null,
lastSubmittedScan: { code: '', at: 0 },
// ---- 绑定操作员(工作台成员)----
operatorDialogVisible: false,
operatorInputFocus: false,
operatorCode: '',
operatorSearching: false,
operatorSearched: false,
operatorResult: null,
operatorBinding: false,
operatorRemoving: false,
workbenchMember: null,
operatorSearchTimer: null,
removeConfirmVisible: false,
orderQuerying: false,
// ---- 打包订单类型 / 无条码复核 ----
isSandan: null,
noBarcodeReviewVisible: false,
noBarcodeReviewTarget: null,
cancelVerifyPopupOpen: false,
logoutConfirmVisible: false,
// ---- 打包流程(预检/上报/完成)----
currentOrderCode: '',
currentWaybillCode: '',
currentDeliveryOrderCode: '',
currentOrderRaw: null,
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,
}
},
computed: {
modeTitle() {
const name = this.workbenchInfo?.name
return name ? `打包模式 - ${name}` : '打包模式'
},
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.workbenchMember ? '扫描/输入运单号' : '扫描/输入操作员登录临时码'
},
topbarOperatorText() {
return this.workbenchMember
? this.workbenchMember.user_name || '已绑定'
: '未绑定'
},
removeTargetName() {
return this.workbenchMember?.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
},
hasPackRecord() {
return !!(this.currentOrderRaw || this.currentOrderCode || this.detailList.length > 0)
},
// 订单是否被禁止打包(命中即隐藏商品明细)
orderBlocked() {
return this.checkOrderBlocked().blocked
},
// 商品明细显示条件:已绑定操作员 + 查询成功 + 订单未被禁止打包
showPackDetail() {
return !!(this.workbenchMember && this.hasPackRecord && !this.orderBlocked)
},
orderBlockReason() {
return this.checkOrderBlocked().reason
},
},
watch: {
groupVerifiedCount(val) {
if (!this.isGroupOrder || !this.precheckPassed || this.packStarted || this.packReporting) {
return
}
if (this.totalKindCount > 0 && val >= this.totalKindCount) {
this.handleSubmitGroupPack()
}
},
},
onLoad() {
// 简单守卫:无 token 时回到登录页
if (!uni.getStorageSync('token')) {
uni.reLaunch({
url: '/pages/login/login',
})
return
}
this.restoreWorkbenchMember()
this.loadTodayPackStat()
this.loadWorkbenchInfo()
},
onShow() {
this.pageActive = true
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
},
onHide() {
this.pageActive = false
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.clearScanTimers()
},
methods: {
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.workbenchMember) {
console.log('[packaging][scan] handlePackSearch -> queryAndBindOperator (未绑定操作员)')
this.queryAndBindOperator(kw)
return
}
// 已绑定:团单已进入核实态时,按核实进度决定扫码含义
if (this.isGroupOrder && this.precheckPassed && this.detailList.length > 0) {
if (this.groupVerifiedCount === 0) {
// 尚未开始核实:先按商品条码匹配,匹配不到则视为新运单号切换订单
const matched = this.detailList.some(
(item) =>
(Array.isArray(item.barcodes) && item.barcodes.includes(kw)) ||
item.barcode === kw
)
if (matched) {
this.matchProductBarcode(kw)
} else {
this.queryPackOrderByCode(kw)
}
} else {
// 已开始核实:扫码内容按商品条码核实
this.matchProductBarcode(kw)
}
return
}
// 已绑定:扫码运单号查询订单
this.queryPackOrderByCode(kw)
},
queryPackOrderByCode(code) {
console.log('[packaging][query] queryPackOrderByCode code =', code)
// 未绑定操作员时禁止查询订单,避免绕过绑定流程直接查询
if (!this.workbenchMember) {
this.speak('未绑定操作员')
uni.showToast({ title: '请先绑定操作员', icon: 'none' })
return
}
const token = this.getWorkbenchToken()
if (!token) {
uni.showToast({ title: '工作台登录已失效', icon: 'none' })
return
}
if (this.orderQuerying) {
return
}
this.orderQuerying = true
// 记录搜索的运单号到扫描记录
this.addScanRecord(code)
queryPackOrder(String(token), code)
.then((body) => {
this.applyQueryResult(body, code)
this.keyword = ''
})
.catch(() => {
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
})
.finally(() => {
this.orderQuerying = false
})
},
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 || ''
const bizCode = body?.code ?? raw?.code ?? null
if (Number(bizCode) === 401) {
this.speak('无记录')
this.handleWorkbenchAuthExpired()
return
}
if (flag === 'failure') {
this.speak('无记录')
uni.showToast({
title: body?.message || body?.msg || '未找到对应订单',
icon: 'none',
})
return
}
if (Number(bizCode) === 403) {
this.speak('无记录')
uni.showToast({ title: '工作台登录已失效,请重新登录', icon: 'none' })
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 : []
// 订单类型:isSandan=1 散单、0 团单(团单需扫码商品条码核验)
const rawSandan = this.pickInfoField(raw, {}, ['isSandan', 'is_sandan'])
this.isSandan = rawSandan === '' ? null : Number(rawSandan)
// 记录当前订单上下文(用于预检/上报)
this.currentOrderRaw = raw
this.currentOrderCode = code || ''
this.packStarted = false
this.precheckPassed = false
// 运单号(散单展示用: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',
])
// 商品数量:优先 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 = 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,
}
})
// ---- 预检与分流 ----
const precheck = this.packPrecheck()
if (!precheck.ok) {
this.speak(precheck.speakText)
uni.showToast({ title: precheck.reason, icon: 'none' })
return
}
this.precheckPassed = true
if (this.isGroupOrder) {
// 团单:无商品明细 = 无需核实,直接提交开始打包
if (this.detailList.length === 0) {
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)) {
this.keyword = ''
this.speak('数据一致')
uni.showToast({ title: `${target.name || ''} 已核实`, icon: 'none' })
return
}
// 按商品种类:扫 1 次即标记为已核实,无需扫满数量
target.scannedQty = Number(target.qty) || 0
this.addScanRecord(barcode)
this.keyword = ''
this.speak('数据一致')
uni.showToast({ title: `${target.name || ''} 已核实`, icon: 'none' })
} else {
this.speak('无记录')
uni.showToast({ title: '条码与待核实商品不匹配', icon: 'none' })
}
},
isItemScanned(item) {
const qty = Number(item?.qty) || 0
const scanned = Number(item?.scannedQty) || 0
return qty > 0 && scanned >= qty
},
handleLongPressProduct(item) {
if (!item || !this.isGroupOrder) {
return
}
if (this.isItemScanned(item)) {
uni.showToast({ title: '该商品已全部扫码', icon: 'none' })
return
}
this.noBarcodeReviewTarget = item
this.noBarcodeReviewVisible = true
},
closeNoBarcodeReview() {
this.noBarcodeReviewVisible = false
this.noBarcodeReviewTarget = null
},
confirmNoBarcodeReview() {
const target = this.noBarcodeReviewTarget
if (!target) {
this.closeNoBarcodeReview()
return
}
const total = Number(target.qty) || 0
if (total <= 0) {
uni.showToast({ title: '该商品无数量,无法标记', icon: 'none' })
return
}
if ((Number(target.scannedQty) || 0) >= total) {
uni.showToast({ title: '该商品已全部扫码', icon: 'none' })
this.closeNoBarcodeReview()
return
}
target.scannedQty = total
this.speak('数据一致')
uni.showToast({ title: `已将「${target.name || ''}」标记为已扫`, icon: 'none' })
this.closeNoBarcodeReview()
},
handleCancelGroupVerify() {
this.cancelVerifyPopupOpen = true
},
handleCloseCancelVerifyPopup() {
this.cancelVerifyPopupOpen = false
},
confirmCancelVerify() {
// 清空核实与订单,回到可查询态
this.clearPackState()
this.cancelVerifyPopupOpen = false
this.speak('已取消核实')
uni.showToast({ title: '已取消核实', icon: 'none' })
},
/**
* 打包预检(本地判断,基于 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') {
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) {
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('工作台登录已失效'))
}
const payload = {
token: String(token),
delivery_order_code:
this.currentDeliveryOrderCode || this.currentOrderCode || this.currentWaveNo || '',
status,
pack_time: Date.now(),
wave_no: this.isGroupOrder && this.currentWaveNo ? this.currentWaveNo : undefined,
items_count: this.totalKindCount || undefined,
items_total: this.productCount || 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 || ''
const bizCode = body?.code ?? raw?.code ?? null
if (Number(bizCode) === 401) {
this.handleWorkbenchAuthExpired()
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(() => {
this.packStarted = true
this.recordTodayPack()
this.speak('开始打包')
})
.catch((err) => {
uni.showToast({ title: err?.message || '打包上报失败', icon: 'none' })
})
.finally(() => {
this.packReporting = false
})
},
handleSubmitGroupPack() {
this.startPack()
},
async ensurePackFinishedBeforeLeave() {
const token = this.getWorkbenchToken()
if (!token || !this.packStarted || this.packFinishing) {
return
}
this.packFinishing = true
try {
await finishPack(String(token))
this.packStarted = false
} catch (e) {
// 失败不阻断
} finally {
this.packFinishing = false
}
},
clearPackState() {
this.detailList = []
this.currentWaveNo = ''
this.waveTotalOrders = ''
this.storeRemark = ''
this.packageMaterialName = ''
this.productCount = 0
this.isSandan = null
this.currentOrderCode = ''
this.currentWaybillCode = ''
this.currentDeliveryOrderCode = ''
this.currentOrderRaw = null
this.precheckPassed = false
this.packStarted = false
},
speak(text) {
console.log('[语音播报] speak 入口:', String(text))
const str = String(text || '').trim()
if (!str) {
return
}
// #ifdef APP-PLUS
// 优先 HTTP 语音接口(平板缺中文语音包时仍可发声),失败再走本地 TTS / Web Speech
this.speakViaHttp(str).then((ok) => {
console.log('[语音播报] HTTP 语音接口结果:', ok)
if (!ok) {
this.speakViaTtsOrWebSpeech(str)
}
})
// #endif
// #ifndef APP-PLUS
this.speakViaTtsOrWebSpeech(str)
// #endif
},
speakViaHttp(msg) {
return new Promise((resolve) => {
let settled = false
const finish = (ok) => {
if (!settled) {
settled = true
resolve(ok)
}
}
uni.request({
url: VOICE_API_URL + encodeURIComponent(msg),
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.playVoiceAudio(src, finish)
// 超时兜底:5 秒后仍未播放完成也视为完成,避免一直等待
setTimeout(() => finish(true), 5000)
} catch (e) {
console.error('[语音播报] HTTP 接口解析异常:', e)
finish(false)
}
},
fail: (err) => {
console.warn('[语音播报] HTTP 语音接口请求失败:', err)
finish(false)
},
})
})
},
playVoiceAudio(src, onEnd) {
try {
if (this.voiceAudioContext) {
try {
this.voiceAudioContext.destroy()
} catch (e) {
// 忽略旧实例销毁异常
}
this.voiceAudioContext = null
}
const audio = uni.createInnerAudioContext()
this.voiceAudioContext = audio
audio.onError((e) => {
console.warn('[语音播报] 音频播放错误:', e)
onEnd(false)
})
audio.onEnded(() => {
onEnd(true)
})
audio.src = src
audio.play()
console.log('[语音播报] 音频已开始播放')
} catch (e) {
console.error('[语音播报] 创建音频上下文异常:', e)
onEnd(false)
}
},
destroyVoiceAudio() {
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
},
handleSearchBlur() {
this.searchFocused = false
this.searchFocus = false
if (this.enableHiddenInputCapture) {
this.scheduleScanInputFocus(150)
}
},
activateSearchInput() {
this.searchFocus = true
},
handleSearchInput() {
// 真机(APP-PLUS)扫码枪走 IME 注入文本、无 DOM keydown 字符,
// 停止输入 1000ms 视为一次完整扫码自动查询(@confirm 仍可即时查询)
if (!this.isPageActive() || !this.isAppPlus()) {
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) {
if (!this.isPageActive()) {
return
}
const key = event.key
const activeEl = typeof document !== 'undefined' ? document.activeElement : null
const inInput = !!(activeEl && (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA'))
if (inInput) {
this.touchScanInput()
return
}
if (this.enableHiddenInputCapture) {
return
}
if (event.ctrlKey || event.altKey || event.metaKey) {
return
}
const isPrintable = !!key && key.length === 1
const isPrefixKey = key === 'Tab' || key === 'Enter'
if (!isPrintable && !isPrefixKey) {
return
}
event.preventDefault()
// 绑定操作员弹窗打开时:扫码内容进入弹窗临时码输入框,不进入主搜索框
if (this.operatorDialogVisible) {
if (!this.workbenchMember) {
if (isPrintable) {
this.operatorCode = (this.operatorCode || '') + key
}
this.operatorInputFocus = true
if (key === 'Enter' && (this.operatorCode || '').trim()) {
this.clearOperatorSearchTimer()
this.handleOperatorSearch()
} else if ((this.operatorCode || '').trim()) {
// 扫码枪无回车结束符时:停止输入后静默自动查询
this.touchOperatorScan()
}
}
return
}
if (isPrintable) {
this.keyword = (this.keyword || '') + key
}
this.searchFocus = true
if (key === 'Enter' && (this.keyword || '').trim()) {
this.handlePackSearch()
}
this.touchScanInput()
},
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() {
// 真机扫码枪走 IME 注入文本(无 DOM keydown 字符)、隐藏 input 会丢字,
// 且隐藏 input 聚焦会反复弹出软键盘;改为可见搜索框直接接收扫码(与登录页一致)
this.enableHiddenInputCapture = !this.hasDomKeyboardSupport()
},
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
},
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() {
if (!this.globalKeyTargets || !this.globalKeyListener) {
return
}
this.globalKeyTargets.forEach((target) => {
target.removeEventListener('keydown', this.globalKeyListener, true)
})
this.globalKeyTargets = []
this.globalKeyListener = null
},
parsePlusKeyCodeToChar(keyCode) {
if (keyCode >= 48 && keyCode <= 57) {
return String.fromCharCode(keyCode)
}
if (keyCode >= 65 && keyCode <= 90) {
return String.fromCharCode(keyCode)
}
if (keyCode >= 96 && keyCode <= 105) {
return String(keyCode - 96)
}
if (keyCode === 189 || keyCode === 109) {
return '-'
}
if (keyCode === 190 || keyCode === 110) {
return '.'
}
if (keyCode === 191 || keyCode === 111) {
return '/'
}
return ''
},
attachPlusKeyboardListener() {
if (!this.hasPlusKeyboardSupport()) {
return
}
if (this.plusKeyListener) {
return
}
this.plusKeyListener = (event) => {
if (!this.isPageActive()) {
return
}
const keyCode = Number(event?.keyCode || 0)
const isEnter = keyCode === 13 || keyCode === 66
const text = this.parsePlusKeyCodeToChar(keyCode)
if (text) {
const now = Date.now()
if (!this.plusKeyBuffer) {
this.plusKeyStartedAt = now
}
this.plusKeyLastAt = now
this.plusKeyBuffer += text
this.clearPlusKeyTimer()
this.plusKeyTimer = setTimeout(() => this.flushPlusKeyBuffer('timer'), 420)
return
}
if (isEnter) {
this.flushPlusKeyBuffer('enter')
}
}
// #ifdef APP-PLUS
plus.key.addEventListener('keydown', this.plusKeyListener)
// #endif
},
removePlusKeyboardListener() {
this.clearPlusKeyTimer()
this.plusKeyBuffer = ''
this.plusKeyStartedAt = 0
this.plusKeyLastAt = 0
if (!this.plusKeyListener) {
return
}
// #ifdef APP-PLUS
if (this.hasPlusKeyboardSupport()) {
plus.key.removeEventListener('keydown', this.plusKeyListener)
}
// #endif
this.plusKeyListener = null
},
flushPlusKeyBuffer(trigger = 'timer') {
if (!this.isPageActive()) {
return
}
const code = (this.plusKeyBuffer || '').trim()
this.plusKeyBuffer = ''
this.plusKeyStartedAt = 0
this.plusKeyLastAt = 0
this.clearPlusKeyTimer()
if (!code) {
return
}
this.submitScanCode(code, 'plus')
},
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)
},
suppressSoftKeyboardBurst() {
if (!this.isPageActive()) {
return
}
this.clearKeyboardSuppressTimers()
// 仅聚焦时隐藏一次软键盘,避免扫描过程中反复 hideKeyboard 打断输入
uni.hideKeyboard?.()
},
dismissSoftKeyboard() {
if (!this.isPageActive()) {
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()) {
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
) {
return
}
this.lastSubmittedScan = { code: trimmed, at: now }
console.log('[packaging][scan] submitScanCode source =', source, 'code =', trimmed)
// 绑定操作员弹窗打开时:扫码内容进入弹窗临时码输入框并查询(plus.key / 隐藏 input 链路)
if (this.operatorDialogVisible) {
if (!this.workbenchMember) {
this.operatorCode = trimmed
this.handleOperatorSearch()
}
return
}
this.keyword = trimmed
this.handlePackSearch()
},
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())}`
this.scanRecords.unshift({ text: code, time })
if (this.scanRecords.length > 50) {
this.scanRecords = this.scanRecords.slice(0, 50)
}
},
getTodayKey() {
const d = new Date()
const pad = (n) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
},
loadTodayPackStat() {
try {
const cached = uni.getStorageSync(TODAY_PACK_STORAGE_KEY)
const today = this.getTodayKey()
if (cached && typeof cached === 'object' && cached.date === today) {
this.todayOrderCount = Number(cached.orderCount) || 0
this.todayProductCount = Number(cached.productCount) || 0
return
}
} catch (e) {
// 忽略:读取失败按无记录处理
}
this.todayOrderCount = 0
this.todayProductCount = 0
},
recordTodayPack() {
const today = this.getTodayKey()
// 跨天或首次:先归零
try {
const cached = uni.getStorageSync(TODAY_PACK_STORAGE_KEY)
if (!(cached && typeof cached === 'object' && cached.date === today)) {
this.todayOrderCount = 0
this.todayProductCount = 0
}
} catch (e) {
this.todayOrderCount = 0
this.todayProductCount = 0
}
this.todayOrderCount += 1
this.todayProductCount += Number(this.productCount) || 0
try {
uni.setStorageSync(TODAY_PACK_STORAGE_KEY, {
date: today,
orderCount: this.todayOrderCount,
productCount: this.todayProductCount,
})
} catch (e) {
// 忽略:存储失败不影响界面展示
}
},
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') || ''
},
restoreWorkbenchMember() {
try {
const cached = uni.getStorageSync(MEMBER_STORAGE_KEY)
if (cached && typeof cached === 'object' && (cached.id || cached.user_name)) {
this.workbenchMember = cached
}
} catch (e) {
// 忽略:缓存读取失败不影响页面
}
},
handleOperatorClick() {
// 已绑定:直接弹出移除操作员确认框,不再打开绑定弹窗
if (this.workbenchMember) {
this.handleRemoveOperator()
return
}
this.operatorDialogVisible = true
this.$nextTick(() => {
if (!this.workbenchMember) {
this.operatorInputFocus = true
}
})
},
closeOperatorDialog() {
this.operatorDialogVisible = false
this.operatorInputFocus = false
this.operatorCode = ''
this.operatorResult = null
this.operatorSearched = false
this.clearOperatorSearchTimer()
// 关闭弹窗后把焦点还给隐藏扫码输入框,避免下次扫码首字符丢失
this.scheduleScanInputFocus(150)
},
handleOperatorInput() {
// 手动输入停止后自动查询
const code = String(this.operatorCode || '').trim()
if (!code) {
return
}
this.touchOperatorScan()
},
touchOperatorScan() {
this.clearOperatorSearchTimer()
this.operatorSearchTimer = setTimeout(() => {
this.handleOperatorSearch()
}, 400)
},
clearOperatorSearchTimer() {
if (this.operatorSearchTimer) {
clearTimeout(this.operatorSearchTimer)
this.operatorSearchTimer = null
}
},
handleOperatorSearch() {
const code = String(this.operatorCode || '').trim()
if (!code) {
uni.showToast({ title: '请输入/扫描登录临时码', icon: 'none' })
return
}
console.log('[packaging][scan] handleOperatorSearch operatorCode =', code)
this.operatorSearched = true
this.operatorResult = null
this.queryAndBindOperator(code)
},
queryAndBindOperator(code) {
if (this.operatorSearching) {
return
}
this.operatorSearching = true
queryUserByToken(code)
.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) {
this.handleWorkbenchAuthExpired()
return
}
if (flag === 'failure' || Number(bizCode) === 404) {
this.operatorResult = null
this.speak('未绑定操作员')
uni.showToast({ title: '未找到该用户', icon: 'none' })
return
}
if (Number(bizCode) === 400) {
this.operatorResult = null
this.speak('未绑定操作员')
uni.showToast({ title: '临时码不能为空', icon: 'none' })
return
}
this.operatorResult = {
real_name: this.pickInfoField(raw, body, ['real_name', 'realName']),
wms_account_id: this.pickInfoField(raw, body, ['wms_account_id', 'wmsAccountId']),
}
// 查询命中后自动绑定(一步完成)
this.doBindOperator(
this.operatorResult.real_name,
this.operatorResult.wms_account_id
)
})
.catch(() => {
this.operatorResult = null
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
})
.finally(() => {
this.operatorSearching = false
})
},
handleBindOperator() {
if (!this.operatorResult) {
uni.showToast({ title: '请先查询操作员', icon: 'none' })
return
}
this.doBindOperator(this.operatorResult.real_name, this.operatorResult.wms_account_id)
},
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 || ''
const bizCode = body?.code ?? raw?.code ?? null
if (Number(bizCode) === 401) {
this.handleWorkbenchAuthExpired()
return
}
if (flag === 'failure') {
this.speak('绑定失败,请点击绑定重试')
if (Number(bizCode) === 403) {
uni.showToast({ title: '工作台不存在或 token 无效', icon: 'none' })
} else {
uni.showToast({ title: body?.message || body?.msg || '绑定失败', icon: 'none' })
}
return
}
this.workbenchMember = {
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']),
}
// 本地缓存,刷新后恢复已绑定状态
uni.setStorageSync(MEMBER_STORAGE_KEY, this.workbenchMember)
// 清空主搜索框(未绑定时扫码内容为临时码,绑定后应清空)
this.keyword = ''
this.speak('绑定成功')
uni.showToast({ title: '绑定成功', icon: 'none' })
// 绑定成功后关闭弹窗
this.closeOperatorDialog()
})
.catch(() => {
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
})
.finally(() => {
this.operatorBinding = false
})
},
handleRemoveOperator() {
if (!this.workbenchMember || !this.workbenchMember.id) {
return
}
if (this.operatorRemoving) {
return
}
this.removeConfirmVisible = true
},
closeRemoveConfirm() {
this.removeConfirmVisible = false
},
confirmRemoveOperator() {
if (!this.workbenchMember || !this.workbenchMember.id) {
this.removeConfirmVisible = false
return
}
this.doRemoveOperator(this.workbenchMember.id)
},
/**
* 解绑操作员(统一入口)
* - 先上报打包完成,再调用 workbench.removeMember
* - silent=true:静默解绑(退出流程用),不弹提示、失败不阻断
* - 成功后清空订单/核实数据,防止残留给下一位操作员
*/
async doRemoveOperator(memberId, options = {}) {
const { silent = false } = options
const token = this.getWorkbenchToken()
if (!token) {
if (!silent) {
this.exitToLogin('工作台登录已失效,请重新登录')
}
return 'expired'
}
if (this.operatorRemoving) {
return 'failed'
}
// 1. 先上报打包完成
this.operatorRemoving = true
if (!silent) {
uni.showLoading({ title: '移除中...', mask: true })
}
await this.ensurePackFinishedBeforeLeave()
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) {
// 401:token 失效,统一回登录页
if (!silent) {
this.handleWorkbenchAuthExpired()
}
return 'expired'
}
if (flag === 'failure') {
if (!silent) {
this.speak('移除失败')
uni.showToast({ title: body?.message || body?.msg || '移除失败', icon: 'none' })
}
return 'failed'
}
const removed = Number(raw?.removed ?? body?.removed ?? 0)
if (removed > 0) {
this.workbenchMember = null
uni.removeStorageSync(MEMBER_STORAGE_KEY)
// 清空订单/核实数据,防止残留给下一位操作员
this.clearPackState()
this.removeConfirmVisible = false
this.operatorCode = ''
this.operatorResult = null
this.operatorSearched = false
if (!silent) {
this.speak('移除成功')
uni.showToast({ title: '已移除操作员', icon: 'none' })
}
return 'success'
}
if (!silent) {
this.speak('移除失败')
uni.showToast({ title: '未找到可移除的成员', icon: 'none' })
}
return 'failed'
} catch (e) {
if (!silent) {
this.speak('移除失败')
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
}
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() {
if (this.infoLoading) {
return
}
const token = uni.getStorageSync('token')
if (!token) {
this.exitToLogin('登录状态已失效,请重新登录')
return
}
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 (flag === 'failure' || Number(bizCode) === 401 || Number(bizCode) === 403) {
this.workbenchInfo = null
this.infoError = '工作台不存在或 token 无效'
// token 已失效:清除本地保存的工作台会话,回到登录页重新绑定
this.exitToLogin('工作台登录已失效,请重新登录')
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
})
.catch(() => {
this.workbenchInfo = null
this.infoError = '网络异常,请稍后重试'
})
.finally(() => {
this.infoLoading = false
})
},
/**
* 工作台 token 失效(401):清除本地会话与操作员缓存,回到登录页
*/
handleWorkbenchAuthExpired() {
this.exitToLogin('工作台登录已失效,请重新登录')
},
exitToLogin(message) {
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.workbenchMember = null
// 主登录态一致性判断:一致(工作台会话即主登录态)→ 清主 token;不一致 → 保留主登录态
if (wbToken && wbToken === mainToken) {
uni.removeStorageSync('token')
}
setTimeout(() => {
uni.reLaunch({
url: '/pages/login/login',
})
}, 400)
},
async finishLogout() {
// 1. 上报打包完成
await this.ensurePackFinishedBeforeLeave()
// 2. 静默解绑操作员(操作员归属当前工作台),失败不阻断
if (this.workbenchMember && this.workbenchMember.id) {
const result = await this.doRemoveOperator(this.workbenchMember.id, { silent: true })
// 401 已失效:被动退出,提示并回登录页
if (result === 'expired') {
this.exitToLogin('工作台登录已失效,请重新登录')
return
}
}
// 3. 清除会话回登录页(主动退出不再额外弹 toast)
this.exitToLogin('')
},
handleLogout() {
// 退出前二次确认;工作台登出仅清理本地会话,不调用 user.logout 接口
this.logoutConfirmVisible = true
},
closeLogoutConfirm() {
this.logoutConfirmVisible = false
},
confirmLogout() {
this.logoutConfirmVisible = false
this.finishLogout()
},
},
mounted() {
// 广播扫描:真机/H5 双链路(隐藏 input + plus.key + DOM 全局监听)
this.setupScanCaptureMode()
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
this.suppressSoftKeyboardBurst()
this.scheduleScanInputFocus(260)
this.initNativeTts()
// 页面进入即聚焦搜索框(H5 无隐藏捕获时)
this.$nextTick(() => {
if (!this.enableHiddenInputCapture) {
this.activateSearchInput()
}
})
},
beforeUnmount() {
this.pageActive = false
this.shutdownNativeTts()
this.destroyVoiceAudio()
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.clearScanTimers()
},
}
</script>
<style>
.page {
height: 100vh;
min-width: 960px;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: stretch;
justify-content: flex-start;
background-color: #e8eaed;
overflow: hidden;
}
.mode-topbar {
background-color: #2f7dff;
display: flex;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
padding: 20rpx 32rpx;
}
.mode-title {
font-size: 38rpx;
font-weight: 600;
color: #ffffff;
}
.mode-title-wrap {
display: flex;
align-items: center;
min-width: 0;
}
.mode-logo {
width: 240rpx;
height: 90rpx;
margin-right: 70rpx;
flex-shrink: 0;
}
.logout-btn {
width: 160rpx;
height: 60rpx;
line-height: 60rpx;
font-size: 30rpx;
margin: 0;
padding: 0;
border-radius: 8rpx;
}
.logout-btn::after {
border: none;
}
.mode-main {
flex: 1;
min-height: 0;
box-sizing: border-box;
display: flex;
flex-direction: column;
padding: 16rpx;
overflow: hidden;
}
.mode-card {
background-color: #fff;
border-radius: 16rpx;
padding: 56rpx 40rpx;
box-sizing: border-box;
text-align: center;
}
.mode-card-title {
display: block;
font-size: 38rpx;
color: #333;
font-weight: 600;
margin-bottom: 16rpx;
}
.mode-card-desc {
display: block;
font-size: 30rpx;
color: #888;
line-height: 1.6;
}
.mode-card--center {
text-align: center;
padding: 48rpx 40rpx;
}
.mode-card--info {
text-align: left;
padding: 40rpx;
}
.mode-card--desc {
margin-top: 24rpx;
padding: 32rpx 40rpx;
text-align: left;
}
.info-stack {
display: flex;
flex-direction: column;
align-items: stretch;
}
.info-head {
text-align: center;
}
.info-name {
display: block;
font-size: 42rpx;
font-weight: 600;
color: #333;
margin-bottom: 16rpx;
}
.mode-tags {
display: flex;
align-items: center;
justify-content: center;
}
.mode-tag {
display: inline-block;
padding: 6rpx 20rpx;
border-radius: 999rpx;
font-size: 28rpx;
color: #2f7dff;
background-color: #eef5ff;
margin: 0 8rpx;
}
.mode-tag--on {
color: #2fbf71;
background-color: #e8f8ef;
}
.mode-tag--off {
color: #e64340;
background-color: #fdeaea;
}
.info-divider {
height: 1rpx;
background-color: #f0f0f0;
margin: 20rpx 0 8rpx;
}
.info-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 16rpx 0;
border-bottom: 1rpx solid #f4f4f4;
}
.info-row:last-child {
border-bottom: none;
}
.info-label {
font-size: 30rpx;
color: #888;
flex-shrink: 0;
}
.info-value {
font-size: 30rpx;
color: #333;
text-align: right;
word-break: break-all;
margin-left: 32rpx;
}
.retry-btn {
width: 200rpx;
height: 64rpx;
line-height: 64rpx;
font-size: 30rpx;
margin: 28rpx auto 0;
padding: 0;
border-radius: 8rpx;
color: #2f7dff;
background-color: #eef5ff;
border: 1rpx solid #bcd7ff;
}
.retry-btn::after {
border: none;
}
/* ===== 打包工作区:左右面板 ===== */
.pack-layout {
flex: 1;
min-height: 0;
display: flex;
}
.pack-left {
flex: 7;
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: #fff;
border: 1rpx solid #dfe3e8;
border-radius: 16rpx;
margin-top: 12rpx;
}
.pack-left-empty-text {
font-size: 40rpx;
color: #bbb;
}
.pack-left-empty-sub {
font-size: 28rpx;
color: #ccc;
margin-top: 16rpx;
}
.pack-right {
flex: 3;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
margin-left: 12rpx;
}
.pack-card {
background-color: #fff;
border-radius: 16rpx;
border: 1rpx solid #dfe3e8;
padding: 15rpx 32rpx 28rpx 32rpx;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
.pack-card-title {
font-size: 32rpx;
font-weight: 600;
color: #333;
margin-bottom: 16rpx;
}
/* 搜索输入框 */
.pack-search {
background-color: #fff;
border-radius: 16rpx;
border: 1rpx solid #dfe3e8;
padding: 8rpx 24rpx;
box-sizing: border-box;
display: flex;
align-items: center;
}
.pack-search-input {
flex: 1;
min-width: 0;
height: 48rpx;
line-height: 48rpx;
font-size: 32rpx;
color: #333;
}
.pack-search-clear {
flex-shrink: 0;
width: 48rpx;
height: 48rpx;
line-height: 48rpx;
text-align: center;
margin-left: 16rpx;
font-size: 36rpx;
color: #999;
background-color: #e8eaed;
border-radius: 50%;
}
/* 波次 */
.pack-wave {
flex-direction: column;
margin-top: 12rpx;
}
.pack-wave-head {
display: flex;
align-items: center;
padding: 16rpx 24rpx;
border-radius: 12rpx;
background-color: #2fbf71;
}
.pack-wave-head .pack-card-title {
margin-bottom: 0;
color: #ffffff;
}
.pack-wave-no {
font-size: 70rpx;
font-weight: 600;
color: #ffffff;
margin-left: 12rpx;
}
.pack-wave-count {
font-size: 50rpx;
color: #ffffff;
margin-left: auto;
}
/* 货主 / 包材 / 商品总数 */
.pack-meta-line {
display: flex;
align-items: center;
margin-top: 20rpx;
}
.pack-meta-item {
display: flex;
flex-direction: row;
align-items: center;
min-width: 0;
}
.pack-meta-item + .pack-meta-item {
margin-left: 48rpx;
}
.pack-meta-label {
font-size: 28rpx;
color: #888;
line-height: 1;
flex-shrink: 0;
}
.pack-meta-value {
font-size: 45rpx;
color: #333;
font-weight: 600;
word-break: break-all;
margin-left: 12rpx;
line-height: 1;
}
/* 商品明细 */
.pack-detail {
flex: 1;
min-height: 0;
margin-top: 12rpx;
}
.pack-blocked {
flex: 1;
min-height: 0;
margin-top: 12rpx;
align-items: center;
justify-content: center;
}
.pack-blocked-text {
font-size: 64rpx;
color: #e64340;
font-weight: 600;
}
.pack-detail-title {
display: flex;
align-items: center;
margin-bottom: 16rpx;
}
.pack-detail-title .pack-card-title {
margin-bottom: 0;
}
.pack-order-type {
font-size: 24rpx;
line-height: 1;
padding: 8rpx 20rpx;
border-radius: 999rpx;
color: #2f7dff;
background-color: #eef5ff;
margin-left: 16rpx;
}
.pack-order-type--group {
color: #2fbf71;
background-color: #e8f8ef;
}
.pack-order-type--single {
color: #2f7dff;
background-color: #eef5ff;
}
.pack-detail-scan-stat {
margin-left: auto;
font-size: 30rpx;
color: #2f7dff;
}
.pack-verify-cancel-btn {
margin: 0 0 0 16rpx;
height: 56rpx;
line-height: 56rpx;
padding: 0 24rpx;
font-size: 26rpx;
border-radius: 8rpx;
color: #ffffff;
background-color: #e64340;
border: 1rpx solid #e64340;
}
.pack-verify-cancel-btn::after {
border: none;
}
.pack-detail-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.pack-empty {
flex: 1;
min-height: 200rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 30rpx;
color: #bbb;
}
.pack-detail-scroll {
flex: 1;
min-height: 0;
}
.pack-detail-row {
display: flex;
align-items: center;
padding: 8rpx 0;
border-bottom: 1rpx solid #e0e0e0;
}
.pack-detail-col {
font-size: 45rpx;
color: #333;
word-break: break-all;
}
.pack-detail-col--index {
flex: 0 0 60rpx;
text-align: center;
color: #2f7dff;
font-size: 40rpx;
}
.pack-detail-col--image {
flex: 0 0 150rpx;
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: 45rpx;
color: #333;
word-break: break-all;
}
.pack-detail-info-barcode {
font-size: 45rpx;
color: #ff8c00;
word-break: break-all;
margin-top: 8rpx;
}
.pack-item-img-wrap {
position: relative;
width: 120rpx;
height: 120rpx;
flex-shrink: 0;
}
.pack-item-img {
width: 120rpx;
height: 120rpx;
border-radius: 8rpx;
background-color: #f2f4f8;
display: block;
}
.pack-item-img-empty {
width: 120rpx;
height: 120rpx;
display: flex;
align-items: center;
justify-content: center;
color: #999;
font-size: 28rpx;
background-color: #f2f4f8;
border-radius: 8rpx;
}
.pack-item-img-badge {
position: absolute;
right: -12rpx;
top: -12rpx;
min-width: 40rpx;
height: 40rpx;
line-height: 40rpx;
padding: 0 10rpx;
box-sizing: border-box;
border-radius: 20rpx;
background-color: #e64340;
color: #fff;
font-size: 20rpx;
text-align: center;
}
.pack-detail-col--qty {
flex: 0 0 120rpx;
text-align: center;
color: #2f7dff;
}
.pack-detail-col--qty-done {
color: #ffffff !important;
}
.pack-detail-row--scanned {
background-color: #2fbf71;
}
.pack-detail-row--scanned .pack-detail-info-name {
color: #ffffff;
}
.pack-detail-row--scanned .pack-detail-col--index {
color: #ffffff;
}
.pack-detail-row--scanned .pack-detail-info-barcode {
color: #ffffff;
}
/* 今日打包 */
.pack-today-stats {
display: flex;
align-items: center;
justify-content: space-around;
padding: 16rpx 0;
}
.pack-stat {
display: flex;
flex-direction: column;
align-items: center;
}
.pack-stat-num {
font-size: 50rpx;
font-weight: 700;
color: #2f7dff;
}
.pack-stat-label {
font-size: 28rpx;
color: #888;
margin-top: 8rpx;
}
/* 扫描记录 */
.pack-records {
flex: 1;
min-height: 0;
margin-top: 12rpx;
overflow: hidden;
padding-left: 0;
padding-right: 0;
}
.pack-records-title {
background-color: #2f7dff;
margin: -15rpx 0 16rpx 0;
padding: 10rpx 20rpx;
}
.pack-records-title-text {
font-size: 32rpx;
font-weight: 600;
color: #fff;
}
.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: 14rpx 20rpx;
border-bottom: 1rpx solid #f4f4f4;
}
.pack-record-item--even {
background-color: #e6effd;
}
.pack-record-text {
flex: 1;
min-width: 0;
font-size: 40rpx;
color: #333;
text-align: left;
word-break: break-all;
}
.pack-record-time {
flex-shrink: 0;
margin-left: 16rpx;
font-size: 28rpx;
color: #aaa;
}
/* 隐藏扫码捕获输入框(真机 WebView 保持聚焦派发按键) */
.scan-hidden-input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
left: -9999px;
top: 0;
}
/* 顶栏按钮区 */
.topbar-actions {
display: flex;
align-items: center;
}
.operator-btn {
min-width: 160rpx;
height: 60rpx;
font-size: 30rpx;
margin: 0 16rpx 0 0;
padding: 0 24rpx;
border-radius: 8rpx;
color: #fff;
background-color: #909399;
border: 1rpx solid #909399;
display: flex;
align-items: center;
justify-content: center;
line-height: 1;
}
.operator-btn::after {
border: none;
}
.operator-btn--bound {
color: #fff;
background-color: #2fbf71;
border-color: #2fbf71;
}
.operator-user-icon {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin-right: 8rpx;
}
.operator-user-icon-head {
width: 14rpx;
height: 14rpx;
background-color: #fff;
border-radius: 50%;
}
.operator-user-icon-body {
width: 22rpx;
height: 10rpx;
margin-top: 3rpx;
background-color: #fff;
border-radius: 10rpx 10rpx 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: 560rpx;
background-color: #fff;
border-radius: 16rpx;
padding: 32rpx;
box-sizing: border-box;
}
.op-dialog-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 24rpx;
}
.op-dialog-title {
font-size: 36rpx;
font-weight: 600;
color: #333;
}
.op-dialog-close {
font-size: 44rpx;
color: #aaa;
line-height: 1;
padding: 0 8rpx;
}
.op-dialog-body {
display: flex;
flex-direction: column;
}
.op-dialog-body > .op-btn {
margin-top: 24rpx;
}
.op-bound-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx 24rpx;
background-color: #f7f9fc;
border-radius: 12rpx;
}
.op-bound-label {
font-size: 30rpx;
color: #888;
}
.op-bound-name {
font-size: 34rpx;
font-weight: 600;
color: #333;
}
.op-scan-row {
background-color: #f7f9fc;
border-radius: 12rpx;
padding: 20rpx 24rpx;
}
.op-scan-input {
height: 60rpx;
line-height: 60rpx;
font-size: 32rpx;
color: #333;
}
.op-result {
padding: 20rpx 24rpx;
background-color: #eef5ff;
border-radius: 12rpx;
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 24rpx;
}
.op-result--empty {
background-color: #fdeaea;
}
.op-result-label {
font-size: 28rpx;
color: #888;
}
.op-result-name {
font-size: 34rpx;
font-weight: 600;
color: #333;
}
.op-result--empty .op-result-name {
font-size: 30rpx;
font-weight: 400;
color: #e64340;
}
.op-dialog-footer {
margin-top: 32rpx;
display: flex;
justify-content: flex-end;
}
.op-btn {
height: 84rpx;
line-height: 84rpx;
font-size: 30rpx;
padding: 0 40rpx;
margin: 0;
border-radius: 8rpx;
border: none;
}
.op-btn::after {
border: none;
}
.op-btn--primary {
color: #fff;
background-color: #2f7dff;
}
.op-btn--danger {
color: #fff;
background-color: #e64340;
}
.op-btn--cancel {
color: #666;
background-color: #f2f2f2;
}
.op-btn[disabled] {
opacity: 0.5;
}
/* 移除操作员确认弹窗 */
.op-dialog--confirm {
width: 680rpx;
}
/* 退出工作台确认弹窗(宽度更大) */
.logout-dialog {
width: 900rpx;
}
.op-confirm-content {
font-size: 40rpx;
color: #333;
line-height: 1.6;
padding: 16rpx 8rpx;
text-align: center;
}
.op-confirm-footer {
margin-top: 32rpx;
display: flex;
justify-content: flex-end;
}
.op-confirm-footer > .op-btn + .op-btn {
margin-left: 16rpx;
}
.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: 100rpx;
display: flex;
align-items: center;
justify-content: center;
z-index: 2;
}
.img-preview-count {
font-size: 30rpx;
color: #fff;
margin-right: 12rpx;
}
.img-preview-scale {
font-size: 28rpx;
color: #fff;
min-width: 100rpx;
text-align: center;
}
.img-preview-btn {
width: 80rpx;
height: 60rpx;
line-height: 60rpx;
padding: 0;
margin: 0;
font-size: 32rpx;
border-radius: 8rpx;
color: #fff;
background-color: rgba(255, 255, 255, 0.16);
}
.img-preview-btn::after {
border: none;
}
.img-preview-btn--close {
width: 120rpx;
}
/* gap 兼容回退:真机 WebView 不支持 flex gap */
.img-preview-toolbar > * + * {
margin-left: 16rpx;
}
.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: 80rpx;
height: 80rpx;
line-height: 80rpx;
text-align: center;
font-size: 60rpx;
color: #fff;
background-color: rgba(0, 0, 0, 0.4);
border-radius: 50%;
z-index: 2;
user-select: none;
}
.img-preview-arrow--prev {
left: 24rpx;
}
.img-preview-arrow--next {
right: 24rpx;
}
</style>