newActivity.vue 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. <template>
  2. <!-- 运营活动管理 - 新增/编辑页面 -->
  3. <div class="table-box" style="width: 100%; min-height: 100%; background-color: white">
  4. <div class="header">
  5. <el-button @click="goBack"> 返回 </el-button>
  6. <h2 class="title">{{ type == "add" ? "新建" : "编辑" }}运营活动</h2>
  7. </div>
  8. <div class="form-wrapper">
  9. <div class="form-wrapper-main">
  10. <el-form ref="ruleFormRef" :model="activityModel" :rules="rules" class="formBox" label-width="140px">
  11. <div class="form-content">
  12. <!-- 活动名称 -->
  13. <el-form-item label="活动名称" prop="activityName">
  14. <el-input v-model="activityModel.activityName" class="form-input" clearable maxlength="50" placeholder="请输入" />
  15. </el-form-item>
  16. <!-- 活动时间 -->
  17. <el-form-item class="activity-time-item" label="活动时间" prop="activityTimeRange">
  18. <el-date-picker
  19. v-model="activityModel.activityTimeRange"
  20. :disabled-date="disabledDate"
  21. class="form-input"
  22. end-placeholder="结束日期"
  23. format="YYYY/MM/DD"
  24. range-separator="-"
  25. start-placeholder="开始日期"
  26. type="daterange"
  27. value-format="YYYY-MM-DD"
  28. />
  29. </el-form-item>
  30. <!-- 用户可参与次数 -->
  31. <el-form-item label="用户可参与次数" prop="participationLimit">
  32. <el-input v-model="activityModel.participationLimit" placeholder="请输入" maxlength="4" />
  33. </el-form-item>
  34. <!-- 活动规则 -->
  35. <el-form-item label="活动规则" prop="activityRule">
  36. <el-cascader
  37. v-model="activityModel.activityRule"
  38. :options="ruleCascaderOptions"
  39. :props="cascaderProps"
  40. class="form-input"
  41. clearable
  42. placeholder="请选择"
  43. style="width: 100%"
  44. />
  45. </el-form-item>
  46. <!-- 优惠券 -->
  47. <el-form-item label="优惠券" prop="couponId">
  48. <el-select v-model="activityModel.couponId" class="form-input" clearable filterable placeholder="请选择">
  49. <el-option v-for="item in couponList" :key="item.id" :label="item.name" :value="item.id" />
  50. </el-select>
  51. </el-form-item>
  52. <!-- 优惠券发放数量 -->
  53. <el-form-item label="优惠券发放数量" prop="couponQuantity">
  54. <el-input v-model="activityModel.couponQuantity" placeholder="请输入" maxlength="5" />
  55. </el-form-item>
  56. <!-- 活动标题图 -->
  57. <el-form-item label="活动标题图" prop="activityTitleImage">
  58. <div class="upload-item-wrapper">
  59. <div class="upload-area upload-area-horizontal-21-9" :class="{ 'upload-full': titleFileList.length >= 1 }">
  60. <el-upload
  61. v-model:file-list="titleFileList"
  62. :accept="'.jpg,.jpeg,.png'"
  63. :auto-upload="false"
  64. :before-remove="handleBeforeRemove"
  65. :disabled="hasUnuploadedImages"
  66. :limit="1"
  67. :on-change="handleTitleUploadChange"
  68. :on-exceed="handleUploadExceed"
  69. :on-preview="handlePictureCardPreview"
  70. :on-remove="handleTitleRemove"
  71. :show-file-list="true"
  72. list-type="picture-card"
  73. >
  74. <template #trigger>
  75. <div v-if="titleFileList.length < 1" class="upload-trigger-card el-upload--picture-card">
  76. <el-icon>
  77. <Plus />
  78. </el-icon>
  79. </div>
  80. </template>
  81. </el-upload>
  82. </div>
  83. <div class="upload-hint">请上传21:9尺寸图片效果更佳,支持jpg、jpeg、png格式,上传图片不得超过20M</div>
  84. </div>
  85. </el-form-item>
  86. <!-- 活动详情图 -->
  87. <el-form-item label="活动详情图" prop="activityDetailImage">
  88. <div class="upload-item-wrapper">
  89. <div class="upload-area upload-area-vertical" :class="{ 'upload-full': detailFileList.length >= 1 }">
  90. <el-upload
  91. v-model:file-list="detailFileList"
  92. :accept="'.jpg,.jpeg,.png'"
  93. :auto-upload="false"
  94. :before-remove="handleBeforeRemove"
  95. :disabled="hasUnuploadedImages"
  96. :limit="1"
  97. :on-change="handleDetailUploadChange"
  98. :on-exceed="handleUploadExceed"
  99. :on-preview="handlePictureCardPreview"
  100. :on-remove="handleDetailRemove"
  101. :show-file-list="true"
  102. list-type="picture-card"
  103. >
  104. <template #trigger>
  105. <div v-if="detailFileList.length < 1" class="upload-trigger-card el-upload--picture-card">
  106. <el-icon>
  107. <Plus />
  108. </el-icon>
  109. </div>
  110. </template>
  111. </el-upload>
  112. </div>
  113. <div class="upload-hint">请上传竖版图片,支持jpg、jpeg、png格式,上传图片不得超过20M</div>
  114. </div>
  115. </el-form-item>
  116. </div>
  117. </el-form>
  118. </div>
  119. <!-- 底部按钮区域 -->
  120. <div class="button-container">
  121. <el-button @click="goBack"> 取消 </el-button>
  122. <el-button type="primary" @click="handleSubmit()"> 提交审核 </el-button>
  123. </div>
  124. </div>
  125. <!-- 图片预览 -->
  126. <el-image-viewer
  127. v-if="imageViewerVisible"
  128. :initial-index="imageViewerInitialIndex"
  129. :url-list="imageViewerUrlList"
  130. @close="imageViewerVisible = false"
  131. />
  132. </div>
  133. </template>
  134. <script lang="tsx" name="newActivity" setup>
  135. /**
  136. * 运营活动管理 - 新增/编辑页面
  137. * 功能:支持运营活动的新增和编辑操作
  138. */
  139. import { computed, nextTick, onMounted, reactive, ref } from "vue";
  140. import type { FormInstance, UploadFile, UploadProps } from "element-plus";
  141. import { ElMessage, ElMessageBox } from "element-plus";
  142. import { Plus } from "@element-plus/icons-vue";
  143. import { useRoute, useRouter } from "vue-router";
  144. import {
  145. addActivity,
  146. getActivityDetail,
  147. getActivityRuleOptions,
  148. getCouponList,
  149. updateActivity
  150. } from "@/api/modules/operationManagement";
  151. import { uploadContractImage } from "@/api/modules/licenseManagement";
  152. import { localGet } from "@/utils";
  153. // ==================== 响应式数据定义 ====================
  154. // 路由相关
  155. const router = useRouter();
  156. const route = useRoute();
  157. // 页面状态
  158. const type = ref<string>(""); // 页面类型:add-新增, edit-编辑
  159. const id = ref<string>(""); // 页面ID参数
  160. // 表单引用
  161. const ruleFormRef = ref<FormInstance>();
  162. // 优惠券列表
  163. const couponList = ref<any[]>([]);
  164. // 文件上传相关
  165. const titleFileList = ref<UploadFile[]>([]);
  166. const detailFileList = ref<UploadFile[]>([]);
  167. const titleImageUrl = ref<string>("");
  168. const detailImageUrl = ref<string>("");
  169. const pendingUploadFiles = ref<UploadFile[]>([]);
  170. const uploading = ref(false);
  171. const imageViewerVisible = ref(false);
  172. const imageViewerUrlList = ref<string[]>([]);
  173. const imageViewerInitialIndex = ref(0);
  174. // 活动规则级联选择器选项
  175. const ruleCascaderOptions = ref<any[]>([]);
  176. // 级联选择器配置
  177. const cascaderProps = {
  178. expandTrigger: "hover" as const,
  179. emitPath: true,
  180. disabled: (data: any) => {
  181. // 除了 "当用户 > 核销并评论 > 优惠券" 这个路径,其余选项不可选择
  182. if (data.disabled !== undefined) {
  183. return data.disabled;
  184. }
  185. return false;
  186. }
  187. };
  188. // 是否有未上传的图片
  189. const hasUnuploadedImages = computed(() => {
  190. return (
  191. titleFileList.value.some(file => file.status === "ready" || file.status === "uploading") ||
  192. detailFileList.value.some(file => file.status === "ready" || file.status === "uploading")
  193. );
  194. });
  195. // ==================== 表单验证规则 ====================
  196. const rules = reactive({
  197. activityName: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  198. activityTimeRange: [
  199. { required: true, message: "请选择活动时间", trigger: "change" },
  200. {
  201. validator: (rule: any, value: any, callback: any) => {
  202. if (!value || !Array.isArray(value) || value.length !== 2) {
  203. callback(new Error("请选择活动时间"));
  204. return;
  205. }
  206. const [startTime, endTime] = value;
  207. if (!startTime || !endTime) {
  208. callback(new Error("请选择完整的活动时间"));
  209. return;
  210. }
  211. const start = new Date(startTime);
  212. const end = new Date(endTime);
  213. const today = new Date();
  214. today.setHours(0, 0, 0, 0);
  215. if (start < today) {
  216. callback(new Error("活动开始时间不能早于当前时间"));
  217. return;
  218. }
  219. if (start >= end) {
  220. callback(new Error("活动开始时间必须早于活动结束时间"));
  221. return;
  222. }
  223. callback();
  224. },
  225. trigger: "change"
  226. }
  227. ],
  228. participationLimit: [
  229. { required: true, message: "请输入用户可参与次数", trigger: "blur" },
  230. {
  231. validator: (rule: any, value: any, callback: any) => {
  232. const numValue = Number(value);
  233. if (isNaN(numValue) || !Number.isInteger(numValue) || numValue <= 0) {
  234. callback(new Error("用户可参与次数必须为正整数"));
  235. return;
  236. }
  237. if (numValue > 9999) {
  238. callback(new Error("用户可参与次数必须小于9999"));
  239. return;
  240. }
  241. callback();
  242. },
  243. trigger: "blur"
  244. }
  245. ],
  246. activityRule: [
  247. { required: true, message: "请选择活动规则", trigger: "change" },
  248. {
  249. validator: (rule: any, value: any, callback: any) => {
  250. if (!value || !Array.isArray(value) || value.length < 2) {
  251. callback(new Error("请选择完整的活动规则(至少选择角色和行为)"));
  252. return;
  253. }
  254. callback();
  255. },
  256. trigger: "change"
  257. }
  258. ],
  259. couponId: [{ required: true, message: "请选择优惠券", trigger: "change" }],
  260. couponQuantity: [
  261. { required: true, message: "请输入优惠券发放数量", trigger: "blur" },
  262. {
  263. validator: (rule: any, value: any, callback: any) => {
  264. const numValue = Number(value);
  265. if (isNaN(numValue) || !Number.isInteger(numValue) || numValue <= 0) {
  266. callback(new Error("优惠券发放数量必须为正整数"));
  267. return;
  268. }
  269. if (numValue > 99999) {
  270. callback(new Error("优惠券发放数量必须小于99999"));
  271. return;
  272. }
  273. callback();
  274. },
  275. trigger: "blur"
  276. }
  277. ],
  278. activityTitleImage: [
  279. {
  280. required: true,
  281. validator: (rule: any, value: any, callback: any) => {
  282. if (!titleImageUrl.value) {
  283. callback(new Error("请上传活动标题图"));
  284. return;
  285. }
  286. callback();
  287. },
  288. trigger: ["change", "blur"]
  289. }
  290. ],
  291. activityDetailImage: [
  292. {
  293. required: true,
  294. validator: (rule: any, value: any, callback: any) => {
  295. if (!detailImageUrl.value) {
  296. callback(new Error("请上传活动详情图"));
  297. return;
  298. }
  299. callback();
  300. },
  301. trigger: ["change", "blur"]
  302. }
  303. ]
  304. });
  305. // ==================== 活动信息数据模型 ====================
  306. const activityModel = ref<any>({
  307. // 活动宣传图(包含标题和详情)
  308. promotionImages: null,
  309. // 活动标题图片
  310. activityTitleImg: null,
  311. // 活动详情图片
  312. activityDetailImg: null,
  313. // 活动标题图(用于表单验证)
  314. activityTitleImage: null,
  315. // 活动详情图(用于表单验证)
  316. activityDetailImage: null,
  317. // 活动名称
  318. activityName: "",
  319. // 活动时间范围
  320. activityTimeRange: [],
  321. // 用户可参与次数
  322. participationLimit: "",
  323. // 活动规则(级联选择器的值数组)
  324. activityRule: [],
  325. // 优惠券ID
  326. couponId: "",
  327. // 优惠券发放数量
  328. couponQuantity: ""
  329. });
  330. // ==================== 日期选择器禁用规则 ====================
  331. // 禁用日期(不能早于今天)
  332. const disabledDate = (time: Date) => {
  333. const today = new Date();
  334. today.setHours(0, 0, 0, 0);
  335. return time.getTime() < today.getTime();
  336. };
  337. // ==================== 图片参数转换函数 ====================
  338. /**
  339. * 图片URL转换为upload组件的参数
  340. * @param imageUrl 图片URL
  341. * @returns UploadFile对象
  342. */
  343. const handleImageParam = (imageUrl: string): UploadFile => {
  344. // 使用split方法以'/'为分隔符将URL拆分成数组
  345. const parts = imageUrl.split("/");
  346. // 取数组的最后一项,即图片名称
  347. const imageName = parts[parts.length - 1];
  348. return {
  349. uid: Date.now() + Math.random(),
  350. name: imageName,
  351. status: "success",
  352. percentage: 100,
  353. url: imageUrl
  354. } as unknown as UploadFile;
  355. };
  356. // ==================== 文件上传相关函数 ====================
  357. /**
  358. * 检查文件是否在排队中(未上传)
  359. */
  360. const isFilePending = (file: any): boolean => {
  361. if (file.status === "ready") {
  362. return true;
  363. }
  364. if (pendingUploadFiles.value.some(item => item.uid === file.uid)) {
  365. return true;
  366. }
  367. return false;
  368. };
  369. /**
  370. * 图片上传 - 删除前确认
  371. */
  372. const handleBeforeRemove = async (uploadFile: any, uploadFiles: any[]): Promise<boolean> => {
  373. if (isFilePending(uploadFile)) {
  374. ElMessage.warning("图片尚未上传,请等待上传完成后再删除");
  375. return false;
  376. }
  377. try {
  378. await ElMessageBox.confirm("确定要删除这张图片吗?", "提示", {
  379. confirmButtonText: "确定",
  380. cancelButtonText: "取消",
  381. type: "warning"
  382. });
  383. return true;
  384. } catch {
  385. return false;
  386. }
  387. };
  388. /**
  389. * 活动标题图片上传 - 移除图片回调
  390. */
  391. const handleTitleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  392. const file = uploadFile as any;
  393. const imageUrl = file.url;
  394. if (imageUrl) {
  395. titleImageUrl.value = "";
  396. activityModel.value.activityTitleImg = null;
  397. activityModel.value.activityTitleImage = null;
  398. // 触发表单验证
  399. nextTick(() => {
  400. ruleFormRef.value?.validateField("activityTitleImage");
  401. });
  402. }
  403. if (file.url && file.url.startsWith("blob:")) {
  404. URL.revokeObjectURL(file.url);
  405. }
  406. titleFileList.value = [...uploadFiles];
  407. ElMessage.success("图片已删除");
  408. };
  409. /**
  410. * 活动详情图片上传 - 移除图片回调
  411. */
  412. const handleDetailRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  413. const file = uploadFile as any;
  414. const imageUrl = file.url;
  415. if (imageUrl) {
  416. detailImageUrl.value = "";
  417. activityModel.value.activityDetailImg = null;
  418. activityModel.value.activityDetailImage = null;
  419. // 触发表单验证
  420. nextTick(() => {
  421. ruleFormRef.value?.validateField("activityDetailImage");
  422. });
  423. }
  424. if (file.url && file.url.startsWith("blob:")) {
  425. URL.revokeObjectURL(file.url);
  426. }
  427. detailFileList.value = [...uploadFiles];
  428. ElMessage.success("图片已删除");
  429. };
  430. /**
  431. * 上传文件超出限制提示
  432. */
  433. const handleUploadExceed: UploadProps["onExceed"] = () => {
  434. ElMessage.warning("最多只能上传1张图片");
  435. };
  436. /**
  437. * 活动标题图片上传 - 文件变更
  438. */
  439. const handleTitleUploadChange: UploadProps["onChange"] = async (uploadFile, uploadFiles) => {
  440. if (uploadFile.raw) {
  441. const fileType = uploadFile.raw.type.toLowerCase();
  442. const fileName = uploadFile.name.toLowerCase();
  443. const validTypes = ["image/jpeg", "image/jpg", "image/png"];
  444. const validExtensions = [".jpg", ".jpeg", ".png"];
  445. const isValidType = validTypes.includes(fileType) || validExtensions.some(ext => fileName.endsWith(ext));
  446. if (!isValidType) {
  447. // 从文件列表中移除不符合类型的文件
  448. const index = titleFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
  449. if (index > -1) {
  450. titleFileList.value.splice(index, 1);
  451. }
  452. // 从 uploadFiles 中移除
  453. const uploadIndex = uploadFiles.findIndex((f: any) => f.uid === uploadFile.uid);
  454. if (uploadIndex > -1) {
  455. uploadFiles.splice(uploadIndex, 1);
  456. }
  457. // 如果文件有 blob URL,释放它
  458. if (uploadFile.url && uploadFile.url.startsWith("blob:")) {
  459. URL.revokeObjectURL(uploadFile.url);
  460. }
  461. ElMessage.warning("只支持上传 JPG、JPEG 和 PNG 格式的图片");
  462. return;
  463. }
  464. // 检查文件大小,不得超过20M
  465. const maxSize = 20 * 1024 * 1024; // 20MB
  466. if (uploadFile.raw.size > maxSize) {
  467. // 从文件列表中移除超过大小的文件
  468. const index = titleFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
  469. if (index > -1) {
  470. titleFileList.value.splice(index, 1);
  471. }
  472. // 从 uploadFiles 中移除
  473. const uploadIndex = uploadFiles.findIndex((f: any) => f.uid === uploadFile.uid);
  474. if (uploadIndex > -1) {
  475. uploadFiles.splice(uploadIndex, 1);
  476. }
  477. // 如果文件有 blob URL,释放它
  478. if (uploadFile.url && uploadFile.url.startsWith("blob:")) {
  479. URL.revokeObjectURL(uploadFile.url);
  480. }
  481. ElMessage.warning("上传图片不得超过20M");
  482. return;
  483. }
  484. }
  485. const existingIndex = titleFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
  486. if (existingIndex === -1) {
  487. titleFileList.value.push(uploadFile);
  488. }
  489. const readyFiles = titleFileList.value.filter(file => file.status === "ready");
  490. if (readyFiles.length) {
  491. readyFiles.forEach(file => {
  492. if (!pendingUploadFiles.value.some(item => item.uid === file.uid)) {
  493. pendingUploadFiles.value.push(file);
  494. }
  495. });
  496. }
  497. processUploadQueue("title");
  498. };
  499. /**
  500. * 活动详情图片上传 - 文件变更
  501. */
  502. const handleDetailUploadChange: UploadProps["onChange"] = async (uploadFile, uploadFiles) => {
  503. if (uploadFile.raw) {
  504. const fileType = uploadFile.raw.type.toLowerCase();
  505. const fileName = uploadFile.name.toLowerCase();
  506. const validTypes = ["image/jpeg", "image/jpg", "image/png"];
  507. const validExtensions = [".jpg", ".jpeg", ".png"];
  508. const isValidType = validTypes.includes(fileType) || validExtensions.some(ext => fileName.endsWith(ext));
  509. if (!isValidType) {
  510. // 从文件列表中移除不符合类型的文件
  511. const index = detailFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
  512. if (index > -1) {
  513. detailFileList.value.splice(index, 1);
  514. }
  515. // 从 uploadFiles 中移除
  516. const uploadIndex = uploadFiles.findIndex((f: any) => f.uid === uploadFile.uid);
  517. if (uploadIndex > -1) {
  518. uploadFiles.splice(uploadIndex, 1);
  519. }
  520. // 如果文件有 blob URL,释放它
  521. if (uploadFile.url && uploadFile.url.startsWith("blob:")) {
  522. URL.revokeObjectURL(uploadFile.url);
  523. }
  524. ElMessage.warning("只支持上传 JPG、JPEG 和 PNG 格式的图片");
  525. return;
  526. }
  527. // 检查文件大小,不得超过20M
  528. const maxSize = 20 * 1024 * 1024; // 20MB
  529. if (uploadFile.raw.size > maxSize) {
  530. // 从文件列表中移除超过大小的文件
  531. const index = detailFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
  532. if (index > -1) {
  533. detailFileList.value.splice(index, 1);
  534. }
  535. // 从 uploadFiles 中移除
  536. const uploadIndex = uploadFiles.findIndex((f: any) => f.uid === uploadFile.uid);
  537. if (uploadIndex > -1) {
  538. uploadFiles.splice(uploadIndex, 1);
  539. }
  540. // 如果文件有 blob URL,释放它
  541. if (uploadFile.url && uploadFile.url.startsWith("blob:")) {
  542. URL.revokeObjectURL(uploadFile.url);
  543. }
  544. ElMessage.warning("上传图片不得超过20M");
  545. return;
  546. }
  547. }
  548. const existingIndex = detailFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
  549. if (existingIndex === -1) {
  550. detailFileList.value.push(uploadFile);
  551. }
  552. const readyFiles = detailFileList.value.filter(file => file.status === "ready");
  553. if (readyFiles.length) {
  554. readyFiles.forEach(file => {
  555. if (!pendingUploadFiles.value.some(item => item.uid === file.uid)) {
  556. pendingUploadFiles.value.push(file);
  557. }
  558. });
  559. }
  560. processUploadQueue("detail");
  561. };
  562. /**
  563. * 处理上传队列 - 逐个上传文件
  564. */
  565. const processUploadQueue = async (type: string) => {
  566. if (uploading.value || pendingUploadFiles.value.length === 0) {
  567. return;
  568. }
  569. const file = pendingUploadFiles.value.shift();
  570. if (file) {
  571. await uploadSingleFile(file, type);
  572. processUploadQueue(type);
  573. }
  574. };
  575. /**
  576. * 单文件上传图片
  577. */
  578. const uploadSingleFile = async (file: UploadFile, uploadType: string) => {
  579. if (!file.raw) {
  580. return;
  581. }
  582. const rawFile = file.raw as File;
  583. const formData = new FormData();
  584. formData.append("file", rawFile);
  585. formData.append("user", "text");
  586. file.status = "uploading";
  587. file.percentage = 0;
  588. uploading.value = true;
  589. try {
  590. const result: any = await uploadContractImage(formData);
  591. if (result?.code === 200 && result.data) {
  592. let imageUrl = result.data[0];
  593. if (!imageUrl) {
  594. throw new Error("上传成功但未获取到图片URL");
  595. }
  596. file.status = "success";
  597. file.percentage = 100;
  598. file.url = imageUrl;
  599. file.response = { url: imageUrl };
  600. if (uploadType === "title") {
  601. titleImageUrl.value = imageUrl;
  602. activityModel.value.activityTitleImg = { url: imageUrl };
  603. activityModel.value.activityTitleImage = imageUrl;
  604. // 触发表单验证
  605. nextTick(() => {
  606. ruleFormRef.value?.validateField("activityTitleImage");
  607. });
  608. } else if (uploadType === "detail") {
  609. detailImageUrl.value = imageUrl;
  610. activityModel.value.activityDetailImg = { url: imageUrl };
  611. activityModel.value.activityDetailImage = imageUrl;
  612. // 触发表单验证
  613. nextTick(() => {
  614. ruleFormRef.value?.validateField("activityDetailImage");
  615. });
  616. }
  617. } else {
  618. throw new Error(result?.msg || "图片上传失败");
  619. }
  620. } catch (error: any) {
  621. // 上传失败时保持进度条为 0
  622. file.percentage = 0;
  623. // 不要设置 file.status = "fail",直接移除文件,避免显示错误占位图
  624. if (file.url && file.url.startsWith("blob:")) {
  625. URL.revokeObjectURL(file.url);
  626. }
  627. // 从文件列表中移除失败的文件
  628. const index =
  629. uploadType === "title"
  630. ? titleFileList.value.findIndex((f: any) => f.uid === file.uid)
  631. : detailFileList.value.findIndex((f: any) => f.uid === file.uid);
  632. if (index > -1) {
  633. if (uploadType === "title") {
  634. titleFileList.value.splice(index, 1);
  635. } else {
  636. detailFileList.value.splice(index, 1);
  637. }
  638. }
  639. // Error message handled by global upload method, except for specific business logic errors
  640. if (error?.message && error.message.includes("未获取到图片URL")) {
  641. ElMessage.error(error.message);
  642. }
  643. } finally {
  644. uploading.value = false;
  645. // 触发视图更新
  646. if (uploadType === "title") {
  647. titleFileList.value = [...titleFileList.value];
  648. } else {
  649. detailFileList.value = [...detailFileList.value];
  650. }
  651. }
  652. };
  653. /**
  654. * 图片预览
  655. */
  656. const handlePictureCardPreview = (file: any) => {
  657. if (isFilePending(file)) {
  658. ElMessage.warning("图片尚未上传,请等待上传完成后再预览");
  659. return;
  660. }
  661. if (file.status === "uploading" && file.url) {
  662. imageViewerUrlList.value = [file.url];
  663. imageViewerInitialIndex.value = 0;
  664. imageViewerVisible.value = true;
  665. return;
  666. }
  667. const allFiles = [...titleFileList.value, ...detailFileList.value];
  668. const urlList = allFiles
  669. .filter((item: any) => item.status === "success" && (item.url || item.response?.data))
  670. .map((item: any) => item.url || item.response?.data);
  671. const currentIndex = urlList.findIndex((url: string) => url === (file.url || file.response?.data));
  672. if (currentIndex < 0) {
  673. ElMessage.warning("图片尚未上传完成,无法预览");
  674. return;
  675. }
  676. imageViewerUrlList.value = urlList;
  677. imageViewerInitialIndex.value = currentIndex;
  678. imageViewerVisible.value = true;
  679. };
  680. // ==================== 生命周期钩子 ====================
  681. /**
  682. * 组件挂载时初始化
  683. */
  684. onMounted(async () => {
  685. id.value = (route.query.id as string) || "";
  686. type.value = (route.query.type as string) || "";
  687. // 加载优惠券列表
  688. try {
  689. const params = {
  690. storeId: localGet("createdId"),
  691. groupType: localGet("businessSection"),
  692. couponType: "2",
  693. couponStatus: "1",
  694. couponsFromType: 1,
  695. pageNum: 1,
  696. pageSize: 99999
  697. };
  698. const res: any = await getCouponList(params);
  699. if (res && res.code == 200) {
  700. couponList.value = res.data?.discountList?.records || [];
  701. }
  702. } catch (error) {
  703. console.error("加载优惠券列表失败:", error);
  704. }
  705. // 加载活动规则级联选择器选项
  706. try {
  707. const res: any = await getActivityRuleOptions();
  708. console.log("ruleCascaderOptions:", res.data);
  709. if (res && res.code == 200) {
  710. ruleCascaderOptions.value = res.data || [];
  711. }
  712. } catch (error) {
  713. console.error("加载活动规则选项失败:", error);
  714. }
  715. // 编辑模式下加载数据
  716. if (type.value != "add" && id.value) {
  717. try {
  718. const res: any = await getActivityDetail({ id: id.value });
  719. if (res && res.code == 200) {
  720. activityModel.value = { ...activityModel.value, ...res.data };
  721. // 处理活动时间范围
  722. if (res.data.startTime && res.data.endTime) {
  723. activityModel.value.activityTimeRange = [res.data.startTime, res.data.endTime];
  724. }
  725. // 如果有标题图片,添加到文件列表
  726. if (res.data.activityTitleImgUrl) {
  727. const titleImgUrl = res.data.activityTitleImgUrl;
  728. if (titleImgUrl) {
  729. titleImageUrl.value = titleImgUrl;
  730. activityModel.value.activityTitleImg = res.data.activityTitleImgUrl;
  731. activityModel.value.activityTitleImage = titleImgUrl;
  732. const titleFile = handleImageParam(titleImgUrl);
  733. titleFileList.value = [titleFile];
  734. }
  735. }
  736. // 如果有详情图片,添加到文件列表
  737. if (res.data.activityDetailImgUrl) {
  738. const detailImgUrl = res.data.activityDetailImgUrl;
  739. if (detailImgUrl) {
  740. detailImageUrl.value = detailImgUrl;
  741. activityModel.value.activityDetailImg = res.data.activityDetailImgUrl;
  742. activityModel.value.activityDetailImage = detailImgUrl;
  743. const detailFile = handleImageParam(detailImgUrl);
  744. detailFileList.value = [detailFile];
  745. }
  746. }
  747. // 加载活动规则
  748. if (res.data.activityRule) {
  749. activityModel.value.activityRule = res.data.activityRule.split(",");
  750. } else {
  751. activityModel.value.activityRule = [];
  752. }
  753. }
  754. } catch (error) {
  755. console.error("加载活动详情失败:", error);
  756. ElMessage.error("加载活动详情失败");
  757. }
  758. }
  759. await nextTick();
  760. ruleFormRef.value?.clearValidate();
  761. });
  762. // ==================== 事件处理函数 ====================
  763. /**
  764. * 返回上一页
  765. */
  766. const goBack = () => {
  767. router.go(-1);
  768. };
  769. /**
  770. * 提交表单
  771. */
  772. const handleSubmit = async () => {
  773. if (!ruleFormRef.value) return;
  774. // 如果有未上传的图片,阻止提交
  775. if (hasUnuploadedImages.value) {
  776. ElMessage.warning("请等待图片上传完成后再提交");
  777. return;
  778. }
  779. await ruleFormRef.value.validate(async valid => {
  780. if (valid) {
  781. const [startTime, endTime] = activityModel.value.activityTimeRange || [];
  782. const params: any = {
  783. activityName: activityModel.value.activityName,
  784. startTime: startTime,
  785. endTime: endTime,
  786. participationLimit: activityModel.value.participationLimit,
  787. activityRule: activityModel.value.activityRule.join(","),
  788. couponId: activityModel.value.couponId,
  789. couponQuantity: activityModel.value.couponQuantity,
  790. activityTitleImg: {
  791. imgUrl: titleImageUrl.value,
  792. imgSort: 0,
  793. storeId: localGet("createdId")
  794. },
  795. activityDetailImg: {
  796. imgUrl: detailImageUrl.value,
  797. imgSort: 0,
  798. storeId: localGet("createdId")
  799. },
  800. storeId: localGet("createdId"),
  801. groupType: localGet("businessSection"),
  802. status: 1 // 1-待审核
  803. };
  804. try {
  805. let res: any;
  806. if (type.value == "add") {
  807. res = await addActivity(params);
  808. } else {
  809. params.id = id.value;
  810. res = await updateActivity(params);
  811. }
  812. if (res && res.code == 200) {
  813. ElMessage.success(type.value == "add" ? "新增成功" : "编辑成功");
  814. goBack();
  815. } else {
  816. ElMessage.error(res?.msg || "操作失败");
  817. }
  818. } catch (error) {
  819. console.error("提交失败:", error);
  820. ElMessage.error("操作失败");
  821. }
  822. }
  823. });
  824. };
  825. </script>
  826. <style lang="scss" scoped>
  827. /* 页面容器 */
  828. .table-box {
  829. display: flex;
  830. flex-direction: column;
  831. height: auto !important;
  832. min-height: 100%;
  833. }
  834. /* 头部区域 */
  835. .header {
  836. display: flex;
  837. align-items: center;
  838. justify-content: center;
  839. padding: 20px 24px;
  840. background-color: #ffffff;
  841. border-bottom: 1px solid #e4e7ed;
  842. box-shadow: 0 2px 4px rgb(0 0 0 / 2%);
  843. }
  844. .title {
  845. flex: 1;
  846. margin: 0;
  847. font-size: 18px;
  848. font-weight: 600;
  849. color: #303133;
  850. text-align: center;
  851. }
  852. /* 表单内容区域 */
  853. .form-content {
  854. padding: 24px;
  855. background-color: #ffffff;
  856. }
  857. /* 表单包装器 */
  858. .form-wrapper {
  859. display: flex;
  860. flex-direction: column;
  861. align-items: center;
  862. background-color: #ffffff;
  863. .form-wrapper-main {
  864. width: 100%;
  865. max-width: 800px;
  866. }
  867. }
  868. /* 上传项容器 */
  869. .upload-item-wrapper {
  870. display: flex;
  871. flex-direction: column;
  872. gap: 12px;
  873. align-items: flex-start;
  874. width: 100%;
  875. }
  876. .upload-hint {
  877. margin-top: 4px;
  878. font-size: 12px;
  879. line-height: 1.5;
  880. color: #909399;
  881. }
  882. /* 规则表格容器 */
  883. .rule-table-container {
  884. margin-top: 20px;
  885. }
  886. /* 底部按钮区域 */
  887. .button-container {
  888. display: flex;
  889. gap: 20px;
  890. justify-content: center;
  891. padding-bottom: 15px;
  892. background-color: #ffffff;
  893. }
  894. .upload-area {
  895. width: 100%;
  896. :deep(.el-upload--picture-card) {
  897. width: 100%;
  898. height: 180px;
  899. }
  900. :deep(.el-upload-list--picture-card) {
  901. width: 100%;
  902. .el-upload-list__item {
  903. width: 100%;
  904. height: 180px;
  905. margin: 0;
  906. }
  907. }
  908. :deep(.el-upload-list--picture-card .el-upload-list__item:hover .el-upload-list__item-status-label) {
  909. display: inline-flex !important;
  910. opacity: 1 !important;
  911. }
  912. :deep(.el-upload-list__item.is-success:focus .el-upload-list__item-status-label) {
  913. display: inline-flex !important;
  914. opacity: 1 !important;
  915. }
  916. :deep(.el-upload-list--picture-card .el-icon--close-tip) {
  917. display: none !important;
  918. }
  919. &.upload-full {
  920. :deep(.el-upload--picture-card) {
  921. display: none !important;
  922. }
  923. }
  924. // 21:9横向图片样式
  925. &.upload-area-horizontal-21-9 {
  926. :deep(.el-upload--picture-card) {
  927. width: 100%;
  928. height: auto;
  929. aspect-ratio: 21 / 9;
  930. }
  931. :deep(.el-upload-list--picture-card) {
  932. width: 100%;
  933. .el-upload-list__item {
  934. width: 100%;
  935. height: auto;
  936. aspect-ratio: 21 / 9;
  937. margin: 0;
  938. }
  939. }
  940. }
  941. // 竖版图片样式
  942. &.upload-area-vertical {
  943. max-width: 300px;
  944. :deep(.el-upload--picture-card) {
  945. width: 100%;
  946. height: 400px;
  947. aspect-ratio: 3 / 4;
  948. }
  949. :deep(.el-upload-list--picture-card) {
  950. width: 100%;
  951. .el-upload-list__item {
  952. width: 100%;
  953. height: 400px;
  954. aspect-ratio: 3 / 4;
  955. margin: 0;
  956. }
  957. }
  958. }
  959. }
  960. .upload-trigger-card {
  961. display: flex;
  962. flex-direction: column;
  963. align-items: center;
  964. justify-content: center;
  965. width: 100%;
  966. height: 100%;
  967. font-size: 28px;
  968. color: #8c939d;
  969. }
  970. /* el-upload 图片预览铺满容器 */
  971. :deep(.el-upload-list--picture-card) {
  972. .el-upload-list__item {
  973. margin: 0;
  974. overflow: hidden;
  975. .el-upload-list__item-thumbnail {
  976. width: 100%;
  977. height: 100%;
  978. object-fit: fill;
  979. }
  980. }
  981. .el-upload-list__item[data-status="ready"],
  982. .el-upload-list__item.is-ready {
  983. position: relative;
  984. pointer-events: none;
  985. cursor: not-allowed;
  986. opacity: 0.6;
  987. &::after {
  988. position: absolute;
  989. inset: 0;
  990. z-index: 1;
  991. content: "";
  992. background-color: rgb(0 0 0 / 30%);
  993. }
  994. .el-upload-list__item-actions {
  995. pointer-events: none;
  996. opacity: 0.5;
  997. }
  998. }
  999. .el-upload-list__item:hover .el-upload-list__item-status-label {
  1000. display: inline-flex !important;
  1001. opacity: 1 !important;
  1002. }
  1003. .el-upload-list__item.is-success:focus .el-upload-list__item-status-label {
  1004. display: inline-flex !important;
  1005. opacity: 1 !important;
  1006. }
  1007. .el-icon--close-tip {
  1008. display: none !important;
  1009. }
  1010. }
  1011. </style>