<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" :class="{ 'at-upload-limit': fileList.length >= (hasVideoInList() ? 1 : 20) }">
            <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
            clearable
            placeholder="请输入地址进行查询"
            remote
            reserve-keyword
            :remote-method="getLonAndLat"
            @change="selectAddress"
            @clear="handleClearLocation"
          >
            <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 { addOrUpdateDynamic } from "@/api/modules/newLoginApi";
import { uploadFilesToOss } from "@/api/upload.js";
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 || formData.storePosition === "") {
    handleClearLocation();
    return;
  }

  if (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 handleClearLocation = () => {
  formData.storePosition = "";
  formData.queryAddress = "";
  formData.storePositionLongitude = "";
  formData.storePositionLatitude = "";
  formData.addressProvince = "";
  formData.location = "";
  formData.locationId = "";
  formData.address = "";
  addressList.value = [];
};

// 表单验证规则
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;

  file.status = "uploading";
  file.percentage = 0;
  uploading.value = true;

  try {
    const isVideo = rawFile.type.startsWith("video/");
    const urls = await uploadFilesToOss(rawFile, isVideo ? "video" : "image");
    const fileUrl = urls[0];
    if (!fileUrl) {
      ElMessage.error("上传失败，未返回文件地址");
      throw new Error("上传失败，未返回文件地址");
    }

    file.status = "success";
    file.percentage = 100;
    file.url = fileUrl;
    file.response = { url: fileUrl };

    if (!formData.images.includes(fileUrl)) {
      formData.images.push(fileUrl);
    }
  } 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);
    }
    // OSS 网络/签名错误已在 upload.js 中 ElMessage，避免重复弹窗
  } 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 {
      // 达到上传限制时隐藏上传组件（+ 按钮）
      &.at-upload-limit :deep(.el-upload--picture-card) {
        display: none;
      }
      :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>
