| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204 |
- <template>
- <view class="container">
- <view class="form-container">
- <up-form
- labelPosition="left"
- :model="formData"
- :rules="rules"
- ref="formRef"
- :labelWidth="100"
- >
- <!-- 商品分类 -->
- <view class="card-title" v-if="!isProductCenter">商品分类</view>
- <up-form-item
- class="form-item"
- label="商品分类"
- prop="categoryIds"
- :borderBottom="false"
- @click="showCategory = true"
- :required="true"
- v-if="!isProductCenter"
- >
- <up-input
- v-model="formData.categoryDisplayName"
- disabled
- disabledColor="#ffffff"
- placeholder="请选择商品分类"
- inputAlign="right"
- border="none"
- ></up-input>
- <template #right>
- <up-icon name="arrow-right"></up-icon>
- </template>
- </up-form-item>
- <!-- 商品信息 -->
- <view class="card-title">商品信息</view>
- <up-form-item
- label="商品名称"
- prop="storeName"
- :borderBottom="false"
- :required="true"
- >
- <up-input
- v-model="formData.storeName"
- placeholder="请输入商品名称"
- inputAlign="right"
- border="none"
- ></up-input>
- </up-form-item>
- <up-form-item
- label="商品关键字"
- prop="keyword"
- :borderBottom="false"
- :required="true"
- v-if="!isProductCenter"
- >
- <up-input
- v-model="formData.keyword"
- placeholder="请输入商品关键字"
- inputAlign="right"
- border="none"
- ></up-input>
- </up-form-item>
- <up-form-item
- label="商品简介"
- prop="storeInfo"
- :borderBottom="false"
- :required="true"
- v-if="!isProductCenter"
- >
- <up-textarea
- v-model="formData.storeInfo"
- placeholder="请输入商品简介"
- inputAlign="right"
- border="none"
- ></up-textarea>
- </up-form-item>
- <up-form-item
- label="单位"
- prop="unitName"
- :borderBottom="false"
- :required="true"
- v-if="!isProductCenter"
- >
- <up-input
- v-model="formData.unitName"
- placeholder="请输入单位"
- inputAlign="right"
- border="none"
- ></up-input>
- </up-form-item>
- <!-- 图片上传 -->
- <view class="upload-section" v-if="!isProductCenter">
- <view class="upload-item">
- <view class="upload-label"><text class="required">*</text>商品封面图</view>
- <up-upload
- @afterRead="async (e) => {
- await afterRead(e);
- getImage();
- }"
- @delete="onPreviewImageDelete"
- name="preview"
- max-count="1"
- :fileList="previewImages"
- >
- <view class="upload-btn">
- <up-icon name="plus" size="20" color="#ccc"></up-icon>
- <text class="upload-tip">点击上传</text>
- </view>
- </up-upload>
- <text class="format-tip">支持上传PNG、JPG格式的图片,每张不超过5MB。</text>
- </view>
- </view>
- <view class="upload-section" v-if="!isProductCenter">
- <view class="upload-item">
- <view class="upload-label"><text class="required">*</text>商品图片</view>
- <up-upload
- @afterRead="async (e) => {
- await afterRead(e);
- getImageProduct();
- }"
- @delete="onProductImageDelete"
- name="product"
- multiple
- :maxCount="10"
- :fileList="productImages"
- >
- <view class="upload-btn">
- <up-icon name="plus" size="20" color="#ccc"></up-icon>
- <text class="upload-tip">点击上传</text>
- </view>
- </up-upload>
- <text class="format-tip">支持上传PNG、JPG格式图片,每张不超过5MB,最多可上传5张。</text>
- </view>
- </view>
- <!-- 商品属性 -->
- <view class="card-title">商品属性</view>
- <up-form-item
- label="材质"
- prop="metalType"
- :borderBottom="false"
- :required="true"
- v-if="!isProductCenter"
- >
- <up-radio-group
- v-model="formData.metalType"
- placement="row"
- >
- <up-radio
- :customStyle="{marginRight: '20rpx'}"
- v-for="(item, index) in materialList"
- :key="index"
- :label="item.name"
- :name="item.code"
- activeColor="#F8C008"
- >
- </up-radio>
- </up-radio-group>
- </up-form-item>
- <up-form-item
- label="重量"
- prop="weight"
- :borderBottom="false"
- :required="true"
- >
- <up-input
- v-model="formData.weight"
- placeholder="请输入重量"
- inputAlign="right"
- border="none"
- type="digit"
- ></up-input>
- <template #right>
- <text class="unit">g</text>
- </template>
- </up-form-item>
- <!-- 商品描述 -->
- <view class="card-title" v-if="!isProductCenter">商品描述</view>
- <view class="editor-section" v-if="!isProductCenter">
- <view class="editor-header">
- <text class="editor-label">商品描述</text>
- <text class="word-count">{{ descriptionText.length }}/500</text>
- </view>
- <sp-editor
- editorId="editor"
- :toolbar-config="toolbarConfig"
- :readOnly="readOnly"
- @input="onEditorInput"
- @upinImage="onUpinImage"
- @init="onEditorInit"
- @overMax="onOverMax"
- ></sp-editor>
- </view>
- <!-- 价格设置 -->
- <view class="card-title">价格设置</view>
- <up-form-item
- label="工费"
- prop="laborCost"
- :borderBottom="false"
- :required="true"
- >
- <up-input
- v-model="formData.laborCost"
- placeholder="请输入工费"
- inputAlign="right"
- border="none"
- type="digit"
- ></up-input>
- <template #right>
- <text class="unit">元/g</text>
- </template>
- </up-form-item>
- <up-form-item
- label="附加费"
- prop="additionalFee"
- :borderBottom="false"
- :required="true"
- >
- <up-input
- v-model="formData.additionalFee"
- placeholder="请输入附加费"
- inputAlign="right"
- border="none"
- type="digit"
- ></up-input>
- <template #right>
- <text class="unit">元</text>
- </template>
- </up-form-item>
- <up-form-item
- class="form-item"
- label="运费模板"
- prop="tempIds"
- :borderBottom="false"
- @click="showTemp = true"
- :required="true"
- >
- <up-input
- v-model="formData.tempName"
- disabled
- disabledColor="#ffffff"
- placeholder="请选择运费模板"
- inputAlign="right"
- border="none"
- ></up-input>
- <template #right>
- <up-icon name="arrow-right"></up-icon>
- </template>
- </up-form-item>
- <up-form-item
- label="库存"
- prop="stock"
- :borderBottom="false"
- :required="true"
- >
- <up-input
- v-model="formData.stock"
- placeholder="请输入库存"
- inputAlign="right"
- border="none"
- type="number"
- ></up-input>
- </up-form-item>
- <up-form-item
- label="商品编号"
- prop="barCode"
- :borderBottom="false"
- :required="true"
- >
- <up-input
- v-model="formData.barCode"
- placeholder="请输入商品编号"
- inputAlign="right"
- border="none"
- type="number"
- ></up-input>
- </up-form-item>
- <view class="upload-section">
- <view class="upload-item">
- <view class="upload-label"><text class="required">*</text>规格图片</view>
- <up-upload
- :fileList="productImagesGg"
- @afterRead="async (e) => {
- await afterRead(e);
- getImageProductGg();
- }"
- @delete="onProductImageGgDelete"
- name="productGg"
- :maxCount="1"
- >
- <view class="upload-btn">
- <up-icon name="plus" size="20" color="#ccc"></up-icon>
- <text class="upload-tip">点击上传</text>
- </view>
- </up-upload>
- <text class="format-tip">支持上传PNG、JPG格式图片,每张不超过5MB,最多可上传5张。</text>
- </view>
- </view>
- <up-form-item
- label="商品排序"
- prop="sort"
- :borderBottom="false"
- >
- <up-input
- v-model="formData.sort"
- placeholder="请输入排序号"
- inputAlign="right"
- border="none"
- type="number"
- ></up-input>
- </up-form-item>
- </up-form>
- </view>
- <!-- 发布按钮 -->
- <view class="btn-view">
- <button class="submit" @click="submitForm">立即发布</button>
- </view>
- <!-- 类目选择弹窗 -->
- <up-popup
- :show="showCategory"
- @close="showCategory = false"
- mode="bottom"
- round="20"
- :closeable="true"
- >
- <view class="popup-content">
- <view class="popup-header">
- <text class="popup-title">选择商品分类</text>
- </view>
- <category-selector
- :categoryList="categoryData"
- :selectedIds="formData.categoryIds"
- @change="onCategoryChange"
- ref="categoryRef"
- />
- <view class="popup-actions">
- <button class="action-btn cancel" @click="showCategory = false">取消</button>
- <button class="action-btn confirm" @click="confirmCategory">确定</button>
- </view>
- </view>
- </up-popup>
- <!-- 运费模板-->
- <up-picker :show="showTemp" v-model="formData.tempIds" :columns="tempColumns" keyName="name" valueName ="id"
- confirmColor="#F8C008"
- @close="showTemp = false" @confirm="tempConfirm" @cancel="showTemp = false"></up-picker>
- </view>
- </template>
- <script setup>
- import { ref, computed, watch,nextTick } from 'vue';
- import { onShow,onLoad } from "@dcloudio/uni-app";
- import { productCategory,productSave,productUpdate,templatesList,productInfo } from "@/api/merchant";
- import CategorySelector from '@/components/CategorySelector';
- import { useAppStore } from "@/stores/app";
- import { useImageUpload } from "@/hooks/useImageUpload";
- import { useToast } from "@/hooks/useToast";
- const { Toast } = useToast();
- const { imageList, afterRead, deletePic, uploadLoading } = useImageUpload({
- pid: 1,
- model: "product",
- });
- const appStore = useAppStore();
- const merchantInfo = appStore.userInfo.merchant
- // 表单验证和提交
- const formRef = ref(null);
- // 表单数据
- const formData = ref({
- categoryIds: [], // 选中的分类ID数组
- categoryDisplayName: '', // 显示的分类名称
- tempName: '', // 显示的运费模板名称
- tempIds: [],
- storeName: '',
- keyword: '',
- storeInfo: '',
- unitName: '',
- metalType: '',
- weight: '',
- laborCost: '',
- additionalFee: '',
- sort: '',
- content: '',
- stock: '',
- barCode: ''
- });
- // 编辑器相关
- const editorIns = ref(null);
- const readOnly = ref(false);
- const descriptionText = ref('');
- const toolbarConfig = ref({
- iconSize: '20px',
- iconColumns: 10,
- excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck']
- });
- // 分类相关
- const showCategory = ref(false);
- const categoryData = ref([]);
- const categoryRef = ref();
- const showTemp = ref(false);
- const tempColumns = ref([])
- // 图片列表
- const previewImages = ref([]);
- const productImages = ref([]);
- const productImagesGg = ref([]);
- const productId = ref(null);
- const isProductCenter = ref(null);
- // 材质列表
- const materialList = ref([
- { name: '黄金',code:'au' },
- { name: '铂金' ,code:'pt'},
- { name: '白银',code:'ag' }
- ]);
- // 验证规则
- const rules = ref({
- categoryIds: {
- type: 'array',
- required: true,
- message: '请选择商品分类',
- trigger: ['blur','change']
- },
- storeName: {
- type: 'string',
- required: true,
- message: '请输入商品名称',
- trigger: ['blur', 'change']
- },
- keyword: {
- type: 'string',
- required: true,
- message: '请输入商品关键字',
- trigger: ['blur', 'change']
- },
- storeInfo: {
- type: 'string',
- required: true,
- message: '请输入商品关键字',
- trigger: ['blur', 'change']
- },
- unitName: {
- type: 'string',
- required: true,
- message: '请输入单位',
- trigger: ['blur', 'change']
- },
- tempIds: {
- type: 'array',
- required: true,
- message: '请选择运费模板',
- trigger: ['blur', 'change']
- },
- metalType: {
- type: 'string',
- required: true,
- message: '请选择材质',
- trigger: ['blur','change']
- },
- weight: {
- type: 'string',
- required: true,
- pattern: /^\d+(\.\d+)?$/,
- message: '重量必须是数字,可以是小数',
- trigger: ['blur', 'change']
- },
- laborCost: {
- type: 'string',
- required: true,
- pattern: /^\d+(\.\d+)?$/,
- message: '工费必须是数字,可以是小数',
- trigger: ['blur', 'change']
- },
- additionalFee: {
- type: 'string',
- required: true,
- pattern: /^\d+(\.\d+)?$/,
- message: '附加费必须是数字,可以是小数',
- trigger: ['blur', 'change']
- },
- sort: {
- type: 'string',
- pattern: /^\d*$/,
- message: '排序号必须是整数',
- trigger: ['blur', 'change'],
- validator: (rule, value) => {
- if (!value || value.trim().length === 0) return true; // 可选字段,为空时通过
- return /^\d+$/.test(value);
- }
- },
- stock: {
- type: 'string',
- required: true,
- pattern: /^\d*$/,
- message: '库存必须是整数',
- trigger: ['blur', 'change'],
- validator: (rule, value) => {
- if (!value || value.trim().length === 0) return false;
- return /^\d+$/.test(value);
- }
- },
- barCode: {
- type: 'string',
- required: true,
- pattern: /^\d*$/,
- message: '商品编号必须是整数',
- trigger: ['blur', 'change'],
- validator: (rule, value) => {
- if (!value || value.trim().length === 0) return false;
- return /^\d+$/.test(value);
- }
- },
- });
- // 页面加载
- onShow(() => {
- })
- onLoad(async (options)=>{
- await getProductCategory();
- await getTempData();
- console.log(options)
- if(options.id){
- productId.value = options.id;
- isProductCenter.value = options.isProductCenter || null;
- await getProductDetail(options.id);
- }else {
- resetForm();
- }
- })
- // 获取商品分类
- async function getProductCategory(){
- let obj = {
- type: 1,
- status: 1
- }
- try {
- const { data } = await productCategory(obj)
- console.log('原始分类数据:', data);
- const newArr = []
- data.forEach((value, index) => {
- newArr[index] = value
- if (value.child) newArr[index].child = value.child.filter(item => item.status === true)
- })
- // 过滤商品分类设置为隐藏的子分类不出现在树形列表里
- categoryData.value = newArr.filter(item => item.code !== 'bb_mall')
- console.log('转换后的分类数据:', categoryData.value);
- } catch (error) {
- console.error('获取商品分类失败:', error);
- uni.showToast({ title: '获取分类失败', icon: 'none' });
- }
- }
- // 获取运费模板
- async function getTempData(){
- let obj = {
- page:1,
- limit:9999
- }
- try {
- const { data } = await templatesList()
- tempColumns.value[0] = data.list;
- } catch (error) {
- console.error('获取商品分类失败:', error);
- uni.showToast({ title: '获取分类失败', icon: 'none' });
- }
- }
- const initFormValidation = async () => {
- await nextTick();
- if (!formRef.value) {
- console.error('表单引用不存在');
- return;
- }
- try {
- // 方法1:清除所有验证状态,然后重新验证
- formRef.value.clearValidate();
- // 方法2:延迟触发字段验证
- setTimeout(async () => {
- // 逐个触发必填字段的验证
- const requiredFields = ['categoryIds', 'storeName', 'keyword', 'storeInfo', 'unitName',
- 'tempIds', 'metalType', 'weight', 'laborCost', 'additionalFee',
- 'stock', 'barCode'];
- for (const field of requiredFields) {
- try {
- await formRef.value.validateField(field);
- } catch (error) {
- console.log(`⚠️ 字段 ${field} 验证状态:`, error);
- }
- }
- }, 300);
- } catch (error) {
- console.error('初始化表单验证状态失败:', error);
- }
- };
- // 获取商品详情
- async function getProductDetail(id){
- try {
- const { data } = await productInfo(id)
- console.log('获取商品详情:',data);
- // 使用Object.assign确保响应式更新
- Object.assign(formData.value, {
- ...data,
- // 确保categoryIds是数组格式
- categoryIds: data.cateId ? (Array.isArray(data.cateId) ? data.cateId : data.cateId.split(',')) : [],
- // 确保tempIds是数组格式
- tempIds: data.tempId ? [data.tempId] : []
- });
- productImages.value = [];
- console.log('分类IDs:', formData.value.categoryIds);
- console.log('运费模板IDs:', formData.value.tempIds);
- // 等待DOM更新
- await nextTick();
- // 更新显示名称
- formData.value.categoryDisplayName = getCategoryDisplayName(formData.value.categoryIds);
- formData.value.tempName = formatterTemp(data.tempId);
- console.log('分类显示名称:', formData.value.categoryDisplayName);
- // 图片处理
- previewImages.value = data.image ? [{ url: data.image }] : [];
- // 商品轮播图
- if(data.sliderImage){
- try {
- const urlArr = typeof data.sliderImage === 'string' ? JSON.parse(data.sliderImage) : data.sliderImage;
- if(urlArr && urlArr.length > 0){
- productImages.value = urlArr.map(url => ({ url }));
- }
- } catch (error) {
- console.error('解析轮播图失败:', error);
- productImages.value = [];
- }
- }
- // 商品属性
- if (data.attrValue && data.attrValue.length > 0) {
- formData.value.additionalFee = data.attrValue[0].additionalAmount;
- formData.value.laborCost = data.attrValue[0].price;
- formData.value.barCode = data.attrValue[0].barCode;
- formData.value.stock = data.attrValue[0].stock;
- formData.value.weight = data.attrValue[0].weight;
- // 规格图片
- productImagesGg.value = data.attrValue[0].image ? [{ url: data.attrValue[0].image }] : [];
- }
- // 商品描述
- descriptionText.value = data.content ? data.content.replace(/<[^>]*>/g, '').substring(0, 500) : '';
- formData.value.content = data.content || '';
- // 设置分类选择器
- if (categoryRef.value && formData.value.categoryIds.length > 0) {
- // 使用nextTick确保组件已渲染
- await nextTick();
- if (categoryRef.value.setSelectedIds) {
- categoryRef.value.setSelectedIds(formData.value.categoryIds);
- }
- }
- // 重要:手动初始化表单验证状态
- await initFormValidation();
- } catch (error) {
- console.error('获取商品详情失败:', error);
- uni.showToast({ title: '获取商品详情失败', icon: 'none' });
- }
- }
- // 运费模板id获取中文名
- function formatterTemp(id) {
- // 假设 tempColumns 是一个数组
- const foundItem = tempColumns.value[0].find(item => item.id == id);
- return foundItem ? foundItem.name : '';
- }
- function tempConfirm(obj){
- formData.value.tempId = obj.value[0].id;
- formData.value.tempName = obj.value[0].name;
- showTemp.value = false;
- setTimeout(() => {
- if (formRef.value) {
- formRef.value.validateField('tempIds');
- }
- }, 100);
- }
- // 分类选择变化
- const onCategoryChange = (result) => {
- console.log('分类选择变化:', result);
- // 这里只更新显示,不直接更新表单数据,等用户点击确定
- }
- // 确认分类选择
- const confirmCategory = () => {
- if (categoryRef.value) {
- const selectedIds = categoryRef.value.getSelectedIds()
- if (selectedIds.length === 0) {
- uni.showToast({ title: '请至少选择一个分类', icon: 'none' })
- return
- }
- // 更新表单数据
- formData.value.categoryIds = selectedIds
- formData.value.categoryDisplayName = getCategoryDisplayName(selectedIds)
- showCategory.value = false
- console.log('最终选中的分类ID:', selectedIds)
- // 触发校验
- setTimeout(() => {
- if (formRef.value) {
- formRef.value.validateField('categoryIds');
- }
- }, 100);
- }
- }
- // 根据选中的ID生成显示名称
- const getCategoryDisplayName = (selectedIds) => {
- if (!selectedIds || selectedIds.length === 0) return ''
- const names = []
- selectedIds.forEach(id => {
- // 检查是否是一级分类(表示全选)
- const firstLevel = categoryData.value.find(item => item.id == id)
- if (firstLevel) {
- // 如果是一级分类,显示"分类名称(全部)"
- names.push(`${firstLevel.name}`)
- } else {
- // 查找二级分类
- for (const parent of categoryData.value) {
- if (parent.child) {
- const secondLevel = parent.child.find(child => child.id == id)
- if (secondLevel) {
- names.push(`${parent.name}-${secondLevel.name}`)
- break
- }
- }
- }
- // 如果没有子分类的一级分类
- const singleLevel = categoryData.value.find(item =>
- !item.child && item.id == id
- )
- if (singleLevel) {
- names.push(singleLevel.name)
- }
- }
- })
- return names.join('、')
- }
- async function getImage() {
- console.log(imageList.value)
- if (imageList.value.length > 0) {
- if (imageList.value[0].status == "success") {
- previewImages.value = imageList.value;
- console.log('previewImages.value',previewImages.value)
- // change();
- } else {
- Toast({ title: "上传失败" });
- }
- }
- imageList.value = [];
- }
- async function getImageProduct() {
- if (imageList.value.length > 0) {
- if (imageList.value[0].status == "success") {
- productImages.value = [...productImages.value,...imageList.value];
- // change();
- } else {
- Toast({ title: "上传失败" });
- }
- }
- imageList.value = [];
- }
- async function getImageProductGg() {
- if (imageList.value.length > 0) {
- if (imageList.value[0].status == "success") {
- productImagesGg.value = imageList.value;
- // change();
- } else {
- Toast({ title: "上传失败" });
- }
- }
- imageList.value = [];
- }
- const onPreviewImageDelete =(e) => {
- previewImages.value.splice(e.index, 1);
- };
- const onProductImageDelete = (e) => {
- productImages.value.splice(e.index, 1);
- };
- const onProductImageGgDelete = (e) => {
- productImagesGg.value.splice(e.index, 1);
- };
- // 编辑器相关方法
- const onEditorInput = (e) => {
- descriptionText.value = e.text || '';
- formData.value.content = e.html || '';
- };
- const onEditorInit = (editor) => {
- editorIns.value = editor;
- };
- const onOverMax = (e) => {
- uni.showToast({ title: '内容长度超出限制', icon: 'none' });
- };
- const onUpinImage = (tempFiles, editorCtx) => {
- const filePath = tempFiles[0].tempFilePath || tempFiles[0].path;
- editorCtx.insertImage({
- src: filePath,
- width: '80%',
- success: () => {
- uni.showToast({ title: '图片插入成功', icon: 'success' });
- }
- });
- };
- const validateForm = () => {
- try {
- if(!isProductCenter.value){
- // 检查图片上传
- if (previewImages.value.length === 0) {
- uni.showToast({ title: '请上传商品预览图', icon: 'none' });
- return;
- }
- if (productImages.value.length === 0) {
- uni.showToast({ title: '请上传商品图片', icon: 'none' });
- return;
- }
- if (formData.value.sort && !/^\d+$/.test(formData.value.sort)) {
- uni.showToast({ title: '排序号必须是整数', icon: 'none' });
- return;
- }
- }
- if (productImagesGg.value.length === 0) {
- uni.showToast({ title: '请上传商品规格图片', icon: 'none' });
- return;
- }
- // 验证数字字段
- if (!/^\d+(\.\d+)?$/.test(formData.value.weight)) {
- uni.showToast({ title: '重量格式不正确', icon: 'none' });
- return;
- }
- if (!/^\d+(\.\d+)?$/.test(formData.value.laborCost)) {
- uni.showToast({ title: '工费格式不正确', icon: 'none' });
- return;
- }
- if (!/^\d+(\.\d+)?$/.test(formData.value.additionalFee)) {
- uni.showToast({ title: '附加费格式不正确', icon: 'none' });
- return;
- }
- if (!/^\d+$/.test(formData.value.stock)) {
- uni.showToast({ title: '库存必须是整数', icon: 'none' });
- return;
- }
- if (!/^\d+$/.test(formData.value.barCode)) {
- uni.showToast({ title: '商品编号必须是整数', icon: 'none' });
- return;
- }
- const valid = formRef.value.validate();
- return valid;
- } catch (error) {
- console.error('表单验证失败:', error);
- return false;
- }
- };
- const submitForm = async () => {
- const valid = validateForm();
- if (valid) {
- const submitData = {
- ...formData.value
- };
- submitData.cateId =formData.value.categoryIds.join(',');
- submitData.image =previewImages.value[0].info.url;
- const urlString = JSON.stringify(productImages.value.map(item => item.info.url));
- submitData.sliderImage =urlString;
- submitData.merchantId =parseInt(merchantInfo.id);
- submitData.specType = 0;
- submitData.isSub = false;
- submitData.attr =[
- {
- "attrName":"规格",
- "attrValues": "默认",
- "id": 0
- }
- ];
- submitData.attrValue =[
- {
- additionalAmount :formData.value.additionalFee,
- attrValue:"{\"规格\":\"默认\"}",
- barCode : formData.value.barCode,
- image : productImagesGg.value[0].info.url,
- price : formData.value.laborCost,
- stock : formData.value.stock,
- weight :formData.value.weight
- }
- ];
- console.log('提交数据:', submitData);
- if(productId.value && !isProductCenter.value){
- const {data} = await productUpdate(submitData);
- uni.showToast({ title: '修改成功', icon: 'success' });
- }else{
- const {data} = await productSave(submitData);
- uni.showToast({ title: '发布成功', icon: 'success' });
- }
- uni.navigateTo({
- url: '/pages/merchantCenters/productManagement'
- })
- }
- }
- // 重置表单(用于新建场景)
- const resetForm = () => {
- formData.value = {
- categoryIds: [],
- categoryDisplayName: '',
- tempName: '',
- tempIds: [],
- storeName: '',
- keyword: '',
- storeInfo: '',
- unitName: '',
- metalType: '',
- weight: '',
- laborCost: '',
- additionalFee: '',
- sort: '',
- content: '',
- stock: '',
- barCode: ''
- };
- previewImages.value = [];
- productImages.value = [];
- productImagesGg.value = [];
- descriptionText.value = '';
- // 清除校验状态
- if (formRef.value) {
- formRef.value.clearValidate();
- }
- }
- </script>
- <style scoped lang="scss">
- .container {
- background-color: #f8f8f8;
- min-height: 100vh;
- padding-bottom: 140rpx;
- }
- .form-container {
- padding: 30rpx;
- }
- .upload-section {
- margin-top: 20rpx;
- margin-bottom: 20rpx;
- background: white;
- border-radius: 16rpx;
- padding: 30rpx;
- }
- .upload-item {
- margin-bottom: 40rpx;
- &:last-child {
- margin-bottom: 0;
- }
- }
- .upload-label {
- display: block;
- font-size: 28rpx;
- color: #333;
- margin-bottom: 20rpx;
- position: relative;
- }
- .required {
- position: absolute;
- left: -9px;
- color: #f56c6c;
- line-height: 20px;
- font-size: 20px;
- top: 3px;
- }
- .upload-btn {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- width: 200rpx;
- height: 200rpx;
- border: 2rpx dashed #ccc;
- border-radius: 12rpx;
- background: #fafafa;
- }
- .upload-tip {
- font-size: 24rpx;
- color: #999;
- margin-top: 10rpx;
- }
- .format-tip {
- display: block;
- font-size: 24rpx;
- color: #999;
- margin-top: 15rpx;
- }
- .card-title {
- font-size: 36rpx;
- color: #333;
- line-height: 60rpx;
- margin-bottom: 20rpx;
- }
- :deep(.u-form-item) {
- background-color: #fff;
- border-radius: 16rpx;
- padding: 8rpx 30rpx;
- box-sizing: border-box;
- margin-bottom: 20rpx;
- }
- :deep(.u-form-item__body__left__content__label) {
- font-size: 28rpx !important;
- color: #333 !important;
- }
- :deep(.u-radio-group--row) {
- justify-content: flex-end;
- }
- .btn-view {
- position: fixed;
- bottom: 0;
- left: 0;
- right: 0;
- background-color: #FFF;
- padding: 20rpx 30rpx;
- box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
- z-index: 5;
- }
- .submit {
- height: 88rpx;
- line-height: 88rpx;
- background: #F8C008;
- border-radius: 16rpx;
- font-size: 32rpx;
- color: #333333;
- border: none;
- width: 100%;
- &:active {
- opacity: 0.8;
- }
- }
- .unit {
- color: #999;
- font-size: 28rpx;
- margin-left: 10rpx;
- }
- /* 编辑器样式 */
- .editor-section {
- background: white;
- border-radius: 16rpx;
- margin-bottom: 20rpx;
- overflow: hidden;
- }
- .editor-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 30rpx;
- border-bottom: 1rpx solid #f0f0f0;
- }
- .editor-label {
- font-size: 28rpx;
- color: #333;
- font-weight: 500;
- }
- .word-count {
- font-size: 24rpx;
- color: #999;
- }
- :deep(.sp-editor) {
- min-height: 400rpx;
- }
- /* 弹窗样式 */
- .popup-content {
- background: #fff;
- border-radius: 20rpx 20rpx 0 0;
- padding-bottom: env(safe-area-inset-bottom);
- }
- .popup-header {
- padding: 30rpx;
- text-align: center;
- border-bottom: 1rpx solid #f0f0f0;
- position: relative;
- }
- .popup-title {
- font-size: 32rpx;
- font-weight: 600;
- color: #333;
- }
- .popup-actions {
- display: flex;
- padding: 30rpx;
- gap: 20rpx;
- }
- .action-btn {
- flex: 1;
- height: 80rpx;
- line-height: 80rpx;
- border-radius: 12rpx;
- font-size: 28rpx;
- border: none;
- &.cancel {
- background: #f0f0f0;
- color: #666;
- }
- &.confirm {
- background: #F8C008;
- color: #333;
- }
- }
- :deep(.u-tabs__wrapper__nav__line){
- background-color: #F8C008 !important;
- }
- :deep(.u-form-item__body__right__message){
- text-align: right;
- }
- :deep(.u-textarea__field){
- text-align: right;
- }
- </style>
|