<template>
  <div
    class="book-reader"
    v-loading="loading && initialLoading"
    element-loading-text="正在加载图书..."
  >
    <div class="magazine-viewport">
      <div ref="magazine" class="magazine">
        <div
          v-for="(page, index) in processedPages"
          :key="index"
          :class="[
            'page',
            `p${index + 1}`,
            {
              hard: !page.isWide && index % 2 === 0,
              odd: !page.isWide && index % 2 !== 0,
              even: !page.isWide && index % 2 === 1,
              mobile: isMobile,
            },
          ]"
        >
          <img
            :data-page-index="index"
            :src="page.src"
            :alt="`第 ${page.page_num} 页`"
            @error="handleImageError(index)"
            :class="['page-image', { 'wide-image': page.isWide }]"
          />

          <!-- 添加小图叠加层 -->
          <div
            v-if="page.images && page.images.length > 0"
            class="small-images-overlay"
          >
            <div
              v-for="(smallImage, imgIndex) in page.images"
              :key="imgIndex"
              class="small-image-container"
              :style="{
                left: `${smallImage.position.x1 * 100}%`,
                top: `${smallImage.position.y1 * 100}%`,
                width: `${
                  (smallImage.position.x2 - smallImage.position.x1) * 100
                }%`,
                height: `${
                  (smallImage.position.y2 - smallImage.position.y1) * 100
                }%`,
              }"
              @click="handleSmallImageClick(smallImage, page.page_num)"
            ></div>
          </div>
        </div>
      </div>
      <!-- <div
        class="left-button mobile-page-button"
        @click="previousPage"
        v-if="isMobile"
      >
        <van-icon name="arrow-left" />
      </div>
      <div
        class="right-button mobile-page-button"
        @click="nextPage"
        v-if="isMobile"
      >
        <van-icon name="arrow" />
      </div> -->
    </div>

    <!-- <div v-if="showExitMessage" class="exit-message">按 ESC 键退出阅读</div> -->

    <!-- 替换为 vue-easy-lightbox 预览组件 -->
    <vue-easy-lightbox
      :visible="showViewer"
      :imgs="previewImages"
      :index="currentImageIndex"
      @hide="showViewer = false"
    />

    <!-- <div class="mobile-gesture-hint" v-if="isMobile">左右滑动切换页面</div> -->

    <!-- Replace directory modal with Element Plus dialog -->
    <GuideMobile
      ref="guideMobileRef"
      :bookmarks="bookmarks"
      @goToPage="goToPage"
    ></GuideMobile>
    <GuidePc
      ref="guidePcRef"
      :bookmarks="bookmarks"
      @goToPage="goToPage"
    ></GuidePc>
  </div>
  <div class="footer">
    <el-row :gutter="10" class="tab-bar">
      <el-col :class="['left', { isMobile }]" :span="isMobile ? 24 : 8">
        <el-tooltip content="目录" placement="top" effect="dark">
          <svg-icon name="menu" size="20" @click="showGuide"></svg-icon>
        </el-tooltip>

        <el-tooltip content="缩小" placement="top" effect="dark">
          <svg-icon
            name="zoom-in"
            size="20"
            v-if="!isMobile"
            @click="zoomOut"
          ></svg-icon>
        </el-tooltip>
        <el-tooltip content="放大" placement="top" effect="dark">
          <svg-icon
            name="zoom-out"
            size="20"
            v-if="!isMobile"
            @click="zoomIn"
          ></svg-icon>
        </el-tooltip>

        <!-- 修改音量图标部分 -->
        <el-tooltip
          :content="isMuted ? '开启音效' : '关闭音效'"
          placement="top"
          effect="dark"
        >
          <svg-icon
            :name="isMuted ? 'volume-mute' : 'volume-high'"
            size="20"
            @click="toggleMute"
          />
        </el-tooltip>
      </el-col>
      <el-col class="center" :span="8">
        <el-tooltip content="跳转到第一页" placement="top" effect="dark">
          <svg-icon name="to-first" size="30" @click="toFirst"></svg-icon>
        </el-tooltip>
        <el-tooltip content="跳转上一页" placement="top" effect="dark">
          <svg-icon name="to-left" size="22" @click="previousPage"></svg-icon>
        </el-tooltip>
        <div class="page-count" v-if="!isMobile">第{{ currentPage }}页</div>
        <el-tooltip content="跳转下一页" placement="top" effect="dark">
          <svg-icon name="to-right" size="22" @click="nextPage"></svg-icon>
        </el-tooltip>
        <el-tooltip content="跳转到最后一页" placement="top" effect="dark">
          <svg-icon name="to-end" size="30" @click="toEnd"></svg-icon>
        </el-tooltip>
      </el-col>
      <el-col class="right" :span="8">
        <!-- <svg-icon name="download" size="20"></svg-icon> -->
        <!-- <svg-icon name="fullscreen" size="20"></svg-icon> -->
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import $ from "jquery";
import "@/assets/js/turn.js"; // 直接导入执行，扩展 jQuery 对象
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from "vue";
import VueEasyLightbox from "vue-easy-lightbox";
import GuideMobile from "../GuideMobile/index.vue";
import audioFlip from "@/assets/audio/flip.mp3";
import throttle from "lodash/throttle";
const props = defineProps({
  pages: {
    type: Array,
    default: () => [],
    required: true,
  },
  bookmarks: {
    type: Array,
    default: () => [],
  },
});

