<template>
  <div
    class="book-reader"
    v-loading="(loading && initialLoading) || pdfLoading"
    :element-loading-text="props.isPdf ? '正在加载PDF...' : '正在加载图书...'"
  >
    <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,
            },
          ]"
        >
          <!-- PDF页面由PdfViewer动态渲染，不需要静态元素 -->
          <!-- 图片页面使用img -->
          <img
            v-if="!page.isPdf"
            :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-row>
  </div>
</template>

<script setup>
import $ from "jquery";
import "@/assets/js/turn.js"; // 直接导入执行，扩展 jQuery 对象
import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  computed,
  toRaw,
} 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 PDF_RATIO = 1.414; // PDF标准比例 1:√2 (高度是宽度的1.414倍)

// 响应式变量
const baseWidth = ref(0);
const baseHeight = ref(0);

// 封装的通用函数
// 计算页面尺寸
const calculatePageDimensions = (viewportWidth, viewportHeight, zoom = 1.0) => {
  try {
    // 计算基于宽度的最大尺寸
    const maxWidth = viewportWidth / 2 - 50;
    const maxHeightByWidth = maxWidth * PDF_RATIO; // 高度 = 宽度 × 1.414
    
    // 计算基于高度的最大尺寸
    const maxHeight = viewportHeight - 100;
    const maxWidthByHeight = maxHeight / PDF_RATIO; // 宽度 = 高度 ÷ 1.414
    
    let baseWidth, baseHeight;
    
    // 选择能撑满一边的方案
    if (maxHeightByWidth <= maxHeight) {
      // 宽度能撑满，高度也满足
      baseWidth = maxWidth;
      baseHeight = maxHeightByWidth;
    } else {
      // 高度能撑满，宽度也满足
      baseWidth = maxWidthByHeight;
      baseHeight = maxHeight;
    }
    
    // 确保不超过移动端的限制
    if (isMobile.value) {
      baseWidth = Math.min(baseWidth, viewportWidth - 20);
      baseHeight = baseWidth * PDF_RATIO; // 高度 = 宽度 × 1.414
    }

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

    return {
      baseWidth,
      baseHeight,
      scaledWidth,
      scaledHeight
    };
  } catch (error) {
    console.error("Error calculating page dimensions:", error);
    return null;
  }
};

// 更新页面尺寸
const updatePageDimensions = (dimensions, $magazine) => {
  // 直接更新 turn.js 尺寸

  if (isMobile.value) { 
    $magazine.turn("size", dimensions.scaledWidth, dimensions.scaledHeight);
  } else {
    $magazine.turn("size", dimensions.scaledWidth * 2, dimensions.scaledHeight);
  }


  // 逐页强制刷新 flip wrapper
  const data = $magazine.data();
  for (let page in data.pages) {
    if (data.pages.hasOwnProperty(page)) {
      data.pages[page].flip('resize', true);
    }
  }

  // 更新 z-index 和交互区域
  $magazine.turn('update');
};

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

// 恢复已加载的图片
const restoreLoadedImages = (visiblePages, $magazine) => {
  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;
    }
  });
};

// 新增：封装 PDF viewport 尺寸计算
const calculatePdfViewportScale = (pdfPage, containerWidth, containerHeight) => {
  try {

    const originalViewport = pdfPage.getViewport({ scale: 1.0 });
    const viewportWidth = originalViewport.viewBox[2];
    const viewportHeight = originalViewport.viewBox[3];
    
    const scaleX = containerWidth / viewportWidth;
    const scaleY = containerHeight / viewportHeight;
    const scale = Math.min(scaleX, scaleY); // 保持比例
    
    // 验证 scale 值
    if (isNaN(scale) || scale <= 0) {
      return null;
    }
    
    // 计算补偿后的 scale
    const cssUnits = pdfjsViewer.CSS_UNITS || (96.0 / 72.0);
    const compensatedScale = scale / cssUnits;
    
    return {
      scale,
      compensatedScale,
      viewportWidth,
      viewportHeight
    };
  } catch (error) {
    console.error("计算 PDF viewport scale 失败:", error);
    return null;
  }
};

// 新增：封装获取可见页面索引
const getVisiblePageIndexes = (currentPage, totalPages, isMobile) => {
  const visiblePages = [];
  if (isMobile) {
    // 移动端只显示当前页
    visiblePages.push(currentPage - 1);
  } else {
    // 桌面端显示当前页和下一页
    visiblePages.push(currentPage - 1);
    if (currentPage < totalPages) {
      visiblePages.push(currentPage);
    }
  }
  return visiblePages;
};

// 新增：封装获取可见页面信息（用于图片恢复）
const getVisiblePageInfo = ($magazine, processedPages) => {
  if (!processedPages.value.length) return [];
  
  const currentPage = $magazine.turn("page");
  const visibleIndexes = getVisiblePageIndexes(currentPage, processedPages.value.length, isMobile.value);
  
  return visibleIndexes.map(index => ({
    page: index + 1,
    isLoaded: processedPages.value[index]?.isLoaded || false
  }));
};

