| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695 |
- <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" v-if="!isProductCenter">商家类目</view>
- <up-form-item class="form-item" label="商家类目" prop="merchantCategoryId" :borderBottom="false"
- @click="showMerchantCategory = true" :required="true" v-if="!isProductCenter">
- <up-input v-model="formData.merchantCategoryDisplayName" 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,最多可上传10张。</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 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>
- <!-- 商品描述 -->
- <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="pro-cate-container">
- <view class="cate-title" v-if="!isProductCenter">商品规格批量设置</view>
- <view class="cate-list">
- <view class="cate-item">
- <view class="cate-pic-line">
- <up-upload :fileList="oneTemplate.imgs" @afterRead="async (e) => {
- await afterRead(e);
- getImageProductGg('oneTemplate');
- }" @delete="onProductImageGgDelete('oneTemplate')" name="productGg" :maxCount="1">
- <view class="upload-btn">
- <up-icon name="plus" size="20" color="#666"></up-icon>
- <text class="upload-tip">上传图片</text>
- </view>
- </up-upload>
- </view>
- <view class="cate-ipt-line">
- <view class="cate-ipt" style="margin-right: 16rpx;">
- <up-input class="" v-model="oneTemplate.price" placeholder="请输入工费" inputAlign="left"
- @blur="keyupEvent('price', oneTemplate.price, 0, 1)" border="none" type="digit"
- labelWidth="">
- <template #suffix>
- <text class="unit">元/g</text>
- </template>
- </up-input>
- </view>
- <view class="cate-ipt">
- <up-input class="" v-model="oneTemplate.stock" placeholder="请输入库存" inputAlign="left"
- @blur="keyupEvent('stock', oneTemplate.stock, 0, 1)" border="none" type="number"
- labelWidth="">
- <template #suffix>
- <text class="unit">件</text>
- </template>
- </up-input>
- </view>
- </view>
- <view class="cate-ipt-line">
- <view class="cate-ipt" style="margin-right: 16rpx;">
- <up-input class="" v-model="oneTemplate.weight" placeholder="请输入重量"
- inputAlign="left" @blur="keyupEvent('weight', oneTemplate.weight, 0, 1)"
- border="none" type="digit" labelWidth="">
- <template #suffix>
- <text class="unit">g</text>
- </template>
- </up-input>
- </view>
- <view class="cate-ipt">
- <up-input class="" v-model="oneTemplate.additionalAmount" placeholder="请输入附加金额"
- inputAlign="left"
- @blur="keyupEvent('additionalAmount', oneTemplate.additionalAmount, 0, 1)"
- border="none" type="number" labelWidth="">
- <template #suffix>
- <text class="unit">元</text>
- </template>
- </up-input>
- </view>
- </view>
- <view class="cate-ipt-line" style="padding: 0;">
- <view class="cate-ipt">
- <up-input class="" v-model="oneTemplate.barCode" placeholder="请输入商品编号"
- inputAlign="left" @blur="keyupEvent('barCode', oneTemplate.barCode, 0, 1)"
- border="none" type="digit" labelWidth="">
- </up-input>
- </view>
- </view>
- </view>
- </view>
- <view class="cate-add" @click="setAllAttr">
- 批量设置规格
- </view>
- </view>
- <!-- 商品规格管理 -->
- <view class="pro-cate-container">
- <view class="cate-title" v-if="!isProductCenter"><text style="color:red;">*</text>商品规格</view>
- <view class="cate-list">
- <view class="cate-item" v-for="(item,index) of attrTable" :key="'attr'+index">
- <view class="cate-pic-line">
- <up-upload :fileList="item.imgs" @afterRead="async (e) => {
- await afterRead(e);
- getImageProductGg(index);
- }" @delete="onProductImageGgDelete(index)" name="productGg" :maxCount="1">
- <view class="upload-btn">
- <up-icon name="plus" size="20" color="#666"></up-icon>
- <text class="upload-tip">上传图片</text>
- </view>
- </up-upload>
- <view class="cate-name">
- {{formatterAttrValue(item.attrValue)}}
- </view>
- </view>
- <view class="cate-ipt-line">
- <view class="cate-ipt" style="margin-right: 16rpx;">
- <up-input class="" v-model="item.price" placeholder="请输入工费" inputAlign="left"
- @blur="keyupEvent('price', item.price, index, 2)" border="none" type="digit"
- labelWidth="">
- <template #suffix>
- <text class="unit">元/g</text>
- </template>
- </up-input>
- </view>
- <view class="cate-ipt">
- <up-input class="" v-model="item.stock" placeholder="请输入库存" inputAlign="left"
- @blur="keyupEvent('stock', item.stock, index, 2)" border="none" type="number"
- labelWidth="">
- <template #suffix>
- <text class="unit">件</text>
- </template>
- </up-input>
- </view>
- </view>
- <view class="cate-ipt-line">
- <view class="cate-ipt" style="margin-right: 16rpx;">
- <up-input class="" v-model="item.weight" placeholder="请输入重量" inputAlign="left"
- @blur="keyupEvent('weight', item.weight, index, 2)" border="none" type="digit"
- labelWidth="">
- <template #suffix>
- <text class="unit">g</text>
- </template>
- </up-input>
- </view>
- <view class="cate-ipt">
- <up-input class="" v-model="item.additionalAmount" placeholder="请输入附加金额"
- inputAlign="left"
- @blur="keyupEvent('additionalAmount', item.additionalAmount, index, 2)"
- border="none" type="number" labelWidth="">
- <template #suffix>
- <text class="unit">元</text>
- </template>
- </up-input>
- </view>
- </view>
- <view class="cate-ipt-line" style="padding: 0;">
- <view class="cate-ipt">
- <up-input class="" v-model="item.barCode" placeholder="请输入商品编号" inputAlign="left"
- @blur="keyupEvent('barCode', item.barCode, index, 2)" border="none" type="digit"
- labelWidth="">
- </up-input>
- </view>
- </view>
- </view>
- </view>
- <view class="cate-add" @click="editCatePage">
- 管理规格
- </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-popup
- :show="showMerchantCategory"
- @close="showMerchantCategory = false"
- mode="bottom"
- round="20"
- :closeable="true"
- >
- <view class="popup-content">
- <view class="popup-header">
- <text class="popup-title">选择商家类目</text>
- </view>
- <category-selector
- :categoryList="merchantCategoryData"
- :selectedIds="formData.merchantCategoryId"
- @change="onMerchantCategoryChange"
- ref="merchantCategoryRef"
- :multiple="false"
- />
- <view class="popup-actions">
- <button class="action-btn cancel" @click="showMerchantCategory = false">取消</button>
- <button class="action-btn confirm" @click="confirmMerchantCategory">确定</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,
- onUnload
- } from "@dcloudio/uni-app";
- import {
- productCategory,
- productSave,
- productUpdate,
- templatesList,
- productInfo,
- getMerchantCategory
- } 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: '', // 显示的分类名称
- merchantCategoryId: [], // 选中的商家类目ID数组(单选:长度始终为1)
- merchantCategoryDisplayName: '', // 显示的商家类目名称
- 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 showMerchantCategory = ref(false);
- const merchantCategoryData = ref([]);
- const merchantCategoryRef = 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 attr = ref([]);
- const attrTable = ref([]);
- const oneTemplate = ref({
- image: '',
- imgs: [],
- price: '',
- additionalAmount: '',
- stock: '',
- barCode: '',
- weight: '',
- })
- let historyAttr = []
- let historyTable = {}
- // 材质列表
- const materialList = ref([{
- name: '黄金',
- code: 'au'
- },
- {
- name: '铂金',
- code: 'pt'
- },
- {
- name: '白银',
- code: 'ag'
- }
- ]);
- // 验证规则
- const rules = ref({
- categoryIds: {
- type: 'array',
- required: true,
- message: '请选择商品分类',
- trigger: ['blur', 'change']
- },
- merchantCategoryId: {
- type: 'array',
- required: true,
- len: 1,
- 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']
- },
- sort: {
- type: 'string',
- pattern: /^\d*$/,
- message: '排序号必须是整数',
- trigger: ['blur', 'change'],
- validator: (rule, value) => {
- if (!value || value.trim().length === 0) return true;
- return /^\d+$/.test(value);
- }
- }
- });
- // 页面生命周期
- onShow(() => {})
- onLoad(async (options) => {
- appStore.SET_CPATTR([])
- appStore.SET_CPATTRVALUE([])
- await getProductCategory();
- await getMerchantCategoryList();
- await getTempData();
- console.log(options)
- if (options.id) {
- productId.value = options.id;
- isProductCenter.value = options.isProductCenter || null;
- await getProductDetail(options.id);
- } else {
- resetForm();
- }
- uni.$on("updateAttr", onUpdateAttr)
- })
- onUnload(() => {
- uni.$off("updateAttr")
- })
- // 规格更新回调
- const onUpdateAttr = (data) => {
- const table = attrFormat(data)
- attr.value = data.concat();
- attrTable.value = table
- }
- // 获取商品分类
- 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 getMerchantCategoryList(){
- try {
- const { data } = await getMerchantCategory();
- console.log('原始商家类目数据:', data);
-
- merchantCategoryData.value = data.map(item => ({
- id: item.id,
- name: item.categoryName,
- child: []
- }));
- console.log('适配后的商家类目数据:', merchantCategoryData.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 {
- formRef.value.clearValidate();
- setTimeout(async () => {
- const requiredFields = ['categoryIds', 'merchantCategoryId', 'storeName', 'keyword', 'storeInfo', 'unitName',
- 'tempIds', 'metalType'
- ];
- 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(formData.value, {
- ...data,
- categoryIds: data.cateId ? (Array.isArray(data.cateId) ? data.cateId : data.cateId.split(',')) : [],
- merchantCategoryId: data.merchantCategoryId ? (Array.isArray(data.merchantCategoryId) ? data.merchantCategoryId : [data.merchantCategoryId]) : [],
- tempIds: data.tempId ? [data.tempId] : []
- });
- productImages.value = [];
- console.log('分类IDs:', formData.value.categoryIds);
- console.log('商家类目IDs:', formData.value.merchantCategoryId);
- console.log('运费模板IDs:', formData.value.tempIds);
- await nextTick();
- formData.value.categoryDisplayName = getCategoryDisplayName(formData.value.categoryIds);
- formData.value.merchantCategoryDisplayName = getMerchantCategoryDisplayName(formData.value.merchantCategoryId);
- formData.value.tempName = formatterTemp(data.tempId);
- // 图片处理
- 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) {
- data.attr.forEach(item => {
- attr.value.push({
- attrName: item.attrName,
- attrValue: item.attrValues.split(',')
- })
- })
- data.attrValue.forEach(item => {
- let attrName = item.suk;
- attrTable.value.push({
- ...item,
- attrName: attrName,
- imgs: item?.image ? [{
- url: item.image
- }] : []
- })
- })
- appStore.SET_CPATTR(attr.value)
- }
- // 商品描述
- descriptionText.value = data.content ? data.content.replace(/<[^>]*>/g, '').substring(0, 500) : '';
- formData.value.content = data.content || '';
- // 设置分类选择器
- if (categoryRef.value && formData.value.categoryIds.length > 0) {
- await nextTick();
- if (categoryRef.value.setSelectedIds) {
- categoryRef.value.setSelectedIds(formData.value.categoryIds);
- }
- }
- // 设置商家类目选择器
- if (merchantCategoryRef.value && formData.value.merchantCategoryId.length > 0) {
- await nextTick();
- if (merchantCategoryRef.value.setSelectedIds) {
- merchantCategoryRef.value.setSelectedIds(formData.value.merchantCategoryId);
- }
- }
- await initFormValidation();
- } catch (error) {
- console.error('获取商品详情失败:', error);
- uni.showToast({
- title: '获取商品详情失败',
- icon: 'none'
- });
- }
- }
- // 运费模板id转名称
- function formatterTemp(id) {
- 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 onMerchantCategoryChange = (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);
- }
- }
- // 确认商家类目选择
- const confirmMerchantCategory = () => {
- if (merchantCategoryRef.value) {
- let selectedIds = merchantCategoryRef.value.getSelectedIds()
- if (selectedIds.length === 0) {
- uni.showToast({ title: '请选择一个商家类目', icon: 'none' })
- return
- }
- if (selectedIds.length > 1) {
- selectedIds = [selectedIds[0]]
- uni.showToast({ title: '商家类目仅支持选择一个', icon: 'none' })
- }
- formData.value.merchantCategoryId = selectedIds
- formData.value.merchantCategoryDisplayName = getMerchantCategoryDisplayName(selectedIds)
- showMerchantCategory.value = false
- console.log('最终选中的商家类目ID(单选):', selectedIds)
- setTimeout(() => {
- if (formRef.value) {
- formRef.value.validateField('merchantCategoryId');
- }
- }, 100);
- }
- }
- // 生成分类显示名称
- 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('、')
- }
- // 生成商家类目显示名称
- const getMerchantCategoryDisplayName = (selectedIds) => {
- if (!selectedIds || selectedIds.length === 0) return ''
- const firstId = selectedIds[0]
- const category = merchantCategoryData.value.find(item => item.id == firstId)
- return category ? category.name : ''
- }
- // 图片上传相关
- async function getImage() {
- console.log(imageList.value)
- if (imageList.value.length > 0) {
- if (imageList.value[0].status == "success") {
- previewImages.value = imageList.value;
- } 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];
- } else {
- Toast({
- title: "上传失败"
- });
- }
- }
- imageList.value = [];
- }
- async function getImageProductGg(index) {
- if (imageList.value.length > 0) {
- if (imageList.value[0].status == "success") {
- if (index == "oneTemplate") {
- oneTemplate.value.imgs = imageList.value
- oneTemplate.value.image = imageList.value[0].info.url
- } else {
- attrTable.value[index].imgs = imageList.value
- attrTable.value[index].image = imageList.value[0].info.url
- }
- } 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) => {
- if (e == "oneTemplate") {
- oneTemplate.value.imgs = []
- } else {
- attrTable.value[e].imgs = []
- }
- 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;
- }
- }
- const valid = formRef.value.validate();
- return valid;
- } catch (error) {
- console.error('表单验证失败:', error);
- return false;
- }
- };
- // 规格验证
- const validateAttr = (item) => {
- if (!item.image) {
- uni.showToast({
- title: '请上传商品规格图片',
- icon: 'none'
- });
- return false;
- }
- if (!/^\d+(\.\d+)?$/.test(item.weight)) {
- uni.showToast({
- title: '重量格式不正确',
- icon: 'none'
- });
- return false;
- }
- if (!/^\d+(\.\d+)?$/.test(item.price)) {
- uni.showToast({
- title: '工费格式不正确',
- icon: 'none'
- });
- return false;
- }
- if (!/^\d+(\.\d+)?$/.test(item.additionalAmount)) {
- uni.showToast({
- title: '附加费格式不正确',
- icon: 'none'
- });
- return false;
- }
- if (!/^\d+$/.test(item.stock)) {
- uni.showToast({
- title: '库存必须是整数',
- icon: 'none'
- });
- return false;
- }
- if (!/^\d+$/.test(item.barCode)) {
- uni.showToast({
- title: '商品编号必须是整数',
- icon: 'none'
- });
- return false;
- }
- return true
- }
- // 提交表单
- const submitForm = async () => {
- const valid = validateForm();
- if (valid) {
- const submitData = {
- ...formData.value
- };
- let urlString = '';
- if (isProductCenter.value) {
- submitData.image = previewImages.value[0].url;
- urlString = JSON.stringify(productImages.value.map(item => item.url));
- } else {
- submitData.image = previewImages.value[0]?.info?.url || previewImages.value[0]?.url;
- urlString = JSON.stringify(productImages.value.map(item => item?.info?.url || item?.url));
- }
- submitData.sliderImage = urlString;
- submitData.cateId = formData.value.categoryIds.join(',');
- submitData.merchantCategoryId = formData.value.merchantCategoryId;
- submitData.merchantId = parseInt(merchantInfo.id);
- submitData.specType = true;
- submitData.isSub = false;
-
- if (!attr.value || attr.value.length <= 0 || !attrTable.value || attrTable.value.length <= 0) {
- return Toast({
- title: "请添加商品规格!"
- });
- }
- let pass = true;
- submitData.attr = attr.value.map(item => {
- return {
- attrName: item.attrName,
- attrValues: item.attrValue.join(','),
- }
- })
- submitData.attrValue = attrTable.value.map(item => {
- if (!validateAttr(item)) {
- pass = false;
- }
- return {
- ...item,
- id: 0,
- productId: 0,
- attrValue: typeof(item.attrValue) == 'object' ? JSON.stringify(item.attrValue) : item.attrValue,
- image: item.image || item.imgs[0]?.info?.url || item.imgs[0]?.url
- }
- })
- if (!pass) return false;
-
- 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'
- });
- }
-
- if (!!productId.value && !isProductCenter.value) {
- uni.navigateBack()
- } else {
- uni.redirectTo({
- url: '/pages/merchantCenters/productManagement'
- })
- }
- }
- }
- // 重置表单
- const resetForm = () => {
- formData.value = {
- categoryIds: [],
- categoryDisplayName: '',
- merchantCategoryId: [],
- merchantCategoryDisplayName: '',
- 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();
- }
- }
- // 规格管理相关
- const editCatePage = () => {
- if (attrTable.value && attrTable.value.length) {
- historyAttr = []
- historyTable = {}
- attrTable.value.forEach(item => {
- historyAttr.push(item.attrName)
- historyTable[item.attrName] = {
- ...item
- }
- })
- }
- uni.navigateTo({
- url: "/pages/merchantCenters/productCate/productCate"
- })
- }
- const setAllAttr = () => {
- if (!validateAttr(oneTemplate.value)) return false;
- uni.showModal({
- title: '提示',
- content: '所有商品规格将修改为当前配置',
- confirmText: '确认',
- cancelText: "取消",
- success(res) {
- if (res.confirm) {
- if (attrTable.value && attrTable.value.length > 0) {
- attrTable.value = attrTable.value.map(item => {
- return {
- ...item,
- ...oneTemplate.value
- }
- })
- }
- }
- }
- })
- }
- // 规格格式化
- function attrFormat(arr) {
- let data = [];
- const res = [];
- return format(arr);
- function format(arr) {
- if (arr.length > 1) {
- arr.forEach((v, i) => {
- if (i === 0) data = arr[i]["attrValue"];
- const tmp = [];
- if (!data) return;
- data.forEach(function(vv) {
- arr[i + 1] &&
- arr[i + 1]["attrValue"] &&
- arr[i + 1]["attrValue"].forEach(g => {
- const rep2 =
- (i !== 0 ? "" : arr[i]["attrName"] + "_") +
- vv +
- "$&" +
- arr[i + 1]["attrName"] +
- "_" +
- g;
- tmp.push(rep2);
- if (i === arr.length - 2) {
- const rep4 = {
- additionalAmount: "",
- image: "",
- price: "",
- cost: 0,
- otPrice: 0,
- stock: "",
- barCode: "",
- weight: "",
- volume: 0,
- brokerage: 0,
- brokerage_two: 0,
- imgs: []
- };
- rep2.split("$&").forEach((h, k) => {
- const rep3 = h.split("_");
- if (!rep4["attrValue"]) rep4["attrValue"] = {};
- rep4["attrValue"][rep3[0]] =
- rep3.length > 1 ? rep3[1] : "";
- });
- for (const attrValueKey in rep4.attrValue) {
- rep4[attrValueKey] = rep4.attrValue[attrValueKey];
- }
- res.push(rep4);
- }
- });
- });
- data = tmp.length ? tmp : [];
- });
- } else {
- const dataArr = [];
- arr.forEach((v, k) => {
- v["attrValue"] &&
- v["attrValue"].forEach((vv, kk) => {
- dataArr[kk] = v["attrName"] + "_" + vv;
- res[kk] = {
- additionalAmount: "",
- image: "",
- price: "",
- cost: 0,
- otPrice: 0,
- stock: "",
- barCode: "",
- weight: "",
- volume: 0,
- brokerage: 0,
- brokerage_two: 0,
- attrValue: {
- [v["attrName"]]: vv
- },
- imgs: []
- };
- for (const attrValueKey in res[kk].attrValue) {
- res[kk][attrValueKey] = res[kk].attrValue[attrValueKey];
- }
- });
- });
- data.push(dataArr.join("$&"));
- }
-
- const result = []
- res.forEach(item => {
- let attrName = [];
- for (const name in item.attrValue) {
- attrName.push(item.attrValue[name]);
- }
- item.attrName = attrName.join(',');
- if (historyAttr.includes(item.attrName)) {
- item = {
- ...historyTable[item.attrName]
- }
- }
- result.push(item)
- })
- return result;
- }
- }
- // 输入框校验
- const keyupEvent = (key, val, index, num) => {
- if (key === "barCode") return;
- var re = /^\D*([0-9]\d*\.?\d{0,2})?.*$/;
- switch (num) {
- case 1:
- if (Number(val) === 0) {
- oneTemplate.value[key] = [
- "stock",
- "cost",
- "otPrice",
- "price",
- "additionalAmount"
- ].includes(key) ?
- 0 :
- 0.01;
- } else {
- oneTemplate.value[key] =
- key === "stock" ?
- parseInt(val) :
- val.toString().replace(re, "$1")
- }
- break;
- case 2:
- if (Number(val) === 0) {
- attrTable.value[index][key] = [
- "stock",
- "cost",
- "otPrice",
- "price",
- "additionalAmount"
- ].includes(key) ?
- 0 :
- 0.01;
- } else {
- attrTable.value[index][key] =
- key === "stock" ?
- parseInt(val) :
- val.toString().replace(re, "$1")
- }
- break;
- default:
- break
- }
- }
- const formatterAttrValue = (attrstrValue) => {
- const data = JSON.parse(attrstrValue);
- const result = `圈号:${data.圈号},重量:${data.重量}g`;
- return result;
- }
- </script>
- <style scoped lang="scss">
- .container {
- background-color: #f9f7f0;
- min-height: 100vh;
- padding-bottom: 140rpx;
- }
- .form-container {
- padding: 16rpx;
- }
- .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: 150rpx;
- height: 150rpx;
- border: 1rpx dashed #DCDFE6;
- border-radius: 8rpx;
- background: #fff;
- }
- .upload-tip {
- font-size: 20rpx;
- color: #666;
- margin-top: 6rpx;
- }
- .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;
- }
-
- ::v-deep .u-upload__wrap__preview__image{
- width: 150rpx !important;
- height: 150rpx !important;
- }
- :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;
- font-weight: bold;
- 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;
- }
- /* 规格样式 */
- .pro-cate-container {
- width: 100%;
- padding: 16rpx;
- background-color: #fff;
- border-radius: 16rpx;
- margin-bottom: 16rpx;
- .cate-title {
- font-size: 28rpx;
- line-height: 44rpx;
- color: #333;
- margin-bottom: 16rpx;
- }
- .cate-add {
- width: 100%;
- height: 88rpx;
- line-height: 88rpx;
- text-align: center;
- border-radius: 16rpx;
- background-color: #FEF8E6;
- color: #F8C008;
- font-size: 32rpx;
- font-weight: bold;
- margin-top: 16rpx;
- }
- .cate-list {
- .cate-item {
- width: 100%;
- background-color: #F9F7F0;
- border-radius: 16rpx;
- padding: 16rpx;
- margin-bottom: 16rpx;
- .upload-btn {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- width: 100rpx;
- height: 100rpx;
- border: 1rpx dashed #DCDFE6;
- border-radius: 8rpx;
- background: #fff;
- }
- .cate-pic-line {
- width: 100%;
- height: 100rpx;
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 16rpx;
- ::v-deep .u-upload {
- flex: 0;
- margin-right: 16rpx;
- width: 100rpx;
- height: 100rpx;
- }
- ::v-deep .u-upload__wrap__preview {
- margin: 0;
- width: 100rpx;
- height: 100rpx;
- }
- ::v-deep .u-upload__wrap__preview__image {
- width: 100rpx !important;
- height: 100rpx !important;
- }
- .cate-name {
- width: 100rpx;
- flex: 1;
- color: #333;
- font-size: 28rpx;
- line-height: 44rpx;
- }
- }
- .cate-ipt-line {
- width: 100%;
- display: flex;
- align-items: center;
- justify-content: space-between;
- flex-wrap: nowrap;
- padding-bottom: 16rpx;
- ::v-deep .u-input {
- height: 100rpx;
- line-height: 100rpx;
- }
- .cate-ipt {
- width: 48%;
- flex: 1;
- height: 100rpx;
- background-color: #fff;
- border-radius: 16rpx;
- padding: 0 16rpx !important;
- font-size: 28rpx;
- .unit {
- color: #333;
- }
- }
- }
- }
- }
- }
- </style>
|