const magazine = ref(null);
const loading = ref(true);
const showExitMessage = ref(false);
const zoomLevel = ref(1);
const isInitialized = ref(false);
const imageObserver = ref(null);
const loadingQueue = ref(new Set());
const maxConcurrentLoads = 3;
const imageCache = ref(new Map());
const loadingTimeouts = ref(new Map());
const isMobile = ref(false);
const touchStartX = ref(0);
const touchStartY = ref(0);

// 简化状态管理，只保留必要的状态
const preloadingPages = ref(new Set()); // 正在预加载的页面集合
const initialLoading = ref(true); // 初始加载状态

// 修改预览相关的状态
const showViewer = ref(false);
const currentImageIndex = ref(0);
const previewImages = ref([]);

// 将 processedPages 改为普通数据属性
const processedPages = ref([]);

// Add new refs for sound and directory
const pageTurnSound = ref(null);
const audioInitialized = ref(false);
const directoryImages = ref([]);
const guideMobileRef = ref(null);
const guidePcRef = ref(null);

const currentPage = ref(0);
const isMuted = ref(false); // 默认不静音

// 检测是否为移动设备
const checkMobile = () => {
  isMobile.value =
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    );
};

// 修改处理页面的函数，只处理必要的属性
const processPages = (pages) => {
  return pages.map((item, index) => ({
    src: "", // 初始不设置src
    originalIndex: index,
    page_num: item.page_num,
    images: item.images || [],
    isWide: false, // 初始设置为false
    isLoaded: false,
    url: item.page_url, // 保存原始URL
  }));
};

const loadImage = async (pageIndex) => {
  const page = processedPages.value[pageIndex];
  if (!page || page.isLoaded || preloadingPages.value.has(pageIndex)) {
    return true;
  }

  const src = page.url;
  if (imageCache.value.has(src)) {
    page.isLoaded = true;
    page.src = src;
    return true;
  }

  if (loadingQueue.value.size >= maxConcurrentLoads) {
    await new Promise((resolve) => setTimeout(resolve, 50));
    return loadImage(pageIndex);
  }

  preloadingPages.value.add(pageIndex); // 标记正在预加载
  loadingQueue.value.add(pageIndex);

  const timeoutId = setTimeout(() => {
    loadingQueue.value.delete(pageIndex);
    preloadingPages.value.delete(pageIndex);
    loadingTimeouts.value.delete(pageIndex);
  }, 5000);
  loadingTimeouts.value.set(pageIndex, timeoutId);

  try {
    const img = new Image();
    await Promise.race([
      new Promise((resolve, reject) => {
        img.onload = () => {
          clearTimeout(timeoutId);
          loadingTimeouts.value.delete(pageIndex);
          imageCache.value.set(src, true);
          page.isLoaded = true;
          page.src = src;
          resolve();
        };
        img.onerror = () => {
          clearTimeout(timeoutId);
          loadingTimeouts.value.delete(pageIndex);
          reject(new Error("Image load failed"));
        };
        img.src = src;
      }),
      new Promise((_, reject) =>
        setTimeout(() => reject(new Error("Timeout")), 3000)
      ),
    ]);
    return true;
  } catch (error) {
    // 如果加载失败，直接显示占位图
    const $img = $(magazine.value).find(`.p${pageIndex + 1} img`);
    if ($img.length) {
      $img[0].src =
        "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iI2YwZjBmMCIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTYiIGZpbGw9IiM5OTkiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj7lvIDlp4vmlbDmja7lupM8L3RleHQ+PC9zdmc+";
    }
    return false;
  } finally {
    loadingQueue.value.delete(pageIndex);
    preloadingPages.value.delete(pageIndex); // 清除预加载标记
  }
};

