releaseProduct.vue 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. <template>
  2. <view class="container">
  3. <view class="form-container">
  4. <up-form
  5. labelPosition="left"
  6. :model="formData"
  7. :rules="rules"
  8. ref="formRef"
  9. :labelWidth="100"
  10. >
  11. <!-- 商品分类 -->
  12. <view class="card-title" v-if="!isProductCenter">商品分类</view>
  13. <up-form-item
  14. class="form-item"
  15. label="商品分类"
  16. prop="categoryIds"
  17. :borderBottom="false"
  18. @click="showCategory = true"
  19. :required="true"
  20. v-if="!isProductCenter"
  21. >
  22. <up-input
  23. v-model="formData.categoryDisplayName"
  24. disabled
  25. disabledColor="#ffffff"
  26. placeholder="请选择商品分类"
  27. inputAlign="right"
  28. border="none"
  29. ></up-input>
  30. <template #right>
  31. <up-icon name="arrow-right"></up-icon>
  32. </template>
  33. </up-form-item>
  34. <!-- 商品信息 -->
  35. <view class="card-title">商品信息</view>
  36. <up-form-item
  37. label="商品名称"
  38. prop="storeName"
  39. :borderBottom="false"
  40. :required="true"
  41. >
  42. <up-input
  43. v-model="formData.storeName"
  44. placeholder="请输入商品名称"
  45. inputAlign="right"
  46. border="none"
  47. ></up-input>
  48. </up-form-item>
  49. <up-form-item
  50. label="商品关键字"
  51. prop="keyword"
  52. :borderBottom="false"
  53. :required="true"
  54. v-if="!isProductCenter"
  55. >
  56. <up-input
  57. v-model="formData.keyword"
  58. placeholder="请输入商品关键字"
  59. inputAlign="right"
  60. border="none"
  61. ></up-input>
  62. </up-form-item>
  63. <up-form-item
  64. label="商品简介"
  65. prop="storeInfo"
  66. :borderBottom="false"
  67. :required="true"
  68. v-if="!isProductCenter"
  69. >
  70. <up-textarea
  71. v-model="formData.storeInfo"
  72. placeholder="请输入商品简介"
  73. inputAlign="right"
  74. border="none"
  75. ></up-textarea>
  76. </up-form-item>
  77. <up-form-item
  78. label="单位"
  79. prop="unitName"
  80. :borderBottom="false"
  81. :required="true"
  82. v-if="!isProductCenter"
  83. >
  84. <up-input
  85. v-model="formData.unitName"
  86. placeholder="请输入单位"
  87. inputAlign="right"
  88. border="none"
  89. ></up-input>
  90. </up-form-item>
  91. <!-- 图片上传 -->
  92. <view class="upload-section" v-if="!isProductCenter">
  93. <view class="upload-item">
  94. <view class="upload-label"><text class="required">*</text>商品封面图</view>
  95. <up-upload
  96. @afterRead="async (e) => {
  97. await afterRead(e);
  98. getImage();
  99. }"
  100. @delete="onPreviewImageDelete"
  101. name="preview"
  102. max-count="1"
  103. :fileList="previewImages"
  104. >
  105. <view class="upload-btn">
  106. <up-icon name="plus" size="20" color="#ccc"></up-icon>
  107. <text class="upload-tip">点击上传</text>
  108. </view>
  109. </up-upload>
  110. <text class="format-tip">支持上传PNG、JPG格式的图片,每张不超过5MB。</text>
  111. </view>
  112. </view>
  113. <view class="upload-section" v-if="!isProductCenter">
  114. <view class="upload-item">
  115. <view class="upload-label"><text class="required">*</text>商品图片</view>
  116. <up-upload
  117. @afterRead="async (e) => {
  118. await afterRead(e);
  119. getImageProduct();
  120. }"
  121. @delete="onProductImageDelete"
  122. name="product"
  123. multiple
  124. :maxCount="10"
  125. :fileList="productImages"
  126. >
  127. <view class="upload-btn">
  128. <up-icon name="plus" size="20" color="#ccc"></up-icon>
  129. <text class="upload-tip">点击上传</text>
  130. </view>
  131. </up-upload>
  132. <text class="format-tip">支持上传PNG、JPG格式图片,每张不超过5MB,最多可上传5张。</text>
  133. </view>
  134. </view>
  135. <!-- 商品属性 -->
  136. <view class="card-title">商品属性</view>
  137. <up-form-item
  138. label="材质"
  139. prop="metalType"
  140. :borderBottom="false"
  141. :required="true"
  142. v-if="!isProductCenter"
  143. >
  144. <up-radio-group
  145. v-model="formData.metalType"
  146. placement="row"
  147. >
  148. <up-radio
  149. :customStyle="{marginRight: '20rpx'}"
  150. v-for="(item, index) in materialList"
  151. :key="index"
  152. :label="item.name"
  153. :name="item.code"
  154. activeColor="#F8C008"
  155. >
  156. </up-radio>
  157. </up-radio-group>
  158. </up-form-item>
  159. <up-form-item
  160. label="重量"
  161. prop="weight"
  162. :borderBottom="false"
  163. :required="true"
  164. >
  165. <up-input
  166. v-model="formData.weight"
  167. placeholder="请输入重量"
  168. inputAlign="right"
  169. border="none"
  170. type="digit"
  171. ></up-input>
  172. <template #right>
  173. <text class="unit">g</text>
  174. </template>
  175. </up-form-item>
  176. <!-- 商品描述 -->
  177. <view class="card-title" v-if="!isProductCenter">商品描述</view>
  178. <view class="editor-section" v-if="!isProductCenter">
  179. <view class="editor-header">
  180. <text class="editor-label">商品描述</text>
  181. <text class="word-count">{{ descriptionText.length }}/500</text>
  182. </view>
  183. <sp-editor
  184. editorId="editor"
  185. :toolbar-config="toolbarConfig"
  186. :readOnly="readOnly"
  187. @input="onEditorInput"
  188. @upinImage="onUpinImage"
  189. @init="onEditorInit"
  190. @overMax="onOverMax"
  191. ></sp-editor>
  192. </view>
  193. <!-- 价格设置 -->
  194. <view class="card-title">价格设置</view>
  195. <up-form-item
  196. label="工费"
  197. prop="laborCost"
  198. :borderBottom="false"
  199. :required="true"
  200. >
  201. <up-input
  202. v-model="formData.laborCost"
  203. placeholder="请输入工费"
  204. inputAlign="right"
  205. border="none"
  206. type="digit"
  207. ></up-input>
  208. <template #right>
  209. <text class="unit">元/g</text>
  210. </template>
  211. </up-form-item>
  212. <up-form-item
  213. label="附加费"
  214. prop="additionalFee"
  215. :borderBottom="false"
  216. :required="true"
  217. >
  218. <up-input
  219. v-model="formData.additionalFee"
  220. placeholder="请输入附加费"
  221. inputAlign="right"
  222. border="none"
  223. type="digit"
  224. ></up-input>
  225. <template #right>
  226. <text class="unit">元</text>
  227. </template>
  228. </up-form-item>
  229. <up-form-item
  230. class="form-item"
  231. label="运费模板"
  232. prop="tempIds"
  233. :borderBottom="false"
  234. @click="showTemp = true"
  235. :required="true"
  236. >
  237. <up-input
  238. v-model="formData.tempName"
  239. disabled
  240. disabledColor="#ffffff"
  241. placeholder="请选择运费模板"
  242. inputAlign="right"
  243. border="none"
  244. ></up-input>
  245. <template #right>
  246. <up-icon name="arrow-right"></up-icon>
  247. </template>
  248. </up-form-item>
  249. <up-form-item
  250. label="库存"
  251. prop="stock"
  252. :borderBottom="false"
  253. :required="true"
  254. >
  255. <up-input
  256. v-model="formData.stock"
  257. placeholder="请输入库存"
  258. inputAlign="right"
  259. border="none"
  260. type="number"
  261. ></up-input>
  262. </up-form-item>
  263. <up-form-item
  264. label="商品编号"
  265. prop="barCode"
  266. :borderBottom="false"
  267. :required="true"
  268. >
  269. <up-input
  270. v-model="formData.barCode"
  271. placeholder="请输入商品编号"
  272. inputAlign="right"
  273. border="none"
  274. type="number"
  275. ></up-input>
  276. </up-form-item>
  277. <view class="upload-section">
  278. <view class="upload-item">
  279. <view class="upload-label"><text class="required">*</text>规格图片</view>
  280. <up-upload
  281. :fileList="productImagesGg"
  282. @afterRead="async (e) => {
  283. await afterRead(e);
  284. getImageProductGg();
  285. }"
  286. @delete="onProductImageGgDelete"
  287. name="productGg"
  288. :maxCount="1"
  289. >
  290. <view class="upload-btn">
  291. <up-icon name="plus" size="20" color="#ccc"></up-icon>
  292. <text class="upload-tip">点击上传</text>
  293. </view>
  294. </up-upload>
  295. <text class="format-tip">支持上传PNG、JPG格式图片,每张不超过5MB,最多可上传5张。</text>
  296. </view>
  297. </view>
  298. <up-form-item
  299. label="商品排序"
  300. prop="sort"
  301. :borderBottom="false"
  302. >
  303. <up-input
  304. v-model="formData.sort"
  305. placeholder="请输入排序号"
  306. inputAlign="right"
  307. border="none"
  308. type="number"
  309. ></up-input>
  310. </up-form-item>
  311. </up-form>
  312. </view>
  313. <!-- 发布按钮 -->
  314. <view class="btn-view">
  315. <button class="submit" @click="submitForm">立即发布</button>
  316. </view>
  317. <!-- 类目选择弹窗 -->
  318. <up-popup
  319. :show="showCategory"
  320. @close="showCategory = false"
  321. mode="bottom"
  322. round="20"
  323. :closeable="true"
  324. >
  325. <view class="popup-content">
  326. <view class="popup-header">
  327. <text class="popup-title">选择商品分类</text>
  328. </view>
  329. <category-selector
  330. :categoryList="categoryData"
  331. :selectedIds="formData.categoryIds"
  332. @change="onCategoryChange"
  333. ref="categoryRef"
  334. />
  335. <view class="popup-actions">
  336. <button class="action-btn cancel" @click="showCategory = false">取消</button>
  337. <button class="action-btn confirm" @click="confirmCategory">确定</button>
  338. </view>
  339. </view>
  340. </up-popup>
  341. <!-- 运费模板-->
  342. <up-picker :show="showTemp" v-model="formData.tempIds" :columns="tempColumns" keyName="name" valueName ="id"
  343. confirmColor="#F8C008"
  344. @close="showTemp = false" @confirm="tempConfirm" @cancel="showTemp = false"></up-picker>
  345. </view>
  346. </template>
  347. <script setup>
  348. import { ref, computed, watch,nextTick } from 'vue';
  349. import { onShow,onLoad } from "@dcloudio/uni-app";
  350. import { productCategory,productSave,productUpdate,templatesList,productInfo } from "@/api/merchant";
  351. import CategorySelector from '@/components/CategorySelector';
  352. import { useAppStore } from "@/stores/app";
  353. import { useImageUpload } from "@/hooks/useImageUpload";
  354. import { useToast } from "@/hooks/useToast";
  355. const { Toast } = useToast();
  356. const { imageList, afterRead, deletePic, uploadLoading } = useImageUpload({
  357. pid: 1,
  358. model: "product",
  359. });
  360. const appStore = useAppStore();
  361. const merchantInfo = appStore.userInfo.merchant
  362. // 表单验证和提交
  363. const formRef = ref(null);
  364. // 表单数据
  365. const formData = ref({
  366. categoryIds: [], // 选中的分类ID数组
  367. categoryDisplayName: '', // 显示的分类名称
  368. tempName: '', // 显示的运费模板名称
  369. tempIds: [],
  370. storeName: '',
  371. keyword: '',
  372. storeInfo: '',
  373. unitName: '',
  374. metalType: '',
  375. weight: '',
  376. laborCost: '',
  377. additionalFee: '',
  378. sort: '',
  379. content: '',
  380. stock: '',
  381. barCode: ''
  382. });
  383. // 编辑器相关
  384. const editorIns = ref(null);
  385. const readOnly = ref(false);
  386. const descriptionText = ref('');
  387. const toolbarConfig = ref({
  388. iconSize: '20px',
  389. iconColumns: 10,
  390. excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck']
  391. });
  392. // 分类相关
  393. const showCategory = ref(false);
  394. const categoryData = ref([]);
  395. const categoryRef = ref();
  396. const showTemp = ref(false);
  397. const tempColumns = ref([])
  398. // 图片列表
  399. const previewImages = ref([]);
  400. const productImages = ref([]);
  401. const productImagesGg = ref([]);
  402. const productId = ref(null);
  403. const isProductCenter = ref(null);
  404. // 材质列表
  405. const materialList = ref([
  406. { name: '黄金',code:'au' },
  407. { name: '铂金' ,code:'pt'},
  408. { name: '白银',code:'ag' }
  409. ]);
  410. // 验证规则
  411. const rules = ref({
  412. categoryIds: {
  413. type: 'array',
  414. required: true,
  415. message: '请选择商品分类',
  416. trigger: ['blur','change']
  417. },
  418. storeName: {
  419. type: 'string',
  420. required: true,
  421. message: '请输入商品名称',
  422. trigger: ['blur', 'change']
  423. },
  424. keyword: {
  425. type: 'string',
  426. required: true,
  427. message: '请输入商品关键字',
  428. trigger: ['blur', 'change']
  429. },
  430. storeInfo: {
  431. type: 'string',
  432. required: true,
  433. message: '请输入商品关键字',
  434. trigger: ['blur', 'change']
  435. },
  436. unitName: {
  437. type: 'string',
  438. required: true,
  439. message: '请输入单位',
  440. trigger: ['blur', 'change']
  441. },
  442. tempIds: {
  443. type: 'array',
  444. required: true,
  445. message: '请选择运费模板',
  446. trigger: ['blur', 'change']
  447. },
  448. metalType: {
  449. type: 'string',
  450. required: true,
  451. message: '请选择材质',
  452. trigger: ['blur','change']
  453. },
  454. weight: {
  455. type: 'string',
  456. required: true,
  457. pattern: /^\d+(\.\d+)?$/,
  458. message: '重量必须是数字,可以是小数',
  459. trigger: ['blur', 'change']
  460. },
  461. laborCost: {
  462. type: 'string',
  463. required: true,
  464. pattern: /^\d+(\.\d+)?$/,
  465. message: '工费必须是数字,可以是小数',
  466. trigger: ['blur', 'change']
  467. },
  468. additionalFee: {
  469. type: 'string',
  470. required: true,
  471. pattern: /^\d+(\.\d+)?$/,
  472. message: '附加费必须是数字,可以是小数',
  473. trigger: ['blur', 'change']
  474. },
  475. sort: {
  476. type: 'string',
  477. pattern: /^\d*$/,
  478. message: '排序号必须是整数',
  479. trigger: ['blur', 'change'],
  480. validator: (rule, value) => {
  481. if (!value || value.trim().length === 0) return true; // 可选字段,为空时通过
  482. return /^\d+$/.test(value);
  483. }
  484. },
  485. stock: {
  486. type: 'string',
  487. required: true,
  488. pattern: /^\d*$/,
  489. message: '库存必须是整数',
  490. trigger: ['blur', 'change'],
  491. validator: (rule, value) => {
  492. if (!value || value.trim().length === 0) return false;
  493. return /^\d+$/.test(value);
  494. }
  495. },
  496. barCode: {
  497. type: 'string',
  498. required: true,
  499. pattern: /^\d*$/,
  500. message: '商品编号必须是整数',
  501. trigger: ['blur', 'change'],
  502. validator: (rule, value) => {
  503. if (!value || value.trim().length === 0) return false;
  504. return /^\d+$/.test(value);
  505. }
  506. },
  507. });
  508. // 页面加载
  509. onShow(() => {
  510. })
  511. onLoad(async (options)=>{
  512. await getProductCategory();
  513. await getTempData();
  514. console.log(options)
  515. if(options.id){
  516. productId.value = options.id;
  517. isProductCenter.value = options.isProductCenter || null;
  518. await getProductDetail(options.id);
  519. }else {
  520. resetForm();
  521. }
  522. })
  523. // 获取商品分类
  524. async function getProductCategory(){
  525. let obj = {
  526. type: 1,
  527. status: 1
  528. }
  529. try {
  530. const { data } = await productCategory(obj)
  531. console.log('原始分类数据:', data);
  532. const newArr = []
  533. data.forEach((value, index) => {
  534. newArr[index] = value
  535. if (value.child) newArr[index].child = value.child.filter(item => item.status === true)
  536. })
  537. // 过滤商品分类设置为隐藏的子分类不出现在树形列表里
  538. categoryData.value = newArr.filter(item => item.code !== 'bb_mall')
  539. console.log('转换后的分类数据:', categoryData.value);
  540. } catch (error) {
  541. console.error('获取商品分类失败:', error);
  542. uni.showToast({ title: '获取分类失败', icon: 'none' });
  543. }
  544. }
  545. // 获取运费模板
  546. async function getTempData(){
  547. let obj = {
  548. page:1,
  549. limit:9999
  550. }
  551. try {
  552. const { data } = await templatesList()
  553. tempColumns.value[0] = data.list;
  554. } catch (error) {
  555. console.error('获取商品分类失败:', error);
  556. uni.showToast({ title: '获取分类失败', icon: 'none' });
  557. }
  558. }
  559. const initFormValidation = async () => {
  560. await nextTick();
  561. if (!formRef.value) {
  562. console.error('表单引用不存在');
  563. return;
  564. }
  565. try {
  566. // 方法1:清除所有验证状态,然后重新验证
  567. formRef.value.clearValidate();
  568. // 方法2:延迟触发字段验证
  569. setTimeout(async () => {
  570. // 逐个触发必填字段的验证
  571. const requiredFields = ['categoryIds', 'storeName', 'keyword', 'storeInfo', 'unitName',
  572. 'tempIds', 'metalType', 'weight', 'laborCost', 'additionalFee',
  573. 'stock', 'barCode'];
  574. for (const field of requiredFields) {
  575. try {
  576. await formRef.value.validateField(field);
  577. } catch (error) {
  578. console.log(`⚠️ 字段 ${field} 验证状态:`, error);
  579. }
  580. }
  581. }, 300);
  582. } catch (error) {
  583. console.error('初始化表单验证状态失败:', error);
  584. }
  585. };
  586. // 获取商品详情
  587. async function getProductDetail(id){
  588. try {
  589. const { data } = await productInfo(id)
  590. console.log('获取商品详情:',data);
  591. // 使用Object.assign确保响应式更新
  592. Object.assign(formData.value, {
  593. ...data,
  594. // 确保categoryIds是数组格式
  595. categoryIds: data.cateId ? (Array.isArray(data.cateId) ? data.cateId : data.cateId.split(',')) : [],
  596. // 确保tempIds是数组格式
  597. tempIds: data.tempId ? [data.tempId] : []
  598. });
  599. productImages.value = [];
  600. console.log('分类IDs:', formData.value.categoryIds);
  601. console.log('运费模板IDs:', formData.value.tempIds);
  602. // 等待DOM更新
  603. await nextTick();
  604. // 更新显示名称
  605. formData.value.categoryDisplayName = getCategoryDisplayName(formData.value.categoryIds);
  606. formData.value.tempName = formatterTemp(data.tempId);
  607. console.log('分类显示名称:', formData.value.categoryDisplayName);
  608. // 图片处理
  609. previewImages.value = data.image ? [{ url: data.image }] : [];
  610. // 商品轮播图
  611. if(data.sliderImage){
  612. try {
  613. const urlArr = typeof data.sliderImage === 'string' ? JSON.parse(data.sliderImage) : data.sliderImage;
  614. if(urlArr && urlArr.length > 0){
  615. productImages.value = urlArr.map(url => ({ url }));
  616. }
  617. } catch (error) {
  618. console.error('解析轮播图失败:', error);
  619. productImages.value = [];
  620. }
  621. }
  622. // 商品属性
  623. if (data.attrValue && data.attrValue.length > 0) {
  624. formData.value.additionalFee = data.attrValue[0].additionalAmount;
  625. formData.value.laborCost = data.attrValue[0].price;
  626. formData.value.barCode = data.attrValue[0].barCode;
  627. formData.value.stock = data.attrValue[0].stock;
  628. formData.value.weight = data.attrValue[0].weight;
  629. // 规格图片
  630. productImagesGg.value = data.attrValue[0].image ? [{ url: data.attrValue[0].image }] : [];
  631. }
  632. // 商品描述
  633. descriptionText.value = data.content ? data.content.replace(/<[^>]*>/g, '').substring(0, 500) : '';
  634. formData.value.content = data.content || '';
  635. // 设置分类选择器
  636. if (categoryRef.value && formData.value.categoryIds.length > 0) {
  637. // 使用nextTick确保组件已渲染
  638. await nextTick();
  639. if (categoryRef.value.setSelectedIds) {
  640. categoryRef.value.setSelectedIds(formData.value.categoryIds);
  641. }
  642. }
  643. // 重要:手动初始化表单验证状态
  644. await initFormValidation();
  645. } catch (error) {
  646. console.error('获取商品详情失败:', error);
  647. uni.showToast({ title: '获取商品详情失败', icon: 'none' });
  648. }
  649. }
  650. // 运费模板id获取中文名
  651. function formatterTemp(id) {
  652. // 假设 tempColumns 是一个数组
  653. const foundItem = tempColumns.value[0].find(item => item.id == id);
  654. return foundItem ? foundItem.name : '';
  655. }
  656. function tempConfirm(obj){
  657. formData.value.tempId = obj.value[0].id;
  658. formData.value.tempName = obj.value[0].name;
  659. showTemp.value = false;
  660. setTimeout(() => {
  661. if (formRef.value) {
  662. formRef.value.validateField('tempIds');
  663. }
  664. }, 100);
  665. }
  666. // 分类选择变化
  667. const onCategoryChange = (result) => {
  668. console.log('分类选择变化:', result);
  669. // 这里只更新显示,不直接更新表单数据,等用户点击确定
  670. }
  671. // 确认分类选择
  672. const confirmCategory = () => {
  673. if (categoryRef.value) {
  674. const selectedIds = categoryRef.value.getSelectedIds()
  675. if (selectedIds.length === 0) {
  676. uni.showToast({ title: '请至少选择一个分类', icon: 'none' })
  677. return
  678. }
  679. // 更新表单数据
  680. formData.value.categoryIds = selectedIds
  681. formData.value.categoryDisplayName = getCategoryDisplayName(selectedIds)
  682. showCategory.value = false
  683. console.log('最终选中的分类ID:', selectedIds)
  684. // 触发校验
  685. setTimeout(() => {
  686. if (formRef.value) {
  687. formRef.value.validateField('categoryIds');
  688. }
  689. }, 100);
  690. }
  691. }
  692. // 根据选中的ID生成显示名称
  693. const getCategoryDisplayName = (selectedIds) => {
  694. if (!selectedIds || selectedIds.length === 0) return ''
  695. const names = []
  696. selectedIds.forEach(id => {
  697. // 检查是否是一级分类(表示全选)
  698. const firstLevel = categoryData.value.find(item => item.id == id)
  699. if (firstLevel) {
  700. // 如果是一级分类,显示"分类名称(全部)"
  701. names.push(`${firstLevel.name}`)
  702. } else {
  703. // 查找二级分类
  704. for (const parent of categoryData.value) {
  705. if (parent.child) {
  706. const secondLevel = parent.child.find(child => child.id == id)
  707. if (secondLevel) {
  708. names.push(`${parent.name}-${secondLevel.name}`)
  709. break
  710. }
  711. }
  712. }
  713. // 如果没有子分类的一级分类
  714. const singleLevel = categoryData.value.find(item =>
  715. !item.child && item.id == id
  716. )
  717. if (singleLevel) {
  718. names.push(singleLevel.name)
  719. }
  720. }
  721. })
  722. return names.join('、')
  723. }
  724. async function getImage() {
  725. console.log(imageList.value)
  726. if (imageList.value.length > 0) {
  727. if (imageList.value[0].status == "success") {
  728. previewImages.value = imageList.value;
  729. console.log('previewImages.value',previewImages.value)
  730. // change();
  731. } else {
  732. Toast({ title: "上传失败" });
  733. }
  734. }
  735. imageList.value = [];
  736. }
  737. async function getImageProduct() {
  738. if (imageList.value.length > 0) {
  739. if (imageList.value[0].status == "success") {
  740. productImages.value = [...productImages.value,...imageList.value];
  741. // change();
  742. } else {
  743. Toast({ title: "上传失败" });
  744. }
  745. }
  746. imageList.value = [];
  747. }
  748. async function getImageProductGg() {
  749. if (imageList.value.length > 0) {
  750. if (imageList.value[0].status == "success") {
  751. productImagesGg.value = imageList.value;
  752. // change();
  753. } else {
  754. Toast({ title: "上传失败" });
  755. }
  756. }
  757. imageList.value = [];
  758. }
  759. const onPreviewImageDelete =(e) => {
  760. previewImages.value.splice(e.index, 1);
  761. };
  762. const onProductImageDelete = (e) => {
  763. productImages.value.splice(e.index, 1);
  764. };
  765. const onProductImageGgDelete = (e) => {
  766. productImagesGg.value.splice(e.index, 1);
  767. };
  768. // 编辑器相关方法
  769. const onEditorInput = (e) => {
  770. descriptionText.value = e.text || '';
  771. formData.value.content = e.html || '';
  772. };
  773. const onEditorInit = (editor) => {
  774. editorIns.value = editor;
  775. };
  776. const onOverMax = (e) => {
  777. uni.showToast({ title: '内容长度超出限制', icon: 'none' });
  778. };
  779. const onUpinImage = (tempFiles, editorCtx) => {
  780. const filePath = tempFiles[0].tempFilePath || tempFiles[0].path;
  781. editorCtx.insertImage({
  782. src: filePath,
  783. width: '80%',
  784. success: () => {
  785. uni.showToast({ title: '图片插入成功', icon: 'success' });
  786. }
  787. });
  788. };
  789. const validateForm = () => {
  790. try {
  791. if(!isProductCenter.value){
  792. // 检查图片上传
  793. if (previewImages.value.length === 0) {
  794. uni.showToast({ title: '请上传商品预览图', icon: 'none' });
  795. return;
  796. }
  797. if (productImages.value.length === 0) {
  798. uni.showToast({ title: '请上传商品图片', icon: 'none' });
  799. return;
  800. }
  801. if (formData.value.sort && !/^\d+$/.test(formData.value.sort)) {
  802. uni.showToast({ title: '排序号必须是整数', icon: 'none' });
  803. return;
  804. }
  805. }
  806. if (productImagesGg.value.length === 0) {
  807. uni.showToast({ title: '请上传商品规格图片', icon: 'none' });
  808. return;
  809. }
  810. // 验证数字字段
  811. if (!/^\d+(\.\d+)?$/.test(formData.value.weight)) {
  812. uni.showToast({ title: '重量格式不正确', icon: 'none' });
  813. return;
  814. }
  815. if (!/^\d+(\.\d+)?$/.test(formData.value.laborCost)) {
  816. uni.showToast({ title: '工费格式不正确', icon: 'none' });
  817. return;
  818. }
  819. if (!/^\d+(\.\d+)?$/.test(formData.value.additionalFee)) {
  820. uni.showToast({ title: '附加费格式不正确', icon: 'none' });
  821. return;
  822. }
  823. if (!/^\d+$/.test(formData.value.stock)) {
  824. uni.showToast({ title: '库存必须是整数', icon: 'none' });
  825. return;
  826. }
  827. if (!/^\d+$/.test(formData.value.barCode)) {
  828. uni.showToast({ title: '商品编号必须是整数', icon: 'none' });
  829. return;
  830. }
  831. const valid = formRef.value.validate();
  832. return valid;
  833. } catch (error) {
  834. console.error('表单验证失败:', error);
  835. return false;
  836. }
  837. };
  838. const submitForm = async () => {
  839. const valid = validateForm();
  840. if (valid) {
  841. const submitData = {
  842. ...formData.value
  843. };
  844. let urlString = '';
  845. if(isProductCenter){
  846. submitData.image =previewImages.value[0].url;
  847. urlString = JSON.stringify(productImages.value.map(item => item.url));
  848. }else{
  849. submitData.image =previewImages.value[0].info.url;
  850. urlString = JSON.stringify(productImages.value.map(item => item.info.url));
  851. }
  852. submitData.sliderImage =urlString;
  853. submitData.cateId =formData.value.categoryIds.join(',');
  854. submitData.merchantId =parseInt(merchantInfo.id);
  855. submitData.specType = 0;
  856. submitData.isSub = false;
  857. submitData.attr =[
  858. {
  859. "attrName":"规格",
  860. "attrValues": "默认",
  861. "id": 0
  862. }
  863. ];
  864. submitData.attrValue =[
  865. {
  866. additionalAmount :formData.value.additionalFee,
  867. attrValue:"{\"规格\":\"默认\"}",
  868. barCode : formData.value.barCode,
  869. image : isProductCenter ? productImagesGg.value[0].url : productImagesGg.value[0].info.url,
  870. price : formData.value.laborCost,
  871. stock : formData.value.stock,
  872. weight :formData.value.weight
  873. }
  874. ];
  875. if(productId.value && !isProductCenter.value){
  876. const {data} = await productUpdate(submitData);
  877. uni.showToast({ title: '修改成功', icon: 'success' });
  878. }else{
  879. const {data} = await productSave(submitData);
  880. uni.showToast({ title: '发布成功', icon: 'success' });
  881. }
  882. uni.navigateTo({
  883. url: '/pages/merchantCenters/productManagement'
  884. })
  885. }
  886. }
  887. // 重置表单(用于新建场景)
  888. const resetForm = () => {
  889. formData.value = {
  890. categoryIds: [],
  891. categoryDisplayName: '',
  892. tempName: '',
  893. tempIds: [],
  894. storeName: '',
  895. keyword: '',
  896. storeInfo: '',
  897. unitName: '',
  898. metalType: '',
  899. weight: '',
  900. laborCost: '',
  901. additionalFee: '',
  902. sort: '',
  903. content: '',
  904. stock: '',
  905. barCode: ''
  906. };
  907. previewImages.value = [];
  908. productImages.value = [];
  909. productImagesGg.value = [];
  910. descriptionText.value = '';
  911. // 清除校验状态
  912. if (formRef.value) {
  913. formRef.value.clearValidate();
  914. }
  915. }
  916. </script>
  917. <style scoped lang="scss">
  918. .container {
  919. background-color: #f8f8f8;
  920. min-height: 100vh;
  921. padding-bottom: 140rpx;
  922. }
  923. .form-container {
  924. padding: 30rpx;
  925. }
  926. .upload-section {
  927. margin-top: 20rpx;
  928. margin-bottom: 20rpx;
  929. background: white;
  930. border-radius: 16rpx;
  931. padding: 30rpx;
  932. }
  933. .upload-item {
  934. margin-bottom: 40rpx;
  935. &:last-child {
  936. margin-bottom: 0;
  937. }
  938. }
  939. .upload-label {
  940. display: block;
  941. font-size: 28rpx;
  942. color: #333;
  943. margin-bottom: 20rpx;
  944. position: relative;
  945. }
  946. .required {
  947. position: absolute;
  948. left: -9px;
  949. color: #f56c6c;
  950. line-height: 20px;
  951. font-size: 20px;
  952. top: 3px;
  953. }
  954. .upload-btn {
  955. display: flex;
  956. flex-direction: column;
  957. align-items: center;
  958. justify-content: center;
  959. width: 200rpx;
  960. height: 200rpx;
  961. border: 2rpx dashed #ccc;
  962. border-radius: 12rpx;
  963. background: #fafafa;
  964. }
  965. .upload-tip {
  966. font-size: 24rpx;
  967. color: #999;
  968. margin-top: 10rpx;
  969. }
  970. .format-tip {
  971. display: block;
  972. font-size: 24rpx;
  973. color: #999;
  974. margin-top: 15rpx;
  975. }
  976. .card-title {
  977. font-size: 36rpx;
  978. color: #333;
  979. line-height: 60rpx;
  980. margin-bottom: 20rpx;
  981. }
  982. :deep(.u-form-item) {
  983. background-color: #fff;
  984. border-radius: 16rpx;
  985. padding: 8rpx 30rpx;
  986. box-sizing: border-box;
  987. margin-bottom: 20rpx;
  988. }
  989. :deep(.u-form-item__body__left__content__label) {
  990. font-size: 28rpx !important;
  991. color: #333 !important;
  992. }
  993. :deep(.u-radio-group--row) {
  994. justify-content: flex-end;
  995. }
  996. .btn-view {
  997. position: fixed;
  998. bottom: 0;
  999. left: 0;
  1000. right: 0;
  1001. background-color: #FFF;
  1002. padding: 20rpx 30rpx;
  1003. box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
  1004. z-index: 5;
  1005. }
  1006. .submit {
  1007. height: 88rpx;
  1008. line-height: 88rpx;
  1009. background: #F8C008;
  1010. border-radius: 16rpx;
  1011. font-size: 32rpx;
  1012. color: #333333;
  1013. border: none;
  1014. width: 100%;
  1015. &:active {
  1016. opacity: 0.8;
  1017. }
  1018. }
  1019. .unit {
  1020. color: #999;
  1021. font-size: 28rpx;
  1022. margin-left: 10rpx;
  1023. }
  1024. /* 编辑器样式 */
  1025. .editor-section {
  1026. background: white;
  1027. border-radius: 16rpx;
  1028. margin-bottom: 20rpx;
  1029. overflow: hidden;
  1030. }
  1031. .editor-header {
  1032. display: flex;
  1033. justify-content: space-between;
  1034. align-items: center;
  1035. padding: 30rpx;
  1036. border-bottom: 1rpx solid #f0f0f0;
  1037. }
  1038. .editor-label {
  1039. font-size: 28rpx;
  1040. color: #333;
  1041. font-weight: 500;
  1042. }
  1043. .word-count {
  1044. font-size: 24rpx;
  1045. color: #999;
  1046. }
  1047. :deep(.sp-editor) {
  1048. min-height: 400rpx;
  1049. }
  1050. /* 弹窗样式 */
  1051. .popup-content {
  1052. background: #fff;
  1053. border-radius: 20rpx 20rpx 0 0;
  1054. padding-bottom: env(safe-area-inset-bottom);
  1055. }
  1056. .popup-header {
  1057. padding: 30rpx;
  1058. text-align: center;
  1059. border-bottom: 1rpx solid #f0f0f0;
  1060. position: relative;
  1061. }
  1062. .popup-title {
  1063. font-size: 32rpx;
  1064. font-weight: 600;
  1065. color: #333;
  1066. }
  1067. .popup-actions {
  1068. display: flex;
  1069. padding: 30rpx;
  1070. gap: 20rpx;
  1071. }
  1072. .action-btn {
  1073. flex: 1;
  1074. height: 80rpx;
  1075. line-height: 80rpx;
  1076. border-radius: 12rpx;
  1077. font-size: 28rpx;
  1078. border: none;
  1079. &.cancel {
  1080. background: #f0f0f0;
  1081. color: #666;
  1082. }
  1083. &.confirm {
  1084. background: #F8C008;
  1085. color: #333;
  1086. }
  1087. }
  1088. :deep(.u-tabs__wrapper__nav__line){
  1089. background-color: #F8C008 !important;
  1090. }
  1091. :deep(.u-form-item__body__right__message){
  1092. text-align: right;
  1093. }
  1094. :deep(.u-textarea__field){
  1095. text-align: right;
  1096. }
  1097. </style>