// 新增：封装创建 PDFPageView
const createPdfPageView = (pageDiv, pageNum, compensatedScale, newViewport, eventBus) => {
  if (!pdfjsViewer) {
    throw new Error('PDF.js viewer not loaded');
  }
  
  return new pdfjsViewer.PDFPageView({
    container: pageDiv,
    id: pageNum - 1,
    scale: compensatedScale,
    defaultViewport: newViewport,
    eventBus: toRaw(eventBus.value),
    textLayerMode: textLayerEnabled.value ? 1 : 0,
    annotationMode: 0,
    renderInteractiveForms: false,
    renderer: svgRendererEnabled.value ? "svg" : "canvas",
    enableXfa: false,
    l10n: null,
    textLayerFactory: new pdfjsViewer.DefaultTextLayerFactory(),
    useOnlyCssZoom: false
  });
};

// 新增：封装 PDF 页面容器尺寸等待逻辑
const waitForContainerSize = async (pageContainer, pageNum) => {
  let containerWidth = pageContainer.clientWidth;
  let containerHeight = pageContainer.clientHeight;

  // 如果容器尺寸为0，等待turn.js完全初始化
  if (containerWidth === 0 || containerHeight === 0) {
    console.log(`页面${pageNum}容器尺寸为0，等待turn.js初始化...`);
    
    await new Promise((resolve) => {
      const checkSize = () => {
        const width = pageContainer.clientWidth;
        const height = pageContainer.clientHeight;
        if (width > 0 && height > 0) {
          containerWidth = width;
          containerHeight = height;
          resolve();
        } else {
          setTimeout(checkSize, 50);
        }
      };
      checkSize();
    });
  }

  return { containerWidth, containerHeight };
};

// PDF.js 相关变量声明
let pdfjsLib = null;
let pdfjsViewer = null;

// 动态加载PDF.js
const loadPdfJs = async () => {
  try {
    // 检查全局变量是否已经存在（通过script标签加载）
    if (window.pdfjsLib && window.pdfjsViewer) {
      pdfjsLib = window.pdfjsLib;
      pdfjsViewer = window.pdfjsViewer;
      console.log('PDF.js already loaded from script tags');
      return;
    }
    
    // 如果全局变量不存在，则动态创建script标签加载
    await loadScript('/pdfjs-dist/build/pdf.js');
    await loadScript('/pdfjs-dist/web/pdf_viewer.js');
    
    // 等待一小段时间确保脚本加载完成
    await new Promise(resolve => setTimeout(resolve, 100));
    
    // 从全局变量获取
    if (window.pdfjsLib && window.pdfjsViewer) {
      pdfjsLib = window.pdfjsLib;
      pdfjsViewer = window.pdfjsViewer;
      
      // 设置PDF.js的worker路径
      // if (pdfjsLib.GlobalWorkerOptions) {
      //   pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdfjs-dist/web/pdf.worker.js';
      // }
      console.log('PDF.js loaded successfully via script tags');
    } else {
      throw new Error('PDF.js failed to load');
    }
  } catch (error) {
    console.error('Failed to load PDF.js:', error);
  }
};

// 动态加载script标签的辅助函数
const loadScript = (src) => {
  return new Promise((resolve, reject) => {
    // 检查是否已经加载过
    if (document.querySelector(`script[src="${src}"]`)) {
      resolve();
      return;
    }
    
    const script = document.createElement('script');
    script.src = src;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
};

const props = defineProps({
  pages: {
    type: Array,
    default: () => [],
    required: true,
  },
  bookmarks: {
    type: Array,
    default: () => [],
  },
  // 新增PDF相关属性
  pdfUrl: {
    type: String,
    default: "",
  },
  isPdf: {
    type: Boolean,
    default: false,
  },
  enableTextLayer: {
    type: Boolean,
    default: true,
  },
  enableSvgRenderer: {
    type: Boolean,
    default: false,
  },

});

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([]);

// PDF相关状态
const pdfDocument = ref(null);
const totalPdfPages = ref(0);
const pdfLoading = ref(false);
const textLayerEnabled = ref(props.enableTextLayer); // 文字层开关状态
// const textLayerEnabled = ref(false); // 文字层开关状态

// SVG渲染器开关状态
const svgRendererEnabled = ref(
  localStorage.getItem("bookReaderSvgRenderer") === "true" || props.enableSvgRenderer
);

// 文本层可见性状态（用于调试）
const textLayerVisible = ref(false);
const renderedPages = ref(new Set()); // 跟踪已渲染的页面
const pdfInitialized = ref(false); // 跟踪PDF是否已完成初始化渲染

// PdfViewer相关状态
const pdfViewerInstances = ref(new Map()); // 存储每个页面的PdfViewer实例
const eventBus = ref(null); // 事件总线
const pdfLinkService = ref(null); // PDF链接服务

// 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
  }));
};

// 处理PDF页面
const processPdfPages = (totalPages) => {
  return Array.from({ length: totalPages }, (_, index) => ({
    src: "",
    originalIndex: index,
    page_num: index + 1,
    images: [],
    isWide: false,
    isLoaded: false,
    url: "", // PDF页面不需要URL
    isPdf: true,
    pageIndex: index,
  }));
};

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;

  // 使用processedPages的长度而不是turn.js的pages值
  const totalPages = processedPages.value.length;

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

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

  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状态管理
};

