<template>
  <div class="photo-album-container">
    <!-- 头部：相册 Tab 和新建按钮 -->
    <div class="header-section">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- <el-tab-pane label="环境" name="environment" />
        <el-tab-pane label="视频" name="video" /> -->
        <el-tab-pane v-for="album in albumList" :key="album.id" :label="album.name" :name="String(album.id)">
          <template #label>
            <span class="album-tab-label">
              {{ album.name }}
              <el-icon class="edit-icon" @click.stop="handleEditAlbum(album)">
                <Edit />
              </el-icon>
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>
      <div class="header-actions">
        <el-button type="primary" @click="openCreateDialog"> 新建相册 </el-button>
      </div>
    </div>

    <!-- 内容区域：仅支持图片上传 -->
    <div class="content-section">
      <div v-if="isAlbumTab && currentAlbumRef" class="upload-tips">
        <span>照片宽高不小于500像素</span>
        <span>大小不超过10M</span>
        <span>可拖拽排序</span>
        <span>暂不支持上传动图</span>
        <span>不可上传手机截屏、含清晰人脸/电话/二维码/第三方水印/LOGO等图片。</span>
      </div>

      <!-- 相册 Tab：图片 -->
      <div v-if="isAlbumTab && currentAlbumRef" class="media-grid">
        <div class="upload-item upload-box">
          <UploadImgs
            v-model:file-list="currentAlbumRef.images"
            :limit="50"
            :file-size="10"
            :file-type="['image/jpeg', 'image/png', 'image/gif', 'image/webp']"
            :width="'100%'"
            :height="'200px'"
            :border-radius="'8px'"
            :api="customImageUploadApi"
            :on-success="handleOfficialImageUploadSuccess"
          >
            <template #tip>
              <div class="upload-tip-text">上传图片 ({{ currentAlbumRef.images?.length || 0 }}/50)</div>
            </template>
          </UploadImgs>
        </div>

        <div v-for="(image, index) in displayImages" :key="image.uid || index" class="media-item">
          <div class="media-wrapper">
            <img :src="image.url || ''" alt="相册图片" />
            <div class="media-overlay">
              <el-button type="primary" link @click="viewImage(image.url || '')"> 查看 </el-button>
              <el-button type="primary" link @click="deleteImage(index)"> 删除 </el-button>
            </div>
            <el-tag v-if="isFirstImage(index)" type="danger" class="cover-tag"> 封面 </el-tag>
          </div>
        </div>
      </div>
    </div>
    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pageable.pageNum"
        v-model:page-size="pageable.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新建/编辑相册弹窗 -->
    <el-dialog v-model="createDialogVisible" :title="editId ? '修改相册名称' : '新建相册'" width="500px" @close="resetCreateForm">
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="0">
        <el-form-item prop="name">
          <el-input v-model="createForm.name" placeholder="请输入相册名称" maxlength="6" clearable show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="footer-left">
            <el-button v-if="editId" type="danger" @click="handleDeleteAlbum"> 删除相册 </el-button>
          </div>
          <div class="footer-right">
            <el-button @click="createDialogVisible = false"> 取消 </el-button>
            <el-button type="primary" @click="handleCreateAlbum"> 确定 </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <PcImagePreviewViewer
      v-model:visible="previewVisible"
      :url-list="previewImageUrl ? [previewImageUrl] : []"
      :initial-index="0"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadUserFile, UploadFile } from "element-plus";
import { Edit } from "@element-plus/icons-vue";
import UploadImgs from "@/components/Upload/Imgs.vue";
import { localGet } from "@/utils";
import {
  getOfficialAlbumList,
  createOrUpdateOfficialAlbum,
  deleteOfficialAlbum,
  saveOfficialImg,
  getOfficialImgList,
  deleteOfficialImg
} from "@/api/modules/storeDecoration";
import { uploadFileToOssWithDownloadMeta } from "@/api/upload.js";
import PcImagePreviewViewer from "@/components/pcMediaPreview/PcImagePreviewViewer.vue";

/** 普通官方相册图 */
const OFFICIAL_IMG_TYPE_ALBUM = 2;
/** 环境 Tab 及约定走环境图类型的相册 Tab（如 id=182） */
const OFFICIAL_IMG_TYPE_ENV_OR_SPECIAL_ALBUM = 4;

