releaseProduct.vue 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  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. submitData.cateId =formData.value.categoryIds.join(',');
  845. submitData.image =previewImages.value[0].info.url;
  846. const urlString = JSON.stringify(productImages.value.map(item => item.info.url));
  847. submitData.sliderImage =urlString;
  848. submitData.merchantId =parseInt(merchantInfo.id);
  849. submitData.specType = 0;
  850. submitData.isSub = false;
  851. submitData.attr =[
  852. {
  853. "attrName":"规格",
  854. "attrValues": "默认",
  855. "id": 0
  856. }
  857. ];
  858. submitData.attrValue =[
  859. {
  860. additionalAmount :formData.value.additionalFee,
  861. attrValue:"{\"规格\":\"默认\"}",
  862. barCode : formData.value.barCode,
  863. image : productImagesGg.value[0].info.url,
  864. price : formData.value.laborCost,
  865. stock : formData.value.stock,
  866. weight :formData.value.weight
  867. }
  868. ];
  869. console.log('提交数据:', submitData);
  870. if(productId.value && !isProductCenter.value){
  871. const {data} = await productUpdate(submitData);
  872. uni.showToast({ title: '修改成功', icon: 'success' });
  873. }else{
  874. const {data} = await productSave(submitData);
  875. uni.showToast({ title: '发布成功', icon: 'success' });
  876. }
  877. uni.navigateTo({
  878. url: '/pages/merchantCenters/productManagement'
  879. })
  880. }
  881. }
  882. // 重置表单(用于新建场景)
  883. const resetForm = () => {
  884. formData.value = {
  885. categoryIds: [],
  886. categoryDisplayName: '',
  887. tempName: '',
  888. tempIds: [],
  889. storeName: '',
  890. keyword: '',
  891. storeInfo: '',
  892. unitName: '',
  893. metalType: '',
  894. weight: '',
  895. laborCost: '',
  896. additionalFee: '',
  897. sort: '',
  898. content: '',
  899. stock: '',
  900. barCode: ''
  901. };
  902. previewImages.value = [];
  903. productImages.value = [];
  904. productImagesGg.value = [];
  905. descriptionText.value = '';
  906. // 清除校验状态
  907. if (formRef.value) {
  908. formRef.value.clearValidate();
  909. }
  910. }
  911. </script>
  912. <style scoped lang="scss">
  913. .container {
  914. background-color: #f8f8f8;
  915. min-height: 100vh;
  916. padding-bottom: 140rpx;
  917. }
  918. .form-container {
  919. padding: 30rpx;
  920. }
  921. .upload-section {
  922. margin-top: 20rpx;
  923. margin-bottom: 20rpx;
  924. background: white;
  925. border-radius: 16rpx;
  926. padding: 30rpx;
  927. }
  928. .upload-item {
  929. margin-bottom: 40rpx;
  930. &:last-child {
  931. margin-bottom: 0;
  932. }
  933. }
  934. .upload-label {
  935. display: block;
  936. font-size: 28rpx;
  937. color: #333;
  938. margin-bottom: 20rpx;
  939. position: relative;
  940. }
  941. .required {
  942. position: absolute;
  943. left: -9px;
  944. color: #f56c6c;
  945. line-height: 20px;
  946. font-size: 20px;
  947. top: 3px;
  948. }
  949. .upload-btn {
  950. display: flex;
  951. flex-direction: column;
  952. align-items: center;
  953. justify-content: center;
  954. width: 200rpx;
  955. height: 200rpx;
  956. border: 2rpx dashed #ccc;
  957. border-radius: 12rpx;
  958. background: #fafafa;
  959. }
  960. .upload-tip {
  961. font-size: 24rpx;
  962. color: #999;
  963. margin-top: 10rpx;
  964. }
  965. .format-tip {
  966. display: block;
  967. font-size: 24rpx;
  968. color: #999;
  969. margin-top: 15rpx;
  970. }
  971. .card-title {
  972. font-size: 36rpx;
  973. color: #333;
  974. line-height: 60rpx;
  975. margin-bottom: 20rpx;
  976. }
  977. :deep(.u-form-item) {
  978. background-color: #fff;
  979. border-radius: 16rpx;
  980. padding: 8rpx 30rpx;
  981. box-sizing: border-box;
  982. margin-bottom: 20rpx;
  983. }
  984. :deep(.u-form-item__body__left__content__label) {
  985. font-size: 28rpx !important;
  986. color: #333 !important;
  987. }
  988. :deep(.u-radio-group--row) {
  989. justify-content: flex-end;
  990. }
  991. .btn-view {
  992. position: fixed;
  993. bottom: 0;
  994. left: 0;
  995. right: 0;
  996. background-color: #FFF;
  997. padding: 20rpx 30rpx;
  998. box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
  999. z-index: 5;
  1000. }
  1001. .submit {
  1002. height: 88rpx;
  1003. line-height: 88rpx;
  1004. background: #F8C008;
  1005. border-radius: 16rpx;
  1006. font-size: 32rpx;
  1007. color: #333333;
  1008. border: none;
  1009. width: 100%;
  1010. &:active {
  1011. opacity: 0.8;
  1012. }
  1013. }
  1014. .unit {
  1015. color: #999;
  1016. font-size: 28rpx;
  1017. margin-left: 10rpx;
  1018. }
  1019. /* 编辑器样式 */
  1020. .editor-section {
  1021. background: white;
  1022. border-radius: 16rpx;
  1023. margin-bottom: 20rpx;
  1024. overflow: hidden;
  1025. }
  1026. .editor-header {
  1027. display: flex;
  1028. justify-content: space-between;
  1029. align-items: center;
  1030. padding: 30rpx;
  1031. border-bottom: 1rpx solid #f0f0f0;
  1032. }
  1033. .editor-label {
  1034. font-size: 28rpx;
  1035. color: #333;
  1036. font-weight: 500;
  1037. }
  1038. .word-count {
  1039. font-size: 24rpx;
  1040. color: #999;
  1041. }
  1042. :deep(.sp-editor) {
  1043. min-height: 400rpx;
  1044. }
  1045. /* 弹窗样式 */
  1046. .popup-content {
  1047. background: #fff;
  1048. border-radius: 20rpx 20rpx 0 0;
  1049. padding-bottom: env(safe-area-inset-bottom);
  1050. }
  1051. .popup-header {
  1052. padding: 30rpx;
  1053. text-align: center;
  1054. border-bottom: 1rpx solid #f0f0f0;
  1055. position: relative;
  1056. }
  1057. .popup-title {
  1058. font-size: 32rpx;
  1059. font-weight: 600;
  1060. color: #333;
  1061. }
  1062. .popup-actions {
  1063. display: flex;
  1064. padding: 30rpx;
  1065. gap: 20rpx;
  1066. }
  1067. .action-btn {
  1068. flex: 1;
  1069. height: 80rpx;
  1070. line-height: 80rpx;
  1071. border-radius: 12rpx;
  1072. font-size: 28rpx;
  1073. border: none;
  1074. &.cancel {
  1075. background: #f0f0f0;
  1076. color: #666;
  1077. }
  1078. &.confirm {
  1079. background: #F8C008;
  1080. color: #333;
  1081. }
  1082. }
  1083. :deep(.u-tabs__wrapper__nav__line){
  1084. background-color: #F8C008 !important;
  1085. }
  1086. :deep(.u-form-item__body__right__message){
  1087. text-align: right;
  1088. }
  1089. :deep(.u-textarea__field){
  1090. text-align: right;
  1091. }
  1092. </style>