// 修改加载可见页面的函数，完全移除loading状态管理
const loadVisiblePages = async (currentPageNum) => {
  if (!magazine.value) return;

  const $magazine = $(magazine.value);
  const totalPages = $magazine.turn("pages");

  // 加载当前页、上一页、下一页
  const startPage = Math.max(1, currentPageNum - 1);
  const endPage = Math.min(totalPages, currentPageNum + 1);
  const highPriority = [currentPageNum, currentPageNum + 1]; // 优先加载当前和下一页

  console.log(`预加载页面: ${currentPageNum}, 范围: ${startPage}-${endPage}`);

  try {
    // 静默加载，不显示loading状态
    await Promise.allSettled(
      highPriority.map((pageIndex) => loadImage(pageIndex - 1))
    );

    // 后台加载其他页面，不阻塞UI
    Promise.allSettled(
      Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i)
        .filter((page) => !highPriority.includes(page))
        .map((pageIndex) => loadImage(pageIndex - 1))
    );
  } catch (error) {
    console.error("加载页面失败:", error);
  }
  // 完全移除finally块中的loading状态管理
};

// 修改初始化函数
const initBook = async () => {
  if (!magazine.value || !processedPages.value.length) return;

  destroyTurn();
  checkMobile();

  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;

  // 移动端使用不同的尺寸计算
  let pageWidth, pageHeight;
  if (isMobile.value) {
    // 移动端：宽度等于设备宽度减去边距
    pageWidth = viewportWidth - 20; // 左右各留10px边距
    // 高度按比例计算（假设标准比例为 4:3）
    pageHeight = (pageWidth * 4) / 3;
    // 确保高度不超过视口高度
    if (pageHeight > viewportHeight - 100) {
      // 上下各留50px边距
      pageHeight = viewportHeight - 92;
      // 重新计算宽度以保持比例
      pageWidth = (pageHeight * 3) / 4;
    }
  } else {
    // 桌面端保持原有逻辑
    pageWidth = Math.min(600, viewportWidth / 2 - 50);
    pageHeight = Math.min(800, viewportHeight - 100);
  }

  await nextTick();

  try {
    const $magazine = $(magazine.value);
    const $viewport = $(".magazine-viewport");

    $viewport.css({
      overflow: "hidden",
      position: "relative",
      width: "100%",
      height: "100%",
    });

    $magazine.children().each(function () {
      const $page = $(this);
      $page.css({
        position: "absolute",
        overflow: "hidden",
        width: pageWidth,
        height: pageHeight,
      });

      const $img = $page.find("img");
      if ($img.length) {
        $img.css({
          width: "100%",
          height: "100%",
          objectFit: "contain",
        });
      }
    });

    // 移动端使用单页显示
    $magazine.turn({
      width: isMobile.value ? pageWidth : pageWidth * 2,
      height: pageHeight,
      display: isMobile.value ? "single" : "double",
      acceleration: true,
      // 启用非corner区域翻页
      enableNonCorner: true,
      // 最大折叠距离比例 (0.1 - 1.0)
      maxFoldingDistance: 0.6,
      // 最小拖拽距离触发翻页
      minDragDistance: 30,
      gradients: true,
      elevation: 80,
      duration: isMobile.value ? 200 : 600,
      autoCenter: true,
      turnCorners: "bl,br",
      page: 1,
      when: {
        turning: (event, page) => {
          // 不阻塞翻页动画，只更新当前页码
          currentPage.value = page;
        },
        turned: (event, page) => {
          currentPage.value = page;
          // 翻页完成后异步预加载，不影响动画，不设置翻页锁
          setTimeout(() => {
            loadVisiblePages(page);
          }, 50);

          // 播放声音
          playPageTurnSound().catch(() => {});
        },
      },
    });

    isInitialized.value = true;
    // 初始化完成后关闭loading
    loading.value = false;
    initialLoading.value = false;
    await loadVisiblePages(1);
  } catch (error) {
    console.error("Turn.js initialization error:", error);
    loading.value = false;
    initialLoading.value = false;
  }
};
// 修改加载图片函数
const loadImages = async () => {
  // loading.value = true;
  try {
    await initBook();
  } catch (error) {
    console.error("加载图片失败:", error);
  } finally {
    // loading.value = false;
  }
};