/** 相册 Tab 的 name 为相册 id 字符串；列入此集合的 Tab 拉列表、保存时 imgType 均为 4 */
const albumTabNamesWithImgType4 = new Set<string>(["182"]);

const isAlbumTabImgType4 = (tabKey: string) => albumTabNamesWithImgType4.has(String(tabKey));

// 扩展图片类型
interface AlbumImage extends UploadUserFile {
  isCover?: boolean;
  businessId?: number; // 相册ID
  imgSort?: number; // 排序
  imgType?: number; // 相册默认 2；环境 / 特殊相册 Tab 为 4
  imgId?: number; // 图片ID（从服务器返回）
}

// 相册接口
interface Album {
  id: string | number;
  name: string;
  albumName?: string; // API返回的字段名
  isFixed?: string | number | boolean;
  images: AlbumImage[];
  coverImageId?: string | number;
}

const createDialogVisible = ref(false);
const createFormRef = ref<FormInstance>();
// 环境 / 视频 / 相册 id（字符串）；初始为空，相册列表加载后默认选中第一项
const activeTab = ref("");
const previewVisible = ref(false);
const previewImageUrl = ref("");
const editId = ref<string | number | null>(null);

// 正在保存的图片URL集合，防止重复保存
const savingImages = ref<Set<string>>(new Set());
// 已处理过的图片URL集合，防止重复处理
const processedImages = ref<Set<string>>(new Set());
// 是否正在加载相册图片（用于跳过watch触发）
const isLoadingAlbumImages = ref(false);

// 相册列表
const albumList = ref<Album[]>([]);

// 当前是否为相册 Tab（动态相册列表中的某一项）
const isAlbumTab = computed(() => albumList.value.some(album => String(album.id) === activeTab.value));

// 环境图片列表（独立的，不属于任何相册）
const environmentImages = ref<AlbumImage[]>([]);

// 当前相册的引用（用于直接绑定，确保响应式更新）
const currentAlbumRef = computed(() => {
  if (activeTab.value === "environment") {
    return null; // 环境tab使用单独的绑定
  }
  const album = albumList.value.find(album => String(album.id) === activeTab.value);
  if (album) {
    if (!album.images) {
      album.images = reactive<AlbumImage[]>([]);
    }
    return album;
  }
  return null;
});

// 分页数据
const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 相册 Tab：分页后的图片列表
const displayImages = computed(() => {
  if (!isAlbumTab.value) {
    return [];
  }
  const images = currentAlbumRef.value?.images || [];
  if (images.length === 0) {
    return [];
  }
  const start = (pageable.pageNum - 1) * pageable.pageSize;
  const end = start + pageable.pageSize;
  return images.slice(start, end);
});

const isFirstImage = (displayIndex: number): boolean => {
  const actualIndex = (pageable.pageNum - 1) * pageable.pageSize + displayIndex;
  return actualIndex === 0;
};

// 新建相册表单
const createForm = reactive({
  name: ""
});

// 新建相册表单校验规则
const createRules = reactive<FormRules>({
  name: [
    { required: true, message: "请输入相册名称", trigger: "blur" },
    { min: 1, max: 6, message: "相册名称长度在1到6个字符", trigger: "blur" }
  ]
});

// 图片尺寸校验函数（不小于500像素）
const validateImageDimensions = (file: File): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e: ProgressEvent<FileReader>) => {
      const img = new Image();
      img.onload = () => {
        const width = img.width;
        const height = img.height;

        // 检查尺寸：不小于500像素
        if (width < 500 || height < 500) {
          ElMessage.warning("照片宽高不小于500像素");
          reject(new Error("图片尺寸不符合要求"));
          return;
        }

        resolve(true);
      };
      img.onerror = () => {
        reject(new Error("图片加载失败"));
      };
      if (e.target?.result) {
        img.src = e.target.result as string;
      }
    };
    reader.onerror = () => {
      reject(new Error("文件读取失败"));
    };
    reader.readAsDataURL(file);
  });
};

