完善商品编辑与查询交互:图片删除关联修复、语音播报优化、保存校验与提示顺序调整

This commit is contained in:
zm2000 2026-04-24 16:21:47 +08:00
parent 08b4275c8b
commit eaa0d03207
3 changed files with 418 additions and 52 deletions

View File

@ -66,6 +66,55 @@ export default {
}
},
methods: {
resolveDeleteIndex(payload) {
const normalizeIndex = (value) => {
const numeric = Number(value);
if (!Number.isFinite(numeric)) {
return -1;
}
const index = Math.trunc(numeric);
return index >= 0 ? index : -1;
};
if (typeof payload === 'number' || typeof payload === 'string') {
return normalizeIndex(payload);
}
if (!payload || typeof payload !== 'object') {
return -1;
}
const directIndex = normalizeIndex(payload.index);
if (directIndex >= 0) {
return directIndex;
}
const detailIndex = normalizeIndex(payload.detail && payload.detail.index);
if (detailIndex >= 0) {
return detailIndex;
}
const file = payload.file || (payload.detail && payload.detail.file) || null;
if (!file || typeof file !== 'object') {
return -1;
}
const fileId = this.getFileId(file);
if (fileId) {
const byIdIndex = this.fileList.findIndex(item => this.getFileId(item) === fileId);
if (byIdIndex >= 0) {
return byIdIndex;
}
}
const fileUrl = file.url || file.path || file.successUrl || '';
if (fileUrl) {
return this.fileList.findIndex(item => (item.url || item.path || item.successUrl || '') === fileUrl);
}
return -1;
},
getFileId(file) {
if (!file || typeof file !== 'object') {
return '';
@ -128,22 +177,62 @@ export default {
|| (file.file && (file.file.file_id || file.file.fileId || file.file.id))
|| '';
},
normalizeFileUrl(url) {
if (!url || typeof url !== 'string') {
return '';
}
const trimmed = url.trim();
if (!trimmed) {
return '';
}
return trimmed.split('?')[0].split('#')[0];
},
getRemoteFileUrl(file) {
if (!file || typeof file !== 'object') {
return '';
}
return this.normalizeFileUrl(
file.url
|| file.path
|| file.fileUrl
|| file.image_url
|| file.img_url
|| file.src
|| (file.file && (file.file.url || file.file.path || file.file.fileUrl))
|| ''
);
},
async getRemoteImageEntries() {
if (!this.business_id) {
return [];
}
const response = await this.$http('common.getImages', {
id: Number(this.business_id),
business_id: Number(this.business_id),
stock_id: Number(this.business_id),
type: this.business_type,
business_type: this.business_type
});
return this.extractImageListFromGetImagesResponse(response)
.map(item => ({
fileId: this.getRemoteFileId(item),
url: this.getRemoteFileUrl(item)
}))
.filter(item => item.fileId || item.url);
},
async getRemoteFileIds() {
if (!this.business_id) {
return [];
}
try {
const response = await this.$http('common.getImages', {
id: Number(this.business_id),
business_id: Number(this.business_id),
stock_id: Number(this.business_id),
type: this.business_type,
business_type: this.business_type
});
return this.extractImageListFromGetImagesResponse(response)
.map(item => this.getRemoteFileId(item))
return (await this.getRemoteImageEntries())
.map(item => item.fileId)
.filter(Boolean);
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
@ -152,6 +241,37 @@ export default {
return [];
}
},
async resolveDeletedFileIds(deletedFile) {
const deletedIds = [];
const directId = this.getFileId(deletedFile);
if (directId) {
deletedIds.push(directId);
}
if (deletedIds.length > 0) {
return Array.from(new Set(deletedIds));
}
const deletedUrl = this.normalizeFileUrl(
(deletedFile && (deletedFile.url || deletedFile.path || deletedFile.successUrl)) || ''
);
if (!deletedUrl) {
return [];
}
try {
const remoteEntries = await this.getRemoteImageEntries();
const matched = remoteEntries
.filter(item => item.fileId && item.url && item.url === deletedUrl)
.map(item => item.fileId);
return Array.from(new Set(matched));
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
console.warn('[UploadImgCos] resolveDeletedFileIds failed', error);
}
return [];
}
},
/**
* 格式化文件列表
@ -408,7 +528,7 @@ export default {
* 关联文件
*/
async referenceFiles(options = {}) {
const { mergeRemote = true } = options;
const { mergeRemote = true, excludedFileIds = [] } = options;
console.log("this.fileList",this.fileList);
try {
// 获取所有成功的文件(包括之前已经关联的)
@ -417,7 +537,11 @@ export default {
.map(item => this.getFileId(item));
const remoteFileIds = mergeRemote ? await this.getRemoteFileIds() : [];
const mergedFileIds = Array.from(new Set([...(remoteFileIds || []), ...(localFileIds || [])]));
const excludedSet = new Set(
(Array.isArray(excludedFileIds) ? excludedFileIds : [excludedFileIds]).filter(Boolean)
);
const mergedFileIds = Array.from(new Set([...(remoteFileIds || []), ...(localFileIds || [])]))
.filter(fileId => !excludedSet.has(fileId));
const validFiles = mergedFileIds.map(fileId => ({ file_id: fileId }));
if (process.env.NODE_ENV !== 'production') {
@ -425,6 +549,7 @@ export default {
business_id: this.business_id,
type: this.business_type,
merge_remote: mergeRemote,
excluded_file_ids: Array.from(excludedSet),
remote_file_ids: remoteFileIds,
local_file_ids: localFileIds,
file_ids: validFiles.map(item => item.file_id),
@ -471,7 +596,13 @@ export default {
/**
* 处理删除 - 修正版本
*/
async handleDelete(index) {
async handleDelete(payload) {
const index = this.resolveDeleteIndex(payload);
if (index < 0 || index >= this.fileList.length) {
console.warn('[UploadImgCos] 删除图片失败:无法定位删除项', payload);
return;
}
const deletedFile = this.fileList[index];
// 从列表中移除
@ -487,9 +618,13 @@ export default {
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
// 异步更新文件关联
// 异步更新文件关联:合并远端+本地,仅排除当前删除项,避免误删其他图片
try {
await this.referenceFiles({ mergeRemote: false });
const deletedFileIds = await this.resolveDeletedFileIds(deletedFile);
await this.referenceFiles({
mergeRemote: true,
excludedFileIds: deletedFileIds
});
} catch (error) {
console.error("删除后重新关联失败:", error);
// 这里可以选择给用户提示,但不阻塞UI
@ -526,5 +661,26 @@ export default {
</script>
<style scoped>
::v-deep .u-upload__deletable {
width: 56rpx !important;
height: 56rpx !important;
top: -16rpx !important;
right: -16rpx !important;
background-color: transparent !important;
border-bottom-left-radius: 0 !important;
}
::v-deep .u-upload__deletable__icon {
position: absolute !important;
top: 10rpx !important;
right: 10rpx !important;
width: 24rpx;
height: 24rpx;
display: flex;
align-items: center;
justify-content: center;
background-color: rgb(55, 55, 55);
border-radius: 100rpx;
transform: none !important;
}
</style>

View File

@ -106,6 +106,7 @@ export default {
cacheKey: '',
saving: false,
canceling: false,
keepVoiceOnExit: false,
bypassBackIntercept: false,
rawItem: null,
initialImageSnapshot: [],
@ -139,6 +140,7 @@ export default {
}
},
onLoad(options) {
this.keepVoiceOnExit = false;
this.cacheKey = (options && options.cacheKey) || '';
this.loadProhibitedTypes();
this.loadStockUnits();
@ -187,10 +189,18 @@ export default {
return false;
},
onUnload() {
if (!this.keepVoiceOnExit) {
this.stopProductEditSpeak();
}
if (this.cacheKey) {
uni.removeStorageSync(this.cacheKey);
}
},
onHide() {
if (!this.keepVoiceOnExit) {
this.stopProductEditSpeak();
}
},
methods: {
normalizePositiveId(value) {
const numericValue = Number(value);
@ -201,6 +211,86 @@ export default {
const normalized = Math.trunc(numericValue);
return normalized > 0 ? normalized : null;
},
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);
},
speakProductEditMessage(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('[ProductEdit] 语音播报失败:', error);
});
}
} catch (error) {
console.warn('[ProductEdit] 语音播报异常:', error);
}
},
stopProductEditSpeak() {
const tools = this.$tools;
if (!tools || typeof tools.stopSpeak !== 'function') {
return;
}
try {
tools.stopSpeak();
} catch (error) {
console.warn('[ProductEdit] 停止语音播报异常:', error);
}
},
showToastMessage(title, icon = 'none', options = {}) {
const message = String(title || '').trim();
if (!message) {
return;
}
uni.showToast({
title: message,
icon
});
if (options.speak !== false) {
this.speakProductEditMessage(options.speakText || message, options.voiceOptions || {});
}
},
resolveStoreId(item) {
if (!item || typeof item !== 'object') {
return null;
@ -852,6 +942,7 @@ export default {
if (this.canceling || this.saving) {
return;
}
this.keepVoiceOnExit = false;
// 防止多次触发
this.bypassBackIntercept = true;
this.canceling = true;
@ -868,40 +959,67 @@ export default {
if (this.saving) {
return;
}
this.keepVoiceOnExit = false;
const itemName = String(this.formData.item_name || '').trim();
if (!itemName) {
uni.showToast({
title: '请输入商品名称',
icon: 'none'
});
this.showToastMessage('请输入商品名称');
return;
}
const itemCode = String(this.formData.goods_code || '').trim();
if (!itemCode) {
uni.showToast({
title: '请输入商品编码',
icon: 'none'
});
return;
}
const grossWeight = String(this.formData.gross_weight || '').trim();
if (!grossWeight) {
uni.showToast({
title: '请输入毛重',
icon: 'none'
});
this.showToastMessage('请输入商品编码');
return;
}
const stockUnit = String(this.formData.stock_unit || '').trim();
if (!stockUnit) {
uni.showToast({
title: '请选择库存单位',
icon: 'none'
});
this.showToastMessage('请选择库存单位');
return;
}
const tagPrice = String(this.formData.tag_price || '').trim();
if (!tagPrice) {
this.showToastMessage('请输入标价');
return;
}
const normalizedTagPrice = Number(tagPrice);
if (!Number.isFinite(normalizedTagPrice) || normalizedTagPrice < 0) {
this.showToastMessage('标价需大于等于0');
return;
}
const retailPrice = String(this.formData.retail_price || '').trim();
if (!retailPrice) {
this.showToastMessage('请输入零售价');
return;
}
const normalizedRetailPrice = Number(retailPrice);
if (!Number.isFinite(normalizedRetailPrice) || normalizedRetailPrice < 0) {
this.showToastMessage('零售价需大于等于0');
return;
}
const grossWeight = String(this.formData.gross_weight || '').trim();
if (!grossWeight) {
this.showToastMessage('请输入毛重');
return;
}
const normalizedGrossWeight = Number(grossWeight);
if (!Number.isFinite(normalizedGrossWeight) || normalizedGrossWeight <= 0) {
this.showToastMessage('毛重需大于0');
return;
}
const netWeight = String(this.formData.net_weight || '').trim();
if (!netWeight) {
this.showToastMessage('请输入净重');
return;
}
const normalizedNetWeight = Number(netWeight);
if (!Number.isFinite(normalizedNetWeight) || normalizedNetWeight <= 0) {
this.showToastMessage('净重需大于0');
return;
}
@ -909,10 +1027,7 @@ export default {
try {
const storeId = this.resolveStoreId(this.rawItem || {});
if (!storeId) {
uni.showToast({
title: '未获取到货主ID',
icon: 'none'
});
this.showToastMessage('未获取到货主ID');
return;
}
@ -1010,19 +1125,15 @@ export default {
timestamp: Date.now()
});
uni.showToast({
title: '保存成功',
icon: 'success'
});
this.showToastMessage('保存成功', 'success');
this.keepVoiceOnExit = true;
setTimeout(() => {
this.navigateBackSafely();
}, 350);
}, 900);
} catch (error) {
uni.showToast({
title: (error && error.message) || '保存失败',
icon: 'none'
});
this.keepVoiceOnExit = false;
this.showToastMessage((error && error.message) || '保存失败');
} finally {
this.saving = false;
}
@ -1115,6 +1226,11 @@ export default {
width: 100%;
}
.product-image-upload-wrap ::v-deep .u-upload__wrap__preview {
margin-right: 35rpx !important;
margin-bottom: 35rpx !important;
}
.product-image-tip {
display: block;
margin-top: 12rpx;

View File

@ -302,7 +302,9 @@
const keyword = this.normalizeKeyword(this.keyword);
if (keyword) {
this.keyword = keyword;
this.handleSearch();
this.handleSearch({
silentVoice: true
});
}
}
const cachedTop = Number(uni.getStorageSync('product_query_scroll_top') || 0);
@ -316,6 +318,7 @@
onHide() {
uni.setStorageSync('product_query_scroll_top', this.listScrollTopCache || 0);
this.safeDispatchBroadcast('pause');
this.stopQuerySpeak();
},
onUnload() {
if (this.storageMetaRefreshTimer) {
@ -323,6 +326,7 @@
this.storageMetaRefreshTimer = null;
}
this.safeDispatchBroadcast('stop');
this.stopQuerySpeak();
},
methods: {
getGoodsItemKey(item, index) {
@ -353,6 +357,85 @@
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;
@ -1357,7 +1440,8 @@
url: `/pages/work/product/detail?cacheKey=${cacheKey}`
});
},
async handleSearch() {
async handleSearch(options = {}) {
const silentVoice = !!(options && options.silentVoice);
const keyword = this.normalizeKeyword(this.keyword);
this.keyword = keyword;
console.log('[ProductQuery] 搜索内容:', keyword, '模式:', this.queryMode);
@ -1372,6 +1456,7 @@
top: 0
};
console.log('[ProductQuery] 搜索内容为空,结果已清空');
this.stopQuerySpeak();
return;
}
@ -1412,6 +1497,9 @@
this.updateDisplayListByMode(mergedList, keyword, isBarcodeKeyword);
console.log('[ProductQuery] 搜索结果数量:', this.list.length);
console.log('[ProductQuery] 搜索结果列表:', this.list);
if (!silentVoice) {
this.speakQueryMessage(this.getSearchVoiceText(keyword, this.list.length));
}
} else {
this.rawList = [];
this.list = [];
@ -1420,6 +1508,9 @@
title: (searchRes && searchRes.message) || (warehouseRes && warehouseRes.message) || (listRes && listRes.message) || '查询失败',
icon: 'none'
});
if (!silentVoice) {
this.speakQueryMessage('查询失败,请重试');
}
}
} catch (error) {
this.rawList = [];
@ -1429,6 +1520,9 @@
title: (error && error.message) || '查询失败',
icon: 'none'
});
if (!silentVoice) {
this.speakQueryMessage('查询失败,请检查网络后重试');
}
} finally {
this.loading = false;
if (this.list.length) {