// 监听 props.pages 的变化
watch(
  () => props.pages,
  (newPages) => {
    if (newPages && newPages.length > 0) {
      processedPages.value = processPages(newPages);
      loadImages();
    }
  },
  { immediate: true }
);

const destroyTurn = () => {
  if (magazine.value && isInitialized.value) {
    try {
      const $magazine = $(magazine.value);
      // 移除所有 turn.js 相关的事件和数据
      $magazine.off(".turn");
      $magazine.removeData("turn");
      isInitialized.value = false;
    } catch (error) {
      console.error("Error destroying turn.js:", error);
    }
  }
};

// 初始化 Intersection Observer

// 修改图片错误处理函数
const handleImageError = async (index) => {
  // 清除超时
  if (loadingTimeouts.value.has(index)) {
    clearTimeout(loadingTimeouts.value.get(index));
    loadingTimeouts.value.delete(index);
  }

  // 尝试重新加载
  const retryCount = 3;
  for (let i = 0; i < retryCount; i++) {
    try {
      const success = await loadImage(index);
      if (success) {
        return;
      }
    } catch (error) {
      // 忽略错误
    }
    // 递增重试延迟
    const delay = 1000 * (i + 1);
    await new Promise((resolve) => setTimeout(resolve, delay));
  }

  // 如果所有重试都失败，使用占位图
  const $img = $(magazine.value).find(`.p${index + 1} img`);
  if ($img.length) {
    $img[0].src =
      "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iI2YwZjBmMCIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTYiIGZpbGw9IiM5OTkiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj7lvIDlp4vmlbDmja7lupM8L3RleHQ+PC9zdmc+";
  }
};

// 移除节流限制，恢复正常翻页速度
const nextPage = () => {
  if (magazine.value && isInitialized.value) {
    const $magazine = $(magazine.value);
    $magazine.turn("next");
  }
};

const previousPage = () => {
  if (magazine.value && isInitialized.value) {
    const $magazine = $(magazine.value);
    $magazine.turn("previous");
  }
};

const toFirst = () => {
  const firstPage = props.pages[0].page_num;
  goToPage(firstPage);
};

const toEnd = () => {
  const endPage = props.pages[props.pages.length - 1].page_num;
  goToPage(endPage);
};

const zoomIn = () => {
  zoomLevel.value = Math.min(zoomLevel.value + 0.2, 2);
  updateZoom();
};

const zoomOut = () => {
  zoomLevel.value = Math.max(zoomLevel.value - 0.2, 0.5);
  updateZoom();
};

const updateZoom = () => {
  if (magazine.value && isInitialized.value) {
    const $magazine = $(magazine.value);
    const currentPage = $magazine.turn("page");

    // 保存当前可见页面的图片状态
    const visiblePages = [];
    const totalPages = $magazine.turn("pages");
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);

    for (let i = startPage; i <= endPage; i++) {
      const $page = $magazine.find(`.p${i}`);
      const $img = $page.find("img");
      if ($img.length) {
        visiblePages.push({
          page: i,
          src: $img[0].src,
          isLoaded: $img[0].complete,
        });
      }
    }

    // 计算新的尺寸
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    const baseWidth = Math.min(600, viewportWidth / 2 - 50);
    const baseHeight = Math.min(800, viewportHeight - 100);

    // 应用缩放
    const scaledWidth = baseWidth * zoomLevel.value;
    const scaledHeight = baseHeight * zoomLevel.value;

    // 直接更新 turn.js 尺寸
    $magazine.turn("size", scaledWidth * 2, scaledHeight);

    // 更新页面尺寸
    $magazine.children().each(function () {
      const $page = $(this);
      $page.css({
        width: scaledWidth,
        height: scaledHeight,
      });
    });

    // 恢复已加载的图片
    visiblePages.forEach((page) => {
      const $page = $magazine.find(`.p${page.page}`);
      const $img = $page.find("img");
      if ($img.length && page.isLoaded) {
        $img[0].src = page.src;
      }
    });

    // 更新视口样式
    const $viewport = $(".magazine-viewport");
    $viewport.css({
      width: "100%",
      height: "100%",
      overflow: "auto",
    });
  }
};

const handleKeyDown = (e) => {
  switch (e.key) {
    case "ArrowRight":
      nextPage();
      break;
    case "ArrowLeft":
      previousPage();
      break;
    case "Escape":
      showExitMessage.value = true;
      setTimeout(() => {
        showExitMessage.value = false;
      }, 2000);
      break;
  }
};