// 自定义图片上传：`upload/simple` 成功且响应含 download_url 后再交给 onSuccess 里保存相册
const customImageUploadApi = async (formData: FormData, options?: Record<string, unknown>): Promise<any> => {
  const raw = formData.get("file");
  const file = raw instanceof File ? raw : null;
  if (!file) {
    throw new Error("请选择文件");
  }

  try {
    await validateImageDimensions(file);
  } catch (error) {
    throw error;
  }

  const { fileUrl, downloadUrl } = await uploadFileToOssWithDownloadMeta(file, options ?? {});
  if (!downloadUrl?.trim()) {
    throw new Error("上传成功但未返回 download_url，无法保存相册");
  }
  const d = downloadUrl.trim();

  const response = {
    data: { fileUrl, downloadUrl: d, download_url: d },
    fileUrl,
    downloadUrl: d,
    download_url: d
  };
  await nextTick();
  return response;
};

/** 仅在上传成功且拿到 download_url 后调用 saveOfficialImg，并回填列表 URL 供展示与后端一致 */
const handleOfficialImageUploadSuccess = (_displayUrl: string, response?: unknown, file?: UploadFile) => {
  if (isLoadingAlbumImages.value) {
    return;
  }

  const r = response as Record<string, unknown> | undefined | null;
  const nested = r?.data !== null && typeof r?.data === "object" ? (r.data as Record<string, unknown>) : undefined;
  const rawDownload =
    (typeof r?.downloadUrl === "string" ? r.downloadUrl : null) ??
    (typeof r?.download_url === "string" ? r.download_url : null) ??
    (nested && typeof nested.downloadUrl === "string" ? nested.downloadUrl : null) ??
    (nested && typeof nested.download_url === "string" ? nested.download_url : null);
  const downloadUrl = rawDownload?.trim() || "";
  if (!downloadUrl) {
    ElMessage.warning("上传响应缺少 download_url，未写入相册记录");
    return;
  }

  let list: AlbumImage[] | null = null;
  if (activeTab.value === "environment") {
    list = environmentImages.value;
  } else if (isAlbumTab.value && currentAlbumRef.value) {
    list = currentAlbumRef.value.images;
  }
  if (list && file?.uid !== undefined) {
    const idx = list.findIndex((i: AlbumImage) => i.uid === file.uid);
    if (idx !== -1) {
      list[idx].url = downloadUrl;
    }
  }

  if (activeTab.value !== "environment" && !isAlbumTab.value) {
    return;
  }

  if (savingImages.value.has(downloadUrl) || processedImages.value.has(downloadUrl)) {
    return;
  }

  processedImages.value.add(downloadUrl);
  saveImageToServer(downloadUrl).catch(error => {
    console.error("保存图片失败:", error);
    processedImages.value.delete(downloadUrl);
  });
};

// 保存图片到服务器
const saveImageToServer = async (imgUrl: string) => {
  // 如果正在保存，直接返回，防止重复保存
  if (savingImages.value.has(imgUrl)) {
    return;
  }

  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      return;
    }

    // 判断是环境图片还是相册图片
    let businessId: number;
    let currentImages: AlbumImage[];

    if (activeTab.value === "environment") {
      // 环境图片：使用 storeId 作为 businessId（需要根据实际API调整）
      businessId = Number(storeId);
      currentImages = environmentImages.value || [];
    } else {
      // 相册图片
      if (!currentAlbumRef.value) {
        return;
      }
      businessId = Number(currentAlbumRef.value.id);
      currentImages = currentAlbumRef.value.images || [];
    }

    // 找到对应的图片（通过URL匹配）
    const targetImage = currentImages.find((img: AlbumImage) => img.url === imgUrl && !img.imgId);
    if (!targetImage) {
      return; // 如果图片已经有ID或找不到，不重复保存
    }

    // 标记为正在保存
    savingImages.value.add(imgUrl);

    const imgSort = currentImages.filter((img: AlbumImage) => img.imgId).length + 1; // 排序为已保存图片数量+1

    const imgType =
      activeTab.value === "environment" || isAlbumTabImgType4(activeTab.value)
        ? OFFICIAL_IMG_TYPE_ENV_OR_SPECIAL_ALBUM
        : OFFICIAL_IMG_TYPE_ALBUM;

    const params = [
      {
        businessId: businessId,
        imgSort: imgSort,
        imgType,
        imgUrl: imgUrl,
        storeId: Number(storeId)
      }
    ];

    const res: any = await saveOfficialImg(params);
    if (res && (res.code === 200 || res.code === "200") && res.data && res.data[0]) {
      // 保存成功后，更新图片的ID和其他信息
      targetImage.imgId = res.data[0].id;
      targetImage.businessId = res.data[0].businessId;
      targetImage.imgSort = res.data[0].imgSort;
      // 保存成功后，从已处理集合中移除，允许后续更新
      processedImages.value.delete(imgUrl);
    }
  } catch (error) {
    console.error("保存图片信息失败:", error);
    // 保存失败时，也从已处理集合中移除，允许重试
    processedImages.value.delete(imgUrl);
  } finally {
    // 无论成功或失败，都移除保存标记
    savingImages.value.delete(imgUrl);
  }
};

