2026-08-30 17:52:14 +08:00

2536 lines
68 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="goods-query-page">
<view class="normar_container">
<view class="page-header">
<page-nav :title="title">
<template #right>
<view class="nav-mode-switch-group">
<view
class="nav-mode-switch-btn"
:class="{ 'nav-mode-switch-btn--active': queryMode === 'batch' }"
@click="setQueryMode('batch')"
>
<text class="nav-mode-switch-btn__text">批次</text>
</view>
<view
class="nav-mode-switch-btn"
:class="{ 'nav-mode-switch-btn--active': queryMode === 'nonBatch' }"
@click="setQueryMode('nonBatch')"
>
<text class="nav-mode-switch-btn__text">非批次</text>
</view>
</view>
</template>
</page-nav>
<view class="search-panel">
<view class="search-input-wrap">
<u-search
v-model="keyword"
placeholder="请输入商品条码或名称"
:bg-color="'#f5f5f5'"
shape="round"
:show-action="false"
@search="handleSearch"
@clear="handleSearch"
></u-search>
<view class="search-actions">
<view class="scan-btn" @click="handleCameraScan">
<u-icon name="scan" size="38rpx" color="#2979ff"></u-icon>
</view>
<view class="search-divider"></view>
<view class="search-btn" @click="handleSearch">
<text class="search-btn__text">搜索</text>
</view>
</view>
</view>
</view>
</view>
<view class="list-content-wrap">
<scroll-view class="list-content" scroll-y :scroll-top="restoreScrollTop" @scroll="handleListScroll">
<view v-if="!loading && list.length === 0" class="empty-state">
<u-icon name="search" size="88" color="#c0c4cc"></u-icon>
<text class="empty-text">暂无商品数据</text>
<text class="empty-hint">请输入关键字进行查询</text>
</view>
<view v-else class="list-wrap">
<view class="goods-item" v-for="(item, index) in list" :key="getGoodsItemKey(item, index)">
<view class="item-summary">
<view class="item-title-row">
<text class="goods-name">{{ item.item_name || item.product_name || item.name || '未命名商品' }}</text>
</view>
<view class="item-main-row">
<view class="item-thumb" @click.stop="previewProductImage(item)">
<u-image
class="goods-image"
:src="getImageUrl(item)"
mode="aspectFill"
width="140rpx"
height="140rpx"
>
<template #error>
<view class="image-placeholder">
<u-icon name="photo" size="32" color="#c0c4cc"></u-icon>
</view>
</template>
</u-image>
<view v-if="getImageCount(item) > 1" class="image-index-badge">
<text class="image-index-text">1/{{ getImageCount(item) }}</text>
</view>
</view>
<view class="item-info">
<view class="item-row">
<text class="label">货主:</text>
<text class="value">{{ getStoreOwnerText(item) }}</text>
</view>
<view class="item-row">
<text class="label">商品编码:</text>
<text class="value">{{ item.item_code || item.goods_code || '--' }}</text>
</view>
<view class="item-row">
<text class="label">条码:</text>
<text class="value">{{ getBarcodeText(item) }}</text>
</view>
<view class="item-row">
<text class="label">SKU规格:</text>
<text class="value">{{ item.sku_property || '--' }}</text>
</view>
<view v-if="hasBatchNumber(item)" class="item-row">
<text class="label">批次号:</text>
<text class="value">{{ getBatchNumberText(item) }}</text>
</view>
</view>
<view class="item-arrow" @click.stop="goProductDetail(item)">
<u-icon name="arrow-right" size="18" color="#c0c4cc" :custom-style="{ pointerEvents: 'none' }"></u-icon>
</view>
</view>
</view>
<view v-if="queryMode === 'nonBatch'" class="storage-section" :id="`storage-section-${getStorageSectionKey(item, index, 'nonBatch')}`">
<view class="storage-head-fixed" :style="getLocalStorageHeadWrapStyle(getStorageSectionKey(item, index, 'nonBatch'), 9 + index)">
<view
class="storage-table storage-table--non-batch storage-table--head-table"
:style="getStorageHeadStyle(getStorageSectionKey(item, index, 'nonBatch'))"
>
<view class="storage-table__head storage-table__row">
<text class="storage-col storage-col--space">库位</text>
<text class="storage-col storage-col--qty storage-col--qty-stock">库存</text>
<text class="storage-col storage-col--qty storage-col--qty-available">可移库存</text>
</view>
</view>
</view>
<scroll-view
class="storage-scroll storage-scroll--body"
scroll-x
:scroll-y="shouldEnableStorageVerticalScroll(item, 'nonBatch')"
:style="getStorageBodyStyle(item, 'nonBatch')"
@scroll="handleStorageHorizontalScroll(getStorageSectionKey(item, index, 'nonBatch'), $event)"
>
<view class="storage-table storage-table--non-batch">
<template v-if="getStorageList(item).length">
<view
v-for="(storageItem, storageIndex) in getStorageList(item)"
:key="getStorageItemKey(storageItem, storageIndex)"
class="storage-table__row"
>
<text class="storage-col storage-col--space">{{ getStorageSpaceText(storageItem) }}</text>
<text class="storage-col storage-col--qty storage-col--qty-stock">{{ getStorageQuantityText(storageItem) }}</text>
<text
class="storage-col storage-col--qty"
:class="{
'storage-col--highlight storage-col--action': !(queryMode === 'nonBatch' && isBatchManagedItem(item, storageItem)),
'storage-col--disabled': queryMode === 'nonBatch' && isBatchManagedItem(item, storageItem)
}"
@click.stop="openRelocationPage(item, storageItem, 'available')"
>{{ getStorageAvailableText(storageItem) }}</text>
</view>
</template>
<view v-else class="storage-table__row storage-table__row--empty">
<text class="storage-col storage-empty-text">暂无库存数据</text>
</view>
</view>
</scroll-view>
</view>
<view v-if="queryMode === 'batch'" class="storage-section" :id="`storage-section-${getStorageSectionKey(item, index, 'batch')}`">
<view class="storage-head-fixed" :style="getLocalStorageHeadWrapStyle(getStorageSectionKey(item, index, 'batch'), 9 + index)">
<view
class="storage-table storage-table--batch storage-table--head-table"
:style="getStorageHeadStyle(getStorageSectionKey(item, index, 'batch'))"
>
<view class="storage-table__head storage-table__row">
<text class="storage-col storage-col--batch">批次号</text>
<text class="storage-col storage-col--space">库位</text>
<text class="storage-col storage-col--qty storage-col--qty-stock">库存</text>
<text class="storage-col storage-col--qty storage-col--qty-available">可移库存</text>
</view>
</view>
</view>
<scroll-view
class="storage-scroll storage-scroll--body"
scroll-x
:scroll-y="shouldEnableStorageVerticalScroll(item, 'batch')"
:style="getStorageBodyStyle(item, 'batch')"
@scroll="handleStorageHorizontalScroll(getStorageSectionKey(item, index, 'batch'), $event)"
>
<view class="storage-table storage-table--batch">
<template v-if="getBatchStorageDisplayList(item).length">
<view
v-for="(storageItem, storageIndex) in getBatchStorageDisplayList(item)"
:key="getBatchStorageItemKey(item, storageItem, storageIndex)"
class="storage-table__row"
>
<text class="storage-col storage-col--batch">{{ getBatchNumberBySource(storageItem, item) }}</text>
<text class="storage-col storage-col--space">{{ getStorageSpaceText(storageItem) }}</text>
<text class="storage-col storage-col--qty storage-col--qty-stock">{{ getStorageQuantityText(storageItem) }}</text>
<text class="storage-col storage-col--qty storage-col--highlight storage-col--action" @click.stop="openRelocationPage(item, storageItem, 'available')">{{ getStorageAvailableText(storageItem) }}</text>
</view>
</template>
<view v-else class="storage-table__row storage-table__row--empty">
<text class="storage-col storage-empty-text">暂无库存数据</text>
</view>
</view>
</scroll-view>
</view>
</view>
</view>
<view v-if="!loading && list.length > 0" class="end-tip">没有更多了</view>
<view class="safe-area-bottom"></view>
</scroll-view>
</view>
</view>
<u-loading-page :loading="loading" bg-color="rgba(255,255,255,0.9)"></u-loading-page>
</view>
</template>
<script>
export default {
data() {
return {
title: '商品查询',
keyword: '',
queryMode: 'nonBatch',
loading: false,
list: [],
rawList: [],
restoreScrollTop: 0,
listScrollTopCache: 0,
storageScrollLeftMap: {},
storageSectionMetas: [],
storageHeaderHeight: 0,
pageHeaderHeight: 0,
storageMetaRefreshTimer: null,
floatingStorageHeader: {
visible: false,
mode: 'nonBatch',
sectionKey: '',
top: 0
},
routeStockId: '',
// 搜索请求序号:用于竞态保护,只有最新一次搜索的结果才会被采用
searchSeq: 0,
// 商品图片/条码缓存(按商品 id),避免重复搜索重复请求;TTL 5 分钟
productImageCache: {},
productBarcodeCache: {},
CACHE_TTL: 5 * 60 * 1000
}
},
computed: {
showGlobalStorageHeader() {
if (this.loading || !Array.isArray(this.list) || !this.list.length) {
return false;
}
return this.list.some(item => {
const storageList = this.queryMode === 'batch'
? this.getBatchStorageList(item)
: this.getStorageList(item);
return Array.isArray(storageList) && storageList.length > 0;
});
},
globalStorageHeaderTop() {
const visualOffset = 0;
const currentTop = Number(this.floatingStorageHeader.top || 0);
if (currentTop > 0) {
return currentTop;
}
const firstMeta = Array.isArray(this.storageSectionMetas) && this.storageSectionMetas.length
? this.storageSectionMetas[0]
: null;
const summaryHeight = Number((firstMeta && firstMeta.summaryHeight) || 0);
const summaryGap = Number((firstMeta && firstMeta.summaryGap) || 0);
return this.pageHeaderHeight + summaryHeight + summaryGap + visualOffset;
}
},
onLoad(options) {
this.safeDispatchBroadcast('setCallbacks', {
onResult: this.handleBroadcastResult
});
this.safeDispatchBroadcast('start');
// 监听商品保存成功事件,失效对应商品的图片/条码缓存,避免返回查询页后仍显示旧值
uni.$on('product:query:updated', this.handleProductQueryUpdated);
this.routeStockId = options?.stock_id || '';
// 优先从存储中读取关键字(解决 URL 传参中文乱码问题)
const storageKeyword = uni.getStorageSync('replenish_query_keyword') || '';
const routeKeyword = this.normalizeKeyword(storageKeyword || options?.keyword || options?.barcode || options?.code || '');
if (storageKeyword) {
uni.removeStorageSync('replenish_query_keyword');
}
if (routeKeyword) {
this.keyword = routeKeyword;
}
this.list = [];
if (routeKeyword) {
this.handleSearch({
silentVoice: true
});
}
},
onShow() {
this.safeDispatchBroadcast('setCallbacks', {
onResult: this.handleBroadcastResult
});
this.safeDispatchBroadcast('resume');
const relocationRefreshMark = Number(uni.getStorageSync('product_query_need_refresh') || 0);
if (relocationRefreshMark > 0) {
uni.removeStorageSync('product_query_need_refresh');
const keyword = this.normalizeKeyword(this.keyword);
if (keyword) {
this.keyword = keyword;
this.handleSearch({
silentVoice: true
});
}
}
const cachedTop = Number(uni.getStorageSync('product_query_scroll_top') || 0);
this.$nextTick(() => {
const top = cachedTop > 0 ? cachedTop : 0;
this.restoreScrollTop = top;
this.listScrollTopCache = top;
this.refreshStorageSectionMetas();
});
},
onHide() {
uni.setStorageSync('product_query_scroll_top', this.listScrollTopCache || 0);
this.safeDispatchBroadcast('pause');
this.stopQuerySpeak();
},
onUnload() {
uni.$off('product:query:updated', this.handleProductQueryUpdated);
if (this.storageMetaRefreshTimer) {
clearTimeout(this.storageMetaRefreshTimer);
this.storageMetaRefreshTimer = null;
}
this.safeDispatchBroadcast('stop');
this.stopQuerySpeak();
},
methods: {
handleProductQueryUpdated(event) {
// 商品在编辑页保存成功:失效该商品的图片/条码缓存,保证下次搜索拉到最新数据
const payload = (event && event.item) || {};
const updatedId = this.normalizePositiveId(payload.id || payload.stock_id || payload.goods_id);
if (updatedId) {
delete this.productImageCache[updatedId];
delete this.productBarcodeCache[updatedId];
} else {
// 拿不到 id 时兜底清空缓存
this.productImageCache = {};
this.productBarcodeCache = {};
}
},
getGoodsItemKey(item, index) {
if (!item || typeof item !== 'object') {
return `goods_${index}`;
}
const baseKey = item.id
|| item.goods_id
|| item.item_id
|| item.goods_code
|| item.item_code
|| item.barcode
|| item.code
|| 'unknown';
return `goods_${baseKey}_${index}`;
},
safeDispatchBroadcast(action, payload) {
try {
const task = this.$store.dispatch(`broadcast/${action}`, payload);
if (task && typeof task.catch === 'function') {
task.catch(error => {
console.warn(`[ProductQuery] broadcast/${action} 调用失败:`, error);
});
}
} catch (error) {
console.warn(`[ProductQuery] broadcast/${action} 调用异常:`, error);
}
},
normalizeSpeechText(message) {
const rawText = String(message || '').trim();
if (!rawText) {
return '';
}
const digitMap = {
'0': '零',
'1': '一',
'2': '二',
'3': '三',
'4': '四',
'5': '五',
'6': '六',
'7': '七',
'8': '八',
'9': '九'
};
const normalizeCodeSegment = (segment) => {
return segment
.split('-')
.map(part => String(part || '')
.split('')
.map(char => (digitMap[char] || char))
.join(''))
.join('的');
};
return rawText.replace(/([A-Za-z0-9]+(?:-[A-Za-z0-9]+)+)/g, normalizeCodeSegment);
},
speakQueryMessage(message, options = {}) {
const text = this.normalizeSpeechText(message);
if (!text) {
return;
}
const tools = this.$tools;
if (!tools || typeof tools.speakText !== 'function') {
return;
}
try {
const task = tools.speakText(text, options);
if (task && typeof task.catch === 'function') {
task.catch(error => {
console.warn('[ProductQuery] 语音播报失败:', error);
});
}
} catch (error) {
console.warn('[ProductQuery] 语音播报异常:', error);
}
},
stopQuerySpeak() {
const tools = this.$tools;
if (!tools || typeof tools.stopSpeak !== 'function') {
return;
}
try {
tools.stopSpeak();
} catch (error) {
console.warn('[ProductQuery] 停止语音播报异常:', error);
}
},
getSearchVoiceText(keyword, count) {
const normalizedCount = Number(count || 0);
const modeText = this.queryMode === 'batch' ? '批次模式' : '非批次模式';
if (normalizedCount > 0) {
return `${modeText},查询到${normalizedCount}条商品`;
}
const normalizedKeyword = String(keyword || '').trim();
if (normalizedKeyword) {
return `${modeText},未查询到${normalizedKeyword}相关商品`;
}
return `${modeText},未查询到商品`;
},
handleListScroll(event) {
const top = event && event.detail ? Number(event.detail.scrollTop || 0) : 0;
this.listScrollTopCache = top;
if ((!this.storageSectionMetas.length || !this.pageHeaderHeight) && this.list.length) {
this.scheduleRefreshStorageSectionMetas();
}
this.updateFloatingStorageHeader(top);
},
getStorageSectionKey(item, index, mode = 'nonBatch') {
if (!item || typeof item !== 'object') {
return `${mode}_${index}`;
}
return `${mode}_${item.id || item.goods_code || item.item_code || item.barcode || index}`;
},
getStorageScrollLeft(sectionKey) {
return Number(this.storageScrollLeftMap[sectionKey] || 0);
},
handleStorageHorizontalScroll(sectionKey, event) {
const scrollLeft = event && event.detail ? Number(event.detail.scrollLeft || 0) : 0;
if (this.getStorageScrollLeft(sectionKey) === scrollLeft) {
return;
}
this.$set(this.storageScrollLeftMap, sectionKey, scrollLeft);
if (this.floatingStorageHeader.visible && this.floatingStorageHeader.sectionKey === sectionKey) {
this.floatingStorageHeader = {
...this.floatingStorageHeader,
sectionKey
};
}
},
getStorageHeadStyle(sectionKey) {
const scrollLeft = this.getStorageScrollLeft(sectionKey);
return {
transform: `translateX(-${scrollLeft}px)`
};
},
getLocalStorageHeadWrapStyle(sectionKey, zIndex = 1) {
const top = 0;
return {
top: `${top}px`,
'--storage-head-offset': `${top}px`,
zIndex
};
},
waitForNextTick() {
return new Promise(resolve => {
this.$nextTick(resolve);
});
},
wait(ms = 0) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
},
scheduleRefreshStorageSectionMetas(delays = [0, 80, 200, 400]) {
if (!Array.isArray(delays) || !delays.length) {
return;
}
if (this.storageMetaRefreshTimer) {
clearTimeout(this.storageMetaRefreshTimer);
this.storageMetaRefreshTimer = null;
}
const queue = [...delays];
const run = () => {
const delay = Number(queue.shift() || 0);
this.storageMetaRefreshTimer = setTimeout(() => {
this.refreshStorageSectionMetas();
if (queue.length) {
run();
} else {
this.storageMetaRefreshTimer = null;
}
}, delay);
};
run();
},
refreshStorageSectionMetas() {
this.$nextTick(() => {
const query = uni.createSelectorQuery().in(this);
query.select('.page-header').boundingClientRect();
query.select('.list-content').boundingClientRect();
query.select('.storage-head-fixed').boundingClientRect();
query.selectAll('.item-summary').boundingClientRect();
query.selectAll('.storage-head-fixed').boundingClientRect();
query.selectAll('.storage-section').boundingClientRect();
query.exec(result => {
const pageHeaderRect = result && result[0] ? result[0] : null;
const listRect = result && result[1] ? result[1] : null;
const headerRect = result && result[2] ? result[2] : null;
const summaryRects = (result && result[3]) || [];
const storageHeadRects = (result && result[4]) || [];
const sectionRects = (result && result[5]) || [];
this.pageHeaderHeight = pageHeaderRect && pageHeaderRect.height ? Number(pageHeaderRect.height) : 0;
if (!listRect || !Array.isArray(sectionRects) || !sectionRects.length) {
this.storageSectionMetas = [];
this.storageHeaderHeight = headerRect && headerRect.height ? Number(headerRect.height) : 0;
this.updateFloatingStorageHeader(this.listScrollTopCache);
return;
}
const headerHeight = headerRect && headerRect.height ? Number(headerRect.height) : 0;
let sectionCursor = 0;
const metas = [];
(this.list || []).forEach((item, index) => {
const rect = sectionRects[sectionCursor++];
const storageHeadRect = storageHeadRects[sectionCursor - 1];
if (!rect) {
return;
}
const summaryRect = summaryRects[index] || null;
metas.push({
key: this.getStorageSectionKey(item, index, this.queryMode),
mode: this.queryMode,
top: this.listScrollTopCache + Number(rect.top || 0) - Number(listRect.top || 0),
height: Number(rect.height || 0),
headerHeight,
summaryHeight: Number((summaryRect && summaryRect.height) || 0),
summaryGap: Math.max(
Number((storageHeadRect && storageHeadRect.top) || rect.top || 0) - (
Number((summaryRect && summaryRect.top) || 0)
+ Number((summaryRect && summaryRect.height) || 0)
),
0
)
});
});
this.storageHeaderHeight = headerHeight;
this.storageSectionMetas = metas;
this.updateFloatingStorageHeader(this.listScrollTopCache);
});
});
},
updateFloatingStorageHeader(scrollTop = 0) {
const passedMetas = this.storageSectionMetas.filter(meta => {
const startTop = meta.top
- Math.max(Number(meta.summaryHeight || 0), 0)
- Math.max(Number(meta.summaryGap || 0), 0);
return scrollTop >= startTop;
});
const activeMeta = passedMetas.length ? passedMetas[passedMetas.length - 1] : null;
if (!activeMeta) {
this.floatingStorageHeader = {
visible: false,
mode: this.queryMode,
sectionKey: '',
top: 0
};
return;
}
this.floatingStorageHeader = {
visible: true,
mode: activeMeta.mode,
sectionKey: activeMeta.key,
top: this.pageHeaderHeight + Math.max(
Math.max(Number(activeMeta.summaryHeight || 0), 0)
+ Math.max(Number(activeMeta.summaryGap || 0), 0)
- Math.max(
scrollTop - (
activeMeta.top
- Math.max(Number(activeMeta.summaryHeight || 0), 0)
- Math.max(Number(activeMeta.summaryGap || 0), 0)
),
0
),
0
)
};
},
normalizeKeyword(value) {
return String(value || '').replace(/\s+/g, '');
},
normalizeScanResult(scanResult) {
if (!scanResult) {
return '';
}
if (typeof scanResult === 'string') {
return this.normalizeKeyword(scanResult);
}
if (typeof scanResult.result === 'string') {
return this.normalizeKeyword(scanResult.result);
}
if (Array.isArray(scanResult.result)) {
const firstResult = scanResult.result.find(item => item);
if (typeof firstResult === 'string') {
return this.normalizeKeyword(firstResult);
}
if (firstResult && typeof firstResult.data === 'string') {
return this.normalizeKeyword(firstResult.data);
}
}
if (typeof scanResult.data === 'string') {
return this.normalizeKeyword(scanResult.data);
}
return '';
},
handleBroadcastResult(result) {
const scanResult = this.normalizeScanResult(result);
if (!scanResult) {
return;
}
this.keyword = scanResult;
this.handleSearch();
},
handleCameraScan() {
uni.scanCode({
onlyFromCamera: true,
scanType: ['barCode', 'qrCode', 'datamatrix', 'pdf417'],
success: (res) => {
const scanResult = this.normalizeScanResult(res);
if (!scanResult) {
uni.showToast({
title: '未识别到有效条码',
icon: 'none'
});
return;
}
this.keyword = scanResult;
this.handleSearch();
},
fail: (error) => {
const errMsg = String(error?.errMsg || '').toLowerCase();
if (errMsg.includes('cancel')) {
return;
}
uni.showToast({
title: '扫码失败,请重试',
icon: 'none'
});
}
});
},
/**
* 带并发上限的 map 执行器:结果与入参顺序一一对应(形态同 Promise.allSettled)
* @param {Array} items 待处理数组
* @param {Number} limit 最大并发数
* @param {Function} mapper 异步处理函数 (item, index) => Promise
* @returns {Promise<Array>} [{ status: 'fulfilled'|'rejected', value | reason }]
*/
async runMapWithConcurrency(items, limit, mapper) {
const source = Array.isArray(items) ? items : [];
if (!source.length) {
return [];
}
const results = new Array(source.length);
const maxConcurrency = Math.max(1, Math.min(Number(limit) || 1, source.length));
let cursor = 0;
const worker = async () => {
while (cursor < source.length) {
const index = cursor;
cursor += 1;
try {
const value = await mapper(source[index], index);
results[index] = { status: 'fulfilled', value };
} catch (error) {
results[index] = { status: 'rejected', reason: error };
}
}
};
const workers = [];
for (let i = 0; i < maxConcurrency; i++) {
workers.push(worker());
}
await Promise.all(workers);
return results;
},
/**
* 从 index.getImages 接口获取商品图片
* @param {Array} mergedList 合并后的商品列表
* @param {Array} warehouseList 仓库列表(包含 id 字段)
*/
async fetchProductImages(mergedList, warehouseList) {
if (!Array.isArray(mergedList) || !mergedList.length) {
return;
}
// 从 warehouseList 中收集有 id 的商品
const warehouseItemMap = new Map();
(warehouseList || []).forEach(item => {
if (item && item.id) {
warehouseItemMap.set(item.id, item);
}
});
// 找到 mergedList 中需要获取图片的商品
const itemsToFetch = [];
mergedList.forEach(item => {
if (!item || typeof item !== 'object') {
return;
}
const id = item.id || item.stock_id;
if (!id) {
return;
}
// 已加载过图片则跳过
if (Array.isArray(item.images) && item.images.length) {
return;
}
// 命中缓存直接回填,避免重复请求
const cached = this.productImageCache[id];
if (cached && Array.isArray(cached.data) && cached.data.length && (Date.now() - cached.ts < this.CACHE_TTL)) {
item.images = cached.data;
return;
}
if (warehouseItemMap.has(id) || !warehouseItemMap.size) {
itemsToFetch.push({ item, id });
}
});
if (!itemsToFetch.length) {
return;
}
console.log('[ProductQuery] 开始获取商品图片,数量:', itemsToFetch.length);
// 限制并发请求图片,避免 PDA 上一股脑发起大量请求导致卡顿
const results = await this.runMapWithConcurrency(
itemsToFetch,
4,
async ({ id }) => this.$http('common.getImages', { type: 'stock', id })
);
// 将图片数据关联到对应商品
itemsToFetch.forEach(({ item, id }, index) => {
const result = results[index];
if (result.status === 'rejected') {
return;
}
const response = result.value;
if (!response || response.code !== 200) {
return;
}
const imageData = this.extractListFromResponse(response);
if (!Array.isArray(imageData) || !imageData.length) {
return;
}
// 提取图片 URL 列表
const imageUrls = imageData
.map(img => {
if (!img) return '';
if (typeof img === 'string') return img;
// 嵌套 file 对象: { file: { file_url, file_name } }
if (img.file && typeof img.file === 'object') {
return img.file.file_url || img.file.url || img.file.path || '';
}
return img.url || img.path || img.image_url || img.fileUrl || img.successUrl || '';
})
.filter(Boolean);
if (imageUrls.length > 0) {
item.images = imageUrls;
this.productImageCache[id] = { data: imageUrls, ts: Date.now() };
console.log(`[ProductQuery] 商品 id=${item.id} 获取到 ${imageUrls.length} 张图片`);
}
});
},
/**
* 从 stock.warehouse.getBarcodes 接口获取商品条码
* @param {Array} mergedList 合并后的商品列表
*/
async fetchProductBarcodes(mergedList) {
if (!Array.isArray(mergedList) || !mergedList.length) {
return;
}
const itemsToFetch = [];
mergedList.forEach(item => {
if (!item || typeof item !== 'object') {
return;
}
const id = item.id || item.stock_id;
if (!id) {
return;
}
// 已加载过条码则跳过
if (Array.isArray(item.barcodes) && item.barcodes.length) {
return;
}
// 命中缓存直接回填,避免重复请求
const cached = this.productBarcodeCache[id];
if (cached && Array.isArray(cached.data) && cached.data.length && (Date.now() - cached.ts < this.CACHE_TTL)) {
item.barcodes = cached.data;
return;
}
itemsToFetch.push(item);
});
if (!itemsToFetch.length) {
return;
}
console.log('[ProductQuery] 开始获取商品条码,数量:', itemsToFetch.length);
const results = await this.runMapWithConcurrency(
itemsToFetch,
4,
async (item) => {
const id = item.id || item.stock_id;
return this.$http('stock.warehouse.getBarcodes', { id: Number(id) });
}
);
itemsToFetch.forEach((item, index) => {
const result = results[index];
if (result.status === 'rejected') {
return;
}
const response = result.value;
if (!response || response.code !== 200) {
return;
}
const barcodeList = this.extractBarcodeListFromResponse(response);
const allBarcodes = (barcodeList || [])
.map(entry => {
if (!entry) return '';
if (typeof entry === 'string') return entry.trim();
if (typeof entry !== 'object') return '';
return String(entry.barcode || entry.code || '').trim();
})
.filter(Boolean);
if (allBarcodes.length > 0) {
item.barcodes = allBarcodes;
const id = item.id || item.stock_id;
if (id) {
this.productBarcodeCache[id] = { data: allBarcodes, ts: Date.now() };
}
console.log(`[ProductQuery] 商品 id=${item.id || item.stock_id} 获取到 ${allBarcodes.length} 个条码`);
}
});
},
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 [];
},
getBarcodeText(item) {
if (!item || typeof item !== 'object') {
return '--';
}
const barcodes = item.barcodes;
if (Array.isArray(barcodes) && barcodes.length > 0) {
return barcodes.filter(code => code !== null && code !== undefined && code !== '').join(';');
}
if (typeof barcodes === 'string' && barcodes.trim()) {
return barcodes;
}
return item.barcode || item.code || '--';
},
getValueOrDash(value) {
return value === null || value === undefined || value === '' ? '--' : value;
},
getStoreOwnerText(item) {
if (!item || typeof item !== 'object') {
return '--';
}
const directValue = item['store.store_remask'] || item['store_stock.store_remask'] || item.store_remask;
if (directValue !== null && directValue !== undefined && directValue !== '') {
return directValue;
}
if (item.store_stock && typeof item.store_stock === 'object' && item.store_stock.store_remask) {
return item.store_stock.store_remask;
}
if (item.store && typeof item.store === 'object' && item.store.store_remask) {
return item.store.store_remask;
}
const nestedValue = this.findStoreRemaskValue(item);
if (nestedValue) {
return nestedValue;
}
return '--';
},
findStoreRemaskValue(source, visited = new Set()) {
if (!source || typeof source !== 'object') {
return '';
}
if (visited.has(source)) {
return '';
}
visited.add(source);
if (typeof source.store_remask === 'string' && source.store_remask.trim()) {
return source.store_remask.trim();
}
const keys = Object.keys(source);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = source[key];
if (key === 'store_remask' && value) {
return String(value).trim();
}
if (value && typeof value === 'object') {
const nested = this.findStoreRemaskValue(value, visited);
if (nested) {
return nested;
}
}
}
return '';
},
isBarcodeLike(value) {
const text = this.normalizeKeyword(value);
if (!text) {
return false;
}
// 纯数字输入一律视为条码(商品名称极少为纯数字)
if (/^\d+$/.test(text)) {
return true;
}
// 其他情况:长度 >= 6 且为字母/数字组合视为条码
return text.length >= 6 && /^[A-Za-z0-9._-]+$/.test(text);
},
extractBarcodeList(item) {
if (!item || typeof item !== 'object') {
return [];
}
let values = [];
if (Array.isArray(item.barcodes)) {
values = values.concat(item.barcodes);
} else if (typeof item.barcodes === 'string' && item.barcodes.trim()) {
values = values.concat(item.barcodes.split(/[;,,\s]+/));
}
values = values.concat([
item.barcode,
item.code,
item.item_barcode,
item.goods_barcode,
item.product_barcode,
item.sku_barcode,
item.bar_code,
item.qr_code
]);
return [...new Set(values
.map(code => this.normalizeKeyword(code))
.filter(Boolean)
)];
},
filterByBarcodeFuzzy(list, keyword) {
const target = this.normalizeKeyword(keyword);
if (!target) {
return list;
}
return (list || []).filter(item =>
this.extractBarcodeList(item).some(barcode => barcode.includes(target))
);
},
extractListFromResponse(response) {
const responseData = response && response.data;
if (Array.isArray(responseData)) {
return responseData;
}
if (responseData && Array.isArray(responseData.list)) {
return responseData.list;
}
if (responseData && Array.isArray(responseData.rows)) {
return responseData.rows;
}
if (responseData && Array.isArray(responseData.data)) {
return responseData.data;
}
return [];
},
getProductMatchKeys(item) {
if (!item || typeof item !== 'object') {
return [];
}
const values = [
item.id,
item.stock_id,
item.goods_id,
item.item_id,
item.product_id,
item.goods_code,
item.item_code,
item.product_code,
item.barcode,
item.code
];
const barcodeList = this.extractBarcodeList(item);
return [...new Set(values
.concat(barcodeList)
.map(value => this.normalizeKeyword(value))
.filter(Boolean)
)];
},
mergeProductResultLists(searchList, warehouseList, detailList) {
const mergedMap = new Map();
const upsert = (sourceItem, preferSource = false) => {
if (!sourceItem || typeof sourceItem !== 'object') {
return;
}
const keys = this.getProductMatchKeys(sourceItem);
const matchedKey = keys.find(key => mergedMap.has(key));
const baseItem = matchedKey ? mergedMap.get(matchedKey) : null;
const mergedItem = baseItem
? (preferSource ? { ...baseItem, ...sourceItem } : { ...sourceItem, ...baseItem })
: { ...sourceItem };
keys.forEach(key => {
mergedMap.set(key, mergedItem);
});
};
(searchList || []).forEach(item => upsert(item, false));
(warehouseList || []).forEach(item => upsert(item, true));
(detailList || []).forEach(item => upsert(item, true));
const uniqueItems = [];
const seen = new Set();
mergedMap.forEach(item => {
if (seen.has(item)) {
return;
}
seen.add(item);
uniqueItems.push(item);
});
return uniqueItems;
},
getProductName(item) {
if (!item || typeof item !== 'object') {
return '';
}
return String(item.item_name || item.product_name || item.name || '').trim();
},
getBatchNumberText(item) {
if (!item || typeof item !== 'object') {
return '--';
}
return item.batch_number || item.batch_no || item.lot_number || item.lot_no || '--';
},
hasBatchNumber(item) {
return this.getBatchNumberText(item) !== '--';
},
applyQueryModeFilter(list) {
if (!Array.isArray(list) || !list.length) {
return [];
}
if (this.queryMode === 'batch') {
return list;
}
return list.filter(item => !this.hasBatchNumber(item));
},
updateDisplayListByMode(sourceList, keyword, isBarcodeKeyword) {
// 无论是条码还是名称,都支持模糊匹配
const filteredByBarcode = this.filterByBarcodeFuzzy(sourceList, keyword);
const filteredByName = this.filterByNameContains(sourceList, keyword);
// 合并去重:以名称为主,补充条码模糊匹配到的额外结果
const mergedMap = new Map();
filteredByName.forEach(item => {
const keys = this.getProductMatchKeys(item);
const key = keys.find(k => k) || JSON.stringify(item);
mergedMap.set(key, item);
});
filteredByBarcode.forEach(item => {
const keys = this.getProductMatchKeys(item);
const key = keys.find(k => k) || JSON.stringify(item);
if (!mergedMap.has(key)) {
mergedMap.set(key, item);
}
});
const merged = Array.from(mergedMap.values());
this.list = this.applyQueryModeFilter(merged);
this.scheduleRefreshStorageSectionMetas();
},
buildQueryParams(keyword) {
const params = {
keyword,
with_stock: true,
is_batch: this.queryMode === 'batch'
};
if (this.routeStockId) {
params.stock_id = this.routeStockId;
}
return params;
},
buildWarehouseListWhereParams(keyword) {
const normalized = this.normalizeKeyword(keyword);
if (!normalized) {
return {};
}
const where = {};
if (normalized) {
if (this.isBarcodeLike(normalized)) {
where.barcode = {
operator: 'like',
value: normalized,
type: 'string'
};
} else {
where.item_name = {
operator: this.routeStockId ? 'eq' : 'like',
value: normalized,
type: 'string'
};
}
}
return where;
},
buildWarehouseListQueryParams(keyword) {
return {
with_stock: true,
is_batch: this.queryMode === 'batch',
where: this.buildWarehouseListWhereParams(keyword),
pagination: {
page: 1,
pageSize: 20
}
};
},
buildListWhereParams(stockIdList) {
const normalizedStockIdList = this.extractStockIdList(stockIdList);
if (!normalizedStockIdList.length) {
return {};
}
return {
stock_id: {
field: 'stock_id',
operator: 'in',
type: 'array',
value: normalizedStockIdList
}
};
},
extractStockIdList(source) {
const sourceList = Array.isArray(source) ? source : [];
const idSet = new Set();
sourceList.forEach(item => {
if (!item || typeof item !== 'object') {
return;
}
const stockIdCandidates = [
item.stock_id,
item.goods_id,
item.item_id,
item.product_id,
item.id
];
stockIdCandidates.forEach(candidate => {
const normalized = this.normalizePositiveId(candidate);
if (normalized) {
idSet.add(normalized);
}
});
});
return [...idSet];
},
buildListQueryParams(stockIdList) {
return {
where: this.buildListWhereParams(stockIdList),
pagination: {
page: 1,
pageSize: 20
},
sort: {
sortField: 'created_at',
sortOrder: 'DESC'
},
group_by_batch: this.queryMode === 'batch'
};
},
setQueryMode(nextMode) {
if (!nextMode || nextMode === this.queryMode) {
return;
}
this.queryMode = nextMode;
const keyword = this.normalizeKeyword(this.keyword);
if (!keyword) {
this.list = this.applyQueryModeFilter(this.rawList);
this.scheduleRefreshStorageSectionMetas();
return;
}
this.handleSearch();
},
filterByNameContains(list, keyword) {
const target = String(keyword || '').trim().toLowerCase();
if (!target) {
return list;
}
return (list || []).filter(item => {
const nameText = this.getProductName(item).toLowerCase();
return nameText.includes(target);
});
},
getImageUrl(item) {
if (!item || typeof item !== 'object') {
return '';
}
const candidate = item.image || item.image_url || item.img || item.pic || item.photo || item.cover || item.cover_url;
if (candidate) {
return String(candidate);
}
if (Array.isArray(item.images) && item.images.length > 0) {
const firstImage = item.images[0];
if (!firstImage) {
return '';
}
if (typeof firstImage === 'string') {
return firstImage;
}
if (typeof firstImage === 'object') {
return String(firstImage.url || firstImage.path || firstImage.successUrl || firstImage.fileUrl || firstImage.image_url || '');
}
return '';
}
if (Array.isArray(item.pics) && item.pics.length > 0) {
return String(item.pics[0]);
}
return '';
},
getImageList(item) {
if (!item || typeof item !== 'object') {
return [];
}
if (Array.isArray(item.images) && item.images.length > 0) {
return item.images
.map(image => {
if (!image) {
return '';
}
if (typeof image === 'string') {
return image;
}
if (typeof image === 'object') {
return image.url || image.path || image.successUrl || image.fileUrl || image.image_url || '';
}
return '';
})
.filter(Boolean);
}
if (Array.isArray(item.pics) && item.pics.length > 0) {
return item.pics.map(url => String(url)).filter(Boolean);
}
const single = this.getImageUrl(item);
return single ? [single] : [];
},
getImageThumbList(item) {
return this.getImageList(item).slice(0, 4);
},
getImageCount(item) {
return this.getImageList(item).length;
},
getStorageList(item) {
if (!item || typeof item !== 'object') {
return [];
}
if (Array.isArray(item.storage)) {
return item.storage.filter(entry => entry && typeof entry === 'object');
}
if (Array.isArray(item.wms_storage)) {
return item.wms_storage.filter(entry => entry && typeof entry === 'object');
}
return [];
},
getBatchStorageList(item) {
const storageList = this.getStorageList(item);
if (storageList.length) {
return storageList;
}
if (item && typeof item === 'object') {
return [item];
}
return [];
},
hasDirectStorageData(item) {
if (!item || typeof item !== 'object') {
return false;
}
return [
item.space_code,
item.space_name,
item.space_barcode,
item.location_name,
item.position_name,
item.quantity,
item.actual_quantity,
item.stock,
item.total_quantity,
item.qty,
item.available_quantity,
item.movable_quantity,
item.moveable_quantity,
item.can_move_quantity,
item.free_quantity,
item.usable_quantity
].some(value => value !== null && value !== undefined && value !== '');
},
getBatchStorageDisplayList(item) {
const storageList = this.getStorageList(item);
if (storageList.length) {
return storageList;
}
return this.hasDirectStorageData(item) ? [item] : [];
},
getStorageDisplayList(item, mode = 'nonBatch') {
return mode === 'batch' ? this.getBatchStorageDisplayList(item) : this.getStorageList(item);
},
getStorageRowCount(item, mode = 'nonBatch') {
const list = this.getStorageDisplayList(item, mode);
return Math.max(Array.isArray(list) ? list.length : 0, 1);
},
shouldEnableStorageVerticalScroll(item, mode = 'nonBatch') {
return this.getStorageRowCount(item, mode) > 4;
},
getStorageBodyStyle(item, mode = 'nonBatch') {
const minRows = 1;
const maxRows = 4;
// 与 CSS .storage-table__row 的 min-height:72rpx + padding:8rpx 0 保持一致
const rowHeight = 88;
const rowCount = this.getStorageRowCount(item, mode);
const visibleRows = Math.min(Math.max(rowCount, minRows), maxRows);
return {
minHeight: `${minRows * rowHeight}rpx`,
maxHeight: `${maxRows * rowHeight}rpx`,
height: `${visibleRows * rowHeight}rpx`
};
},
getStorageItemKey(item, index) {
if (!item || typeof item !== 'object') {
return index;
}
return item.id || item.space_id || item.storage_id || item.space_barcode || item.space_name || index;
},
getBatchStorageItemKey(sourceItem, storageItem, index) {
if (!storageItem || typeof storageItem !== 'object') {
return this.getStorageItemKey(sourceItem, index);
}
return storageItem.id
|| storageItem.batch_id
|| storageItem.space_id
|| `${this.getBatchNumberBySource(storageItem, sourceItem)}_${this.getStorageSpaceText(storageItem)}_${index}`;
},
getBatchNumberBySource(item, fallbackItem) {
const currentBatch = this.getBatchNumberText(item);
if (currentBatch !== '--') {
return currentBatch;
}
return this.getBatchNumberText(fallbackItem);
},
getStorageSpaceText(item) {
if (!item || typeof item !== 'object') {
return '--';
}
return item.custom_name
|| item.space?.custom_name
|| item.space_code
|| item.space?.code
|| item.space?.space_code
|| item.space?.name
|| item.space_name
|| item.space_barcode
|| item.location_name
|| item.position_name
|| item.name
|| '--';
},
getStorageQuantityText(item) {
if (!item || typeof item !== 'object') {
return '--';
}
return this.getValueOrDash(
item.quantity
?? item.actual_quantity
?? item.stock
?? item.total_quantity
?? item.qty
);
},
getStorageAvailableText(item) {
if (!item || typeof item !== 'object') {
return '--';
}
return this.getValueOrDash(
item.available_quantity
?? item.movable_quantity
?? item.moveable_quantity
?? item.can_move_quantity
?? item.free_quantity
?? item.usable_quantity
);
},
getStorageSpaceCode(item) {
if (!item || typeof item !== 'object') {
return '';
}
return item.space_barcode
|| item.space_code
|| item.space?.barcode
|| item.space?.code
|| item.space?.space_code
|| item.location_code
|| item.position_code
|| '';
},
getRelocationQuantityByType(item, quantityType = 'available') {
if (!item || typeof item !== 'object') {
return '';
}
const value = quantityType === 'stock'
? (item.quantity ?? item.actual_quantity ?? item.stock ?? item.total_quantity ?? item.qty)
: (item.available_quantity ?? item.movable_quantity ?? item.moveable_quantity ?? item.can_move_quantity ?? item.free_quantity ?? item.usable_quantity);
return value === null || value === undefined || value === '' ? '' : String(value);
},
normalizePositiveId(value) {
const numericValue = Number(value);
if (!Number.isFinite(numericValue)) {
return null;
}
const normalized = Math.trunc(numericValue);
return normalized > 0 ? normalized : null;
},
getRelocationStorageId(item) {
if (!item || typeof item !== 'object') {
return null;
}
const directCandidates = [
item.storage_id,
item.id
];
for (let i = 0; i < directCandidates.length; i++) {
const normalized = this.normalizePositiveId(directCandidates[i]);
if (normalized) {
return normalized;
}
}
return null;
},
getRelocationProductStockId(item) {
if (!item || typeof item !== 'object') {
return null;
}
const directCandidates = [
item.stock_id,
item.goods_id,
item.item_id,
item.product_id,
item.id
];
for (let i = 0; i < directCandidates.length; i++) {
const normalized = this.normalizePositiveId(directCandidates[i]);
if (normalized) {
return normalized;
}
}
return null;
},
openRelocationPage(productItem, storageItem, quantityType = 'available') {
if (!productItem || typeof productItem !== 'object' || !storageItem || typeof storageItem !== 'object') {
uni.showToast({
title: '缺少移库数据',
icon: 'none'
});
return;
}
const isNonBatchMode = this.queryMode === 'nonBatch';
if (isNonBatchMode && this.isBatchManagedItem(productItem, storageItem)) {
uni.showToast({
title: '该商品已开启批次管理,请在批次模式下移库!',
icon: 'none'
});
return;
}
const relocationStorageId = this.getRelocationStorageId(storageItem) || this.getRelocationStorageId(productItem);
const relocationProductStockId = this.getRelocationProductStockId(storageItem) || this.getRelocationProductStockId(productItem);
const sourceSpaceId = this.normalizePositiveId(
storageItem.space_id || storageItem.space?.id || productItem.space_id || productItem.space?.id
);
if (!isNonBatchMode && !relocationStorageId) {
uni.showToast({
title: '未获取到库存记录ID',
icon: 'none'
});
return;
}
if (isNonBatchMode && (!sourceSpaceId || !relocationProductStockId)) {
uni.showToast({
title: '未获取到库位或商品ID',
icon: 'none'
});
return;
}
const cacheKey = `relocation_prefill_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
uni.setStorageSync(cacheKey, {
stock: {
...productItem,
...storageItem,
relocation_storage_id: relocationStorageId,
relocation_product_stock_id: relocationProductStockId,
relocation_query_mode: this.queryMode
},
sourceSpace: {
id: sourceSpaceId || null,
name: this.getStorageSpaceText(storageItem),
code: this.getStorageSpaceCode(storageItem)
},
moveQuantity: this.getRelocationQuantityByType(storageItem, quantityType)
});
uni.navigateTo({
url: `/pages/work/storage/relocation?cacheKey=${cacheKey}`
});
},
isBatchManagedItem(productItem, storageItem) {
const candidates = [productItem, storageItem].filter(item => item && typeof item === 'object');
return candidates.some(item => item.is_batch_mgmt_enabled === true);
},
getExtraImageCount(item) {
const total = this.getImageList(item).length;
return total > 4 ? total - 4 : 0;
},
previewProductImage(item) {
const urls = this.getImageList(item);
if (!urls.length) {
uni.showToast({
title: '暂无可预览图片',
icon: 'none'
});
return;
}
uni.previewImage({
current: urls[0],
urls
});
},
async goProductDetail(item) {
if (!item || typeof item !== 'object') {
return;
}
// 进入详情前,按 id 精确拉取完整商品数据,避免列表合并/异步补充导致部分详情字段缺失
const itemId = this.normalizePositiveId(item.id || item.stock_id);
let detailItem = item;
if (itemId) {
try {
const res = await this.$http('stock.warehouse.list', {
with_stock: true,
where: {
id: {
operator: 'eq',
value: itemId,
type: 'number'
}
},
pagination: {
page: 1,
pageSize: 1
}
});
if (res && Number(res.code) === 200) {
const fetchedList = this.extractListFromResponse(res);
if (fetchedList && fetchedList.length) {
// 以完整商品数据为准,并保留列表项中的条码/图片等补充字段
detailItem = { ...item, ...fetchedList[0] };
}
}
} catch (error) {
console.warn('[ProductQuery] 获取商品完整详情失败:', error);
}
}
const cacheKey = `product_detail_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
uni.setStorageSync(cacheKey, detailItem);
uni.navigateTo({
url: `/pages/work/product/detail?cacheKey=${cacheKey}`
});
},
async handleSearch(options = {}) {
const silentVoice = !!(options && options.silentVoice);
const keyword = this.normalizeKeyword(this.keyword);
this.keyword = keyword;
console.log('[ProductQuery] 搜索内容:', keyword, '模式:', this.queryMode);
if (!keyword) {
this.rawList = [];
this.list = [];
this.storageSectionMetas = [];
this.floatingStorageHeader = {
visible: false,
mode: this.queryMode,
sectionKey: '',
top: 0
};
console.log('[ProductQuery] 搜索内容为空,结果已清空');
this.stopQuerySpeak();
return;
}
const isBarcodeKeyword = this.isBarcodeLike(keyword);
const queryParams = this.buildQueryParams(keyword);
const searchSeq = ++this.searchSeq;
console.log('[ProductQuery] 搜索参数:', queryParams);
this.loading = true;
try {
// 阶段1:stock.warehouse.search 与 stock.warehouse.list 互不依赖,并行发出
const warehouseListPromise = this.$http('stock.warehouse.list', this.buildWarehouseListQueryParams(keyword)).catch(error => {
console.warn('[ProductQuery] stock.warehouse.list 调用失败:', error);
return null;
});
const stage1StartTime = Date.now();
const [searchRes, warehouseRes] = await Promise.all([
this.$http('stock.warehouse.search', queryParams),
warehouseListPromise
]);
console.log('[ProductQuery] 阶段1 并行(search+list)耗时:', Date.now() - stage1StartTime, 'ms');
// 竞态保护:若已有更新的搜索发起,则丢弃本次结果,避免旧响应覆盖新结果
if (searchSeq !== this.searchSeq) {
return;
}
const searchOk = searchRes && searchRes.code === 200;
const warehouseOk = warehouseRes && warehouseRes.code === 200;
const nextList = searchOk ? this.extractListFromResponse(searchRes) : [];
const warehouseList = warehouseOk ? this.extractListFromResponse(warehouseRes) : [];
// 基础接口全部失败(此时 stockIdList 为空,inventory 也无法查询),按失败处理
if (!searchOk && !warehouseOk) {
this.rawList = [];
this.list = [];
console.log('[ProductQuery] 搜索失败响应:', searchRes || warehouseRes);
uni.showToast({
title: (searchRes && searchRes.message) || (warehouseRes && warehouseRes.message) || '查询失败',
icon: 'none'
});
if (!silentVoice) {
this.speakQueryMessage('查询失败,请重试');
}
return;
}
// 阶段1:先用 search + warehouse 渲染首屏,提前关闭 loading(真机上缩短串行等待)
let stockIdList = this.extractStockIdList([].concat(nextList || [], warehouseList || []));
// inventory.list 分页上限 20 条,只需传入前 20 个商品 id 即可。
// search 匹配大量商品时若传入全部 id,后端 IN 聚合查询会非常慢(真机实测约 4.5s)
const MAX_INVENTORY_STOCK_IDS = 20;
if (stockIdList.length > MAX_INVENTORY_STOCK_IDS) {
stockIdList = stockIdList.slice(0, MAX_INVENTORY_STOCK_IDS);
}
console.log('[ProductQuery] stockIdList 数量:', stockIdList.length);
let mergedList = this.mergeProductResultLists(nextList, warehouseList, []);
mergedList = this.applySearchStorageOverride(mergedList, nextList);
mergedList = this.applyRouteStockFilter(mergedList);
// 异步获取商品图片/条码(不阻塞主流程)
this.fetchProductImages(mergedList, warehouseList).then(() => {
if (searchSeq === this.searchSeq) {
this.$forceUpdate();
}
}).catch(error => {
console.warn('[ProductQuery] 获取商品图片异常:', error);
});
this.fetchProductBarcodes(mergedList).catch(error => {
console.warn('[ProductQuery] 获取商品条码异常:', error);
});
this.rawList = mergedList;
this.updateDisplayListByMode(mergedList, keyword, isBarcodeKeyword);
this.loading = false;
console.log('[ProductQuery] 首屏搜索结果数量:', this.list.length);
// 阶段2:异步补充库存明细(不阻塞首屏)
this.fetchInventoryDetails(nextList, warehouseList, stockIdList, searchSeq).catch(error => {
console.warn('[ProductQuery] 补充库存明细异常:', error);
});
} catch (error) {
if (searchSeq !== this.searchSeq) {
return;
}
this.rawList = [];
this.list = [];
console.error('[ProductQuery] 搜索异常:', error);
uni.showToast({
title: (error && error.message) || '查询失败',
icon: 'none'
});
if (!silentVoice) {
this.speakQueryMessage('查询失败,请检查网络后重试');
}
} finally {
if (searchSeq !== this.searchSeq) {
return;
}
this.loading = false;
if (this.list.length) {
// 合并重复的布局测量:单次调度多次延时刷新即可覆盖图片/布局稳定,
// 避免真机上反复 createSelectorQuery 造成卡顿
await this.waitForNextTick();
this.updateFloatingStorageHeader(this.listScrollTopCache);
this.scheduleRefreshStorageSectionMetas([0, 60, 160, 320]);
}
}
},
/**
* 阶段2:用 search + warehouse 的 stock_id 集合异步补充库存明细,不阻塞首屏
*/
async fetchInventoryDetails(nextList, warehouseList, stockIdList, searchSeq) {
if (!Array.isArray(stockIdList) || !stockIdList.length) {
return;
}
const listStartTime = Date.now();
const listRes = await this.$http('storage.inventory.list', this.buildListQueryParams(stockIdList)).catch(error => {
console.warn('[ProductQuery] storage.inventory.list 调用失败:', error);
return null;
});
console.log('[ProductQuery] 阶段2 inventory.list 耗时:', Date.now() - listStartTime, 'ms');
// 竞态保护:请求期间可能已发起新的搜索
if (searchSeq !== this.searchSeq) {
return;
}
const listOk = listRes && listRes.code === 200;
if (!listOk) {
return;
}
const detailList = this.extractListFromResponse(listRes);
let mergedList = this.mergeProductResultLists(nextList, warehouseList, detailList);
mergedList = this.applySearchStorageOverride(mergedList, nextList);
mergedList = this.applyRouteStockFilter(mergedList);
if (searchSeq !== this.searchSeq) {
return;
}
this.rawList = mergedList;
this.updateDisplayListByMode(mergedList, this.keyword, this.isBarcodeLike(this.keyword));
this.scheduleRefreshStorageSectionMetas([0, 80, 200]);
},
/**
* 优先使用 stock.warehouse.search 的库存数据(storage 数组)覆盖其他来源
* 注意:必须用 id 精确匹配,不能用条码等共享字段,否则多个商品共用同一条码时会互相覆盖
*/
applySearchStorageOverride(mergedList, nextList) {
if (!Array.isArray(nextList) || !nextList.length) {
return mergedList;
}
const searchStorageById = new Map();
nextList.forEach(item => {
if (item && typeof item === 'object' && Array.isArray(item.storage)) {
const id = this.normalizePositiveId(item.id);
if (id) {
searchStorageById.set(id, item.storage);
}
}
});
if (!searchStorageById.size) {
return mergedList;
}
return (mergedList || []).map(item => {
const id = this.normalizePositiveId(item.id || item.stock_id);
if (id && searchStorageById.has(id)) {
return { ...item, storage: searchStorageById.get(id) };
}
return item;
});
},
/**
* 从分拣缺货补货进入时,根据 stock_id 精确匹配
*/
applyRouteStockFilter(mergedList) {
if (!this.routeStockId) {
return mergedList;
}
const targetStockId = Number(this.routeStockId);
return (mergedList || []).filter(item => {
const id = Number(item.id || item.stock_id);
return id === targetStockId;
});
}
}
}
</script>
<style lang="scss" scoped>
.goods-query-page {
background: #f7f8fa;
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.normar_container {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
overflow: hidden;
}
.page-header {
position: sticky;
top: 0;
z-index: 20;
background: #fff;
flex-shrink: 0;
box-shadow: 0 2rpx 10rpx rgba(15, 23, 42, 0.04);
}
.search-panel {
padding: 20rpx;
background: #fff;
border-bottom: 1rpx solid #f2f2f2;
flex-shrink: 0;
position: relative;
z-index: 1;
}
::v-deep .nav-title .right {
width: auto;
min-width: 182rpx;
display: flex;
justify-content: flex-end;
}
.nav-mode-switch-group {
height: 50rpx;
padding: 3rpx;
border-radius: 26rpx;
background: #edf2ff;
display: inline-flex;
align-items: center;
justify-content: flex-end;
box-sizing: border-box;
border: 1rpx solid #dbe7ff;
}
.nav-mode-switch-btn {
min-width: 76rpx;
height: 42rpx;
padding: 0 14rpx;
border-radius: 21rpx;
display: inline-flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
&__text {
font-size: 20rpx;
font-weight: 600;
color: #5f6b7a;
line-height: 1;
}
&:active {
opacity: 0.88;
}
}
.nav-mode-switch-btn--active {
background: #2979ff;
box-shadow: 0 3rpx 8rpx rgba(41, 121, 255, 0.18);
.nav-mode-switch-btn__text {
color: #fff;
}
}
.search-input-wrap {
position: relative;
::v-deep .u-search {
width: 100%;
}
::v-deep .u-search__content {
padding-right: 200rpx;
}
::v-deep .u-search__content__close {
margin-right: 12rpx;
}
}
.search-actions {
position: absolute;
right: 24rpx;
top: 50%;
transform: translateY(-50%);
height: 68rpx;
display: flex;
align-items: center;
}
.scan-btn {
height: 68rpx;
padding: 0 8rpx 0 4rpx;
display: flex;
align-items: center;
justify-content: center;
&:active {
opacity: 0.88;
}
}
.search-divider {
width: 1rpx;
height: 28rpx;
background: #dcdfe6;
margin: 0 16rpx 0 10rpx;
}
.search-btn {
height: 68rpx;
padding: 0 8rpx;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
&__text {
font-size: 30rpx;
font-weight: 500;
color: #2979ff;
line-height: 1;
}
&:active {
opacity: 0.88;
}
}
.list-content-wrap {
flex: 1;
min-height: 0;
position: relative;
display: flex;
flex-direction: column;
overflow: hidden;
}
.list-content {
flex: 1;
min-height: 0;
height: 100%;
position: relative;
z-index: 0;
}
.list-wrap {
padding: 20rpx 8rpx;
}
.goods-item {
background: #fff;
border-radius: 12rpx;
padding: 24rpx 16rpx;
margin-bottom: 28rpx;
border: 1rpx solid #e9edf3;
box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
position: relative;
}
.item-summary {
position: relative;
background: #fff;
padding-bottom: 18rpx;
margin-bottom: 8rpx;
border-radius: 12rpx 12rpx 0 0;
box-shadow: 0 6rpx 14rpx rgba(15, 23, 42, 0.06);
}
.item-main-row {
display: flex;
align-items: center;
position: relative;
padding-right: 92rpx;
}
.item-thumb {
width: 140rpx;
margin-right: 20rpx;
margin-top: 0;
flex-shrink: 0;
position: relative;
}
.goods-image {
border-radius: 10rpx;
overflow: hidden;
background: #f5f7fa;
}
.goods-image-grid {
width: 140rpx;
height: 140rpx;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-content: space-between;
}
.grid-cell {
position: relative;
width: 68rpx;
height: 68rpx;
border-radius: 8rpx;
overflow: hidden;
background: #f5f7fa;
}
.grid-image {
border-radius: 8rpx;
overflow: hidden;
}
.image-placeholder {
width: 100%;
height: 140rpx;
display: flex;
align-items: center;
justify-content: center;
background: #f5f7fa;
}
.image-placeholder-small {
height: 68rpx;
}
.image-index-badge {
position: absolute;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
border-radius: 10rpx 0 10rpx 0;
padding: 2rpx 10rpx;
display: flex;
align-items: center;
justify-content: center;
z-index: 2;
pointer-events: none;
}
.image-index-text {
font-size: 20rpx;
color: #fff;
font-weight: 500;
}
.more-mask {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.45);
display: flex;
align-items: center;
justify-content: center;
}
.more-text {
font-size: 22rpx;
color: #fff;
font-weight: 600;
}
.item-info {
flex: 1;
min-width: 0;
}
.item-arrow {
position: absolute;
right: -16rpx;
top: 50%;
transform: translateY(-50%);
display: flex;
align-items: center;
justify-content: center;
width: 112rpx;
height: 112rpx;
z-index: 1;
}
.item-title-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10rpx;
}
.goods-name {
font-size: 42rpx;
color: #303133;
font-weight: 600;
flex: 1;
padding-right: 20rpx;
}
.item-row {
display: flex;
align-items: center;
flex-wrap: nowrap;
line-height: 1.4;
margin-bottom: 2rpx;
}
.item-row:last-child {
margin-bottom: 0;
}
.storage-section {
margin-top: 20rpx;
padding-top: 0;
border-top: 0;
position: relative;
}
.storage-head-fixed {
position: relative;
left: 0;
overflow: visible;
margin-bottom: 0;
border: 1rpx solid #dfe7f5;
border-bottom: 0;
border-radius: 10rpx 10rpx 0 0;
background: #edf4ff;
box-sizing: border-box;
z-index: 1;
isolation: isolate;
&::before {
display: none;
}
}
.storage-scroll {
width: 100%;
white-space: nowrap;
border-radius: 10rpx;
border: 1rpx solid #dfe7f5;
background: #f8faff;
box-sizing: border-box;
overflow: hidden;
::v-deep .uni-scroll-view-content,
::v-deep .uni-scroll-view {
padding-top: 0 !important;
margin-top: 0 !important;
}
}
.storage-scroll--body {
margin-top: -1rpx;
border-top: 0;
border-radius: 0 0 10rpx 10rpx;
}
.storage-table {
background: #f8faff;
overflow: visible;
border: 0;
display: block;
width: 100%;
box-sizing: border-box;
}
.storage-table--head-table {
background: #edf4ff;
will-change: transform;
}
.storage-table--non-batch {
min-width: 680rpx;
}
.storage-table--batch {
min-width: 680rpx;
}
.storage-table--batch .storage-col {
font-size: 32rpx;
}
.storage-table--batch .storage-col--batch {
flex: 0.62;
}
.storage-table--batch .storage-col--space {
flex: 0.95;
}
.storage-table__row {
display: grid;
align-items: center;
min-height: 72rpx;
padding: 8rpx 0;
border-bottom: 1rpx solid #e8eef7;
box-sizing: border-box;
}
.storage-table--non-batch .storage-table__row {
grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.72fr) minmax(0, 0.72fr);
}
.storage-table--batch .storage-table__row {
grid-template-columns: minmax(0, 0.65fr) minmax(0, 0.85fr) minmax(0, 0.4fr) minmax(0, 0.4fr);
}
.storage-table__row:last-child {
border-bottom: 0;
}
.storage-table__head {
background: #edf4ff;
border-bottom: 1rpx solid #dbe6f7;
position: relative;
z-index: 21;
box-shadow: none;
margin-bottom: -1rpx;
border-bottom-color: #e8eef7;
opacity: 1;
}
.storage-table__head.storage-table__row {
min-height: 48rpx;
padding: 0;
background: #edf4ff;
}
.storage-table__row--empty {
grid-template-columns: minmax(0, 1fr) !important;
}
.storage-head-fixed + .storage-table__row {
border-top: 1rpx solid #e8eef7;
margin-top: -1rpx;
}
.storage-col {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-width: 0;
font-size: 35rpx;
color: #606266;
line-height: 1.2;
padding: 8rpx 4rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
border-right: 1rpx solid #e8eef7;
box-sizing: border-box;
}
.storage-table__row .storage-col:last-child {
border-right: 0;
}
.storage-col--space {
flex: none;
}
.storage-col--batch {
flex: none;
}
.storage-col--qty {
flex: none;
}
.storage-col--qty-stock {
color: #e74c3c;
font-weight: 600;
}
.storage-col--qty-available {
color: #2979ff;
font-weight: 600;
}
.storage-col--action {
color: #2979ff;
font-weight: 600;
text-decoration: underline;
text-decoration-color: rgba(41, 121, 255, 0.45);
&:active {
opacity: 0.7;
}
}
.storage-col--disabled {
color: #606266;
font-weight: 400;
text-decoration: none;
}
.storage-table--batch .storage-col--qty {
padding-left: 1rpx;
padding-right: 1rpx;
}
.storage-col--highlight {
color: #2979ff;
font-weight: 600;
}
.storage-empty-text {
grid-column: 1 / -1;
border-right: 0 !important;
color: #909399;
font-size: 28rpx;
min-height: 56rpx;
padding-top: 4rpx;
padding-bottom: 4rpx;
}
.label {
width: auto;
margin-right: 6rpx;
font-size: 35rpx;
color: #909399;
white-space: nowrap;
flex-shrink: 0;
}
.value {
flex: 1;
font-size: 35rpx;
color: #000;
word-break: break-all;
}
.empty-state {
padding: 160rpx 0 100rpx;
display: flex;
flex-direction: column;
align-items: center;
}
.empty-text {
font-size: 30rpx;
color: #909399;
margin-top: 24rpx;
}
.empty-hint {
font-size: 24rpx;
color: #c0c4cc;
margin-top: 10rpx;
}
.end-tip {
padding: 8rpx 0 20rpx;
text-align: center;
font-size: 28rpx;
color: #c0c4cc;
}
.safe-area-bottom {
height: calc(30rpx + env(safe-area-inset-bottom));
}
</style>