// 渲染可见的PDF页面
const renderVisiblePdfPages = async (currentPageNum) => {
  if (!magazine.value || !pdfDocument.value) return;

  // 避免在PDF加载过程中重复渲染
  if (pdfLoading.value) {
    console.log(`PDF正在加载中，跳过渲染页面: ${currentPageNum}`);
    return;
  }

  // 使用processedPages的长度而不是turn.js的pages值，因为turn.js可能还没有完全初始化
  const totalPages = processedPages.value.length;
  
  // 渲染当前页、上一页、下一页
  const startPage = Math.max(1, currentPageNum - 1);
  const endPage = Math.min(totalPages, currentPageNum + 1);
  const highPriority = [currentPageNum, currentPageNum + 1]; // 优先渲染当前和下一页

  console.log(`渲染PDF页面: ${currentPageNum}, 范围: ${startPage}-${endPage}, 总页数: ${totalPages}`);

  try {
    console.log(`开始渲染高优先级页面: ${highPriority.join(", ")}`);
    // 优先渲染高优先级页面
    await Promise.allSettled(
      highPriority.map((pageIndex) => renderPdfPage(pageIndex - 1))
    );

    // 后台渲染其他页面，不阻塞UI
    const otherPages = Array.from(
      { length: endPage - startPage + 1 },
      (_, i) => startPage + i
    ).filter((page) => !highPriority.includes(page));

    if (otherPages.length > 0) {
      console.log(`后台渲染其他页面: ${otherPages.join(", ")}`);
      Promise.allSettled(
        otherPages.map((pageIndex) => renderPdfPage(pageIndex - 1))
      );
    }
  } catch (error) {
    console.error("渲染PDF页面失败:", error);
  }
};

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

  destroyTurn();
  checkMobile();

  // 确保DOM中有正确数量的页面元素
  const $magazine = $(magazine.value);
  const expectedPages = processedPages.value.length;
  const currentPages = $magazine.children().length;
  
  console.log(`初始化turn.js: 期望页面数=${expectedPages}, 当前DOM页面数=${currentPages}`);
  
  // 如果DOM中的页面数量不正确，重新创建页面元素
  if (currentPages !== expectedPages) {
    console.log(`页面数量不匹配，重新创建页面元素`);
    $magazine.empty();
    
    // 为每个页面创建DOM元素
    processedPages.value.forEach((page, index) => {
      const pageDiv = document.createElement('div');
      pageDiv.className = `page p${index + 1}`;
      pageDiv.setAttribute('data-page-index', index);
      pageDiv.setAttribute('data-page-num', page.page_num);
      
      // 如果是PDF页面，添加特殊标识
      if (page.isPdf) {
        pageDiv.setAttribute('data-is-pdf', 'true');
      }
      
      $magazine.append(pageDiv);
    });
    
    console.log(`重新创建了 ${processedPages.value.length} 个页面元素`);
    
    // 等待DOM更新完成
    await nextTick();
  }

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

  // 使用封装的函数计算页面尺寸
  const dimensions = calculatePageDimensions(viewportWidth, viewportHeight, 1.0);
  if (!dimensions) {
    console.error("计算页面尺寸失败");
    return;
  }

  // 更新响应式变量
  baseWidth.value = dimensions.baseWidth;
  baseHeight.value = dimensions.baseHeight;

  const pageWidth = dimensions.baseWidth;
  const pageHeight = dimensions.baseHeight;
  
  // 添加调试信息
  console.log(`视口尺寸: ${viewportWidth}x${viewportHeight}`);
  console.log(`计算出的页面尺寸: ${pageWidth}x${pageHeight}, 比例: ${(pageWidth/pageHeight).toFixed(3)}`);
  console.log(`PDF标准比例: ${PDF_RATIO}, 实际比例: ${(pageWidth/pageHeight).toFixed(3)}`);

  await nextTick();

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

    $magazine.children().each(function (index) {
      const $page = $(this);
      const pageIndex = index;
      const pageData = processedPages.value[pageIndex];

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

      // 确保PDF页面容器有正确的尺寸
      if ($page.find("img").length === 0 && !props.isPdf) {
        // 这是非PDF页面，设置容器尺寸
        $page.css({
          width: pageWidth,
          height: pageHeight,
          // 移除 minWidth 和 minHeight，避免影响边缘检测
          minWidth: pageWidth,
          minHeight: pageHeight,
        });
      }
    });

    // 移动端使用单页显示
    console.log(`turn.js初始化参数: 宽度=${isMobile.value ? pageWidth : pageWidth * 2}, 高度=${pageHeight}`);
    $magazine.turn({
      width: isMobile.value ? pageWidth : pageWidth * 2,
      height: pageHeight,
      display: isMobile.value ? "single" : "double",
      acceleration: true,
      // 启用非corner区域翻页
      enableNonCorner: false,
      // 最大折叠距离比例 (0.1 - 1.0)
      maxFoldingDistance: 2,
      // 最小拖拽距离触发翻页
      minDragDistance: 20,
      gradients: true,
      elevation: 80,
      duration: isMobile.value ? 200 : 400,
      autoCenter: true,
      turnCorners: "bl,br",
      page: 1,
      when: {
        turning: (event, page) => {
          // 不阻塞翻页动画，只更新当前页码
          currentPage.value = page;
        },
        turned: (event, page) => {
          currentPage.value = page;
          console.log(`turn.js翻页到第${page}页`);

          // 翻页完成后异步预加载，不影响动画，不设置翻页锁
          setTimeout(() => {
            if (props.isPdf && pdfDocument.value) {
              // 避免在初始化时重复渲染
              if (
                isInitialized.value &&
                !pdfLoading.value &&
                pdfInitialized.value
              ) {
                console.log(`开始渲染第${page}页的PDF内容`);
                renderVisiblePdfPages(page);
              }
            } else {
              loadVisiblePages(page);
            }

            // 调试：检查页面状态
            // setTimeout(() => debugPageStatus(), 100);
          }, 50);

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

    isInitialized.value = true;
    // 初始化完成后关闭loading
    loading.value = false;
    initialLoading.value = false;

    // 确认turn.js事件绑定状态
    console.log('turn.js初始化完成，事件绑定状态:');
    console.log('- turning事件:', $magazine.data('turn')?.when?.turning ? '已绑定' : '未绑定');
    console.log('- turned事件:', $magazine.data('turn')?.when?.turned ? '已绑定' : '未绑定');
    console.log('- 当前页码:', $magazine.turn("page"));

    // 只处理图片页面，PDF页面在loadPdf中处理
    if (!props.isPdf) {
      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 {
    // 只处理图片页面，不初始化turn.js（PDF模式下已经初始化）
    if (!props.isPdf) {
      await initBook();
    }
  } catch (error) {
    console.error("加载图片失败:", error);
  } finally {
    // loading.value = false;
  }
};

// 加载PDF
const loadPdf = async () => {
  if (!props.pdfUrl) {
    console.error("PDF URL 未提供");
    return;
  }

  // 防止重复加载
  if (pdfLoading.value) {
    console.log("PDF 正在加载中，跳过重复加载");
    return;
  }
  
  if (pdfDocument.value && pdfInitialized.value) {
    console.log("PDF 已经加载并初始化完成，跳过重复加载");
    return;
  }

  try {
    pdfLoading.value = true;
    console.log("开始加载PDF:", props.pdfUrl);

    // 加载PDF文档
    if (!pdfjsLib) {
      throw new Error('PDF.js not loaded');
    }
    const loadingTask = pdfjsLib.getDocument(props.pdfUrl);
    const rawPdfDocument = await loadingTask.promise;
    pdfDocument.value = rawPdfDocument;
    totalPdfPages.value = rawPdfDocument.numPages;

    console.log('pdfjsViewer exists:', !!pdfjsViewer);
    console.log('DefaultTextLayerFactory exists:', !!pdfjsViewer.DefaultTextLayerFactory);

    // 设置PDF链接服务
    if (pdfLinkService.value) {
      pdfLinkService.value.setDocument(rawPdfDocument);
    }

    console.log("PDF加载成功，总页数:", totalPdfPages.value);

    // 处理PDF页面
    processedPages.value = processPdfPages(totalPdfPages.value);

    // 清除之前的渲染状态
    renderedPages.value.clear();
    pdfViewerInstances.value.clear(); // 清除之前的页面视图实例
    pdfInitialized.value = false; // 重置PDF初始化状态

    // 等待Vue响应式更新完成
    await nextTick();
    
    // 初始化turn.js
    await initBook();

    // 先关闭loading状态，再渲染第一页PDF
    pdfLoading.value = false;

    // 等待turn.js完全初始化完成
    await new Promise((resolve) => setTimeout(resolve, 200));

    // 渲染第一页PDF
    await renderVisiblePdfPages(1);

    // 标记PDF已完成初始化渲染
    pdfInitialized.value = true;

    // 等待一小段时间，确保turn.js事件处理完成
    await new Promise((resolve) => setTimeout(resolve, 100));

    // 确认PDF模式下的turn.js事件绑定状态
    if (magazine.value) {
      const $magazine = $(magazine.value);
      console.log('PDF加载完成，turn.js事件绑定状态:');
      console.log('- turning事件:', $magazine.data('turn')?.when?.turning ? '已绑定' : '未绑定');
      console.log('- turned事件:', $magazine.data('turn')?.when?.turned ? '已绑定' : '未绑定');
      console.log('- 当前页码:', $magazine.turn("page"));
    }

    console.log("PDF渲染完成");
  } catch (error) {
    console.error("PDF加载失败:", error);
    pdfLoading.value = false;
  }
};

// 监听 props.pages 的变化
watch(
  () => props.pages,
  (newPages, oldPages) => {
    // 避免在组件初始化时重复加载
    if (newPages && newPages.length > 0 && !props.isPdf && newPages !== oldPages) {
      processedPages.value = processPages(newPages);
      loadImages();
    }
  },
  { immediate: true }
);

// 监听PDF URL的变化
watch(
  () => props.pdfUrl,
  async (newUrl, oldUrl) => {
    // 避免在组件初始化时重复加载
    // 只有在URL真正变化且不是从undefined到有值时才重新加载
    if (newUrl && props.isPdf && oldUrl && newUrl !== oldUrl) {
      console.log("PDF URL 变化，重新加载:", newUrl);
      await loadPdf();
    }
  }
);

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

// 渲染单个PDF页面 - 使用PdfViewer的PDFPageView
const renderPdfPage = async (pageIndex, forceCheck = true) => {
  if (!pdfDocument.value || !magazine.value) return;

  let pageNum = pageIndex + 1;

  const pageInfo = getPageInfoByPageNum(pageNum);
  // 检查页面是否已经渲染过
  if (renderedPages.value.has(pageIndex)) {
    if (forceCheck) {
     
      if (!pageInfo) {
        console.warn(`页面${pageNum}信息获取失败，跳过scale检查`);
        return;
      }
      
      const { scaleInfo } = pageInfo;
      console.log(`页面 ${pageNum} 已经渲染过，但需要检查scale是否需要调整`);
      // 在forceCheck模式下，检查已渲染页面的scale
      await checkAndUpdatePdfPageScale(pageIndex);
      return;
    } else {
      console.log(`页面 ${pageNum} 已经渲染过，跳过`);
      return;
    }
  }

  console.log(`开始渲染PDF页面 ${pageNum}，使用PdfViewer`);

  
  try {
    // 获取页面容器

    const pageContainer = magazine.value.querySelector(`.p${pageNum}`);
    if (!pageContainer) {
      console.warn(`Page container not found for page ${pageNum}`);
      return;
    }

    // 这里是为了读取页面尺寸，这个比较准
    let pageWrapper = magazine.value.querySelector(`.turn-page-wrapper[page="${pageNum}"]`);
    if (!pageWrapper) {
      console.warn(`Page wrapper not found for page ${pageNum}`);
      return;
    }

    // 清理容器内容
    pageContainer.innerHTML = '';

    // 创建页面div元素
    // todo 这里可能能够优化一下
    const pageDiv = document.createElement('div');
    pageDiv.className = 'pdfViewer';
    pageDiv.setAttribute('data-page-number', pageNum);
    
    // 将页面div添加到容器中
    pageContainer.appendChild(pageDiv);

    // 等待DOM更新完成
    await nextTick();

    const containerWidth = pageWrapper.clientWidth;
    const containerHeight = pageWrapper.clientHeight;

    // 使用封装的函数等待容器尺寸
    // const { containerWidth, containerHeight } = await waitForContainerSize(pageContainer, pageNum);
    // console.log(`页面${pageNum}容器尺寸: ${containerWidth}x${containerHeight}`);

    // 创建PDF页面视图
    const rawPdfDocument = toRaw(pdfDocument.value);
    const pdfPage = await rawPdfDocument.getPage(pageNum);

    // 使用封装的函数计算缩放比例
    const scaleInfo = calculatePdfViewportScale(pdfPage, containerWidth, containerHeight);
    if (!scaleInfo) {
      console.error(`页面${pageNum} scale 计算失败`);
      return;
    }

    // 使用补偿后的 scale 创建 viewport
    const newViewport = pdfPage.getViewport(scaleInfo.compensatedScale);

    // 使用封装的函数创建 PDFPageView
    const pageView = createPdfPageView(pageDiv, pageNum, scaleInfo.compensatedScale, newViewport, eventBus);

    // 设置PDF页面
    pageView.setPdfPage(pdfPage);

    // 存储页面视图实例
    pdfViewerInstances.value.set(pageIndex, pageView);

    // 渲染页面
    await pageView.draw();

    // 标记页面已渲染
    renderedPages.value.add(pageIndex);


    // 验证渲染结果
    const canvas = pageDiv.querySelector('canvas');
    const svg = pageDiv.querySelector('svg');
    const renderElement = canvas || svg;
    
    if (renderElement) {
      const rect = renderElement.getBoundingClientRect();
      const elementStyle = window.getComputedStyle(renderElement);
      const containerStyle = window.getComputedStyle(pageDiv);
      
      console.log(
        `PDF页面 ${pageNum} 渲染完成 (${renderElement.tagName})，尺寸: ${rect.width}x${rect.height}, 容器尺寸: ${containerWidth}x${containerHeight}`
      );
      
      if (canvas) {
        console.log(`Canvas CSS尺寸: ${elementStyle.width}x${elementStyle.height}, 实际尺寸: ${canvas.width}x${canvas.height}`);
      
      }
    }

    // 标记页面已加载
    if (processedPages.value[pageIndex]) {
      processedPages.value[pageIndex].isLoaded = true;
    }

  } catch (error) {
    console.error(`渲染PDF页面 ${pageNum} 失败:`, error);
  }
};

// 检查并更新PDF页面的scale
const checkAndUpdatePdfPageScale = async (pageIndex) => {
  if (!pdfViewerInstances.value.has(pageIndex)) return false;

  const pageNum = pageIndex + 1;
  const pageInfo = getPageInfoByPageNum(pageNum);
  if (!pageInfo) {
    console.warn(`页面${pageIndex + 1}信息获取失败，跳过scale检查`);
    return false;
  }
  
  const { pageContainer, pageView, scaleInfo } = pageInfo;

  const newScale = scaleInfo.compensatedScale;

  try {
    // 获取当前scale值
    let currentScale = newScale; // 默认值
    
    console.log(`before pageView: ${pageView}`);
    if (pageView.viewport && typeof pageView.viewport.scale === 'number') {
      currentScale = pageView.viewport.scale;
      console.log(`从pageView.viewport.scale获取当前scale: ${currentScale}`);
    } else {
      console.warn(`页面${pageNum} viewport.scale无效，使用新计算的scale`);
    }
    
    const scaleDifference = Math.abs(currentScale - newScale);
    const scaleThreshold = 0.01; // 允许的scale差异阈值

    console.log(`页面${pageNum} scale检查: 当前=${currentScale}, 新计算=${newScale}, 差异=${scaleDifference}, 阈值=${scaleThreshold}`);

    if (scaleDifference > scaleThreshold) {
      console.log(`页面${pageNum} scale不一致，需要重新创建PDFPageView，差异: ${scaleDifference}`);
      
      // 销毁旧的PDFPageView实例
      if (pageView && typeof pageView.destroy === 'function') {
        pageView.destroy();
      }
      
      // 清除渲染状态
      renderedPages.value.delete(pageIndex);
      pdfViewerInstances.value.delete(pageIndex);

      // 找到原来的pdfViewer div并清空内容
      const existingPdfDiv = pageContainer.querySelector(`.pdfViewer[data-page-number="${pageNum}"]`);
      if (existingPdfDiv) {
        // 直接清空现有div的内容，而不是重新创建
        existingPdfDiv.innerHTML = '';
        console.log(`找到现有pdfViewer div (页面${pageNum})，已清空内容`);
      } else {
        console.warn(`未找到页面${pageNum}的pdfViewer div，创建新的`);
        // 如果没有找到，才创建新的
        const pageDiv = document.createElement('div');
        pageDiv.className = 'pdfViewer';
        pageDiv.setAttribute('data-page-number', pageNum);
        pageContainer.appendChild(pageDiv);
      }

      // 等待DOM更新完成
      await nextTick();

      // 获取PDF页面和视口
      const rawPdfDocument = toRaw(pdfDocument.value);
      const pdfPage = await rawPdfDocument.getPage(pageNum);

      // 获取新的容器尺寸
      const containerWidth = pageContainer.clientWidth;
      const containerHeight = pageContainer.clientHeight;

      // 使用封装的函数计算缩放比例
      const scaleInfo = calculatePdfViewportScale(pdfPage, containerWidth, containerHeight);
      if (!scaleInfo) {
        console.error(`页面${pageNum} scale检查时重新计算scale失败`);
        return false;
      }

      // 使用补偿后的 scale 创建 viewport
      const newViewport = pdfPage.getViewport(scaleInfo.compensatedScale);

      // 使用现有的或新创建的div
      const targetDiv = existingPdfDiv || pageContainer.querySelector('.pdfViewer');

      // 使用封装的函数创建新的 PDFPageView
      const newPageView = createPdfPageView(targetDiv, pageNum, scaleInfo.compensatedScale, newViewport, eventBus);

      // 设置PDF页面
      newPageView.setPdfPage(pdfPage);

      // 存储新的页面视图实例
      pdfViewerInstances.value.set(pageIndex, newPageView);

      // 渲染页面
      await newPageView.draw();

      // 重新标记页面已渲染
      renderedPages.value.add(pageIndex);
      
      console.log(`页面${pageNum} PDFPageView重新创建完成，新scale: ${scaleInfo.compensatedScale}`);
      return true;
    } else {
      console.log(`页面${pageNum} scale一致，无需刷新`);
      return false;
    }

  } catch (error) {
    console.error(`检查页面${pageNum} scale失败:`, error);
    return false;
  }
};

const getPageInfoByPageNum = (pageNum) => {
  try {
    // 首先尝试查找翻页容器，这个容器时动态计算的
    let pageContainer = magazine.value.querySelector(`.turn-page-wrapper[page="${pageNum}"]`);
    
    // 检查容器尺寸
    const clientWidth = pageContainer.clientWidth;
    const clientHeight = pageContainer.clientHeight;
    
    if (clientWidth === 0 || clientHeight === 0) {
      console.warn(`页面${pageNum}容器尺寸为0: ${clientWidth}x${clientHeight}`);
      return null;
    }

    // 获取页面视图实例
    const pageIndex = pageNum - 1;
    const pageView = pdfViewerInstances.value.get(pageIndex);
    if (!pageView) {
      console.warn(`页面${pageNum}的PDFPageView实例未找到`);
      return null;
    }

    // 获取PDF页面对象
    const pdfPage = pageView.pdfPage;
    if (!pdfPage) {
      console.warn(`页面${pageNum}的PDF页面对象未找到`);
      return null;
    }

    // 计算缩放比例
    const scaleInfo = calculatePdfViewportScale(pdfPage, clientWidth, clientHeight);
    if (!scaleInfo) {
      console.warn(`页面${pageNum} scale计算失败`);
      return null;
    }

    return {  
      pageContainer,
      pageView,
      scaleInfo
    };
  } catch (error) {
    console.error(`获取页面${pageNum}信息时出错:`, error);
    return null;
  }
}

// 重新调整PDF页面尺寸
const resizePdfPage = async (pageIndex) => {
  if (!pdfViewerInstances.value.has(pageIndex)) return;

  const pageNum = pageIndex + 1;

  try {

    // 使用通用的scale检查函数
    await checkAndUpdatePdfPageScale(pageIndex);

    console.log(`页面${pageNum} resize 完成`);

  } catch (error) {
    console.error(`调整页面${pageNum}尺寸失败:`, error);
  }
};

// 批量重新调整所有可见PDF页面尺寸
const resizeVisiblePdfPages = async () => {
  if (!magazine.value || !isInitialized.value) return;

  const $magazine = $(magazine.value);
  if (!$magazine.length || !$magazine.turn) return;

  try {
    const currentPage = $magazine.turn("page");
    const totalPages = processedPages.value.length;
    
    // 使用封装的函数获取可见页面索引
    const visiblePages = getVisiblePageIndexes(currentPage, totalPages, isMobile.value);

    console.log(`开始检查可见页面: ${visiblePages.map(i => i + 1).join(', ')}`);

    // 对所有可见页面进行检查和调整
    for (const pageIndex of visiblePages) {
      if (renderedPages.value.has(pageIndex)) {
        // 已渲染的页面，检查scale是否需要调整
        console.log(`检查已渲染页面 ${pageIndex + 1} 的scale`);
        await resizePdfPage(pageIndex); // 使用resizePdfPage来检查已渲染页面的scale
      } else {
        // 未渲染的页面，重新调整尺寸
        console.log(`调整未渲染页面 ${pageIndex + 1} 的尺寸`);
        await resizePdfPage(pageIndex);
      }
    }

    console.log('所有可见 PDF 页面 resize 完成');

  } catch (error) {
    console.error("重新调整PDF页面尺寸失败:", error);
  }
};

// 修改图片错误处理函数
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;
};

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 updateZoomCommon = async (isResize = false) => {

  if (!magazine.value || !isInitialized.value) return;

  const $magazine = $(magazine.value);
  if (!$magazine.length) return;

  try {
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    
    const dimensions = calculatePageDimensions(viewportWidth, viewportHeight, zoomLevel.value);
    if (!dimensions) return;

    baseWidth.value = dimensions.baseWidth;
    baseHeight.value = dimensions.baseHeight;

    updatePageDimensions(dimensions, $magazine);

    
    // 等待DOM更新完成后再处理PDF页面
    await nextTick();
    
    
    // 使用封装的函数获取可见页面信息
    // if (processedPages.value.length > 0) {
    //   const visiblePages = getVisiblePageInfo($magazine, processedPages);
    //   restoreLoadedImages(visiblePages, $magazine);
    // }

    // 处理PDF页面缩放 - 在magazine尺寸更新后重新计算scale
    if (props.isPdf && pdfInitialized.value) {
        await resizeVisiblePdfPages();
    }

    // updateViewportStyles();
  } catch (error) {
    console.error("Error updating zoom:", error);
  }
};

const updateZoom = () => {
  updateZoomCommon(true);
};

const handleResize = async () => {
  await updateZoomCommon(true);
};

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 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);
};

// 添加文字层开关函数
const toggleTextLayer = () => {
  textLayerEnabled.value = !textLayerEnabled.value;

  if (textLayerEnabled.value) {
    console.log("启用文字层，重新渲染所有可见页面");
    // 清除渲染状态，重新渲染所有可见页面
    renderedPages.value.clear();
    pdfViewerInstances.value.clear(); // 清除页面视图实例
    const $magazine = $(magazine.value);
    if ($magazine.length) {
      const currentPage = $magazine.turn("page");
      renderVisiblePdfPages(currentPage);
    }
  } else {
    console.log("禁用文字层，重新渲染所有可见页面");
    // 清除渲染状态，重新渲染所有可见页面（不包含文字层）
    renderedPages.value.clear();
    pdfViewerInstances.value.clear(); // 清除页面视图实例
    const $magazine = $(magazine.value);
    if ($magazine.length) {
      const currentPage = $magazine.turn("page");
      renderVisiblePdfPages(currentPage);
    }
  }

  // 保存设置到本地存储
  localStorage.setItem("bookReaderTextLayer", textLayerEnabled.value);
};

// 添加渲染器切换函数
const toggleRenderer = () => {
  svgRendererEnabled.value = !svgRendererEnabled.value;

  console.log(`切换到${svgRendererEnabled.value ? 'SVG' : 'Canvas'}渲染模式，重新渲染所有可见页面`);
  
  // 清除渲染状态，重新渲染所有可见页面
  renderedPages.value.clear();
  pdfViewerInstances.value.clear(); // 清除页面视图实例
  const $magazine = $(magazine.value);
  if ($magazine.length) {
    const currentPage = $magazine.turn("page");
    renderVisiblePdfPages(currentPage);
  }

  // 保存设置到本地存储
  localStorage.setItem("bookReaderSvgRenderer", svgRendererEnabled.value);
};

// 专门处理turn.js坐标变换的函数
const fixTurnJsCoordinateSystem = () => {
  try {
    const allPages = document.querySelectorAll('.pdf-page-container');
    let totalFixed = 0;
    
    allPages.forEach(pageDiv => {
      const textLayer = pageDiv.querySelector('.textLayer');
      if (!textLayer) return;
      
      const textDivs = textLayer.querySelectorAll('div');
      const container = pageDiv.closest('.pdf-page-container');
      const turnPage = container ? container.closest('.page') : null;
      
      if (!turnPage || !container) return;
      
      const pageRect = turnPage.getBoundingClientRect();
      const containerRect = container.getBoundingClientRect();
      
      // 计算turn.js的缩放比例
      const scaleX = pageRect.width / containerRect.width;
      const scaleY = pageRect.height / containerRect.height;
      
      textDivs.forEach(div => {
        // 获取原始位置数据
        const calculatedPos = div.getAttribute('data-calculated-pos');
        if (calculatedPos) {
          try {
            const pos = JSON.parse(calculatedPos);
            
            // 应用turn.js的缩放修正
            const correctedX = pos.x * scaleX;
            const correctedY = pos.y * scaleY;
            
            // 强制应用修正后的位置
            div.style.left = `${correctedX}px !important`;
            div.style.top = `${correctedY}px !important`;
            
            // 更新CSS变量
            div.style.setProperty('--text-left', `${correctedX}px`);
            div.style.setProperty('--text-top', `${correctedY}px`);
            
            totalFixed++;
          } catch (e) {
            console.error('解析位置数据失败:', e);
          }
        }
      });
    });
    
    if (totalFixed > 0) {
      console.log(`修正了 ${totalFixed} 个文本元素的turn.js坐标变换`);
    }
    
    return totalFixed;
  } catch (error) {
    console.error('修正turn.js坐标变换失败:', error);
    return 0;
  }
};


// 添加调试函数：检查页面状态
const debugPageStatus = () => {
  if (!magazine.value) return;

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

  console.log(`=== 页面状态调试 ===`);
  console.log(`当前页码: ${currentPage}, 总页数: ${totalPages}`);
  console.log(
    `已渲染页面:`,
    Array.from(renderedPages.value).map((i) => i + 1)
  );

  // 检查当前页面的PdfViewer状态
  const currentPageContainer = magazine.value.querySelector(`.p${currentPage}`);
  if (currentPageContainer) {
    const pageView = pdfViewerInstances.value.get(currentPage - 1);
    if (pageView) {
      // 使用更安全的方式检查状态，避免访问私有字段
      try {
        const hasTextLayer = pageView.textLayer && typeof pageView.textLayer === 'object';
        const hasAnnotationLayer = pageView.annotationLayer && typeof pageView.annotationLayer === 'object';
        console.log(
          `当前页面PdfViewer状态: 实例存在=true, 文字层=${hasTextLayer ? '启用' : '禁用'}, 注释层=${hasAnnotationLayer ? '启用' : '禁用'}`
        );
      } catch (error) {
        console.log(`当前页面PdfViewer状态: 实例存在=true, 状态检查失败=${error.message}`);
      }
    } else {
      console.log(`当前页面没有PdfViewer实例`);
    }
  }

  // 检查所有页面的状态
  for (let i = 1; i <= totalPages; i++) {
    const pageContainer = magazine.value.querySelector(`.p${i}`);
    const pageView = pdfViewerInstances.value.get(i - 1);
    const isRendered = renderedPages.value.has(i - 1);
    console.log(
      `页面${i}: 容器存在=${!!pageContainer}, PdfViewer实例存在=${!!pageView}, 已渲染=${isRendered}`
    );
  }
  console.log(`====================`);
};

// 添加防抖处理
let resizeTimeout;

onMounted(async () => {
  // 先加载PDF.js
  await loadPdfJs();
  
  // 配置PDF.js worker - 使用标准的worker文件而不是.mjs
  if (pdfjsLib && pdfjsLib.GlobalWorkerOptions) {
    // 使用pdfjs-dist/build目录下的标准worker文件
    pdfjsLib.GlobalWorkerOptions.workerSrc = "/pdf.worker.js";
  }

  // 初始化PdfViewer相关服务
  if (pdfjsViewer) {
    eventBus.value = new pdfjsViewer.EventBus();
    pdfLinkService.value = new pdfjsViewer.PDFLinkService({
      eventBus: eventBus.value,
    });
  }

  // 从本地存储读取静音状态
  const savedMuted = localStorage.getItem("bookReaderMuted");
  if (savedMuted !== null) {
    isMuted.value = savedMuted === "true";
  }

  // 从本地存储读取文字层设置
  const savedTextLayer = localStorage.getItem("bookReaderTextLayer");
  if (savedTextLayer !== null) {
    textLayerEnabled.value = savedTextLayer === "true";
  }

  // 根据类型选择加载方式
  if (props.isPdf && props.pdfUrl) {
    console.log('组件挂载时加载PDF:', props.pdfUrl);
    await loadPdf();
  } else if (props.pages && props.pages.length > 0) {
    console.log('组件挂载时加载图片');
    await loadImages();
  } else {
    console.log('组件挂载时无需加载内容');
  }

  initAudio();
  window.addEventListener("keydown", handleKeyDown);
  
  // 添加防抖的resize监听器
  console.log('绑定resize事件监听器');
  window.addEventListener("resize", () => {
    console.log('resize事件触发');
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
      console.log('调用handleResize');
      handleResize();
    }, 250);
  });
  
  // Load directory images
  loadDirectoryImages();
  
  console.log('onMounted完成，事件绑定完成');
});

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

  // 清除所有状态
  imageCache.value.clear();
  loadingQueue.value.clear();
  preloadingPages.value.clear();
  renderedPages.value.clear(); // 清除PDF渲染状态
  pdfInitialized.value = false; // 清除PDF初始化状态

  // 清理PdfViewer实例
  pdfViewerInstances.value.forEach((pageView) => {
    if (pageView && typeof pageView.destroy === 'function') {
      try {
        pageView.destroy();
      } catch (error) {
        console.warn('清理PdfViewer实例时出错:', error);
      }
    }
  });
  pdfViewerInstances.value.clear();

  // 清理事件总线和链接服务
  if (eventBus.value) {
    eventBus.value = null;
  }
  if (pdfLinkService.value) {
    pdfLinkService.value = null;
  }

  // 重置状态
  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 = async (pageNum) => {
  if (magazine.value && isInitialized.value) {
    const $magazine = $(magazine.value);
    $magazine.turn("page", pageNum);
    
    // 等待turn.js完成页面跳转
    await new Promise((resolve) => setTimeout(resolve, 100));
    
    // 如果是PDF模式，重新调整页面尺寸
    if (props.isPdf && pdfInitialized.value) {
      await resizeVisiblePdfPages();
    }
  }
};

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;
}

/* PDF页面样式 - 支持PdfViewer */
.page {
  background-color: white;
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  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);
}

.page-canvas.wide-canvas {
  width: 100%;
  height: 100%;
}

/* 缩放状态样式 */
.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 !important;
  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>