// 打开新建相册弹窗
const openCreateDialog = () => {
  editId.value = null;
  createDialogVisible.value = true;
  resetCreateForm();
};

// 重置新建表单
const resetCreateForm = () => {
  createForm.name = "";
  editId.value = null;
  createFormRef.value?.clearValidate();
};

// 创建/更新相册
const handleCreateAlbum = async () => {
  if (!createFormRef.value) return;

  try {
    await createFormRef.value.validate();
  } catch (error) {
    return;
  }

  if (!createForm.name.trim()) {
    ElMessage.warning("请输入相册名称");
    return;
  }

  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      ElMessage.error("未找到店铺ID");
      return;
    }

    const params: any = {
      albumName: createForm.name.trim(),
      storeId: Number(storeId)
    };

    if (editId.value) {
      params.id = editId.value;
    }

    const res: any = await createOrUpdateOfficialAlbum(params);
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success(editId.value ? "修改相册成功" : "新建相册成功");
      createDialogVisible.value = false;

      // 保存当前选中的相册ID
      const currentAlbumId = activeTab.value;

      resetCreateForm();
      await getAlbumList();

      // 如果是编辑相册，重新加载当前相册的图片
      if (editId.value && currentAlbumId) {
        activeTab.value = currentAlbumId;
        await loadAlbumImages(currentAlbumId);
      } else if (!editId.value && albumList.value.length > 0) {
        // 如果是新建相册，切换到新创建的相册并加载图片
        const newAlbum = albumList.value[albumList.value.length - 1];
        activeTab.value = String(newAlbum.id);
        await loadAlbumImages(String(newAlbum.id));
      }
    } else {
      ElMessage.error(res?.msg || (editId.value ? "修改相册失败" : "新建相册失败"));
    }
  } catch (error: any) {
    console.error("保存相册失败:", error);
    ElMessage.error(error?.msg || "操作失败，请重试");
  }
};

// Tab 切换
const handleTabClick = async (tab: any) => {
  const tabName = tab.props.name;
  // 如果已经是当前tab，不重复加载
  if (activeTab.value === tabName) {
    return;
  }
  activeTab.value = tabName;
  pageable.pageNum = 1;

  // 根据tab类型加载数据（watch 会处理加载，这里只更新分页）
  await nextTick();
  updatePagination();
};

// 编辑相册
const handleEditAlbum = (album?: Album) => {
  const targetAlbum = album || albumList.value.find(album => String(album.id) === activeTab.value);
  if (!targetAlbum) {
    ElMessage.warning("请先选择要编辑的相册");
    return;
  }
  editId.value = targetAlbum.id;
  createForm.name = targetAlbum.name || targetAlbum.albumName || "";
  createDialogVisible.value = true;
  createFormRef.value?.clearValidate();
};

// 删除相册
const handleDeleteAlbum = async () => {
  if (!editId.value) {
    return;
  }

  try {
    await ElMessageBox.confirm("确认删除该相册吗？删除后相册内的图片也将一并删除。", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 找到要删除的相册
    const albumToDelete = albumList.value.find(album => album.id === editId.value);
    if (!albumToDelete) {
      ElMessage.error("未找到要删除的相册");
      return;
    }

    // 调用删除接口
    const res: any = await deleteOfficialAlbum([albumToDelete]);
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("删除相册成功");
      createDialogVisible.value = false;
      resetCreateForm();

      // 重新获取相册列表（当前 tab 若已不存在会自动选中第一项或清空）
      await getAlbumList();
    } else {
      ElMessage.error(res?.msg || "删除相册失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除相册失败:", error);
      ElMessage.error(error?.msg || "删除失败，请重试");
    }
  }
};