const handleResize = async () => {
  if (magazine.value && isInitialized.value) {
    try {
      const $magazine = $(magazine.value);
      const currentPage = $magazine.turn("page");
      const currentZoom = zoomLevel.value;

      // 保存当前可见页面的图片状态
      const visiblePages = [];
      const totalPages = $magazine.turn("pages");
      const startPage = Math.max(1, currentPage - 2);
      const endPage = Math.min(totalPages, currentPage + 2);

      for (let i = startPage; i <= endPage; i++) {
        const $page = $magazine.find(`.p${i}`);
        const $img = $page.find("img");
        if ($img.length) {
          visiblePages.push({
            page: i,
            src: $img[0].src,
            isLoaded: $img[0].complete,
          });
        }
      }

      // 计算新的尺寸
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      const baseWidth = Math.min(600, viewportWidth / 2 - 50);
      const baseHeight = Math.min(800, viewportHeight - 100);

      // 应用缩放
      const scaledWidth = baseWidth * currentZoom;
      const scaledHeight = baseHeight * currentZoom;

      // 直接更新 turn.js 尺寸
      $magazine.turn("size", scaledWidth * 2, scaledHeight);

      // 更新页面尺寸
      $magazine.children().each(function () {
        const $page = $(this);
        $page.css({
          width: scaledWidth,
          height: scaledHeight,
        });
      });

      // 恢复已加载的图片
      visiblePages.forEach((page) => {
        const $page = $magazine.find(`.p${page.page}`);
        const $img = $page.find("img");
        if ($img.length && page.isLoaded) {
          $img[0].src = page.src;
        }
      });

      // 更新视口样式
      const $viewport = $(".magazine-viewport");
      $viewport.css({
        width: "100%",
        height: "100%",
        overflow: "auto",
      });
    } catch (error) {
      console.error("Error handling resize:", error);
    }
  }
};

const initAudio = () => {
  try {
    pageTurnSound.value = new Audio(audioFlip);
    pageTurnSound.value.volume = 0.5;
    pageTurnSound.value.preload = "auto";
    pageTurnSound.value.muted = isMuted.value; // 设置初始静音状态

    pageTurnSound.value.addEventListener("canplaythrough", () => {
      audioInitialized.value = true;
    });

    pageTurnSound.value.addEventListener("error", () => {
      console.error("Audio loading failed");
    });
  } catch (error) {
    console.error("Audio initialization error:", error);
  }
};
// 添加静音切换函数
const toggleMute = () => {
  isMuted.value = !isMuted.value;
  if (pageTurnSound.value) {
    pageTurnSound.value.muted = isMuted.value;
  }

  // 如果需要本地存储静音状态，可以在这里添加
  localStorage.setItem("bookReaderMuted", isMuted.value);
};

// 添加防抖处理
let resizeTimeout;
window.addEventListener("resize", () => {
  clearTimeout(resizeTimeout);
  resizeTimeout = setTimeout(() => {
    handleResize();
  }, 250);
});

onMounted(async () => {
  // 从本地存储读取静音状态
  const savedMuted = localStorage.getItem("bookReaderMuted");
  if (savedMuted !== null) {
    isMuted.value = savedMuted === "true";
  }
  await loadImages();
  initAudio();
  window.addEventListener("keydown", handleKeyDown);
  window.addEventListener("resize", handleResize);
  // Load directory images
  loadDirectoryImages();
});

onUnmounted(() => {
  // 清除所有超时
  loadingTimeouts.value.forEach((timeoutId) => clearTimeout(timeoutId));
  loadingTimeouts.value.clear();

  // 清除所有状态
  imageCache.value.clear();
  loadingQueue.value.clear();
  preloadingPages.value.clear();

  // 重置状态
  initialLoading.value = true;

  if (imageObserver.value) {
    imageObserver.value.disconnect();
  }
  destroyTurn();
  window.removeEventListener("keydown", handleKeyDown);
  window.removeEventListener("resize", handleResize);

  // 清理resize监听器
  if (typeof window !== "undefined" && window.removeEventListener) {
    clearTimeout(resizeTimeout);
  }
});

