| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030 |
- <template>
- <div class="publish-dynamic-container">
- <!-- 头部导航 -->
- <div class="header-section">
- <el-button @click="handleGoBack" class="back-btn"> 返回 </el-button>
- <div class="header-title">动态发布</div>
- </div>
- <!-- 表单内容 -->
- <div class="form-container">
- <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
- <!-- 图片/视频上传 -->
- <el-form-item label="图片/视频" prop="images">
- <div class="upload-section">
- <el-upload
- v-model:file-list="fileList"
- list-type="picture-card"
- :limit="hasVideoInList() ? 1 : 20"
- :on-preview="handlePicturePreview"
- :on-remove="handleRemoveImage"
- :on-change="handleFileChange"
- :before-upload="beforeImageUpload"
- :http-request="handleImageUpload"
- accept="image/*,video/mp4,video/*"
- multiple
- class="dynamic-upload"
- >
- <template #file="{ file }">
- <div class="upload-file-preview">
- <!-- 视频缩略图 -->
- <video v-if="isVideoFile(file)" :src="file.url" class="upload-video-thumb" />
- <!-- 图片缩略图 -->
- <img v-else :src="file.url" class="upload-image-thumb" />
- <!-- 操作按钮 -->
- <div class="upload-actions">
- <span class="upload-action-item" @click.stop="handlePicturePreview(file)">
- <el-icon :size="20"><ZoomIn /></el-icon>
- </span>
- <span class="upload-action-item" @click.stop="handleRemoveFile(file)">
- <el-icon :size="20"><Delete /></el-icon>
- </span>
- </div>
- </div>
- </template>
- <div class="upload-trigger">
- <el-icon :size="32" color="#999">
- <Plus />
- </el-icon>
- <div class="upload-count">({{ fileList.length }}/{{ hasVideoInList() ? 1 : 20 }})</div>
- </div>
- </el-upload>
- </div>
- </el-form-item>
- <!-- 标题 -->
- <el-form-item label="标题" prop="title">
- <el-input v-model="formData.title" placeholder="请输入标题" maxlength="50" show-word-limit size="large" />
- </el-form-item>
- <!-- 正文 -->
- <el-form-item label="正文" prop="content">
- <el-input
- v-model="formData.content"
- type="textarea"
- placeholder="请输入正文"
- :rows="8"
- maxlength="500"
- show-word-limit
- />
- </el-form-item>
- <!-- 位置 -->
- <el-form-item label="位置" prop="location">
- <el-select
- v-model="formData.storePosition"
- filterable
- placeholder="请输入地址进行查询"
- remote
- reserve-keyword
- :remote-method="getLonAndLat"
- @change="selectAddress"
- >
- <el-option v-for="item in addressList" :key="item.id" :label="item.name" :value="item.location">
- <span style="float: left">{{ item.name }}</span>
- <span style="float: right; font-size: 13px; color: var(--el-text-color-secondary)">{{ item.district }}</span>
- </el-option>
- </el-select>
- </el-form-item>
- </el-form>
- <div class="footer-actions">
- <el-button size="large" class="draft-btn" @click="handleSaveDraft"> 保存草稿 </el-button>
- <el-button type="primary" size="large" class="publish-btn" :loading="publishing" @click="handlePublish"> 发布 </el-button>
- </div>
- </div>
- <!-- 图片/视频预览对话框 -->
- <el-dialog v-model="previewDialogVisible" width="800px" append-to-body>
- <!-- 视频预览 -->
- <video v-if="previewIsVideo" :src="previewImageUrl" controls style="width: 100%; max-height: 70vh" />
- <!-- 图片预览 -->
- <img v-else :src="previewImageUrl" alt="预览图片" style="width: 100%" />
- </el-dialog>
- <!-- 位置选择对话框 -->
- <el-dialog v-model="locationDialogVisible" title="选择位置" width="500px" append-to-body>
- <el-input v-model="locationSearch" placeholder="搜索位置" clearable>
- <template #prefix>
- <el-icon>
- <Search />
- </el-icon>
- </template>
- </el-input>
- <div class="location-list">
- <div v-for="location in locationList" :key="location.id" class="location-item" @click="handleChooseLocation(location)">
- <el-icon>
- <Location />
- </el-icon>
- <span>{{ location.name }}</span>
- </div>
- <el-empty v-if="locationList.length === 0" description="暂无位置信息" />
- </div>
- </el-dialog>
- </div>
- </template>
- <script setup lang="ts" name="publishDynamic">
- import { ref, reactive, onMounted } from "vue";
- import { useRouter, useRoute } from "vue-router";
- import { ElMessage, ElMessageBox } from "element-plus";
- import { ArrowLeft, Plus, Location, Search, ZoomIn, Delete } from "@element-plus/icons-vue";
- import type { FormInstance, FormRules, UploadUserFile, UploadFile } from "element-plus";
- // import { publishDynamic, saveDraft, uploadDynamicImage } from "@/api/modules/dynamicManagement";
- // import { addOrUpdateDynamic } from "@/api/modules/dynamicManagement";
- import { uploadImg, addOrUpdateDynamic } from "@/api/modules/newLoginApi";
- import { useUserStore } from "@/stores/modules/user";
- import { getUserDraftDynamics, getInputPrompt } from "@/api/modules/newLoginApi";
- const router = useRouter();
- const route = useRoute();
- const userStore = useUserStore();
- // 接口定义
- interface FormData {
- title: string;
- content: string;
- images: string[];
- location: string;
- locationId?: string;
- address?: string; // 经纬度
- addressProvince?: string; // 省市
- storePosition: string;
- queryAddress: string;
- storePositionLongitude: string;
- storePositionLatitude: string;
- }
- interface LocationItem {
- id: string;
- name: string;
- address: string;
- latitude?: string; // 纬度
- longitude?: string; // 经度
- province?: string; // 省市
- }
- // 响应式数据
- const formRef = ref<FormInstance>();
- const fileList = ref<UploadUserFile[]>([]);
- const previewDialogVisible = ref(false);
- const previewImageUrl = ref("");
- const previewIsVideo = ref(false); // 预览的是否为视频
- const locationDialogVisible = ref(false);
- const locationSearch = ref("");
- const locationList = ref<LocationItem[]>([]);
- const publishing = ref(false);
- const pendingUploadFiles = ref<UploadFile[]>([]);
- const uploading = ref(false);
- const currentDraftId = ref<number | string | null>(null); // 当前编辑的草稿ID
- const isEditMode = ref(false); // 是否为编辑模式
- // 表单数据
- const formData = reactive<FormData>({
- title: "",
- content: "",
- images: [],
- location: "",
- address: "", // 经纬度
- addressProvince: "", // 省市
- storePosition: "",
- queryAddress: "",
- storePositionLongitude: "",
- storePositionLatitude: ""
- });
- // 经纬度查询
- const addressMap = new Map();
- const addressList = ref<any[]>([]);
- const getLonAndLat = async (keyword: string) => {
- if (keyword) {
- console.log("地址查询", keyword);
- let param = {
- addressName: keyword
- };
- let res: any = await getInputPrompt(param as any);
- if (res.code == "200") {
- res.data.tips.forEach((item: any) => {
- addressMap.set(item.location, item.name);
- });
- addressList.value = res?.data?.tips || [];
- console.log("res", res);
- } else {
- ElMessage.error("新增失败!");
- }
- } else {
- addressList.value = [];
- }
- };
- const selectAddress = async (param: any) => {
- if (!formData.storePosition || typeof formData.storePosition !== "string") {
- ElMessage.warning("地址格式不正确,请重新选择");
- return;
- }
- if (!formData.storePosition.includes(",")) {
- ElMessage.warning("地址格式不正确,缺少经纬度信息");
- return;
- }
- // 安全地分割地址字符串
- let locationList = formData.storePosition.split(",");
- // 查找对应的地址名称
- addressList.value.forEach((item: any) => {
- console.log(item);
- if (item.location == formData.storePosition) {
- formData.queryAddress = item.name;
- formData.addressProvince = item.district;
- }
- });
- formData.storePositionLongitude = locationList[0]?.trim();
- formData.storePositionLatitude = locationList[1]?.trim();
- };
- // 表单验证规则
- const rules = reactive<FormRules<FormData>>({
- title: [{ required: true, message: "请输入标题", trigger: "blur" }],
- content: [{ required: true, message: "请输入正文", trigger: "blur" }]
- });
- // 返回上一页
- const handleGoBack = async () => {
- // 检查是否有未保存的内容
- if (formData.title || formData.content || fileList.value.length > 0) {
- try {
- await ElMessageBox.confirm("当前有未保存的内容,确定要离开吗?", "提示", {
- confirmButtonText: "确定",
- cancelButtonText: "取消",
- type: "warning"
- });
- router.back();
- } catch {
- // 用户取消
- }
- } else {
- router.back();
- }
- };
- // 文件改变
- const handleFileChange = (uploadFile: UploadFile, uploadFiles: UploadFile[]) => {
- // 验证文件
- if (uploadFile.raw) {
- const isImage = uploadFile.raw.type.startsWith("image/");
- const isVideo = uploadFile.raw.type.startsWith("video/");
- const isValidType = isImage || isVideo;
- if (!isValidType) {
- const index = uploadFiles.findIndex(f => f.uid === uploadFile.uid);
- if (index > -1) {
- uploadFiles.splice(index, 1);
- }
- ElMessage.warning("只能上传图片或视频文件");
- return;
- }
- // 权限:已上传视频则不能再传;已上传图片则只能继续传图片(检查时排除当前文件,用已存在的列表)
- const otherFiles = fileList.value.filter(f => f.uid !== uploadFile.uid);
- const alreadyHasVideo = otherFiles.some(f => isVideoFile(f));
- const alreadyHasImage = otherFiles.some(f => !isVideoFile(f));
- if (alreadyHasVideo) {
- const index = uploadFiles.findIndex(f => f.uid === uploadFile.uid);
- if (index > -1) uploadFiles.splice(index, 1);
- ElMessage.warning("已上传视频,只能上传一个视频,不可再上传");
- return;
- }
- if (alreadyHasImage && isVideo) {
- const index = uploadFiles.findIndex(f => f.uid === uploadFile.uid);
- if (index > -1) uploadFiles.splice(index, 1);
- // ElMessage.warning("已上传图片,后续只能上传图片,不能上传视频");
- return;
- }
- // 根据文件类型设置不同的大小限制
- const maxSize = isVideo ? 100 : 20;
- const isLtMaxSize = uploadFile.raw.size / 1024 / 1024 < maxSize;
- if (!isLtMaxSize) {
- const index = uploadFiles.findIndex(f => f.uid === uploadFile.uid);
- if (index > -1) {
- uploadFiles.splice(index, 1);
- }
- ElMessage.warning(`${isVideo ? "视频" : "图片"}大小不能超过 ${maxSize}MB`);
- return;
- }
- }
- // 为视频文件创建临时预览URL
- if (uploadFile.raw && uploadFile.raw.type.startsWith("video/") && !uploadFile.url) {
- uploadFile.url = URL.createObjectURL(uploadFile.raw);
- console.log("为视频创建临时URL:", uploadFile.url);
- }
- // 添加到待上传队列
- const existingIndex = fileList.value.findIndex(f => f.uid === uploadFile.uid);
- if (existingIndex === -1 && uploadFile.status) {
- fileList.value.push(uploadFile as UploadUserFile);
- }
- const readyFiles = fileList.value.filter(file => file.status === "ready");
- if (readyFiles.length) {
- readyFiles.forEach(file => {
- if (!pendingUploadFiles.value.some(item => item.uid === file.uid)) {
- pendingUploadFiles.value.push(file as UploadFile);
- }
- });
- }
- processUploadQueue();
- };
- // 处理上传队列
- const processUploadQueue = async () => {
- if (uploading.value || pendingUploadFiles.value.length === 0) {
- return;
- }
- const file = pendingUploadFiles.value.shift();
- if (file) {
- await uploadSingleFile(file);
- processUploadQueue();
- }
- };
- // 单个文件上传
- const uploadSingleFile = async (file: UploadFile) => {
- if (!file.raw) {
- return;
- }
- const rawFile = file.raw as File;
- const uploadFormData = new FormData();
- uploadFormData.append("file", rawFile);
- file.status = "uploading";
- file.percentage = 0;
- uploading.value = true;
- try {
- console.log("开始上传文件:", rawFile.name, "类型:", rawFile.type);
- // 图片和视频都使用同一个上传接口
- const result: any = await uploadImg(uploadFormData);
- console.log("上传接口返回:", result);
- if (result?.code === 200 && result.data) {
- let fileUrl = "";
- // 处理不同的返回格式
- if (Array.isArray(result.data) && result.data.length > 0) {
- fileUrl = result.data[0]; // 数组格式
- } else if (typeof result.data === "string") {
- fileUrl = result.data; // 字符串格式
- } else if (result.data.url) {
- fileUrl = result.data.url; // 对象格式
- }
- if (fileUrl) {
- file.status = "success";
- file.percentage = 100;
- file.url = fileUrl;
- file.response = { url: fileUrl };
- console.log("上传成功,文件URL:", fileUrl);
- // 添加到 formData.images
- if (!formData.images.includes(fileUrl)) {
- formData.images.push(fileUrl);
- console.log("添加到 images 数组,当前长度:", formData.images.length);
- }
- } else {
- throw new Error("上传接口返回数据格式错误");
- }
- } else {
- throw new Error(result?.msg || "文件上传失败");
- }
- } catch (error: any) {
- console.error("上传失败:", error);
- file.status = "fail";
- if (file.url && file.url.startsWith("blob:")) {
- URL.revokeObjectURL(file.url);
- }
- const index = fileList.value.findIndex(f => f.uid === file.uid);
- if (index > -1) {
- fileList.value.splice(index, 1);
- }
- ElMessage.error(error?.message || "文件上传失败");
- } finally {
- uploading.value = false;
- fileList.value = [...fileList.value];
- }
- };
- // 图片上传前验证
- const beforeImageUpload = (file: File) => {
- const isImage = file.type.startsWith("image/");
- const isVideo = file.type.startsWith("video/");
- const isValidType = isImage || isVideo;
- if (!isValidType) {
- ElMessage.error("只能上传图片或视频文件!");
- return false;
- }
- // 权限:已上传视频则不能再传;已上传图片则只能继续传图片(排除当前文件,避免清除图片后选视频被误判)
- const permission = checkUploadPermission(file, file);
- if (!permission.allowed) {
- ElMessage.warning(permission.message);
- return false;
- }
- // 图片和视频使用不同的大小限制
- const maxSize = isVideo ? 100 : 20; // 视频100MB,图片20MB
- const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
- if (!isLtMaxSize) {
- ElMessage.error(`${isVideo ? "视频" : "图片"}大小不能超过 ${maxSize}MB!`);
- return false;
- }
- return true;
- };
- // 自定义上传
- const handleImageUpload = async (options: any) => {
- // 上传逻辑已在 uploadSingleFile 中处理
- return;
- };
- // 判断文件是否为视频
- const isVideoFile = (file: any) => {
- const fileName = file.name || file.url || "";
- return fileName.toLowerCase().endsWith(".mp4") || file.raw?.type?.startsWith("video/") || false;
- };
- // 上传类型权限:第一个是图片则只能继续传图片;第一个是视频则只能传一个视频
- const hasVideoInList = () => fileList.value.some(f => isVideoFile(f));
- const hasImageInList = () => fileList.value.some(f => !isVideoFile(f));
- /** 校验上传权限,excludeRawFile 为当前正在校验的文件,校验时排除它(避免刚选中的文件已被加入列表导致误判) */
- const checkUploadPermission = (file: File, excludeRawFile?: File): { allowed: boolean; message?: string } => {
- const isVideo = file.type.startsWith("video/");
- const existingFiles = excludeRawFile ? fileList.value.filter(f => f.raw !== excludeRawFile) : fileList.value;
- const existingHasVideo = existingFiles.some(f => isVideoFile(f));
- const existingHasImage = existingFiles.some(f => !isVideoFile(f));
- if (existingHasVideo) {
- return { allowed: false, message: "已上传视频,只能上传一个视频,不可再上传" };
- }
- if (existingHasImage && isVideo) {
- return { allowed: false, message: "已上传图片,后续只能上传图片,不能上传视频" };
- }
- return { allowed: true };
- };
- // 图片/视频预览
- const handlePicturePreview = (uploadFile: UploadUserFile) => {
- previewImageUrl.value = uploadFile.url!;
- // 判断是否为视频文件
- previewIsVideo.value = isVideoFile(uploadFile);
- previewDialogVisible.value = true;
- };
- // 移除图片/视频(组件回调)
- const handleRemoveImage = (uploadFile: UploadUserFile, uploadFiles: UploadUserFile[]) => {
- console.log("组件回调删除文件:", uploadFile);
- // 从 formData.images 中移除对应的 URL
- const fileUrl = uploadFile.url || (uploadFile.response as any)?.url;
- if (fileUrl) {
- // 清理 blob URL
- if (fileUrl.startsWith("blob:")) {
- URL.revokeObjectURL(fileUrl);
- }
- const index = formData.images.findIndex(url => url === fileUrl);
- if (index > -1) {
- formData.images.splice(index, 1);
- }
- }
- };
- // 手动移除文件(点击自定义删除按钮)
- const handleRemoveFile = (file: UploadUserFile) => {
- console.log("删除文件:", file);
- // 从 formData.images 中移除对应的 URL
- const fileUrl = file.url || (file.response as any)?.url;
- console.log("文件URL:", fileUrl);
- if (fileUrl) {
- // 清理 blob URL
- if (fileUrl.startsWith("blob:")) {
- URL.revokeObjectURL(fileUrl);
- console.log("清理临时URL");
- }
- const index = formData.images.findIndex(url => url === fileUrl);
- console.log("在 images 数组中的索引:", index);
- if (index > -1) {
- formData.images.splice(index, 1);
- }
- }
- // 从 fileList 中移除
- const fileIndex = fileList.value.findIndex(f => f.uid === file.uid);
- console.log("在 fileList 中的索引:", fileIndex);
- if (fileIndex > -1) {
- fileList.value.splice(fileIndex, 1);
- }
- console.log("删除后 fileList 长度:", fileList.value.length);
- console.log("删除后 images 长度:", formData.images.length);
- };
- // 选择位置
- const handleChooseLocation = (location: LocationItem) => {
- formData.location = location.name;
- formData.locationId = location.id;
- // 保存经纬度和省市信息(如果有)
- if (location.longitude && location.latitude) {
- formData.address = `${location.longitude},${location.latitude}`;
- }
- if (location.province) {
- formData.addressProvince = location.province;
- }
- console.log("选择位置:", {
- name: formData.location,
- address: formData.address,
- province: formData.addressProvince
- });
- locationDialogVisible.value = false;
- };
- // 保存草稿
- const handleSaveDraft = async () => {
- if (!formData.title && !formData.content && fileList.value.length === 0) {
- ElMessage.warning("请至少填写标题或正文");
- return;
- }
- // 检查是否有图片/视频正在上传
- if (uploading.value || pendingUploadFiles.value.length > 0) {
- ElMessage.warning("图片/视频正在上传中,请稍候...");
- return;
- }
- try {
- // 获取当前用户信息
- const phone = userStore.userInfo?.phone || "";
- const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;
- const createId = userStore.userInfo?.id || userStore.userInfo?.userId || 0;
- // 调用保存草稿接口
- const params: any = {
- title: formData.title || "未命名",
- context: formData.content || "", // 正文
- imagePath: formData.images.join(","), // 多个图片/视频用逗号分隔
- phoneId: currentUserPhoneId, // 店铺ID
- createId: createId, // 创建者ID
- type: "2", // 动态类型
- draft: 1, // ✅ 1表示草稿
- addressName: formData.queryAddress, // 地址名称
- address: formData.storePositionLongitude + "," + formData.storePositionLatitude, // 经纬度
- addressProvince: formData.addressProvince || "" // 省市
- };
- // 如果是编辑模式,传递ID
- if (isEditMode.value && currentDraftId.value) {
- params.id = currentDraftId.value;
- }
- await addOrUpdateDynamic(params);
- ElMessage.success("草稿保存成功");
- router.back();
- } catch (error) {
- console.error("保存草稿失败:", error);
- ElMessage.error("保存草稿失败");
- }
- };
- // 发布动态
- const handlePublish = async () => {
- if (!formRef.value) return;
- await formRef.value.validate(async (valid: boolean) => {
- if (valid) {
- // 检查是否有图片正在上传
- if (uploading.value || pendingUploadFiles.value.length > 0) {
- ElMessage.warning("图片/视频正在上传中,请稍候...");
- return;
- }
- // 检查是否有上传的文件
- if (formData.images.length === 0) {
- ElMessage.warning("请至少上传一张图片或一个视频");
- return;
- }
- publishing.value = true;
- try {
- // 获取当前用户信息
- const phone = userStore.userInfo?.phone || "";
- const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;
- const createId = userStore.userInfo?.id || userStore.userInfo?.userId || 0;
- // 调用发布动态接口
- const params: any = {
- title: formData.title,
- context: formData.content, // 正文
- imagePath: formData.images.join(","), // 多个图片/视频用逗号分隔
- phoneId: currentUserPhoneId, // 店铺ID
- createId: createId, // 创建者ID
- type: "2", // 动态类型
- draft: 0, // 0表示发布
- addressName: formData.queryAddress, // 地址名称
- address: formData.storePositionLongitude + "," + formData.storePositionLatitude, // 经纬度
- addressProvince: formData.addressProvince || "" // 省市
- };
- // 如果是编辑模式,传递ID
- if (isEditMode.value && currentDraftId.value) {
- params.id = currentDraftId.value;
- }
- await addOrUpdateDynamic(params);
- ElMessage.success("发布成功");
- router.back();
- } catch (error) {
- console.error("发布失败:", error);
- ElMessage.error("发布失败");
- } finally {
- publishing.value = false;
- }
- }
- });
- };
- // 加载草稿数据
- const loadDraftData = async (draftId: string | number) => {
- try {
- console.log("加载草稿数据,ID:", draftId);
- // 获取当前用户的手机号
- const phone = userStore.userInfo?.phone || "";
- const phoneId = phone.startsWith("store_") ? phone : `store_${phone}`;
- // 调用接口获取草稿列表
- const res: any = await getUserDraftDynamics({
- phoneId: phoneId,
- page: 1,
- size: 1000
- });
- if (res.code === 200) {
- const dataList = res.data?.records || res.data?.list || [];
- // 查找指定的草稿
- const draft = dataList.find((item: any) => item.id == draftId);
- if (draft) {
- console.log("找到草稿数据:", draft);
- // 回显标题
- formData.title = draft.title || "";
- // 回显正文
- formData.content = draft.context || "";
- // 回显位置
- formData.location = draft.addressName || "";
- formData.address = draft.address || "";
- formData.addressProvince = draft.addressProvince || "";
- formData.storePosition = draft.address || ""; // 回显到下拉框(经纬度格式)
- formData.queryAddress = draft.addressName || ""; // 回显地址名称
- formData.storePositionLongitude = draft.address ? draft.address.split(",")[0]?.trim() : "";
- formData.storePositionLatitude = draft.address ? draft.address.split(",")[1]?.trim() : "";
- // 如果有地址,需要将其添加到 addressList 中以便下拉框显示
- if (draft.address && draft.addressName) {
- addressList.value = [
- {
- id: draft.id || Date.now(),
- name: draft.addressName,
- location: draft.address,
- district: draft.addressProvince || ""
- }
- ];
- }
- // 回显图片/视频
- if (draft.imagePath) {
- const imageUrls = draft.imagePath.split(",").filter((url: string) => url.trim());
- formData.images = imageUrls;
- // 构建文件列表用于显示
- fileList.value = imageUrls.map((url: string, index: number) => {
- const isVideo = url.toLowerCase().endsWith(".mp4");
- return {
- uid: Date.now() + index,
- name: isVideo ? `video_${index + 1}.mp4` : `image_${index + 1}.jpg`,
- status: "success" as const,
- url: url,
- response: { url: url }
- };
- });
- console.log("回显图片/视频列表:", fileList.value);
- }
- ElMessage.success("草稿数据加载成功");
- } else {
- ElMessage.warning("未找到指定的草稿");
- }
- }
- } catch (error) {
- console.error("加载草稿数据失败:", error);
- ElMessage.error("加载草稿数据失败");
- }
- };
- // 初始化
- onMounted(() => {
- // 检查是否为编辑草稿模式
- const draftId = route.query.draftId;
- const mode = route.query.mode;
- if (draftId && mode === "edit") {
- console.log("进入编辑草稿模式, draftId:", draftId);
- isEditMode.value = true;
- currentDraftId.value = draftId as string | number;
- loadDraftData(draftId as string | number);
- }
- });
- </script>
- <style scoped lang="scss">
- .header-section {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 16px 0;
- border-bottom: 1px solid #e4e7ed;
- .back-btn {
- display: flex;
- gap: 4px;
- align-items: center;
- padding: 8px 16px;
- margin-left: 20px;
- font-size: 15px;
- color: #606266;
- transition: all 0.3s;
- &:hover {
- color: #409eff;
- background: #ecf5ff;
- }
- }
- .header-title {
- flex: 1;
- font-size: 20px;
- font-weight: 600;
- color: #303133;
- text-align: center;
- }
- .header-right {
- width: 100px;
- }
- }
- .publish-dynamic-container {
- display: flex;
- flex-direction: column;
- background: #ffffff;
- // 头部导航
- .header-bar {
- position: sticky;
- top: 0;
- z-index: 100;
- display: flex;
- align-items: center;
- justify-content: space-between;
- height: 60px;
- .header-left {
- flex: 1;
- .return-btn {
- background: #ffffff;
- border: 1px solid #dcdfe6;
- }
- :deep(.el-button) {
- padding: 8px 0;
- font-size: 16px;
- color: #606266;
- &:hover {
- color: #409eff;
- }
- .el-icon {
- margin-right: 4px;
- }
- }
- }
- .header-title {
- flex: 1;
- font-size: 18px;
- font-weight: 600;
- color: #303133;
- text-align: center;
- }
- .header-right {
- flex: 1;
- }
- }
- // 表单容器
- .form-container {
- flex: 1;
- width: 100%;
- max-width: 800px;
- padding: 30px 20px;
- margin: 0 auto;
- :deep(.el-form) {
- .el-form-item {
- margin-bottom: 15px;
- .el-form-item__label {
- padding-bottom: 5px;
- font-size: 16px;
- font-weight: 600;
- color: #303133;
- }
- }
- }
- // 图片上传区域
- .upload-section {
- :deep(.el-upload-list) {
- display: flex;
- flex-wrap: wrap;
- gap: 8px;
- }
- :deep(.el-upload--picture-card) {
- width: 138px;
- height: 138px;
- border: 1px dashed #dcdfe6;
- border-radius: 8px;
- transition: all 0.3s;
- &:hover {
- border-color: #409eff;
- }
- .upload-trigger {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- height: 100%;
- .upload-count {
- margin-top: 8px;
- font-size: 14px;
- color: #909399;
- }
- }
- }
- :deep(.el-upload-list--picture-card .el-upload-list__item) {
- width: 138px;
- height: 138px;
- margin: 0;
- border-radius: 8px;
- }
- // 自定义文件预览
- .upload-file-preview {
- position: relative;
- width: 100%;
- height: 100%;
- overflow: hidden;
- border-radius: 8px;
- .upload-video-thumb,
- .upload-image-thumb {
- width: 100%;
- height: 100%;
- object-fit: cover;
- }
- .upload-actions {
- position: absolute;
- top: 0;
- left: 0;
- z-index: 10;
- display: flex;
- gap: 8px;
- align-items: center;
- justify-content: center;
- width: 100%;
- height: 100%;
- background: rgb(0 0 0 / 50%);
- opacity: 0;
- transition: opacity 0.3s;
- .upload-action-item {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 36px;
- height: 36px;
- color: #ffffff;
- cursor: pointer;
- background: rgb(0 0 0 / 50%);
- border-radius: 50%;
- transition: transform 0.2s;
- &:hover {
- transform: scale(1.1);
- }
- }
- }
- &:hover .upload-actions {
- opacity: 1;
- }
- }
- }
- // 输入框样式
- :deep(.el-input__inner),
- :deep(.el-textarea__inner) {
- border-radius: 8px;
- }
- :deep(.el-textarea__inner) {
- padding: 12px 15px;
- font-size: 15px;
- line-height: 1.6;
- }
- }
- // 底部操作按钮
- .footer-actions {
- display: flex;
- justify-content: center;
- .el-button {
- min-width: 150px;
- height: 45px;
- margin-top: 20px;
- font-size: 16px;
- border-radius: 8px;
- }
- .draft-btn {
- color: #606266;
- background: #f5f7fa;
- border-color: #dcdfe6;
- &:hover {
- color: #409eff;
- background: #ecf5ff;
- border-color: #409eff;
- }
- }
- .publish-btn {
- background: #409eff;
- border-color: #409eff;
- }
- }
- // 位置选择对话框
- :deep(.el-dialog) {
- border-radius: 12px;
- .location-list {
- max-height: 400px;
- margin-top: 16px;
- overflow-y: auto;
- .location-item {
- display: flex;
- gap: 12px;
- align-items: center;
- padding: 12px 16px;
- cursor: pointer;
- border-radius: 8px;
- transition: all 0.3s;
- &:hover {
- background: #f5f7fa;
- }
- .el-icon {
- font-size: 18px;
- color: #909399;
- }
- span {
- font-size: 15px;
- color: #303133;
- }
- }
- }
- }
- }
- // 响应式适配
- @media (width <= 768px) {
- .publish-dynamic-container {
- .form-container {
- padding: 20px 16px 100px;
- }
- .footer-actions {
- padding: 12px 16px;
- .el-button {
- min-width: 140px;
- height: 44px;
- font-size: 15px;
- }
- }
- }
- }
- </style>
|