// 查看图片
const viewImage = (url: string) => {
  previewImageUrl.value = url;
  previewVisible.value = true;
};

// 删除图片
const deleteImage = async (index: number) => {
  const actualIndex = (pageable.pageNum - 1) * pageable.pageSize + index;

  // 根据当前tab获取对应的图片列表
  let imageList: AlbumImage[];
  if (activeTab.value === "environment") {
    imageList = environmentImages.value;
  } else {
    imageList = currentAlbumRef.value?.images || [];
  }

  const image = imageList[actualIndex] as AlbumImage;
  if (!image) {
    return;
  }

  try {
    // 如果图片有ID，说明已保存到服务器，需要调用删除接口
    if (image.imgId) {
      // 调用删除接口，参数是图片ID数组
      const params = [image.imgId];

      const res: any = await deleteOfficialImg(params);
      if (res && (res.code === 200 || res.code === "200")) {
        imageList.splice(actualIndex, 1);
        updatePagination();
        ElMessage.success("删除成功");
      } else {
        ElMessage.error(res?.msg || "删除失败");
      }
    } else {
      // 如果图片还没有保存到服务器，直接删除本地数据
      imageList.splice(actualIndex, 1);
      updatePagination();
      ElMessage.success("删除成功");
    }
  } catch (error: any) {
    console.error("删除图片失败:", error);
    ElMessage.error(error?.msg || "删除失败，请重试");
  }
};

// 更新分页总数
const updatePagination = () => {
  if (activeTab.value === "environment") {
    pageable.total = environmentImages.value?.length || 0;
  } else if (isAlbumTab.value) {
    pageable.total = currentAlbumRef.value?.images?.length || 0;
  } else {
    pageable.total = 0;
  }
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pageable.pageSize = size;
  pageable.pageNum = 1;
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pageable.pageNum = page;
};

// 图片列表变化时仅更新分页（保存相册改由上传成功回调 handleOfficialImageUploadSuccess 触发）
watch(
  () => {
    if (activeTab.value === "environment") {
      return environmentImages.value || [];
    }
    if (isAlbumTab.value && currentAlbumRef.value) {
      return currentAlbumRef.value.images || [];
    }
    return [];
  },
  () => {
    const isImageAlbumTab = isAlbumTab.value && currentAlbumRef.value;
    if (activeTab.value !== "environment" && !isImageAlbumTab) {
      return;
    }
    updatePagination();
  },
  { deep: true }
);

// 监听tab切换，加载对应的数据
watch(
  () => activeTab.value,
  async (newVal, oldVal) => {
    // 如果tab没有变化，不重复加载
    if (newVal === oldVal) {
      return;
    }
    // 重置分页到第一页
    pageable.pageNum = 1;

    // 根据tab类型加载数据
    if (newVal === "environment") {
      await loadEnvironmentImages();
    } else if (newVal) {
      // 相册tab
      await loadAlbumImages(newVal);
    }
    // 注意：updatePagination 在各自的 load 函数中已调用
  }
);

// 获取相册列表
const getAlbumList = async () => {
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      console.warn("未找到店铺ID");
      return;
    }

    const params = {
      storeId: Number(storeId)
    };
    const res: any = await getOfficialAlbumList(params);
    if (res && (res.code === 200 || res.code === "200") && res.data) {
      const dataList = Array.isArray(res.data) ? res.data : [];
      albumList.value = dataList.map((album: any) => ({
        id: album.id,
        name: album.albumName || album.name,
        albumName: album.albumName,
        isFixed: album.isFixed,
        images: reactive<AlbumImage[]>([]), // 使用 reactive 确保响应式
        coverImageId: album.coverImageId
      }));
      // 默认选中第一个相册；若当前 tab 仍有效则保留（如刷新列表、新建后切到最后一个）
      const prev = activeTab.value;
      const idSet = new Set(albumList.value.map(a => String(a.id)));
      if (albumList.value.length > 0) {
        const keepSpecial = prev === "environment";
        const keepAlbum = Boolean(prev && idSet.has(String(prev)));
        if (!keepSpecial && !keepAlbum) {
          activeTab.value = String(albumList.value[0].id);
        }
      } else if (prev !== "environment") {
        activeTab.value = "";
      }
    }
  } catch (error) {
    console.error("获取相册列表失败:", error);
  }
};