// 修改小图点击事件处理函数
const handleSmallImageClick = (smallImage, pageNum) => {
  // 获取当前页面所有小图的URL
  const currentPage = props.pages.find((page) => page.page_num === pageNum);
  if (currentPage && currentPage.images) {
    // // 设置当前点击的图片索引
    currentImageIndex.value = currentPage.images.findIndex(
      (img) => img.url === smallImage.url
    );
    // const images = currentPage.images.map((img) => img.url);

    // showImagePreview({
    //   images,
    //   closeable: true,
    //   startPosition: currentImageIndex.value,
    // });
    previewImages.value = currentPage.images.map((img) => ({
      src: img.url,
      title: `第 ${pageNum} 页`,
    }));

    // 显示预览组件
    showViewer.value = true;
  }
};

// Add new methods for sound and directory
const playPageTurnSound = async () => {
  if (pageTurnSound.value && !isMuted.value) {
    try {
      pageTurnSound.value.currentTime = 0;
      await pageTurnSound.value.play();
    } catch (error) {
      console.log("Audio play failed:", error);
      // 可以在这里添加用户交互后解锁音频的逻辑
    }
  }
};

const generateThumbnailUrl = (url) => {
  return url.replace(/(\.[^.]+)$/, "_low$1");
};

const loadDirectoryImages = () => {
  directoryImages.value = props.pages.map((page) => ({
    src: generateThumbnailUrl(page.page_url),
    pageNum: page.page_num,
  }));
};

const goToPage = (pageNum) => {
  if (magazine.value && isInitialized.value) {
    const $magazine = $(magazine.value);
    $magazine.turn("page", pageNum);
  }
};

const showGuide = () => {
  if (isMobile.value) {
    guideMobileRef.value.show();
  } else {
    guidePcRef.value.show();
  }
};
</script>

<style scoped lang="scss">
// .page {
//   width: 100%;
//   height: 100%;
//   background-color: white !important; // 确保翻页时有白色背景
//   overflow: hidden;
//   backface-visibility: visible; // 确保背面可见
//   img {
//     width: 100%;
//     height: 100%;
//     object-fit: contain;
//   }
// }

.book-reader-container {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: white; // 主容器背景

  .magazine-viewport {
    position: relative;
    overflow: hidden;
    background-color: white; // 视口背景
    contain: strict; // 启用CSS Contain隔离布局
    .magazine {
      background-color: white; // 书本背景
    }
  }
}

.book-reader {
  width: 100vw;
  height: calc(100vh - 92px);
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #333;
  position: relative;
  background-image: url("@/assets/images/bg4.png");
  background-size: 100% 100%;
  touch-action: pan-y pinch-zoom;
}

.magazine-viewport {
  width: 100vw;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden !important;
  -webkit-overflow-scrolling: touch;
}

.magazine {
  position: relative;
  transform-origin: center center;
  background-color: #fff;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
  will-change: transform;
  visibility: visible !important;
  // backface-visibility: hidden;
  transform-style: preserve-3d;
}

.page {
  background-color: white;
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  user-select: none;
  visibility: visible !important;
  backface-visibility: visible;
  transform-style: preserve-3d;
  transform: translate3d(0, 0, 0);
  box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.05);
}

/* 缩放状态样式 */
.magazine.zoomed {
  cursor: move;
}

.magazine.zoomed .page {
  pointer-events: none;
}

/* 确保 turn.js 不会修改视口样式 */
.magazine-viewport.turn-page-wrapper {
  overflow: hidden !important;
  &:last-child {
    background-color: #fff;
  }
}

.small-images-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  /* 允许点击穿透到下层 */
}

.small-image-container {
  position: absolute;
  cursor: pointer;
  pointer-events: auto;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.small-image-container:hover {
  border-color: rgba(255, 255, 255, 0.5);
  box-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
}

.small-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  pointer-events: none;
  /* 防止图片本身接收点击事件 */
}

.mobile-page-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 50%;
  background-color: #444;
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}
.left-button {
  left: 4px;
}

.right-button {
  right: 4px;
}

.footer {
  background-color: #444;
  padding: 0 20px;
  height: 46px;
  .tab-bar {
    background-color: #444;
    color: #ccc;
    width: 100%;
    height: 100%;
    .svg-icon {
      cursor: pointer;
    }
    .left,
    .right,
    .center {
      display: flex;
      align-items: center;
      height: 100%;
    }
    .center {
      justify-content: center;
      .svg-icon {
        margin: 20px;
      }
    }
    .left {
      justify-content: flex-start;
      .svg-icon {
        margin-right: 20px;
      }
    }
    .isMobile {
      justify-content: center;
    }
    .right {
      justify-content: flex-end !important;
      .svg-icon {
        margin-right: 20px;
      }
    }
  }
}
</style>
