WMS_PDA/pages/work/order/picking.vue

2365 lines
66 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="order-picking-page">
<view class="normar_container">
<page-nav :title="title" @click.native="handleTitleClick">
<template #left>
<view class="nav-action-btn nav-action-btn--bind" @click="openBindCartPopup">
<text class="nav-action-btn__text">拣货车</text>
</view>
</template>
<template #right>
<view class="nav-right" :class="{ 'nav-right--disabled': !hasActiveTask }">
<u-icon name="more-dot-fill" size="22" @click="openActionsPopup"></u-icon>
</view>
</template>
</page-nav>
<view v-if="!taskId" class="empty-wrap">
<view class="empty-card">
<u-icon name="scan" size="72rpx" color="#2979ff"></u-icon>
<text class="empty-title">开始拣货</text>
<text class="empty-desc">扫描快递单号或波次号开始拣货</text>
</view>
</view>
<view v-else class="content-wrap">
<view v-if="loadingTaskDetail" class="loading-wrap">
<text class="loading-text">任务详情加载中...</text>
</view>
<template v-else>
<view class="top-detail-panel">
<view v-if="!selectedPickItem" class="list-empty">暂无拣货数据</view>
<view v-else class="pick-card">
<view class="detail-main">
<view class="detail-main-left">
<view v-if="getSelectedImageList().length > 0" class="goods-image-single" @click="handleImageClick">
<u-image
class="goods-image"
:src="getCurrentDisplayImage()"
width="200rpx"
height="200rpx"
mode="aspectFill"
></u-image>
<view v-if="getSelectedImageList().length > 1" class="image-index-badge">
<text class="image-index-text">{{ currentImageIndex + 1 }}/{{ getSelectedImageList().length }}</text>
</view>
</view>
<view v-else class="pick-image-empty">{{ selectedItemImageLoading ? '图片加载中...' : '暂无商品图片' }}</view>
</view>
<view
class="detail-main-right"
:class="{ 'detail-main-right--matched': isSelectedItemMatchedHighlight() }"
@click="goProductQueryByCurrentBarcode"
>
<view class="pick-card__head">
<text class="pick-name">{{ selectedPickItem.itemName || '--' }}</text>
<text v-if="boundCartNo" class="pick-cart-tag">拣货车:{{ boundCartNo }}{{ boundCartName ? `(${boundCartName})` : '' }}</text>
</view>
<view class="pick-row"><text class="pick-label">商品条码:</text><text class="pick-value">{{ selectedItemBarcodeLoading ? '条码加载中...' : (selectedItemBarcode || '--') }}</text></view>
<view class="pick-row"><text class="pick-label">库位:</text><text class="pick-value pick-value--highlight">{{ selectedPickItem.spaceName || '--' }}</text></view>
<view class="pick-row"><text class="pick-label">应拣总数:</text><text class="pick-value">{{ selectedPickItem.totalQty }}</text></view>
</view>
</view>
<view class="alloc-panel">
<view class="pick-row pick-row--top"><text class="pick-label">分配篮号:</text><text class="pick-value">篮子总数:{{ boxList.length }}</text></view>
<scroll-view class="alloc-scroll" scroll-y>
<view class="alloc-wrap" v-if="selectedPickItem.boxAllocations && selectedPickItem.boxAllocations.length">
<view class="alloc-item" v-for="alloc in selectedPickItem.boxAllocations" :key="`${selectedPickItem.itemCode}-${alloc.boxId}`">
<text class="alloc-text">{{ alloc.boxNo }}号篮: {{ alloc.allocatedQty }}</text>
</view>
</view>
<view v-else class="alloc-empty">暂无分配</view>
<view class="alloc-safe-bottom"></view>
</scroll-view>
<view class="alloc-nav" v-if="filteredPickItems.length > 1">
<view
class="alloc-nav-btn"
:class="{ 'alloc-nav-btn--disabled': selectedIndex <= 0 }"
@click="handlePrevItem"
>
<text class="alloc-nav-btn__text">上一个</text>
</view>
<view
class="alloc-nav-btn alloc-nav-btn--primary"
:class="{ 'alloc-nav-btn--disabled': selectedIndex >= filteredPickItems.length - 1 }"
@click="handleNextItem"
>
<text class="alloc-nav-btn__text">下一个</text>
</view>
</view>
</view>
</view>
</view>
<scroll-view class="bottom-grid-panel" scroll-y>
<view v-if="filteredPickItems.length === 0" class="list-empty">暂无拣货数据</view>
<view v-else class="index-grid">
<view
v-for="(item, index) in filteredPickItems"
:key="`${item.spaceId}-${item.itemCode}-${index}`"
class="index-cell"
:class="{ 'index-cell--active': selectedIndex === index, 'index-cell--picked': isPickItemPicked(item) }"
@click="selectPickItem(index)"
>
<text class="index-text">{{ index + 1 }}</text>
</view>
</view>
<view class="safe-bottom"></view>
</scroll-view>
</template>
</view>
</view>
<!-- ====== 调试输入框 - 长按标题5次切换 ====== -->
<view v-if="showDebugInput" class="debug-input-bar" @touchstart.stop>
<text class="debug-input-label">调试扫描</text>
<input
class="debug-input-field"
v-model="debugInput"
:focus="debugInputFocus"
placeholder="输入模拟扫描内容"
@confirm="handleDebugSubmit"
@blur="handleDebugSubmit"
/>
<text class="debug-input-btn" @click="handleDebugSubmit">发送</text>
<text class="debug-input-close" @click="showDebugInput = false">✕</text>
</view>
<u-popup :show="bindCartPopupVisible" mode="bottom" :closeable="true" border-radius="20" @close="closeBindCartPopup">
<view class="bind-cart-popup">
<view class="popup-header">
<text class="popup-title">绑定拣货车</text>
</view>
<view class="bind-cart-form">
<view class="bind-cart-search-row">
<u-input v-model="bindCartNoInput" placeholder="请输入或扫描拣货车编号" clearable></u-input>
<view class="bind-cart-query-btn" @click="handleBindCartSearch">查询</view>
</view>
</view>
<scroll-view class="bind-cart-list" scroll-y>
<view v-if="bindCartListLoading" class="bind-cart-empty">拣货车列表加载中...</view>
<view v-else-if="bindCartList.length === 0" class="bind-cart-empty">暂无拣货车数据</view>
<view
v-else
v-for="item in bindCartList"
:key="getBindCartItemKey(item)"
class="bind-cart-item"
:class="{ 'bind-cart-item--active': isBindCartSelected(item) }"
@click="selectBindCartItem(item)"
>
<view class="bind-cart-item__head">
<text class="bind-cart-item__title">{{ getBindCartNo(item) }}{{ getBindCartName(item) ? `(${getBindCartName(item)})` : '' }}</text>
<text v-if="isBindCartBound(item)" class="bind-cart-item__bound">已绑定</text>
</view>
</view>
</scroll-view>
<view class="bind-cart-actions">
<view class="bind-cart-btn bind-cart-btn--cancel" @click="closeBindCartPopup">取消</view>
<view class="bind-cart-btn bind-cart-btn--confirm" @click="confirmBindCart">确定</view>
</view>
</view>
</u-popup>
<!-- 操作弹窗 -->
<u-popup :show="showActionsPopup" mode="bottom" :closeable="true" border-radius="20" @close="showActionsPopup = false">
<view class="actions-popup">
<view class="actions-popup-title">操作</view>
<view class="actions-popup-body">
<view
v-if="canCancelPickTask"
class="actions-popup-btn actions-popup-btn--cancel"
@click="handleCancelPick"
>
<text class="actions-popup-btn__text actions-popup-btn__text--cancel">取消拣货</text>
</view>
<view class="actions-popup-btn actions-popup-btn--complete" @click="handleCompletePick">
<text class="actions-popup-btn__text actions-popup-btn__text--complete">完成拣货</text>
</view>
</view>
<view class="actions-popup-footer">
<view class="actions-popup-close-btn" @click="showActionsPopup = false">关闭</view>
</view>
</view>
</u-popup>
</view>
</template>
<script>
import voice from '@/core/utils/voice';
export default {
data() {
return {
title: '订单拣货',
taskId: '',
keyword: '',
debugInput: '',
showDebugInput: false,
debugInputFocus: false,
selectedIndex: 0,
loadingTaskDetail: false,
selectedItemImageLoading: false,
selectedItemImageUrl: '',
selectedItemImageUrls: [],
currentImageIndex: 0,
itemImageCache: {},
itemImageListCache: {},
selectedItemBarcodeLoading: false,
selectedItemBarcode: '',
itemBarcodeCache: {},
pickedItemKeys: [],
pickedStateStorageKey: 'order_picking_picked_state_v1',
confirmedOrderIds: [],
confirmedOrderStateStorageKey: 'order_picking_confirmed_order_ids_v1',
boundCartNo: '',
boundCartName: '',
bindCartNoInput: '',
bindCartPopupVisible: false,
bindCartListLoading: false,
bindCartList: [],
selectedBindCartItem: null,
bindCartQueryKeyword: '',
boundCartStorageKey: 'order_picking_bound_cart_v1',
showActionsPopup: false,
submittingWavePickTask: false,
currentWavePickSubmitPromise: null,
wavePickSubmitQueue: [],
isNetworkConnected: true,
isFlushingWavePickSubmitQueue: false,
taskInfo: {
taskId: '',
taskNo: '',
batchNo: '',
status: 0,
creatorId: '',
creatorName: ''
},
boxList: [],
pickingSummary: {
totalLines: 0,
totalQty: 0,
distinctSpaces: 0,
distinctItems: 0
},
pickingView: {
modeCode: '',
modeName: '--',
items: []
}
};
},
computed: {
hasActiveTask() {
const currentTaskId = Number(this.taskInfo?.taskId || this.taskId || 0);
return Number.isFinite(currentTaskId) && currentTaskId > 0;
},
currentLoginUserId() {
return String(
this.$store?.getters?.user?.id ||
this.$store?.getters?.user?.user_id ||
this.$store?.getters?.user?.employees_id ||
this.$store?.getters?.roleId ||
''
).trim();
},
canCancelPickTask() {
const creatorId = String(this.taskInfo?.creatorId || '').trim();
const currentUserId = String(this.currentLoginUserId || '').trim();
if (!creatorId || !currentUserId) {
return true;
}
return creatorId === currentUserId;
},
modeName() {
return this.pickingView.modeName || '--';
},
filteredPickItems() {
return Array.isArray(this.pickingView.items) ? this.pickingView.items : [];
},
selectedPickItem() {
if (!this.filteredPickItems.length) {
return null;
}
return this.filteredPickItems[this.selectedIndex] || this.filteredPickItems[0];
}
},
watch: {
filteredPickItems(newList) {
if (!Array.isArray(newList) || newList.length === 0) {
this.selectedIndex = 0;
return;
}
if (this.selectedIndex > newList.length - 1) {
this.selectedIndex = 0;
}
},
selectedPickItem: {
handler(item) {
this.loadSelectedItemImage(item);
this.loadSelectedItemBarcode(item);
},
immediate: true
}
},
onLoad(options) {
this.initWavePickSubmitNetworkStatus();
this.bindNetworkStatusChange();
this.$store.dispatch('broadcast/setCallbacks', {
onResult: this.handleBroadcastScan
});
this.$store.dispatch('broadcast/start');
const incomingTaskId = options?.taskId || options?.task_id || '';
if (incomingTaskId !== '') {
this.taskId = String(incomingTaskId || '').trim();
this.requestWavePickTaskDetail();
return;
}
this.requestCurrentWavePickTask();
},
onShow() {
this.$store.dispatch('broadcast/resume');
},
onHide() {
this.$store.dispatch('broadcast/stop');
},
onUnload() {
this.unbindNetworkStatusChange();
this.$store.dispatch('broadcast/stop');
},
methods: {
initWavePickSubmitNetworkStatus() {
uni.getNetworkType({
success: res => {
const networkType = String(res?.networkType || '').toLowerCase();
this.isNetworkConnected = networkType !== 'none';
if (this.isNetworkConnected) {
this.flushWavePickSubmitQueue();
}
},
fail: () => {
this.isNetworkConnected = true;
}
});
},
bindNetworkStatusChange() {
if (this._networkStatusChangeHandler) {
return;
}
this._networkStatusChangeHandler = res => {
const isConnected = Boolean(res?.isConnected) && String(res?.networkType || '').toLowerCase() !== 'none';
this.isNetworkConnected = isConnected;
if (isConnected) {
this.flushWavePickSubmitQueue();
}
};
uni.onNetworkStatusChange(this._networkStatusChangeHandler);
},
unbindNetworkStatusChange() {
if (!this._networkStatusChangeHandler) {
return;
}
if (typeof uni.offNetworkStatusChange === 'function') {
uni.offNetworkStatusChange(this._networkStatusChangeHandler);
}
this._networkStatusChangeHandler = null;
},
enqueueWavePickSubmitTask(taskIdNumber) {
const normalizedTaskId = Number(taskIdNumber || 0);
if (!normalizedTaskId) {
return;
}
if (this.wavePickSubmitQueue.includes(normalizedTaskId)) {
return;
}
this.wavePickSubmitQueue.push(normalizedTaskId);
},
dequeueWavePickSubmitTask(taskIdNumber) {
const normalizedTaskId = Number(taskIdNumber || 0);
this.wavePickSubmitQueue = this.wavePickSubmitQueue.filter(id => Number(id) !== normalizedTaskId);
},
async flushWavePickSubmitQueue() {
if (!this.isNetworkConnected || this.isFlushingWavePickSubmitQueue || !this.wavePickSubmitQueue.length) {
return;
}
this.isFlushingWavePickSubmitQueue = true;
try {
while (this.isNetworkConnected && this.wavePickSubmitQueue.length) {
const taskIdNumber = Number(this.wavePickSubmitQueue[0] || 0);
if (!taskIdNumber) {
this.wavePickSubmitQueue.shift();
continue;
}
try {
const response = await this.requestWavePickTaskSubmit(taskIdNumber, 8000);
this.handleWavePickTaskSubmitResponse(response);
this.wavePickSubmitQueue.shift();
} catch (error) {
if (!this.isNetworkConnected || this.isWeakNetworkError(error)) {
break;
}
break;
}
}
} finally {
this.isFlushingWavePickSubmitQueue = false;
}
},
getSelectedImageList() {
if (Array.isArray(this.selectedItemImageUrls) && this.selectedItemImageUrls.length) {
return this.selectedItemImageUrls;
}
if (this.selectedItemImageUrl) {
return [this.selectedItemImageUrl];
}
return [];
},
getCurrentDisplayImage() {
const list = this.getSelectedImageList();
if (!list.length) {
return '';
}
const index = Math.min(this.currentImageIndex, list.length - 1);
return list[index] || list[0] || '';
},
handleImageClick() {
this.previewSelectedItemImage();
},
normalizeScanResult(scanResult) {
if (!scanResult) {
return '';
}
if (typeof scanResult === 'string') {
return scanResult.trim();
}
if (typeof scanResult?.result === 'string') {
return scanResult.result.trim();
}
if (typeof scanResult?.data === 'string') {
return scanResult.data.trim();
}
return '';
},
normalizeBarcodeText(barcode) {
return String(barcode || '').trim().replace(/\s+/g, '').toUpperCase();
},
getPickItemUniqueKey(item) {
if (!item || typeof item !== 'object') {
return '';
}
const stockId = String(item.stockId || '').trim();
const spaceId = String(item.spaceId || '').trim();
const itemCode = String(item.itemCode || '').trim();
return [stockId, spaceId, itemCode].join('|');
},
getCurrentTaskIdNumber() {
return Number(this.taskInfo?.taskId || this.taskId || 0);
},
loadPickedStateMap() {
try {
const raw = uni.getStorageSync(this.pickedStateStorageKey);
if (!raw) {
return {};
}
if (typeof raw === 'string') {
const parsed = JSON.parse(raw);
return parsed && typeof parsed === 'object' ? parsed : {};
}
return raw && typeof raw === 'object' ? raw : {};
} catch (error) {
return {};
}
},
savePickedStateMap(map) {
try {
uni.setStorageSync(this.pickedStateStorageKey, map || {});
} catch (error) {
// ignore storage write error
}
},
persistPickedStateForCurrentTask() {
const taskIdNumber = this.getCurrentTaskIdNumber();
if (!taskIdNumber) {
return;
}
const map = this.loadPickedStateMap();
map[String(taskIdNumber)] = Array.from(new Set(this.pickedItemKeys.filter(Boolean)));
this.savePickedStateMap(map);
},
restorePickedStateForCurrentTask() {
const taskIdNumber = this.getCurrentTaskIdNumber();
if (!taskIdNumber) {
this.pickedItemKeys = [];
this.boundCartNo = '';
return;
}
const map = this.loadPickedStateMap();
const restored = Array.isArray(map[String(taskIdNumber)]) ? map[String(taskIdNumber)] : [];
this.pickedItemKeys = restored.filter(Boolean);
},
loadConfirmedOrderStateMap() {
try {
const raw = uni.getStorageSync(this.confirmedOrderStateStorageKey);
if (!raw) {
return {};
}
if (typeof raw === 'string') {
const parsed = JSON.parse(raw);
return parsed && typeof parsed === 'object' ? parsed : {};
}
return raw && typeof raw === 'object' ? raw : {};
} catch (error) {
return {};
}
},
saveConfirmedOrderStateMap(map) {
try {
uni.setStorageSync(this.confirmedOrderStateStorageKey, map || {});
} catch (error) {
// ignore storage write error
}
},
normalizeConfirmedOrderIds(orderIds) {
if (!Array.isArray(orderIds)) {
return [];
}
return Array.from(new Set(orderIds
.map(id => Number(id))
.filter(id => Number.isFinite(id) && id > 0)));
},
persistConfirmedOrderIdsForCurrentTask(orderIds) {
const taskIdNumber = this.getCurrentTaskIdNumber();
const normalizedOrderIds = this.normalizeConfirmedOrderIds(orderIds);
if (!taskIdNumber) {
this.confirmedOrderIds = normalizedOrderIds;
return;
}
const map = this.loadConfirmedOrderStateMap();
map[String(taskIdNumber)] = normalizedOrderIds;
this.saveConfirmedOrderStateMap(map);
this.confirmedOrderIds = normalizedOrderIds;
},
restoreConfirmedOrderIdsForCurrentTask() {
const taskIdNumber = this.getCurrentTaskIdNumber();
if (!taskIdNumber) {
this.confirmedOrderIds = [];
return;
}
const map = this.loadConfirmedOrderStateMap();
this.confirmedOrderIds = this.normalizeConfirmedOrderIds(map[String(taskIdNumber)]);
},
clearConfirmedOrderIdsForTask(taskIdNumber) {
const normalizedTaskId = Number(taskIdNumber || 0);
if (!normalizedTaskId) {
this.confirmedOrderIds = [];
return;
}
const map = this.loadConfirmedOrderStateMap();
delete map[String(normalizedTaskId)];
this.saveConfirmedOrderStateMap(map);
if (normalizedTaskId === this.getCurrentTaskIdNumber()) {
this.confirmedOrderIds = [];
}
},
extractConfirmedOrderIdsFromSubmitResponse(response) {
const payload = response || {};
const candidateLists = [
payload?.confirmed_order_ids,
payload?.confirmedOrderIds,
payload?.data?.confirmed_order_ids,
payload?.data?.confirmedOrderIds,
payload?.data?.data?.confirmed_order_ids,
payload?.data?.data?.confirmedOrderIds,
payload?.result?.confirmed_order_ids,
payload?.result?.confirmedOrderIds,
payload?.result?.data?.confirmed_order_ids,
payload?.result?.data?.confirmedOrderIds
];
for (let i = 0; i < candidateLists.length; i += 1) {
const normalizedOrderIds = this.normalizeConfirmedOrderIds(candidateLists[i]);
if (normalizedOrderIds.length) {
return normalizedOrderIds;
}
}
return [];
},
handleWavePickTaskSubmitResponse(response) {
console.log('[pick.wavePickTaskSubmit] response:', response);
const confirmedOrderIds = this.extractConfirmedOrderIdsFromSubmitResponse(response);
console.log('[pick.wavePickTaskSubmit] confirmed_order_ids:', confirmedOrderIds);
if (!confirmedOrderIds.length) {
console.log('[pick.wavePickTaskSubmit] no confirmed_order_ids extracted');
return response;
}
const mergedOrderIds = [
...this.confirmedOrderIds,
...confirmedOrderIds
];
this.persistConfirmedOrderIdsForCurrentTask(mergedOrderIds);
console.log('[pick.wavePickTaskSubmit] merged confirmedOrderIds:', this.normalizeConfirmedOrderIds(mergedOrderIds));
return response;
},
getBoundCartTaskKey() {
return String(this.getCurrentTaskIdNumber() || '').trim();
},
loadBoundCartMap() {
try {
const raw = uni.getStorageSync(this.boundCartStorageKey);
if (!raw) {
return {};
}
if (typeof raw === 'string') {
const parsed = JSON.parse(raw);
return parsed && typeof parsed === 'object' ? parsed : {};
}
return raw && typeof raw === 'object' ? raw : {};
} catch (error) {
return {};
}
},
saveBoundCartMap(map) {
try {
uni.setStorageSync(this.boundCartStorageKey, map || {});
} catch (error) {
// ignore
}
},
restoreBoundCartForCurrentTask() {
const taskKey = this.getBoundCartTaskKey();
if (!taskKey) {
this.boundCartNo = '';
this.boundCartName = '';
this.bindCartNoInput = '';
this.bindCartList = [];
this.selectedBindCartItem = null;
return;
}
const map = this.loadBoundCartMap();
const saved = map[taskKey];
const boundCartNo = typeof saved === 'object'
? String(saved?.cartNo || saved?.cart_code || '').trim()
: String(saved || '').trim();
const boundCartName = typeof saved === 'object'
? String(saved?.cartName || saved?.cart_name || '').trim()
: '';
this.boundCartNo = boundCartNo;
this.boundCartName = boundCartName;
this.bindCartNoInput = boundCartNo;
},
persistBoundCartForCurrentTask(cartNo, cartName = '') {
const taskKey = this.getBoundCartTaskKey();
if (!taskKey) {
return;
}
const map = this.loadBoundCartMap();
map[taskKey] = {
cartNo: String(cartNo || '').trim(),
cartName: String(cartName || '').trim()
};
this.saveBoundCartMap(map);
},
openBindCartPopup() {
if (!this.hasActiveTask) {
uni.showToast({
title: '请先进入拣货任务',
icon: 'none'
});
return;
}
this.bindCartNoInput = this.boundCartNo || '';
this.bindCartQueryKeyword = this.bindCartNoInput || '';
this.selectedBindCartItem = null;
this.bindCartPopupVisible = true;
this.handleBindCartSearch();
},
closeBindCartPopup() {
this.bindCartPopupVisible = false;
},
applyBindCartScanResult(rawValue) {
const scanText = this.normalizeScanResult(rawValue);
if (!scanText) {
uni.showToast({
title: '未识别到有效拣货车编码',
icon: 'none'
});
return;
}
this.bindCartNoInput = scanText;
this.bindCartQueryKeyword = scanText;
this.handleBindCartSearch();
},
handleBindCartScan() {
uni.scanCode({
onlyFromCamera: true,
scanType: ['barCode', 'qrCode'],
success: res => {
this.applyBindCartScanResult(res);
},
fail: () => {
uni.showToast({
title: '扫码失败,请重试',
icon: 'none'
});
}
});
},
getBindCartItemKey(item) {
const cartNo = this.getBindCartNo(item);
return String(item?.id || item?.cart_id || item?.cartId || cartNo || '').trim();
},
getBindCartNo(item) {
return String(
item?.cart_code ||
item?.cartCode ||
item?.cart_no ||
item?.cartNo ||
item?.code ||
'--'
).trim() || '--';
},
getBindCartName(item) {
return String(
item?.cart_name ||
item?.cartName ||
item?.cart?.cart_name ||
item?.cart?.cartName ||
item?.name ||
''
).trim();
},
getBindCartStatusText(item) {
const status = String(item?.status ?? item?.cart_status ?? '').trim();
if (!status) {
return '--';
}
const map = {
0: '未绑定',
1: '已绑定',
2: '可用',
3: '停用'
};
return map[status] || status;
},
getBindCartDesc(item) {
const cartName = this.getBindCartName(item);
const taskId = String(item?.current_task_id || item?.task_id || item?.taskId || '').trim();
const taskText = taskId ? `当前任务:${taskId}` : '当前任务:无';
return cartName ? `名称:${cartName},${taskText}` : taskText;
},
isBindCartSelected(item) {
return this.getBindCartItemKey(item) === this.getBindCartItemKey(this.selectedBindCartItem);
},
isBindCartBound(item) {
const currentBoundNo = this.normalizeBarcodeText(this.boundCartNo);
const itemCartNo = this.normalizeBarcodeText(this.getBindCartNo(item));
return Boolean(currentBoundNo) && currentBoundNo === itemCartNo;
},
selectBindCartItem(item) {
this.selectedBindCartItem = item || null;
this.bindCartNoInput = this.getBindCartNo(item);
},
async handleBindCartSearch() {
const keyword = String(this.bindCartQueryKeyword || this.bindCartNoInput || '').trim();
this.bindCartQueryKeyword = keyword;
this.bindCartListLoading = true;
try {
const response = keyword
? await this.$http('pickCart.scan', { cart_code: keyword }, '', false)
: await this.$http('pickCart.list', {
pagination: { page: 1, pageSize: 20 },
where: {
keyword: '',
status: '',
current_task_id: this.getCurrentTaskIdNumber() || ''
}
}, '', false);
const payload = response?.data?.data || response?.data || response?.result || response || {};
const list = Array.isArray(payload?.list)
? payload.list
: Array.isArray(payload?.rows)
? payload.rows
: Array.isArray(payload?.items)
? payload.items
: (payload?.cart
? [payload.cart]
: (payload?.data && typeof payload.data === 'object' ? [payload.data] : (payload && typeof payload === 'object' ? [payload] : [])));
this.bindCartList = list.filter(item => this.getBindCartNo(item) !== '--');
if (this.bindCartList.length > 0 && !this.selectedBindCartItem) {
const boundItem = this.bindCartList.find(item => this.isBindCartBound(item));
this.selectedBindCartItem = boundItem || this.bindCartList[0];
this.bindCartNoInput = this.getBindCartNo(this.selectedBindCartItem);
}
} catch (error) {
this.bindCartList = [];
this.showErrorModal(this.getApiErrorMessage(error, '查询拣货车失败'));
} finally {
this.bindCartListLoading = false;
}
},
async confirmBindCart() {
const cartNo = String(this.bindCartNoInput || this.getBindCartNo(this.selectedBindCartItem) || '').trim();
if (!cartNo) {
uni.showToast({
title: '请输入拣货车编号',
icon: 'none'
});
return;
}
const taskIdNumber = this.getCurrentTaskIdNumber();
if (!taskIdNumber) {
uni.showToast({
title: '缺少拣货任务ID',
icon: 'none'
});
return;
}
let cartName = this.getBindCartName(this.selectedBindCartItem);
let selectedCartId = Number(
this.selectedBindCartItem?.id ||
this.selectedBindCartItem?.cart_id ||
this.selectedBindCartItem?.cartId ||
0
);
if (!cartName) {
try {
const response = await this.$http('pickCart.scan', { cart_code: cartNo }, '', false);
const payload = response?.data?.data || response?.data || response?.result || response || {};
const scannedItem = payload?.cart || payload?.data || payload;
cartName = this.getBindCartName(scannedItem);
selectedCartId = Number(
scannedItem?.id ||
scannedItem?.cart_id ||
scannedItem?.cartId ||
selectedCartId ||
0
);
} catch (error) {
cartName = '';
}
}
const bindPayload = {
task_id: taskIdNumber
};
if (Number.isFinite(selectedCartId) && selectedCartId > 0) {
bindPayload.cart_id = selectedCartId;
}
try {
const bindResponse = await this.$http('pickCart.bindTaskCart', bindPayload, '', false);
if (String(bindResponse?.flag || '').toLowerCase() === 'failure') {
this.showErrorModal(bindResponse?.message || '绑定拣货车失败');
return;
}
} catch (error) {
this.showErrorModal(this.getApiErrorMessage(error, '绑定拣货车失败'));
return;
}
this.boundCartNo = cartNo;
this.boundCartName = cartName;
this.persistBoundCartForCurrentTask(cartNo, cartName);
this.bindCartPopupVisible = false;
uni.showToast({
title: '绑定成功',
icon: 'none'
});
},
isPickItemPicked(item) {
const key = this.getPickItemUniqueKey(item);
return Boolean(key) && this.pickedItemKeys.includes(key);
},
markPickItemPicked(item) {
const key = this.getPickItemUniqueKey(item);
if (!key || this.pickedItemKeys.includes(key)) {
return;
}
this.pickedItemKeys = [...this.pickedItemKeys, key];
this.persistPickedStateForCurrentTask();
},
isSelectedItemMatchedHighlight() {
return this.isPickItemPicked(this.selectedPickItem);
},
triggerBarcodeMatchedHighlight(item) {
this.markPickItemPicked(item);
},
sleep(ms = 0) {
return new Promise(resolve => {
setTimeout(resolve, Number(ms) || 0);
});
},
isWeakNetworkError(error) {
const errorText = String(
error?.errMsg ||
error?.message ||
error?.msg ||
error?.data?.message ||
''
).toLowerCase();
if (!errorText) {
return false;
}
return (
errorText.includes('timeout') ||
errorText.includes('timed out') ||
errorText.includes('network') ||
errorText.includes('request:fail') ||
errorText.includes('连接') ||
errorText.includes('超时')
);
},
createSubmitTimeoutError(timeoutMs) {
const error = new Error(`提交超时(${timeoutMs}ms)`);
error.code = 'REQUEST_TIMEOUT';
error.errMsg = `request:fail timeout ${timeoutMs}`;
return error;
},
requestWavePickTaskSubmit(taskIdNumber, timeoutMs = 8000) {
console.log('[pick.wavePickTaskSubmit] request:', {
task_id: taskIdNumber
});
const requestPromise = this.$http('pick.wavePickTaskSubmit', {
task_id: taskIdNumber
});
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(this.createSubmitTimeoutError(timeoutMs));
}, timeoutMs);
});
return Promise.race([requestPromise, timeoutPromise]);
},
async submitWavePickTaskIntermediate() {
const taskIdNumber = this.getCurrentTaskIdNumber();
if (!taskIdNumber || this.submittingWavePickTask) {
return this.currentWavePickSubmitPromise;
}
this.currentWavePickSubmitPromise = (async () => {
if (!this.isNetworkConnected) {
this.enqueueWavePickSubmitTask(taskIdNumber);
uni.showToast({
title: '当前离线,已加入补提队列',
icon: 'none'
});
return;
}
const maxAttempts = 3;
let lastError = null;
this.submittingWavePickTask = true;
try {
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
try {
const response = await this.requestWavePickTaskSubmit(taskIdNumber, 8000);
this.handleWavePickTaskSubmitResponse(response);
this.dequeueWavePickSubmitTask(taskIdNumber);
return;
} catch (error) {
lastError = error;
const isWeakNetwork = this.isWeakNetworkError(error);
if (!this.isNetworkConnected) {
this.enqueueWavePickSubmitTask(taskIdNumber);
break;
}
if (!isWeakNetwork || attempt >= maxAttempts) {
break;
}
await this.sleep(attempt * 600);
}
}
if (!this.isNetworkConnected) {
return;
}
const fallbackMessage = this.isWeakNetworkError(lastError)
? '网络较差,提交拣货中间态失败,请重试'
: '提交拣货中间态失败';
this.showErrorModal(this.getApiErrorMessage(lastError, fallbackMessage));
} finally {
this.submittingWavePickTask = false;
this.currentWavePickSubmitPromise = null;
}
})();
return this.currentWavePickSubmitPromise;
},
handleScanKeywordEntry(rawKeyword) {
const scanText = this.normalizeScanResult(rawKeyword);
if (!scanText) {
uni.showToast({
title: '未识别到有效条码',
icon: 'none'
});
return;
}
this.keyword = scanText;
if (!this.hasActiveTask) {
this.requestPickTaskByKeyword(scanText);
return;
}
this.handleSearch();
},
// ====== 调试功能 ======
handleTitleClick() {
this._titleClickCount = (this._titleClickCount || 0) + 1;
if (this._titleClickCount >= 5) {
this._titleClickCount = 0;
this.showDebugInput = !this.showDebugInput;
if (this.showDebugInput) {
this.$nextTick(() => {
this.debugInputFocus = true;
});
}
}
},
handleDebugSubmit() {
if (!this.debugInput) return;
const payload = { data: this.debugInput };
this.handleBroadcastScan(payload);
this.debugInput = '';
this.debugInputFocus = true;
},
handleBroadcastScan(payload) {
const scanText = this.normalizeScanResult(payload);
if (this.bindCartPopupVisible) {
this.applyBindCartScanResult(scanText);
return;
}
if (!this.hasActiveTask) {
this.handleScanKeywordEntry(scanText);
return;
}
const scanBarcode = this.normalizeBarcodeText(scanText);
const rawParts = (this.selectedItemBarcode || '').split(/[,,、\s]+/);
const currentBarcodes = [];
rawParts.forEach(part => {
const normalized = this.normalizeBarcodeText(part);
if (!normalized) return;
currentBarcodes.push(normalized);
// 包含汉字时,额外添加去除汉字后的部分作为候选
if (/[\u4e00-\u9fff]/.test(normalized)) {
const stripped = normalized.replace(/[\u4e00-\u9fff]+/g, '');
if (stripped) {
console.log('[Picking] 候选条码含汉字,已添加去汉字版本:', normalized, '→', stripped);
currentBarcodes.push(stripped);
}
}
});
console.log('[Picking] 扫描条码:', scanBarcode, '原始值:', scanText);
console.log('[Picking] 商品候选条码:', currentBarcodes, '原始字段:', this.selectedItemBarcode);
if (scanBarcode && currentBarcodes.length > 0 && currentBarcodes.includes(scanBarcode)) {
this.triggerBarcodeMatchedHighlight(this.selectedPickItem);
this.submitWavePickTaskIntermediate();
return;
}
uni.showToast({
title: '商品条码不一致',
icon: 'none'
});
},
extractTaskIdCandidate(rawValue) {
if (rawValue === null || rawValue === undefined || rawValue === '') {
return null;
}
const taskId = Number(rawValue);
if (!Number.isFinite(taskId) || taskId <= 0) {
return null;
}
return taskId;
},
extractTaskIdFromPickQueryResponse(response) {
const payload = response?.data?.data || response?.data || response?.result || response || {};
const candidates = [
payload?.task_id,
payload?.taskId,
payload?.existing_task_id,
payload?.created_task_id,
payload?.existing?.task_id,
payload?.existing?.taskId,
payload?.created?.task_id,
payload?.created?.taskId,
payload?.task?.task_id,
payload?.task?.taskId
];
for (let i = 0; i < candidates.length; i += 1) {
const resolvedTaskId = this.extractTaskIdCandidate(candidates[i]);
if (resolvedTaskId) {
return resolvedTaskId;
}
}
return null;
},
extractPickTaskConflictInfo(error) {
const responseData = error?.data || error?.response?.data || {};
const payload = responseData?.data || responseData || {};
const message = String(
payload?.message ||
payload?.msg ||
responseData?.message ||
responseData?.msg ||
error?.message ||
''
).trim();
const code = String(payload?.code || responseData?.code || error?.code || '').toLowerCase();
const creatorName = String(
payload?.creator_name ||
payload?.owner_name ||
payload?.task_creator_name ||
payload?.creator?.real_name ||
payload?.creator?.name ||
''
).trim();
const taskId = this.extractTaskIdCandidate(
payload?.task_id ?? payload?.existing_task_id ?? payload?.task?.task_id ?? null
);
const identifyText = `${code} ${message}`.toLowerCase();
const isConflict = identifyText.includes('conflict') || identifyText.includes('owner') || identifyText.includes('创建人') || identifyText.includes('归属') || identifyText.includes('非当前用户') || identifyText.includes('非本人');
return {
isConflict,
creatorName,
taskId,
message
};
},
buildPickTaskConflictMessage(conflictInfo) {
const lines = ['该拣货任务已被其他人员占用'];
if (conflictInfo?.creatorName) {
lines.push(`创建人:${conflictInfo.creatorName}`);
}
if (conflictInfo?.taskId) {
lines.push(`任务ID:${conflictInfo.taskId}`);
}
if (conflictInfo?.message) {
lines.push(conflictInfo.message);
}
return lines.join('\n');
},
showErrorModal(message, title = '提示') {
uni.showModal({
title,
content: String(message || '请求失败'),
showCancel: false
});
},
async requestPickTaskByKeyword(keyword) {
const normalizedKeyword = String(keyword || '').trim();
if (!normalizedKeyword) {
uni.showToast({
title: '请输入运单号或波次号',
icon: 'none'
});
return;
}
uni.showLoading({
title: '正在查询任务...'
});
try {
const response = await this.$http('pick.query', {
keyword: normalizedKeyword
}, '', false);
if (String(response?.flag || '').toLowerCase() === 'failure') {
this.showErrorModal(response?.message || '任务查询失败');
return;
}
const taskId = this.extractTaskIdFromPickQueryResponse(response);
if (!taskId) {
uni.showToast({
title: '未查询到可拣货任务',
icon: 'none'
});
return;
}
this.taskId = String(taskId);
this.keyword = '';
await this.requestWavePickTaskDetail();
} catch (error) {
const conflictInfo = this.extractPickTaskConflictInfo(error);
if (conflictInfo.isConflict) {
uni.showModal({
title: '任务归属冲突',
content: this.buildPickTaskConflictMessage(conflictInfo),
showCancel: false
});
return;
}
this.showErrorModal(this.getApiErrorMessage(error, '任务查询失败'));
} finally {
uni.hideLoading();
}
},
openActionsPopup() {
if (!this.hasActiveTask) {
return;
}
this.showActionsPopup = true;
},
requestWavePickTaskComplete(taskIdNumber, options = {}) {
const payload = {
task_id: taskIdNumber,
mode: Number(options?.mode || 1)
};
if (payload.mode === 2 && Array.isArray(options?.order_ids) && options.order_ids.length) {
payload.order_ids = options.order_ids;
}
console.log('[pick.wavePickTaskComplete] request:', payload);
return this.$http('pick.wavePickTaskComplete', payload, '', false).then(response => {
console.log('[pick.wavePickTaskComplete] response:', response);
return response;
}).catch(error => {
console.log('[pick.wavePickTaskComplete] error:', error);
throw error;
});
},
handleCompletePick() {
this.showActionsPopup = false;
if (!this.hasActiveTask) {
uni.showToast({
title: '缺少拣货任务',
icon: 'none'
});
return;
}
const taskIdNumber = Number(this.taskInfo?.taskId || this.taskId || 0);
if (!taskIdNumber) {
uni.showToast({
title: '缺少任务ID',
icon: 'none'
});
return;
}
uni.showModal({
title: '完成拣货',
content: '确认完成当前拣货任务吗?',
success: async res => {
if (!res?.confirm) {
return;
}
uni.showLoading({
title: '正在提交...'
});
try {
if (this.currentWavePickSubmitPromise) {
await this.currentWavePickSubmitPromise;
}
const confirmedOrderIds = this.normalizeConfirmedOrderIds(this.confirmedOrderIds);
const completeMode = confirmedOrderIds.length ? 2 : 1;
console.log('[pick.wavePickTaskComplete] derived state:', {
task_id: taskIdNumber,
confirmedOrderIds,
completeMode
});
const response = await this.requestWavePickTaskComplete(taskIdNumber, {
mode: completeMode,
order_ids: confirmedOrderIds
});
if (String(response?.flag || '').toLowerCase() === 'failure') {
this.showErrorModal(response?.message || '完成拣货失败');
return;
}
uni.showToast({
title: '完成成功',
icon: 'none'
});
voice.speak('拣货完成');
// 通知列表页更新该波次状态为已复核
const completedBatchNo = String(this.taskInfo?.batchNo || '').trim();
if (completedBatchNo) {
uni.setStorageSync('pick_completed_wave', completedBatchNo);
}
this.taskId = '';
this.keyword = '';
this.taskInfo = {
taskId: '',
taskNo: '',
batchNo: '',
status: 0,
creatorId: '',
creatorName: ''
};
this.boxList = [];
this.pickingSummary = {
totalLines: 0,
totalQty: 0,
distinctSpaces: 0,
distinctItems: 0
};
this.pickingView = {
modeCode: '',
modeName: '--',
items: []
};
this.selectedIndex = 0;
this.selectedItemImageLoading = false;
this.selectedItemImageUrl = '';
this.selectedItemImageUrls = [];
this.selectedItemBarcodeLoading = false;
this.selectedItemBarcode = '';
this.boundCartNo = '';
this.boundCartName = '';
this.bindCartNoInput = '';
this.bindCartList = [];
this.selectedBindCartItem = null;
this.bindCartQueryKeyword = '';
this.pickedItemKeys = [];
this.clearConfirmedOrderIdsForTask(taskIdNumber);
} catch (error) {
this.showErrorModal(this.getApiErrorMessage(error, '完成拣货失败'));
} finally {
uni.hideLoading();
}
}
});
},
handleCancelPick() {
this.showActionsPopup = false;
if (!this.canCancelPickTask) {
uni.showToast({
title: '仅任务创建人可取消',
icon: 'none'
});
return;
}
const taskIdNumber = Number(this.taskInfo?.taskId || this.taskId || 0);
if (!taskIdNumber) {
uni.showToast({
title: '缺少任务ID',
icon: 'none'
});
return;
}
uni.showModal({
title: '取消拣货',
content: '确认取消当前拣货任务吗?',
success: async res => {
if (!res?.confirm) {
return;
}
uni.showLoading({
title: '正在取消...'
});
try {
const response = await this.$http('order.wave.wavePickTaskCancelSelf', {
task_id: taskIdNumber
});
const payload = response?.data?.data || response?.data || response || {};
const cancelledCount = Number(payload?.cancelled_count ?? 0);
const taskNo = String(payload?.task_no || this.taskInfo?.taskNo || '').trim();
const successTitle = cancelledCount > 0
? (taskNo ? `已取消:${taskNo}` : '取消成功')
: '取消完成';
uni.showToast({
title: successTitle,
icon: 'none'
});
if (cancelledCount > 0) {
this.taskId = '';
this.taskInfo = {
taskId: '',
taskNo: '',
batchNo: '',
status: 0,
creatorId: '',
creatorName: ''
};
this.pickingView = {
modeCode: '',
modeName: '--',
items: []
};
this.selectedIndex = 0;
}
} catch (error) {
uni.showToast({
title: this.getApiErrorMessage(error, '取消拣货失败'),
icon: 'none'
});
} finally {
uni.hideLoading();
}
}
});
},
getApiErrorMessage(error, fallback = '请求失败') {
const message = error?.message || error?.msg || error?.errMsg || error?.data?.message;
return String(message || fallback);
},
extractTaskDetailPayload(response) {
return response?.data?.data || response?.data || response?.result || response || {};
},
extractCurrentTaskIdFromResponse(response) {
const payload = response?.data?.data || response?.data || response?.result || response || {};
const candidate = payload?.task_id ?? payload?.taskId ?? payload?.task?.task_id ?? payload?.task?.taskId ?? null;
if (candidate === null || candidate === undefined || candidate === '') {
return null;
}
const taskId = Number(candidate);
return Number.isFinite(taskId) && taskId > 0 ? taskId : null;
},
async requestCurrentWavePickTask() {
try {
const response = await this.$http('pick.wavePickTaskCurrent', {});
const currentTaskId = this.extractCurrentTaskIdFromResponse(response);
if (currentTaskId) {
this.taskId = String(currentTaskId);
this.requestWavePickTaskDetail();
return;
}
return;
} catch (error) {
uni.showToast({
title: this.getApiErrorMessage(error, '请扫描面单或拣货单进入拣货流程'),
icon: 'none'
});
}
},
normalizeTaskDetailPayload(payload = {}) {
const task = payload?.task || {};
const summary = payload?.picking_summary || {};
const view = payload?.picking_view || {};
const viewItems = Array.isArray(view?.items) ? view.items : [];
const creatorId = task?.creator_id ?? task?.created_by ?? task?.create_user_id ?? task?.creator_user_id ?? task?.operator_id ?? task?.picker_id ?? task?.creator?.id ?? task?.creator?.user_id ?? '';
const creatorName = task?.creator_name || task?.created_by_name || task?.operator_name || task?.picker_name || task?.creator?.real_name || task?.creator?.name || '';
this.taskInfo = {
taskId: task?.task_id ?? this.taskId,
taskNo: task?.task_no || '',
batchNo: task?.batch_no || '',
status: Number(task?.status || 0),
creatorId: String(creatorId || '').trim(),
creatorName: String(creatorName || '').trim()
};
this.boxList = Array.isArray(payload?.boxes) ? payload.boxes : [];
this.pickingSummary = {
totalLines: Number(summary?.total_lines || 0),
totalQty: Number(summary?.total_qty || 0),
distinctSpaces: Number(summary?.distinct_spaces || 0),
distinctItems: Number(summary?.distinct_items || 0)
};
this.pickingView = {
modeCode: view?.mode_code ?? '',
modeName: view?.mode_name || '--',
items: viewItems.map(item => ({
spaceId: item?.space_id ?? '',
spaceName: item?.space_name || item?.location_space?.custom_name || '--',
spaceBarcode: item?.location_space?.custom_barcode || '--',
itemCode: item?.item_code || '--',
itemName: item?.item_name || '--',
stockId: Number(item?.stock_id || item?.item_snapshot?.stock_id || 0),
totalQty: Number(item?.total_qty || 0),
boxAllocations: (Array.isArray(item?.box_allocations) ? item.box_allocations : []).map(alloc => ({
boxId: alloc?.box_id ?? '',
boxNo: alloc?.box_no ?? '--',
allocatedQty: Number(alloc?.allocated_qty || 0)
}))
}))
};
this.restorePickedStateForCurrentTask();
this.restoreConfirmedOrderIdsForCurrentTask();
this.restoreBoundCartForCurrentTask();
this.selectedIndex = 0;
},
async requestWavePickTaskDetail() {
const taskIdNumber = Number(this.taskId || 0);
if (!taskIdNumber) {
return;
}
this.loadingTaskDetail = true;
try {
const response = await this.$http('pick.wavePickTaskDetail', {
task_id: taskIdNumber
}, '', false);
if (String(response?.flag || '').toLowerCase() === 'failure') {
this.pickingView.items = [];
const msg = String(response?.message || '').trim();
// 存在未分配储位订单时,显示引导提示
if (msg.includes('未分配储位')) {
this.showErrorModal('存在未分配储位的订单。如需拣其他货,请点击\'更多\'→\'取消拣货\'。');
} else {
this.showErrorModal(msg || '任务详情获取失败');
}
return;
}
const payload = this.extractTaskDetailPayload(response);
this.normalizeTaskDetailPayload(payload);
} catch (error) {
this.pickingView.items = [];
this.showErrorModal(this.getApiErrorMessage(error, '任务详情获取失败'));
} finally {
this.loadingTaskDetail = false;
}
},
getSelectedItemImageKey(item) {
if (!item || typeof item !== 'object') {
return '';
}
return String(item.stockId || item.itemCode || '').trim();
},
extractImageListFromGetImagesResponse(response) {
if (!response || typeof response !== 'object') {
return [];
}
const candidates = [
response.data,
response.data && response.data.data,
response.data && response.data.images,
response.data && response.data.list,
response.data && response.data.rows,
response.data && response.data.records,
response.data && response.data.result,
response.data && response.data.result && response.data.result.images,
response.data && response.data.result && response.data.result.list,
response.images,
response.list,
response.rows,
response.records
];
for (let i = 0; i < candidates.length; i += 1) {
const current = candidates[i];
if (!current) {
continue;
}
if (Array.isArray(current)) {
return current;
}
if (typeof current === 'object') {
const objectCandidates = [current.images, current.list, current.rows, current.records, current.data];
for (let j = 0; j < objectCandidates.length; j += 1) {
if (Array.isArray(objectCandidates[j])) {
return objectCandidates[j];
}
}
}
}
return [];
},
resolveImageUrlFromEntry(entry) {
if (!entry) {
return '';
}
if (typeof entry === 'string') {
return entry;
}
if (typeof entry !== 'object') {
return '';
}
return String(
entry.url ||
entry.path ||
entry.fileUrl ||
entry.file_url ||
(entry.file && (entry.file.file_url || entry.file.fileUrl)) ||
entry.image_url ||
entry.img_url ||
entry.src ||
''
).trim();
},
async loadSelectedItemImage(item) {
if (!item) {
this.selectedItemImageUrl = '';
this.selectedItemImageUrls = [];
this.currentImageIndex = 0;
this.selectedItemImageLoading = false;
return;
}
const imageKey = this.getSelectedItemImageKey(item);
if (!imageKey) {
this.selectedItemImageUrl = '';
this.selectedItemImageUrls = [];
this.currentImageIndex = 0;
this.selectedItemImageLoading = false;
return;
}
if (Object.prototype.hasOwnProperty.call(this.itemImageCache, imageKey)) {
this.selectedItemImageUrl = this.itemImageCache[imageKey] || '';
this.selectedItemImageUrls = Array.isArray(this.itemImageListCache[imageKey]) ? this.itemImageListCache[imageKey] : [];
this.currentImageIndex = 0;
this.selectedItemImageLoading = false;
return;
}
this.selectedItemImageLoading = true;
this.selectedItemImageUrl = '';
this.selectedItemImageUrls = [];
this.currentImageIndex = 0;
try {
const stockId = Number(item.stockId || 0);
const response = await this.$http('common.getImages', {
id: stockId,
business_id: stockId,
stock_id: stockId,
type: 'stock',
business_type: 'stock'
});
const list = this.extractImageListFromGetImagesResponse(response);
const urls = list.map(entry => this.resolveImageUrlFromEntry(entry)).filter(Boolean);
const firstUrl = urls[0] || '';
this.$set(this.itemImageCache, imageKey, firstUrl || '');
this.$set(this.itemImageListCache, imageKey, urls);
if (this.getSelectedItemImageKey(this.selectedPickItem) === imageKey) {
this.selectedItemImageUrl = firstUrl || '';
this.selectedItemImageUrls = urls;
this.currentImageIndex = 0;
}
} catch (error) {
this.$set(this.itemImageCache, imageKey, '');
this.$set(this.itemImageListCache, imageKey, []);
if (this.getSelectedItemImageKey(this.selectedPickItem) === imageKey) {
this.selectedItemImageUrl = '';
this.selectedItemImageUrls = [];
this.currentImageIndex = 0;
}
} finally {
if (this.getSelectedItemImageKey(this.selectedPickItem) === imageKey) {
this.selectedItemImageLoading = false;
}
}
},
getSelectedItemBarcodeKey(item) {
if (!item || typeof item !== 'object') {
return '';
}
return String(item.stockId || '').trim();
},
extractBarcodeListFromResponse(response) {
const candidates = [
response?.data,
response?.data?.data,
response?.list,
response
];
for (let i = 0; i < candidates.length; i += 1) {
if (Array.isArray(candidates[i])) {
return candidates[i];
}
}
return [];
},
resolveBarcodeFromEntry(entry) {
if (!entry) {
return '';
}
if (typeof entry === 'string') {
return entry.trim();
}
if (typeof entry !== 'object') {
return '';
}
return String(entry.barcode || entry.code || '').trim();
},
async loadSelectedItemBarcode(item) {
if (!item) {
this.selectedItemBarcode = '';
this.selectedItemBarcodeLoading = false;
return;
}
const barcodeKey = this.getSelectedItemBarcodeKey(item);
if (!barcodeKey) {
this.selectedItemBarcode = '';
this.selectedItemBarcodeLoading = false;
return;
}
if (Object.prototype.hasOwnProperty.call(this.itemBarcodeCache, barcodeKey)) {
this.selectedItemBarcode = this.itemBarcodeCache[barcodeKey] || '';
this.selectedItemBarcodeLoading = false;
return;
}
this.selectedItemBarcodeLoading = true;
this.selectedItemBarcode = '';
try {
const stockId = Number(item.stockId || 0);
const response = await this.$http('stock.warehouse.getBarcodes', {
id: stockId
});
const list = this.extractBarcodeListFromResponse(response);
const allBarcodes = (list || [])
.map(entry => this.resolveBarcodeFromEntry(entry))
.filter(b => b);
const joinedBarcodes = allBarcodes.join(',');
this.$set(this.itemBarcodeCache, barcodeKey, joinedBarcodes || '');
if (this.getSelectedItemBarcodeKey(this.selectedPickItem) === barcodeKey) {
this.selectedItemBarcode = joinedBarcodes || '';
}
} catch (error) {
this.$set(this.itemBarcodeCache, barcodeKey, '');
if (this.getSelectedItemBarcodeKey(this.selectedPickItem) === barcodeKey) {
this.selectedItemBarcode = '';
}
} finally {
if (this.getSelectedItemBarcodeKey(this.selectedPickItem) === barcodeKey) {
this.selectedItemBarcodeLoading = false;
}
}
},
selectPickItem(index) {
this.selectedIndex = Number(index || 0);
},
handlePrevItem() {
if (this.selectedIndex > 0) {
this.selectedIndex -= 1;
}
},
handleNextItem() {
if (this.selectedIndex < this.filteredPickItems.length - 1) {
this.selectedIndex += 1;
}
},
previewSelectedItemImage() {
const urls = Array.isArray(this.selectedItemImageUrls) && this.selectedItemImageUrls.length
? this.selectedItemImageUrls
: (this.selectedItemImageUrl ? [this.selectedItemImageUrl] : []);
if (!urls.length) {
return;
}
const currentIndex = this.selectedItemImageUrl ? Math.max(urls.indexOf(this.selectedItemImageUrl), 0) : 0;
this.$tools.previewImage(urls, currentIndex);
},
goProductQueryByCurrentBarcode() {
if (this.selectedItemBarcodeLoading) {
uni.showToast({
title: '条码加载中,请稍后',
icon: 'none'
});
return;
}
const barcode = String(this.selectedItemBarcode || '').trim();
if (!barcode) {
uni.showToast({
title: '当前商品暂无条码',
icon: 'none'
});
return;
}
// 取第一个条码,并去除汉字/全角标点
const firstPart = barcode.split(/[,,、\s]+/)[0] || barcode;
const searchKeyword = firstPart.replace(/[\u4e00-\u9fff\uFF00-\uFFEF]+/g, '').trim() || firstPart;
uni.navigateTo({
url: `/pages/work/product/query?keyword=${encodeURIComponent(searchKeyword)}`
});
},
handleCameraScan() {
uni.scanCode({
onlyFromCamera: true,
scanType: ['barCode', 'qrCode'],
success: res => {
this.handleScanKeywordEntry(res);
},
fail: () => {
uni.showToast({
title: '扫码失败,请重试',
icon: 'none'
});
}
});
}
}
};
</script>
<style lang="scss" scoped>
.order-picking-page {
min-height: 100vh;
background: #f8f9fa;
}
::v-deep .normar_container {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.empty-wrap {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: 24rpx;
box-sizing: border-box;
}
.empty-card {
width: 100%;
max-width: 620rpx;
background: #ffffff;
border-radius: 16rpx;
border: 1rpx solid #e8eefc;
padding: 48rpx 24rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 14rpx;
}
.empty-title {
font-size: 36rpx;
line-height: 1.2;
color: #303133;
font-weight: 600;
}
.empty-desc {
font-size: 30rpx;
line-height: 1.4;
color: #606266;
text-align: center;
}
.content-wrap {
flex: 1;
padding: 24rpx;
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 16rpx;
min-height: 0;
}
.top-detail-panel {
flex: 1;
min-height: 0;
}
.nav-right {
padding-right: 24rpx;
display: flex;
align-items: center;
justify-content: flex-end;
min-width: 0;
}
::v-deep .nav-right .u-icon {
flex-shrink: 0;
}
.nav-action-btn {
height: 48rpx;
padding: 0 12rpx;
border-radius: 999rpx;
display: flex;
align-items: center;
justify-content: center;
background: #eaf2ff;
border: 1rpx solid #cfe1ff;
flex-shrink: 1;
}
.nav-action-btn--bind {
background: #2979ff;
border-color: #2979ff;
border-radius: 8rpx;
height: 60rpx;
padding: 0 22rpx;
margin-left: 20rpx;
}
.nav-action-btn--bind .nav-action-btn__text {
color: #ffffff;
font-size: 28rpx;
font-weight: 600;
}
.nav-action-btn__text {
font-size: 24rpx;
color: #2979ff;
line-height: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.nav-right--disabled {
opacity: 0.45;
pointer-events: none;
}
/* 操作弹窗 */
.actions-popup {
padding: 48rpx 32rpx calc(40rpx + env(safe-area-inset-bottom));
background: #ffffff;
border-top-left-radius: 20rpx;
border-top-right-radius: 20rpx;
}
.actions-popup-title {
font-size: 38rpx;
font-weight: 600;
color: #303133;
text-align: center;
margin-bottom: 36rpx;
}
.actions-popup-body {
display: flex;
gap: 20rpx;
margin-bottom: 32rpx;
}
.actions-popup-btn {
flex: 1;
height: 100rpx;
border-radius: 16rpx;
display: flex;
align-items: center;
justify-content: center;
}
.actions-popup-btn--cancel {
background: #fff1f0;
border: 2rpx solid #ffccc7;
}
.actions-popup-btn--complete {
background: #2979ff;
border: 2rpx solid #2979ff;
}
.actions-popup-btn__text {
font-size: 34rpx;
font-weight: 500;
line-height: 1;
}
.actions-popup-btn__text--cancel {
color: #f56c6c;
}
.actions-popup-btn__text--complete {
color: #ffffff;
}
.actions-popup-footer {
display: flex;
justify-content: center;
}
.actions-popup-close-btn {
padding: 16rpx 48rpx;
font-size: 34rpx;
color: #909399;
border: 1rpx solid #dcdfe6;
border-radius: 10rpx;
background: #f5f5f5;
}
.loading-wrap {
background: #ffffff;
border-radius: 12rpx;
padding: 24rpx;
border: 1rpx solid #ebeef5;
}
.loading-text {
font-size: 30rpx;
color: #606266;
}
.bottom-grid-panel {
flex: 0 0 300rpx;
height: 300rpx;
background: #ffffff;
border-radius: 12rpx;
padding: 12rpx;
border: 1rpx solid #ebeef5;
}
.list-empty {
background: #ffffff;
border-radius: 12rpx;
padding: 28rpx;
border: 1rpx solid #ebeef5;
font-size: 30rpx;
color: #909399;
}
.pick-card {
background: #ffffff;
border-radius: 12rpx;
padding: 20rpx;
border: 1rpx solid #ebeef5;
height: 100%;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.pick-card__head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12rpx;
flex-wrap: wrap;
}
.pick-name {
font-size: 36rpx;
color: #303133;
font-weight: 600;
flex: 1;
}
.pick-cart-tag {
padding: 6rpx 16rpx;
border-radius: 999rpx;
background: #f0f9eb;
color: #67c23a;
font-size: 28rpx;
line-height: 1.4;
border: 1rpx solid #d9f0cf;
}
.pick-row {
display: flex;
align-items: center;
font-size: 34rpx;
line-height: 52rpx;
margin-top: 6rpx;
}
.detail-main {
display: flex;
align-items: flex-start;
gap: 16rpx;
}
.detail-main-left {
width: 200rpx;
min-width: 200rpx;
}
.goods-image {
border-radius: 10rpx;
overflow: hidden;
background: #f5f7fa;
}
.goods-image-single {
position: relative;
width: 200rpx;
height: 200rpx;
border-radius: 10rpx;
overflow: hidden;
background: #f5f7fa;
}
.image-index-badge {
position: absolute;
right: 8rpx;
bottom: 8rpx;
background: rgba(0, 0, 0, 0.5);
border-radius: 16rpx;
padding: 2rpx 12rpx;
display: flex;
align-items: center;
justify-content: center;
}
.image-index-text {
font-size: 22rpx;
color: #ffffff;
font-weight: 500;
}
.detail-main-right {
flex: 1;
min-width: 0;
cursor: pointer;
border-radius: 10rpx;
transition: all 0.2s ease;
}
.detail-main-right--matched {
background: #ecf5ff;
box-shadow: inset 0 0 0 2rpx #2979ff;
}
.pick-image-empty {
width: 200rpx;
height: 200rpx;
border-radius: 10rpx;
border: 1rpx dashed #dcdfe6;
color: #909399;
font-size: 22rpx;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
padding: 6rpx;
box-sizing: border-box;
}
.pick-row--top {
margin-top: 10rpx;
justify-content: space-between;
}
.alloc-panel {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.alloc-scroll {
flex: 1;
min-height: 0;
}
.pick-label {
width: 170rpx;
min-width: 170rpx;
color: #909399;
}
.pick-value {
color: #303133;
}
.pick-value--highlight {
color: #2979ff;
font-weight: 700;
}
.index-grid {
display: flex;
flex-wrap: wrap;
gap: 8rpx;
}
.alloc-wrap {
display: flex;
flex-wrap: wrap;
gap: 8rpx;
margin-top: 8rpx;
}
.alloc-item {
padding: 6rpx 12rpx;
border-radius: 999rpx;
background: #f2f7ff;
}
.alloc-text {
font-size: 30rpx;
color: #2979ff;
}
.alloc-empty {
font-size: 30rpx;
color: #909399;
margin-top: 8rpx;
}
.alloc-safe-bottom {
height: 8rpx;
}
.alloc-nav {
display: flex;
gap: 16rpx;
margin-top: 12rpx;
flex-shrink: 0;
}
.alloc-nav-btn {
flex: 1;
height: 64rpx;
border-radius: 10rpx;
display: flex;
align-items: center;
justify-content: center;
background: #f5f7fa;
border: 1rpx solid #dcdfe6;
}
.alloc-nav-btn--primary {
background: #2979ff;
border-color: #2979ff;
}
.alloc-nav-btn--disabled {
opacity: 0.4;
pointer-events: none;
}
.alloc-nav-btn__text {
font-size: 32rpx;
color: #606266;
font-weight: 500;
}
.alloc-nav-btn--primary .alloc-nav-btn__text {
color: #ffffff;
}
.index-cell {
flex: 0 0 calc((100% - 32rpx) / 5);
width: calc((100% - 32rpx) / 5);
aspect-ratio: 1 / 1;
box-sizing: border-box;
border-radius: 12rpx;
background: #f5f7fa;
border: 1rpx solid #e4e7ed;
display: flex;
align-items: center;
justify-content: center;
}
.index-cell--active {
background: #eaf2ff;
border-color: #2979ff;
}
.index-cell--picked {
background: #2d8a2d;
border-color: #1a6b1a;
}
.index-cell--picked .index-text {
color: #ffffff;
}
.bind-cart-popup {
padding: 20rpx 24rpx 28rpx;
box-sizing: border-box;
}
.popup-header {
display: flex;
align-items: center;
justify-content: center;
padding: 8rpx 0 18rpx;
}
.popup-title {
font-size: 32rpx;
color: #303133;
font-weight: 600;
}
.bind-cart-form {
padding: 0 0 20rpx;
}
.bind-cart-search-row {
display: flex;
align-items: center;
gap: 12rpx;
}
.bind-cart-query-btn {
height: 68rpx;
border-radius: 12rpx;
display: flex;
align-items: center;
justify-content: center;
padding: 0 18rpx;
box-sizing: border-box;
font-size: 26rpx;
flex-shrink: 0;
}
.bind-cart-query-btn {
min-width: 96rpx;
background: #2979ff;
color: #ffffff;
}
.bind-cart-tip {
margin-top: 10rpx;
font-size: 22rpx;
color: #909399;
}
.bind-cart-list {
max-height: 420rpx;
padding: 0 0 20rpx;
box-sizing: border-box;
}
.bind-cart-empty {
padding: 20rpx 0;
text-align: center;
font-size: 26rpx;
color: #909399;
}
.bind-cart-item {
margin-bottom: 12rpx;
padding: 18rpx;
border-radius: 14rpx;
background: #f8f9fa;
border: 1rpx solid #ebeef5;
}
.bind-cart-item--active {
background: #ecf5ff;
border-color: #2979ff;
}
.bind-cart-item__head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12rpx;
}
.bind-cart-item__title {
font-size: 28rpx;
color: #303133;
font-weight: 600;
}
.bind-cart-item__bound {
font-size: 22rpx;
color: #67c23a;
padding: 2rpx 10rpx;
border-radius: 999rpx;
background: #f0f9eb;
border: 1rpx solid #d9f0cf;
line-height: 1.4;
flex-shrink: 0;
}
.bind-cart-item__status {
font-size: 22rpx;
color: #67c23a;
}
.bind-cart-item__desc {
display: block;
margin-top: 8rpx;
font-size: 24rpx;
color: #606266;
}
.bind-cart-actions {
display: flex;
align-items: center;
gap: 16rpx;
}
.bind-cart-btn {
flex: 1;
height: 76rpx;
border-radius: 12rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 28rpx;
font-weight: 500;
}
.bind-cart-btn--cancel {
background: #f5f7fa;
color: #606266;
}
.bind-cart-btn--confirm {
background: #2979ff;
color: #ffffff;
}
.index-text {
font-size: 34rpx;
font-weight: 600;
color: #2979ff;
}
.safe-bottom {
height: calc(20rpx + env(safe-area-inset-bottom));
}
</style>