// 加载环境图片列表
const loadEnvironmentImages = async () => {
  try {
    isLoadingAlbumImages.value = true;
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      return;
    }

    // 环境图片：使用 storeId 作为 businessId（需要根据实际API调整）
    // 或者如果环境图片不需要 businessId，可能需要使用其他API
    // 这里先使用 storeId 作为 businessId
    const imageRes: any = await getOfficialImgList(Number(storeId), Number(storeId), OFFICIAL_IMG_TYPE_ENV_OR_SPECIAL_ALBUM);

    if (imageRes && (imageRes.code === 200 || imageRes.code === "200") && imageRes.data) {
      const imageList = Array.isArray(imageRes.data) ? imageRes.data : [];
      const images: AlbumImage[] = imageList
        .filter((img: any) => img.deleteFlag !== 1)
        .map((img: any) => ({
          uid: img.id || Date.now() + Math.random(),
          name: img.imgUrl?.split("/").pop() || "image",
          url: img.imgUrl,
          status: "success",
          imgId: img.id,
          businessId: img.businessId,
          imgSort: img.imgSort,
          imgType: img.imgType,
          isCover: false
        }))
        .sort((a: AlbumImage, b: AlbumImage) => (a.imgSort || 0) - (b.imgSort || 0));
      // 使用数组替换确保响应式更新
      environmentImages.value.splice(0, environmentImages.value.length, ...images);
    } else {
      environmentImages.value.splice(0, environmentImages.value.length);
    }

    processedImages.value.clear();
  } catch (error) {
    console.error("获取环境图片列表失败:", error);
    environmentImages.value.splice(0, environmentImages.value.length);
  } finally {
    isLoadingAlbumImages.value = false;
    await nextTick();
    updatePagination();
  }
};

// 图片相册：getOfficialImgList（与改造前一致）
const loadAlbumPicturesForAlbum = async (albumId: string) => {
  const userInfo: any = localGet("geeker-user")?.userInfo || {};
  const storeId = userInfo.storeId;
  if (!storeId || !albumId) {
    return;
  }

  const current = albumList.value.find(album => String(album.id) === albumId);
  if (!current) {
    return;
  }

  const listImgType = isAlbumTabImgType4(albumId) ? OFFICIAL_IMG_TYPE_ENV_OR_SPECIAL_ALBUM : OFFICIAL_IMG_TYPE_ALBUM;
  const imageRes: any = await getOfficialImgList(Number(albumId), Number(storeId), listImgType);

  if (imageRes && (imageRes.code === 200 || imageRes.code === "200") && imageRes.data) {
    const imageList = Array.isArray(imageRes.data) ? imageRes.data : [];
    const images: AlbumImage[] = imageList
      .filter((img: any) => img.deleteFlag !== 1)
      .map((img: any) => ({
        uid: img.id || Date.now() + Math.random(),
        name: img.imgUrl?.split("/").pop() || "image",
        url: img.imgUrl,
        status: "success",
        imgId: img.id,
        businessId: img.businessId,
        imgSort: img.imgSort,
        imgType: img.imgType,
        isCover: false
      }))
      .sort((a: AlbumImage, b: AlbumImage) => (a.imgSort || 0) - (b.imgSort || 0));
    if (!current.images) {
      current.images = reactive<AlbumImage[]>([]);
    }
    current.images.splice(0, current.images.length, ...images);
  } else {
    if (!current.images) {
      current.images = reactive<AlbumImage[]>([]);
    } else {
      current.images.splice(0, current.images.length);
    }
  }
};

const loadAlbumImages = async (albumId: string) => {
  try {
    isLoadingAlbumImages.value = true;

    const current = albumList.value.find(album => String(album.id) === albumId);
    if (!current) {
      return;
    }

    await loadAlbumPicturesForAlbum(albumId);

    processedImages.value.clear();
  } catch (error) {
    console.error("获取相册图片列表失败:", error);
    const current = albumList.value.find(album => String(album.id) === albumId);
    if (current) {
      processedImages.value.clear();
      if (!current.images) {
        current.images = reactive<AlbumImage[]>([]);
      } else {
        current.images.splice(0, current.images.length);
      }
    }
  } finally {
    isLoadingAlbumImages.value = false;
    await nextTick();
    updatePagination();
  }
};

