2026-08-12 14:08:50 +08:00

1641 lines
49 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.item_code" placeholder="请输入商品编码" clearable></u-input>
</u-form-item>
<u-form-item label="商品条码">
<u-input v-model="formData.barcodes" 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>
<!-- 管理标识 -->
<view class="form-section-title">管理标识</view>
<u-form-item label="序列号管理">
<u-switch v-model="formData.is_sn_mgmt" active-color="#2979ff"></u-switch>
</u-form-item>
<u-form-item label="保质期管理">
<u-switch v-model="formData.is_shelf_life_mgmt" active-color="#2979ff"></u-switch>
</u-form-item>
<view v-if="formData.is_shelf_life_mgmt" class="shelf-life-block">
<u-form-item label="保质期天数" label-width="240rpx">
<u-input v-model="formData.shelf_life_days" type="number" placeholder="请输入保质期天数" clearable></u-input>
</u-form-item>
<u-form-item label="入库最小天数" label-width="240rpx">
<u-input v-model="formData.inbound_min_days" type="number" placeholder="请输入入库最小天数" clearable></u-input>
</u-form-item>
<u-form-item label="出库最小天数" label-width="240rpx">
<u-input v-model="formData.outbound_min_days" type="number" placeholder="请输入出库最小天数" clearable></u-input>
</u-form-item>
<u-form-item label="剩余有效期" label-width="240rpx">
<u-input v-model="formData.remaining_threshold_days" type="number" placeholder="请输入剩余有效期" clearable></u-input>
</u-form-item>
</view>
<u-form-item label="批次管理">
<u-switch v-model="formData.is_batch_mgmt" active-color="#2979ff"></u-switch>
</u-form-item>
<!-- 尺寸信息 -->
<view class="form-section-title">尺寸信息</view>
<u-form-item label="长度(cm)">
<u-input v-model="formData.length" type="digit" placeholder="请输入长度" clearable></u-input>
</u-form-item>
<u-form-item label="宽度(cm)">
<u-input v-model="formData.width" type="digit" placeholder="请输入宽度" clearable></u-input>
</u-form-item>
<u-form-item label="高度(cm)">
<u-input v-model="formData.height" type="digit" placeholder="请输入高度" clearable></u-input>
</u-form-item>
<u-form-item label="体积(cm³)">
<u-input v-model="formData.volume" type="digit" placeholder="请输入体积" clearable></u-input>
</u-form-item>
<!-- 箱规信息 -->
<view class="form-section-title">箱规信息</view>
<u-form-item label="启用箱规">
<u-switch v-model="formData.enable_box_spec" active-color="#2979ff"></u-switch>
</u-form-item>
<view v-if="formData.enable_box_spec" class="box-spec-block">
<u-form-item label="每箱数量" required label-width="240rpx">
<u-input v-model="formData.quantity_per_box" type="digit" placeholder="请输入每箱数量" clearable></u-input>
</u-form-item>
<u-form-item label="箱毛重(g)" label-width="240rpx">
<u-input v-model="formData.box_gross_weight" type="digit" placeholder="请输入箱毛重" clearable></u-input>
</u-form-item>
<u-form-item label="箱净重(g)" label-width="240rpx">
<u-input v-model="formData.box_net_weight" type="digit" placeholder="请输入箱净重" clearable></u-input>
</u-form-item>
<u-form-item label="箱长(cm)" label-width="240rpx">
<u-input v-model="formData.box_length" type="digit" placeholder="请输入箱长" clearable></u-input>
</u-form-item>
<u-form-item label="箱宽(cm)" label-width="240rpx">
<u-input v-model="formData.box_width" type="digit" placeholder="请输入箱宽" clearable></u-input>
</u-form-item>
<u-form-item label="箱高(cm)" label-width="240rpx">
<u-input v-model="formData.box_height" type="digit" placeholder="请输入箱高" clearable></u-input>
</u-form-item>
<u-form-item label="箱体积(m³)" label-width="240rpx">
<u-input v-model="formData.box_volume" type="digit" placeholder="请输入箱体积" clearable></u-input>
</u-form-item>
</view>
<!-- 打包要求 -->
<u-form-item label="打包要求">
<u-textarea v-model="formData.packing_requirements" placeholder="请输入打包要求" height="140" border="surround"></u-textarea>
</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: '',
detailCacheKey: '',
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: '',
item_code: '',
barcodes: '',
brand_name: '',
sku_property: '',
prohibited_type_id: null,
prohibited_type_name: '',
gross_weight: '',
net_weight: '',
is_sn_mgmt: false,
is_shelf_life_mgmt: false,
is_batch_mgmt: false,
shelf_life_days: '',
inbound_min_days: '',
outbound_min_days: '',
remaining_threshold_days: '',
length: '',
width: '',
height: '',
volume: '',
enable_box_spec: false,
quantity_per_box: '1',
box_gross_weight: '',
box_net_weight: '',
box_length: '',
box_width: '',
box_height: '',
box_volume: '',
packing_requirements: '',
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.detailCacheKey = (options && options.detailCacheKey) || '';
this.safeDispatchBroadcast('setCallbacks', {
onResult: this.handleBroadcastResult
});
this.safeDispatchBroadcast('start');
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.item_code = String(cached.item_code || cached.goods_code || '');
this.formData.goods_code = String(cached.goods_code || '');
this.formData.barcodes = this.normalizeBarcodeDisplay(cached);
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.is_sn_mgmt = this.toBooleanFlag(cached.is_sn_mgmt);
this.formData.is_shelf_life_mgmt = this.toBooleanFlag(cached.is_shelf_life_mgmt);
this.formData.is_batch_mgmt = this.toBooleanFlag(cached.is_batch_mgmt);
this.formData.shelf_life_days = this.normalizeInputValue(cached.shelf_life_days);
this.formData.inbound_min_days = this.normalizeInputValue(cached.inbound_min_days);
this.formData.outbound_min_days = this.normalizeInputValue(cached.outbound_min_days);
this.formData.remaining_threshold_days = this.normalizeInputValue(cached.remaining_threshold_days);
this.formData.length = this.normalizeInputValue(cached.length);
this.formData.width = this.normalizeInputValue(cached.width);
this.formData.height = this.normalizeInputValue(cached.height);
this.formData.volume = this.normalizeInputValue(cached.volume);
this.formData.enable_box_spec = this.toBooleanFlag(cached.enable_box_spec);
const cachedQuantityPerBox = this.normalizeInputValue(cached.quantity_per_box);
this.formData.quantity_per_box = cachedQuantityPerBox && Number(cachedQuantityPerBox) > 0 ? cachedQuantityPerBox : '1';
this.formData.box_gross_weight = this.normalizeInputValue(cached.box_gross_weight);
this.formData.box_net_weight = this.normalizeInputValue(cached.box_net_weight);
this.formData.box_length = this.normalizeInputValue(cached.box_length);
this.formData.box_width = this.normalizeInputValue(cached.box_width);
this.formData.box_height = this.normalizeInputValue(cached.box_height);
this.formData.box_volume = this.normalizeInputValue(cached.box_volume);
this.formData.packing_requirements = String(cached.packing_requirements || '');
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();
},
onShow() {
// 返回页面时重新注册广播回调并恢复扫描
this.safeDispatchBroadcast('setCallbacks', {
onResult: this.handleBroadcastResult
});
this.safeDispatchBroadcast('resume');
},
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();
}
this.safeDispatchBroadcast('stop');
if (this.cacheKey) {
uni.removeStorageSync(this.cacheKey);
}
},
onHide() {
if (!this.keepVoiceOnExit) {
this.stopProductEditSpeak();
}
this.safeDispatchBroadcast('pause');
},
methods: {
safeDispatchBroadcast(action, payload) {
try {
const task = this.$store.dispatch(`broadcast/${action}`, payload);
if (task && typeof task.catch === 'function') {
task.catch(error => {
console.warn(`[ProductEdit] broadcast/${action} 调用失败:`, error);
});
}
} catch (error) {
console.warn(`[ProductEdit] broadcast/${action} 调用异常:`, error);
}
},
normalizeScanResult(scanResult) {
if (!scanResult) {
return '';
}
let value = '';
if (typeof scanResult === 'string') {
value = scanResult;
} else if (typeof scanResult.result === 'string') {
value = scanResult.result;
} else if (Array.isArray(scanResult.result)) {
const firstResult = scanResult.result.find(item => item);
if (typeof firstResult === 'string') {
value = firstResult;
} else if (firstResult && typeof firstResult.data === 'string') {
value = firstResult.data;
}
} else if (typeof scanResult.data === 'string') {
value = scanResult.data;
}
return String(value || '').replace(/\s+/g, '').trim();
},
handleBroadcastResult(result) {
const scanResult = this.normalizeScanResult(result);
if (!scanResult) {
return;
}
// 广播扫描仅支持单个条码:直接替换当前值
this.formData.barcodes = scanResult;
this.showToastMessage(`已录入条码 ${scanResult}`, 'none', { speak: false });
},
normalizePositiveId(value) {
const numericValue = Number(value);
if (!Number.isFinite(numericValue)) {
return null;
}
const normalized = Math.trunc(numericValue);
return normalized > 0 ? normalized : null;
},
normalizeBarcodeDisplay(item) {
if (!item || typeof item !== 'object') {
return '';
}
const source = item.barcodes || item.barcode || '';
if (Array.isArray(source)) {
return source
.map(entry => {
if (entry === null || entry === undefined) {
return '';
}
if (typeof entry === 'string') {
return entry.trim();
}
if (typeof entry === 'object') {
return String(entry.barcode || entry.code || '').trim();
}
return '';
})
.filter(Boolean)
.join(';');
}
return String(source || '').trim();
},
parseBarcodeInput(value) {
const raw = String(value || '');
return raw
.split(/[;,,\s]+/)
.map(item => item.trim())
.filter(Boolean);
},
extractSavedIdFromResponse(response) {
if (!response || typeof response !== 'object') {
return null;
}
const data = response.data;
const candidates = [
data && typeof data === 'object' ? (data.id || data.stock_id) : null,
typeof data === 'number' || typeof data === 'string' ? data : null,
response.id,
response.stock_id
];
for (let i = 0; i < candidates.length; i++) {
const normalized = this.normalizePositiveId(candidates[i]);
if (normalized) {
return normalized;
}
}
return 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);
},
toBooleanFlag(value) {
if (value === true || value === 1 || value === '1' || value === 'true' || value === 'Y' || value === 'y' || value === '是' || value === '启用') {
return true;
}
return false;
},
toApiFlag(value) {
return value ? 1 : 0;
},
toYesNoFlag(value) {
return value ? 'Y' : 'N';
},
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;
}
// 商品编码即 item_code(真实商品编码,如 011000001536),货品编码 goods_code 单独维护
const saveItemCode = String(this.formData.item_code || this.formData.goods_code || '').trim();
if (!saveItemCode) {
this.showToastMessage('请输入商品编码');
return;
}
const goodsCode = String(this.formData.goods_code || saveItemCode).trim();
const stockUnit = String(this.formData.stock_unit || '').trim();
if (!stockUnit) {
this.showToastMessage('请选择库存单位');
return;
}
let normalizedTagPrice = Number(this.formData.tag_price);
if (!Number.isFinite(normalizedTagPrice) || normalizedTagPrice < 0) {
normalizedTagPrice = 0;
}
let normalizedRetailPrice = Number(this.formData.retail_price);
if (!Number.isFinite(normalizedRetailPrice) || normalizedRetailPrice < 0) {
normalizedRetailPrice = 0;
}
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;
}
// 箱规校验:启用箱规时,每箱数量为必填项且必须大于0
const enableBoxSpec = this.toBooleanFlag(this.formData.enable_box_spec);
let normalizedQuantityPerBox = 0;
if (enableBoxSpec) {
const quantityText = String(this.formData.quantity_per_box || '').trim();
if (!quantityText) {
this.showToastMessage('每箱数量为必填项');
return;
}
normalizedQuantityPerBox = Number(quantityText);
if (!Number.isFinite(normalizedQuantityPerBox) || normalizedQuantityPerBox <= 0) {
this.showToastMessage('每箱数量必须大于0');
return;
}
}
// 保质期校验:启用保质期管理时,保质期天数、入库最小天数、出库最小天数、剩余有效期均为必填且必须大于0
const shelfLifeMgmtEnabled = this.toBooleanFlag(this.formData.is_shelf_life_mgmt);
if (shelfLifeMgmtEnabled) {
const shelfLifeFields = [
{ key: 'shelf_life_days', label: '保质期天数' },
{ key: 'inbound_min_days', label: '入库最小天数' },
{ key: 'outbound_min_days', label: '出库最小天数' },
{ key: 'remaining_threshold_days', label: '剩余有效期' }
];
for (let i = 0; i < shelfLifeFields.length; i++) {
const field = shelfLifeFields[i];
const valueText = String(this.formData[field.key] || '').trim();
if (!valueText) {
this.showToastMessage(`${field.label}不能为空`);
return;
}
const numericValue = Number(valueText);
if (!Number.isFinite(numericValue) || numericValue <= 0) {
this.showToastMessage(`${field.label}必须大于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: saveItemCode,
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 barcodeList = this.parseBarcodeInput(this.formData.barcodes);
const savePayload = {
item_code: saveItemCode,
store_id: Number(storeId),
store_name: String((this.rawItem && this.rawItem.store_name) || '').trim(),
barcode: barcodeList[0] || (this.rawItem && this.rawItem.barcode) || '',
item_name: itemName,
sku_property: String(this.formData.sku_property || '').trim(),
stock_unit: stockUnit,
packing_requirements: String(this.formData.packing_requirements || '').trim(),
length: Number(this.formData.length) || 0,
width: Number(this.formData.width) || 0,
height: Number(this.formData.height) || 0,
volume: Number(this.formData.volume) || 0,
gross_weight: normalizedGrossWeight,
net_weight: Number(this.formData.net_weight) || 0,
tag_price: normalizedTagPrice,
retail_price: normalizedRetailPrice,
is_sn_mgmt: this.toYesNoFlag(this.formData.is_sn_mgmt),
is_shelf_life_mgmt: this.toYesNoFlag(this.formData.is_shelf_life_mgmt),
shelf_life_days: Number(this.formData.shelf_life_days) || 0,
is_batch_mgmt: this.toYesNoFlag(this.formData.is_batch_mgmt),
inbound_min_days: Number(this.formData.inbound_min_days) || 0,
outbound_min_days: Number(this.formData.outbound_min_days) || 0,
remaining_threshold_days: Number(this.formData.remaining_threshold_days) || 0,
brand_name: String(this.formData.brand_name || '').trim(),
managementFlags: [],
enable_box_spec: enableBoxSpec,
quantity_per_box: enableBoxSpec ? normalizedQuantityPerBox : 0,
box_gross_weight: Number(this.formData.box_gross_weight) || 0,
box_net_weight: Number(this.formData.box_net_weight) || 0,
box_length: Number(this.formData.box_length) || 0,
box_width: Number(this.formData.box_width) || 0,
box_height: Number(this.formData.box_height) || 0,
box_volume: Number(this.formData.box_volume) || 0,
box_unit: String((this.rawItem && this.rawItem.box_unit) || ''),
goods_code: goodsCode
};
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) || '保存失败');
}
// 保存商品条码:stock.warehouse.saveWarehouseStockBarcode
const targetStockId = recordId || this.extractSavedIdFromResponse(saveRes);
if (targetStockId && barcodeList.length > 0) {
const barcodeRes = await this.$http('stock.warehouse.saveWarehouseStockBarcode', {
id: Number(targetStockId),
barcodes: barcodeList
});
if (!barcodeRes || Number(barcodeRes.code) !== 200) {
throw new Error((barcodeRes && barcodeRes.message) || '商品条码保存失败');
}
}
let latestItem = null;
try {
const refreshRes = await this.$http(
'stock.warehouse.list',
this.buildRefreshQuery(recordId, saveItemCode, 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: goodsCode,
item_code: saveItemCode,
barcodes: barcodeList,
barcode: barcodeList[0] || (this.rawItem && this.rawItem.barcode) || '',
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(),
is_sn_mgmt: this.toYesNoFlag(this.formData.is_sn_mgmt),
is_shelf_life_mgmt: this.toYesNoFlag(this.formData.is_shelf_life_mgmt),
is_batch_mgmt: this.toYesNoFlag(this.formData.is_batch_mgmt),
shelf_life_days: Number(this.formData.shelf_life_days) || 0,
inbound_min_days: Number(this.formData.inbound_min_days) || 0,
outbound_min_days: Number(this.formData.outbound_min_days) || 0,
remaining_threshold_days: Number(this.formData.remaining_threshold_days) || 0,
length: String(this.formData.length || ''),
width: String(this.formData.width || ''),
height: String(this.formData.height || ''),
volume: String(this.formData.volume || ''),
enable_box_spec: this.toApiFlag(this.formData.enable_box_spec),
quantity_per_box: enableBoxSpec ? normalizedQuantityPerBox : 0,
box_gross_weight: String(this.formData.box_gross_weight || ''),
box_net_weight: String(this.formData.box_net_weight || ''),
box_length: String(this.formData.box_length || ''),
box_width: String(this.formData.box_width || ''),
box_height: String(this.formData.box_height || ''),
box_volume: String(this.formData.box_volume || ''),
packing_requirements: String(this.formData.packing_requirements || '').trim(),
images: normalizedImages,
image: normalizedImageUrls[0] || '',
stock_unit: stockUnit,
tag_price: String(normalizedTagPrice),
retail_price: String(normalizedRetailPrice)
};
uni.$emit('product:detail:updated', {
item: nextItem,
timestamp: Date.now()
});
// 同步更新详情页缓存,保证详情页返回后展示最新数据(含商品条码)
if (this.detailCacheKey) {
uni.setStorageSync(this.detailCacheKey, nextItem);
}
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;
}
.form-section-title {
padding: 24rpx 0 8rpx;
font-size: 30rpx;
font-weight: bold;
color: #303133;
}
.shelf-life-block {
margin: 12rpx 0 16rpx;
padding: 8rpx 20rpx 20rpx;
border: 2rpx solid #dcdfe6;
border-radius: 12rpx;
background: #f8fafc;
}
.box-spec-block {
margin: 12rpx 0 16rpx;
padding: 8rpx 20rpx 20rpx;
border: 2rpx solid #dcdfe6;
border-radius: 12rpx;
background: #f8fafc;
}
::v-deep .shelf-life-block .u-form-item__body,
::v-deep .box-spec-block .u-form-item__body {
padding: 8rpx 0;
}
.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>