1283 lines
34 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="product-edit-page">
<view class="normar_container">
<page-nav title="修改商品" @back="handleCancel"></page-nav>
<scroll-view class="edit-content" scroll-y>
<view class="form-card">
<u-form :model="formData" ref="formRef" label-width="170rpx">
<u-form-item label="商品名称" required>
<u-input v-model="formData.item_name" placeholder="请输入商品名称" clearable></u-input>
</u-form-item>
<u-form-item label="商品编码">
<u-input v-model="formData.goods_code" placeholder="请输入商品编码" clearable></u-input>
</u-form-item>
<u-form-item label="品牌">
<u-input v-model="formData.brand_name" placeholder="请输入品牌" clearable></u-input>
</u-form-item>
<u-form-item label="SKU规格">
<u-input v-model="formData.sku_property" placeholder="请输入SKU规格" clearable></u-input>
</u-form-item>
<u-form-item class="prohibited-type-item" label="违禁品类型" label-width="220rpx">
<view class="picker-display" @click="showProhibitedPicker = true">
<view :class="['picker-display__text', !formData.prohibited_type_name ? 'picker-display__placeholder' : '']">
{{ formData.prohibited_type_name || '请选择违禁品类型' }}
</view>
<u-icon name="arrow-right" size="38rpx" color="#c0c4cc"></u-icon>
</view>
</u-form-item>
<u-form-item label="库存单位" required>
<view class="picker-display" @click="showStockUnitPicker = true">
<text :class="['picker-display__text', !formData.stock_unit ? 'picker-display__placeholder' : '']">
{{ formData.stock_unit || '请选择库存单位' }}
</text>
<u-icon name="arrow-right" size="38rpx" color="#c0c4cc"></u-icon>
</view>
</u-form-item>
<u-form-item label="标价(¥)">
<u-input v-model="formData.tag_price" type="digit" placeholder="请输入标价" clearable></u-input>
</u-form-item>
<u-form-item label="零售价(¥)">
<u-input v-model="formData.retail_price" type="digit" placeholder="请输入零售价" clearable></u-input>
</u-form-item>
<u-form-item label="毛重(g)" required>
<u-input v-model="formData.gross_weight" type="digit" placeholder="请输入毛重" clearable></u-input>
</u-form-item>
<u-form-item label="净重(g)">
<u-input v-model="formData.net_weight" type="digit" placeholder="请输入净重" clearable></u-input>
</u-form-item>
<u-form-item label="商品图片">
<view class="product-image-upload-wrap">
<uploadImgCos
ref="productImageUploadRef"
business_type="stock"
:value="formData.images"
:business_id="productImageBusinessId"
:disabled="!productImageBusinessId"
@change="handleImagesChange"
></uploadImgCos>
<text class="product-image-tip">支持jpg/png格式,单张不超过10MB</text>
<text v-if="!productImageBusinessId" class="product-image-tip">请先保存一次商品后再上传图片</text>
</view>
</u-form-item>
</u-form>
</view>
<view class="safe-padding-bottom"></view>
</scroll-view>
<view class="action-bar">
<u-button class="action-btn action-btn--cancel" @click="handleCancel">取消</u-button>
<u-button class="action-btn" type="primary" :loading="saving" @click="handleSave">保存</u-button>
</view>
</view>
<inputAndSelect
title="选择违禁品类型"
:list="prohibitedTypeList"
:show="showProhibitedPicker"
:value="formData.prohibited_type_id"
:itemFontSize="32"
searchBorder="none"
:allowCreate="true"
@change="handleProhibitedTypeChange"
@create="handleProhibitedTypeCreate"
@close="showProhibitedPicker = false"
></inputAndSelect>
<inputAndSelect
title="选择库存单位"
:list="stockUnitList"
:show="showStockUnitPicker"
:value="formData.stock_unit_value"
:itemFontSize="32"
searchBorder="none"
:allowCreate="true"
@change="handleStockUnitChange"
@create="handleStockUnitCreate"
@close="showStockUnitPicker = false"
></inputAndSelect>
</view>
</template>
<script>
export default {
data() {
return {
cacheKey: '',
saving: false,
canceling: false,
keepVoiceOnExit: false,
bypassBackIntercept: false,
rawItem: null,
initialImageSnapshot: [],
initialImageFileIds: [],
sessionUploadedFileIds: [],
latestImagesLoadPromise: null,
showProhibitedPicker: false,
showStockUnitPicker: false,
prohibitedTypeList: [],
stockUnitList: [],
formData: {
item_name: '',
goods_code: '',
brand_name: '',
sku_property: '',
prohibited_type_id: null,
prohibited_type_name: '',
gross_weight: '',
net_weight: '',
images: [],
stock_unit_value: '',
stock_unit: '',
tag_price: '',
retail_price: ''
}
};
},
computed: {
productImageBusinessId() {
return this.resolveWarehouseStockId(this.rawItem || {}) || 0;
}
},
onLoad(options) {
this.keepVoiceOnExit = false;
this.cacheKey = (options && options.cacheKey) || '';
this.loadProhibitedTypes();
this.loadStockUnits();
if (!this.cacheKey) {
return;
}
const cached = uni.getStorageSync(this.cacheKey);
if (!cached || typeof cached !== 'object') {
return;
}
this.rawItem = {
...cached
};
this.formData.item_name = String(cached.item_name || cached.product_name || cached.name || '');
this.formData.goods_code = String(cached.goods_code || cached.item_code || '');
this.formData.brand_name = String(cached.brand_name || '');
this.formData.sku_property = String(cached.sku_property || '');
this.formData.prohibited_type_id = this.getProhibitedTypeId(cached);
this.formData.prohibited_type_name = String((cached.prohibited && cached.prohibited.type_name) || '');
this.formData.gross_weight = this.normalizeInputValue(cached.gross_weight);
this.formData.net_weight = this.normalizeInputValue(cached.net_weight);
this.formData.images = this.normalizeImageListForUpload(cached);
this.formData.stock_unit = String(cached.stock_unit || '');
this.formData.stock_unit_value = String(cached.stock_unit || '');
this.formData.tag_price = this.normalizeInputValue(cached.tag_price);
this.formData.retail_price = this.normalizeInputValue(cached.retail_price);
this.initialImageSnapshot = this.buildImageListForCache(this.formData.images);
this.initialImageFileIds = this.extractImageFileIds(this.initialImageSnapshot);
this.sessionUploadedFileIds = [];
this.latestImagesLoadPromise = this.loadLatestImages();
},
onBackPress() {
if (this.bypassBackIntercept || this.saving) {
// 已经在回退流程中,放行系统返回
return false;
}
// 标记已拦截,防止多次触发
this.bypassBackIntercept = true;
// 只做图片回滚,不主动 navigateBack,交给系统返回
this.rollbackImageReferences().catch(err => {
console.warn('[ProductEdit] 返回时回滚商品图片失败:', err);
});
// 返回 false,让系统继续处理返回(页面会被销毁)
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);
if (!Number.isFinite(numericValue)) {
return null;
}
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;
}
const candidates = [
item.store_id,
item.owner_id,
item.store && item.store.id,
item.store_stock && item.store_stock.store_id
];
for (let i = 0; i < candidates.length; i++) {
const normalized = this.normalizePositiveId(candidates[i]);
if (normalized) {
return normalized;
}
}
return null;
},
resolveWarehouseStockId(item) {
if (!item || typeof item !== 'object') {
return null;
}
const candidates = [
item.stock_id,
item.warehouse_stock_id,
item.storage_id,
item.id
];
for (let i = 0; i < candidates.length; i++) {
const normalized = this.normalizePositiveId(candidates[i]);
if (normalized) {
return normalized;
}
}
return null;
},
extractImageListFromGetImagesResponse(response) {
if (!response || typeof response !== 'object') {
return [];
}
const isImageLike = (item) => {
if (!item) {
return false;
}
if (typeof item === 'string') {
return true;
}
if (typeof item !== 'object') {
return false;
}
return Boolean(item.url || item.path || item.fileUrl || item.image_url || item.img_url || item.src);
};
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++) {
const current = candidates[i];
if (!current) {
continue;
}
if (Array.isArray(current)) {
if (current.length === 0 || isImageLike(current[0])) {
return current;
}
continue;
}
if (typeof current === 'object') {
const objectCandidates = [current.images, current.list, current.rows, current.records, current.data];
for (let j = 0; j < objectCandidates.length; j++) {
if (Array.isArray(objectCandidates[j])) {
return objectCandidates[j];
}
}
}
}
return [];
},
extractImageEntriesFromResponse(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++) {
const current = candidates[i];
if (!current) {
continue;
}
if (Array.isArray(current)) {
return current;
}
if (typeof current === 'object') {
const nestedCandidates = [current.images, current.list, current.rows, current.records, current.data];
for (let j = 0; j < nestedCandidates.length; j++) {
if (Array.isArray(nestedCandidates[j])) {
return nestedCandidates[j];
}
}
}
}
return [];
},
extractImageFileIdsFromResponse(response) {
return Array.from(new Set(
this.extractImageEntriesFromResponse(response)
.map(item => {
if (!item || typeof item !== 'object') {
return '';
}
return item.file_id || item.fileId || item.id || item.image_id || '';
})
.filter(Boolean)
));
},
async fetchRemoteImageFileIds() {
const businessId = this.productImageBusinessId;
if (!businessId) {
return [];
}
const response = await this.$http('common.getImages', {
id: Number(businessId),
business_id: Number(businessId),
stock_id: Number(businessId),
type: 'stock',
business_type: 'stock'
});
return this.extractImageFileIdsFromResponse(response);
},
normalizeImageRecord(image) {
if (!image) {
return null;
}
if (typeof image === 'string') {
return {
url: image,
status: 'success'
};
}
if (typeof image !== 'object') {
return null;
}
const imageUrl = image.url || image.path || image.fileUrl || image.image_url || image.img_url || image.src || '';
if (!imageUrl) {
return null;
}
const fileId = image.file_id || image.fileId || image.id || image.image_id || '';
return {
...image,
url: imageUrl,
id: fileId,
file_id: fileId,
status: image.status || 'success'
};
},
async loadLatestImages() {
const businessId = this.productImageBusinessId;
if (!businessId) {
this.latestImagesLoadPromise = null;
return;
}
try {
const response = await this.$http('common.getImages', {
id: Number(businessId),
business_id: Number(businessId),
stock_id: Number(businessId),
type: 'stock',
business_type: 'stock'
});
const remoteFileIds = this.extractImageFileIdsFromResponse(response);
if (remoteFileIds.length) {
this.initialImageFileIds = remoteFileIds;
}
const list = this.extractImageListFromGetImagesResponse(response)
.map(image => this.normalizeImageRecord(image))
.filter(Boolean);
if (!list.length) {
if (process.env.NODE_ENV !== 'production') {
console.warn('[ProductEdit] getImages未返回有效图片,保留当前图片列表', {
businessId,
response
});
}
return;
}
this.formData.images = list;
this.initialImageSnapshot = this.buildImageListForCache(list);
this.initialImageFileIds = this.extractImageFileIds(this.initialImageSnapshot).length
? this.extractImageFileIds(this.initialImageSnapshot)
: this.initialImageFileIds;
this.rawItem = {
...(this.rawItem || {}),
images: list,
image: (list[0] && list[0].url) || ''
};
} catch (error) {
console.warn('[ProductEdit] 获取最新商品图片失败:', error);
} finally {
this.latestImagesLoadPromise = null;
}
},
buildRefreshQuery(recordId, itemCode, storeId) {
const where = {};
if (recordId) {
where.id = {
operator: 'eq',
value: Number(recordId),
type: 'number'
};
} else {
where.item_code = {
operator: 'eq',
value: String(itemCode || '').trim(),
type: 'string'
};
where.store_id = {
operator: 'eq',
value: Number(storeId),
type: 'number'
};
}
return {
with_stock: true,
pagination: {
page: 1,
pageSize: 1
},
where
};
},
extractFirstListItem(response) {
if (!response || typeof response !== 'object') {
return null;
}
const data = response.data;
if (Array.isArray(data) && data.length > 0) {
return data[0];
}
if (data && typeof data === 'object' && !Array.isArray(data)) {
return data;
}
return null;
},
getProhibitedTypeId(item) {
if (!item || typeof item !== 'object') {
return null;
}
const candidates = [
item.prohibited_type_id,
item.prohibited_id,
item.prohibited && item.prohibited.id,
item.prohibited && item.prohibited.type_id
];
for (let i = 0; i < candidates.length; i++) {
const value = candidates[i];
if (value === null || value === undefined || value === '') {
continue;
}
return value;
}
return null;
},
normalizeProhibitedTypeList(source) {
const list = Array.isArray(source) ? source : [];
return list
.map(item => {
if (!item || typeof item !== 'object') {
return null;
}
const value = item.id || item.type_id || item.value || item.code || item.name || item.type_name;
const label = item.type_name || item.name || item.label || item.title || '';
if (value === null || value === undefined || value === '' || !String(label).trim()) {
return null;
}
return {
value,
label: String(label).trim(),
raw: item
};
})
.filter(Boolean);
},
normalizeStockUnitList(source) {
const list = Array.isArray(source) ? source : [];
return list
.map(item => {
if (item === null || item === undefined) {
return null;
}
if (typeof item === 'string' || typeof item === 'number') {
const text = String(item).trim();
if (!text) {
return null;
}
return {
value: text,
label: text,
raw: item
};
}
if (typeof item !== 'object') {
return null;
}
const value = item.value || item.unit || item.code || item.name || item.label || item.id;
const label = item.label || item.name || item.unit || item.value || item.code;
if (value === null || value === undefined || value === '' || !String(label || '').trim()) {
return null;
}
return {
value: String(value).trim(),
label: String(label).trim(),
raw: item
};
})
.filter(Boolean);
},
async loadProhibitedTypes() {
try {
const res = await this.$http('stock.warehouse.getProhibitedType', {});
if (!res || Number(res.code) !== 200) {
throw new Error((res && res.message) || '违禁品类型获取失败');
}
const dataList = Array.isArray(res.data) ? res.data : [];
this.prohibitedTypeList = this.normalizeProhibitedTypeList(dataList);
} catch (error) {
console.warn('[ProductEdit] 获取违禁品类型失败:', error);
this.prohibitedTypeList = [];
}
},
async loadStockUnits() {
try {
const res = await this.$http('stock.warehouse.getStockUnits', {});
if (!res || Number(res.code) !== 200) {
throw new Error((res && res.message) || '库存单位获取失败');
}
const dataList = Array.isArray(res.data) ? res.data : [];
this.stockUnitList = this.normalizeStockUnitList(dataList);
} catch (error) {
console.warn('[ProductEdit] 获取库存单位失败:', error);
this.stockUnitList = [];
}
},
handleProhibitedTypeChange(option) {
if (!option || typeof option !== 'object') {
this.formData.prohibited_type_id = null;
this.formData.prohibited_type_name = '';
return;
}
this.formData.prohibited_type_id = option.value;
this.formData.prohibited_type_name = String(option.label || '').trim();
},
handleProhibitedTypeCreate(value) {
const text = String(value || '').trim();
if (!text) {
return;
}
if (!this.prohibitedTypeList.some(item => String(item && item.label || '').trim() === text)) {
this.prohibitedTypeList = [
{
value: `custom_prohibited_${Date.now()}`,
label: text,
raw: { type_name: text, is_custom: true }
},
...this.prohibitedTypeList
];
}
this.formData.prohibited_type_id = null;
this.formData.prohibited_type_name = text;
},
handleStockUnitChange(option) {
if (!option || typeof option !== 'object') {
this.formData.stock_unit_value = '';
this.formData.stock_unit = '';
return;
}
this.formData.stock_unit_value = String(option.value || '').trim();
this.formData.stock_unit = String(option.label || option.value || '').trim();
},
handleStockUnitCreate(value) {
const text = String(value || '').trim();
if (!text) {
return;
}
if (!this.stockUnitList.some(item => String(item && item.label || '').trim() === text)) {
this.stockUnitList = [
{
value: text,
label: text,
raw: { unit: text, is_custom: true }
},
...this.stockUnitList
];
}
this.formData.stock_unit_value = text;
this.formData.stock_unit = text;
},
normalizeInputValue(value) {
if (value === null || value === undefined) {
return '';
}
return String(value);
},
normalizeImageListForUpload(item) {
if (!item || typeof item !== 'object') {
return [];
}
if (Array.isArray(item.images) && item.images.length > 0) {
return item.images
.map(image => {
if (!image) return null;
if (typeof image === 'string') {
return { url: image, status: 'success' };
}
if (typeof image === 'object') {
const imageUrl = image.url || image.path || image.fileUrl || image.image_url;
if (!imageUrl) return null;
return {
...image,
url: imageUrl,
status: image.status || 'success'
};
}
return null;
})
.filter(Boolean);
}
const singleImage = item.image || item.image_url || item.img || item.pic || item.photo || item.cover || item.cover_url;
if (singleImage) {
return [{ url: String(singleImage), status: 'success' }];
}
return [];
},
extractImageUrls(list) {
if (!Array.isArray(list)) {
return [];
}
return list
.map(image => {
if (!image) return '';
if (typeof image === 'string') return image;
if (typeof image === 'object') return image.url || image.path || image.successUrl || image.fileUrl || '';
return '';
})
.filter(Boolean);
},
buildImageListForCache(list) {
if (!Array.isArray(list)) {
return [];
}
return list
.map(image => {
if (!image) return null;
if (typeof image === 'string') {
return { url: image, status: 'success' };
}
if (typeof image === 'object') {
const imageUrl = image.url || image.path || image.successUrl || image.fileUrl || image.image_url || '';
if (!imageUrl) return null;
return {
...image,
url: imageUrl,
id: image.id || image.fileId || image.file_id || '',
status: image.status || 'success'
};
}
return null;
})
.filter(Boolean);
},
extractImageFileIds(list) {
if (!Array.isArray(list)) {
return [];
}
return Array.from(new Set(
list
.map(image => {
if (!image || typeof image !== 'object') {
return '';
}
return image.id || image.fileId || image.file_id || image.image_id || '';
})
.filter(Boolean)
));
},
trackSessionUploadedFileIds(nextImages) {
const nextIds = this.extractImageFileIds(Array.isArray(nextImages) ? nextImages : []);
if (!nextIds.length) {
return;
}
const initialIds = new Set(this.initialImageFileIds || []);
const mergedIds = new Set(this.sessionUploadedFileIds || []);
nextIds.forEach(fileId => {
if (!initialIds.has(fileId)) {
mergedIds.add(fileId);
}
});
this.sessionUploadedFileIds = Array.from(mergedIds);
},
async rollbackImageReferences() {
const businessId = this.productImageBusinessId;
if (!businessId) {
return;
}
if (this.latestImagesLoadPromise) {
try {
await this.latestImagesLoadPromise;
} catch (error) {
console.warn('[ProductEdit] 等待图片初始化完成失败:', error);
}
}
const snapshot = this.buildImageListForCache(this.initialImageSnapshot);
const snapshotFileIds = this.extractImageFileIds(snapshot);
let targetFileIds = Array.isArray(this.initialImageFileIds) ? [...this.initialImageFileIds] : [];
if (!targetFileIds.length && snapshotFileIds.length) {
targetFileIds = snapshotFileIds;
}
if (!targetFileIds.length) {
try {
const remoteFileIds = await this.fetchRemoteImageFileIds();
const uploadedIds = new Set(this.sessionUploadedFileIds || []);
targetFileIds = remoteFileIds.filter(fileId => !uploadedIds.has(fileId));
} catch (error) {
console.warn('[ProductEdit] 取消时获取远端图片ID失败:', error);
}
}
const requestPayload = {
id: Number(businessId),
type: 'stock',
images: targetFileIds.map(fileId => ({ file_id: fileId }))
};
console.log('[ProductEdit] ReferenceFile request', {
source: 'cancel-or-back',
trigger: this.canceling ? 'cancel' : 'back',
payload: requestPayload
});
const response = await this.$http('common.ReferenceFile', requestPayload);
console.log('[ProductEdit] ReferenceFile response', {
source: 'cancel-or-back',
trigger: this.canceling ? 'cancel' : 'back',
response
});
this.formData.images = snapshot;
this.rawItem = {
...(this.rawItem || {}),
images: snapshot,
image: (snapshot[0] && snapshot[0].url) || ''
};
},
navigateBackSafely() {
this.bypassBackIntercept = true;
uni.navigateBack({
delta: 1,
complete: () => {
setTimeout(() => {
this.bypassBackIntercept = false;
}, 300);
}
});
},
handleImagesChange(nextImages) {
this.trackSessionUploadedFileIds(nextImages);
this.formData.images = Array.isArray(nextImages) ? [...nextImages] : [];
},
async handleCancel() {
if (this.canceling || this.saving) {
return;
}
this.keepVoiceOnExit = false;
// 防止多次触发
this.bypassBackIntercept = true;
this.canceling = true;
try {
await this.rollbackImageReferences();
} catch (error) {
console.warn('[ProductEdit] 取消时回滚商品图片失败:', error);
} finally {
this.canceling = false;
this.navigateBackSafely();
}
},
async handleSave() {
if (this.saving) {
return;
}
this.keepVoiceOnExit = false;
const itemName = String(this.formData.item_name || '').trim();
if (!itemName) {
this.showToastMessage('请输入商品名称');
return;
}
const itemCode = String(this.formData.goods_code || '').trim();
if (!itemCode) {
this.showToastMessage('请输入商品编码');
return;
}
const stockUnit = String(this.formData.stock_unit || '').trim();
if (!stockUnit) {
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;
}
this.saving = true;
try {
const storeId = this.resolveStoreId(this.rawItem || {});
if (!storeId) {
this.showToastMessage('未获取到货主ID');
return;
}
const recordId = this.resolveWarehouseStockId(this.rawItem || {});
const checkPayload = {
item_code: itemCode,
store_id: Number(storeId)
};
if (recordId) {
checkPayload.id = Number(recordId);
}
const checkRes = await this.$http('stock.warehouse.checkItemCodeUnique', checkPayload);
if (!checkRes || Number(checkRes.code) !== 200) {
throw new Error((checkRes && checkRes.message) || '商品编码已存在,请更换');
}
const savePayload = {
store_id: Number(storeId),
item_name: itemName,
item_code: itemCode,
brand_name: String(this.formData.brand_name || '').trim(),
sku_property: String(this.formData.sku_property || '').trim(),
prohibited_type_id: this.formData.prohibited_type_id ? Number(this.formData.prohibited_type_id) : null,
prohibited_type_name: String(this.formData.prohibited_type_name || '').trim(),
gross_weight: grossWeight,
net_weight: String(this.formData.net_weight || '').trim(),
images: this.extractImageUrls(this.formData.images),
stock_unit: stockUnit,
tag_price: String(this.formData.tag_price || '').trim(),
retail_price: String(this.formData.retail_price || '').trim()
};
if (recordId) {
savePayload.id = Number(recordId);
}
const saveRes = await this.$http('stock.warehouse.saveWarehouseStock', savePayload);
if (!saveRes || Number(saveRes.code) !== 200) {
throw new Error((saveRes && saveRes.message) || '保存失败');
}
let latestItem = null;
try {
const refreshRes = await this.$http(
'stock.warehouse.list',
this.buildRefreshQuery(recordId, itemCode, storeId)
);
if (refreshRes && Number(refreshRes.code) === 200) {
latestItem = this.extractFirstListItem(refreshRes);
}
} catch (refreshError) {
console.warn('[ProductEdit] 刷新商品数据失败:', refreshError);
}
const normalizedImages = this.buildImageListForCache(this.formData.images);
const normalizedImageUrls = this.extractImageUrls(normalizedImages);
const nextItem = {
...(this.rawItem || {}),
...(latestItem || {}),
id: recordId || (this.rawItem && this.rawItem.id),
store_id: Number(storeId),
item_name: itemName,
product_name: itemName,
name: itemName,
goods_code: itemCode,
item_code: itemCode,
brand_name: String(this.formData.brand_name || '').trim(),
sku_property: String(this.formData.sku_property || '').trim(),
prohibited_type_id: this.formData.prohibited_type_id,
prohibited: {
...((this.rawItem && this.rawItem.prohibited) || {}),
id: this.formData.prohibited_type_id,
type_name: String(this.formData.prohibited_type_name || '').trim()
},
gross_weight: grossWeight,
net_weight: String(this.formData.net_weight || '').trim(),
images: normalizedImages,
image: normalizedImageUrls[0] || '',
stock_unit: stockUnit,
tag_price: String(this.formData.tag_price || '').trim(),
retail_price: String(this.formData.retail_price || '').trim()
};
uni.$emit('product:detail:updated', {
item: nextItem,
timestamp: Date.now()
});
uni.setStorageSync('product_query_need_refresh', Date.now());
uni.$emit('product:query:updated', {
item: nextItem,
timestamp: Date.now()
});
this.showToastMessage('保存成功', 'success');
this.keepVoiceOnExit = true;
setTimeout(() => {
this.navigateBackSafely();
}, 900);
} catch (error) {
this.keepVoiceOnExit = false;
this.showToastMessage((error && error.message) || '保存失败');
} finally {
this.saving = false;
}
}
}
};
</script>
<style lang="scss" scoped>
.product-edit-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;
}
.edit-content {
flex: 1;
min-height: 0;
}
.form-card {
margin: 20rpx;
padding: 20rpx;
border-radius: 12rpx;
background: #fff;
}
.picker-display {
min-height: 72rpx;
padding: 0 6rpx;
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
min-width: 0;
}
::v-deep .prohibited-type-item .u-form-item__body__right {
flex: 1;
min-width: 0;
overflow: hidden;
}
::v-deep .prohibited-type-item .u-form-item__body {
align-items: center;
}
::v-deep .prohibited-type-item .u-form-item__body__right__content {
width: 100%;
min-width: 0;
overflow: hidden;
}
.picker-display__text {
font-size: 36rpx;
color: #303133;
line-height: 50rpx;
display: block;
max-width: 100%;
height: 50rpx;
padding-right: 16rpx;
flex: 1;
width: 0;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
word-break: normal;
}
::v-deep .prohibited-type-item .u-icon {
flex-shrink: 0;
}
.picker-display__placeholder {
color: #c0c4cc;
}
.product-image-upload-wrap {
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;
font-size: 24rpx;
color: #909399;
}
.safe-padding-bottom {
height: 170rpx;
}
.action-bar {
position: fixed;
left: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
gap: 20rpx;
padding: 20rpx;
padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
background: #fff;
box-shadow: 0 -6rpx 20rpx rgba(15, 23, 42, 0.08);
z-index: 99;
}
.action-btn {
flex: 1;
}
.action-btn--cancel {
border: 1rpx solid #d9d9d9;
color: #606266;
background: #fff;
}
</style>