// 页面初始化：拉相册列表后默认第一项，图片由 watch(activeTab) 加载
onMounted(async () => {
  await getAlbumList();
});
</script>

<style scoped lang="scss">
.photo-album-container {
  position: relative;
  min-height: 100%;
  padding: 20px;
  background-color: white;
  .header-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    :deep(.el-tabs) {
      flex: 1;
      .el-tabs__header {
        margin: 0;
      }
    }
    .header-actions {
      display: flex;
      gap: 12px;
      align-items: center;
    }
    .album-tab-label {
      display: inline-flex;
      gap: 8px;
      align-items: center;
      .edit-icon {
        font-size: 14px;
        color: #909399;
        cursor: pointer;
        transition: color 0.3s;
        &:hover {
          color: #409eff;
        }
      }
    }
  }
  .content-section {
    .upload-tips {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      margin-bottom: 20px;
      font-size: 14px;
      color: #606266;
    }
    .media-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 16px;
      margin-bottom: 20px;
      .upload-item {
        position: relative;
        width: 100%;
        min-height: 200px;

        // 只隐藏已上传的列表项，保留上传按钮
        :deep(.el-upload-list__item) {
          display: none !important;
        }

        // 确保上传按钮容器正常
        :deep(.upload-box) {
          display: block !important;
          width: 100% !important;
        }

        // 确保上传组件容器正常
        :deep(.upload) {
          display: block !important;
          width: 100% !important;
        }

        // 确保上传列表容器宽度正确
        :deep(.el-upload-list--picture-card) {
          display: block !important;
          width: 100% !important;
        }

        // 确保上传按钮正常显示和可点击，覆盖组件内部的固定宽度
        :deep(.el-upload--picture-card) {
          position: relative !important;
          box-sizing: border-box !important;
          display: inline-block !important;
          width: 100% !important;
          max-width: 100% !important;
          height: 200px !important;
          pointer-events: auto !important;
          cursor: pointer !important;
        }

        // 确保上传输入框覆盖整个按钮区域
        :deep(.el-upload--picture-card .el-upload__input) {
          position: absolute !important;
          top: 0 !important;
          left: 0 !important;
          z-index: 10 !important;
          width: 100% !important;
          height: 100% !important;
          cursor: pointer !important;
          opacity: 0 !important;
        }

        // 确保上传按钮内容不阻挡点击
        :deep(.el-upload--picture-card .upload-empty) {
          position: relative !important;
          z-index: 1 !important;
          pointer-events: none !important;
        }
      }
      .media-item {
        position: relative;
        min-height: 200px;
        .media-wrapper {
          position: relative;
          width: 100%;
          height: 200px;
          overflow: hidden;
          background-color: #f0f0f0;
          border-radius: 8px;
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          .media-overlay {
            position: absolute;
            inset: 0;
            z-index: 2;
            display: flex;
            gap: 12px;
            align-items: center;
            justify-content: center;
            background-color: rgb(0 0 0 / 60%);
            opacity: 0;
            transition: opacity 0.3s;
            .el-button {
              color: white;
            }
          }
          &:hover .media-overlay {
            opacity: 1;
          }
          .cover-tag {
            position: absolute;
            top: 8px;
            right: 8px;
          }
        }
      }
    }
  }
  .empty-state {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 400px;
    .empty-text {
      font-size: 16px;
      color: #909399;
    }
  }
  .upload-tip-text {
    margin-top: 8px;
    font-size: 12px;
    color: #909399;
    text-align: center;
  }
  .dialog-footer {
    display: flex;
    gap: 12px;
    align-items: center;
    justify-content: space-between;
    .footer-left {
      display: flex;
      gap: 12px;
    }
    .footer-right {
      display: flex;
      gap: 12px;
    }
  }
}
.pagination-section {
  position: absolute;
  right: 40px;
  bottom: 20px;
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
}
</style>
