698 lines
18 KiB
Vue

<template>
<view class="product-edit-page">
<view class="normar_container">
<page-nav title="修改商品"></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>
</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"
:allowCreate="true"
@change="handleProhibitedTypeChange"
@create="handleProhibitedTypeCreate"
@close="showProhibitedPicker = false"
></inputAndSelect>
<inputAndSelect
title="选择库存单位"
:list="stockUnitList"
:show="showStockUnitPicker"
:value="formData.stock_unit_value"
:itemFontSize="32"
:allowCreate="true"
@change="handleStockUnitChange"
@create="handleStockUnitCreate"
@close="showStockUnitPicker = false"
></inputAndSelect>
</view>
</template>
<script>
export default {
data() {
return {
cacheKey: '',
saving: false,
rawItem: 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: '',
stock_unit_value: '',
stock_unit: '',
tag_price: '',
retail_price: ''
}
};
},
onLoad(options) {
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.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);
},
onUnload() {
if (this.cacheKey) {
uni.removeStorageSync(this.cacheKey);
}
},
methods: {
normalizePositiveId(value) {
const numericValue = Number(value);
if (!Number.isFinite(numericValue)) {
return null;
}
const normalized = Math.trunc(numericValue);
return normalized > 0 ? normalized : null;
},
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.id,
item.stock_id,
item.warehouse_stock_id,
item.storage_id
];
for (let i = 0; i < candidates.length; i++) {
const normalized = this.normalizePositiveId(candidates[i]);
if (normalized) {
return normalized;
}
}
return 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);
},
handleCancel() {
uni.navigateBack({
delta: 1
});
},
async handleSave() {
if (this.saving) {
return;
}
const itemName = String(this.formData.item_name || '').trim();
if (!itemName) {
uni.showToast({
title: '请输入商品名称',
icon: 'none'
});
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'
});
return;
}
const stockUnit = String(this.formData.stock_unit || '').trim();
if (!stockUnit) {
uni.showToast({
title: '请选择库存单位',
icon: 'none'
});
return;
}
this.saving = true;
try {
const storeId = this.resolveStoreId(this.rawItem || {});
if (!storeId) {
uni.showToast({
title: '未获取到货主ID',
icon: 'none'
});
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(),
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 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(),
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()
});
uni.showToast({
title: '保存成功',
icon: 'success'
});
setTimeout(() => {
uni.navigateBack({
delta: 1
});
}, 350);
} catch (error) {
uni.showToast({
title: (error && error.message) || '保存失败',
icon: 'none'
});
} 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;
}
.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>