releaseProduct.vue 36 KB

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