<script lang="ts">
import type { PropType } from 'vue';
import { defineComponent } from 'vue';
import VuePdfEmbed from 'vue-pdf-embed';
import uniqBy from 'lodash/uniqBy';
import PaginationControl from './PaginationControl.vue';

interface CompareResult {
  baseBoxArea: string;
  baseDiffContent: string;
  baseDiffType: 'modify' | 'insert' | 'delete';
  basePageNum: number;
  compareBoxArea: string;
  compareDiffContent: string;
  compareDiffType: 'modify' | 'insert' | 'delete';
  comparePageNum: number;
  firstPageNum: number;
  secondPageNum: number;
  id: number;
}

interface CanvasMap {
  [key: number]: HTMLCanvasElement;
}

interface ContextMap {
  [key: number]: CanvasRenderingContext2D | null;
}

// 添加重试计数和强制设置页数功能
export default defineComponent({
  name: 'ContractViewer',
  components: {
    PaginationControl,
    VuePdfEmbed
  },
  props: {
    type: {
      type: String as PropType<'original' | 'compare'>,
      required: true,
      validator: (value: string) => ['original', 'compare'].includes(value)
    },
    currentPage: {
      type: Number,
      required: true
    },
    totalPages: {
      type: Number,
      required: true
    },
    compareResults: {
      type: Array as PropType<CompareResult[]>,
      required: true
    },
    selectedDiff: {
      type: Object as PropType<CompareResult | null>,
      default: null
    },
    pdfUrl: {
      type: String,
      required: false,
      default: ''
    },
    isLoading: {
      type: Boolean,
      default: false
    },
    loadError: {
      type: String as PropType<string | null>,
      default: null
    }
  },
  data() {
    return {
      canvases: {} as CanvasMap,
      ctxs: {} as ContextMap,
      resizeTimer: null as number | null,
      pdfDoc: null as any, // PDF 文档引用
      overlayCanvases: {} as CanvasMap, // 用于绘制边框的叠加层画布
      overlayCtxs: {} as ContextMap, // 叠加层画布上下文
      pdfLoaded: false, // 标记 PDF 是否已加载
      scrollTimer: null as number | null, // 滚动防抖计时器

      scale: 1.5 // PDF 渲染缩放比例（用于实际渲染）
    };
  },
  computed: {
    realTotalPages(): number {
      return this.totalPages || 1;
    }
  },
  watch: {
    selectedDiff() {
      // 只重绘下划线，不重绘 bbox
      this.clearOverlays(); // 只清除所有 overlay
      this.drawDiffBoxes(); // 重新绘制所有 bbox
      if (this.selectedDiff) {
        this.drawSelectedUnderline();
      }
    },
    currentPage() {
      // 当前页变化时，滚动到该页
      this.$nextTick().then(() => {
        this.scrollToPage(this.currentPage);

        // 延迟执行其他操作
        setTimeout(() => {
          this.initOverlayCanvas();
          if (this.selectedDiff) {
            this.drawSelectedUnderline();
          }
        }, 300);
      });
    },
    pdfUrl() {
      // 当 PDF URL 变化时，重置并重新初始化
      this.pdfLoaded = false;
      this.$nextTick().then(() => {
        // 重置状态
        this.changePage(1);
        this.overlayCanvases = {};
        this.overlayCtxs = {};
      });
    },
    compareResults: {
      handler() {
        // 当比较结果变化时，重绘叠加层
        this.clearOverlays();
        this.drawDiffBoxes();
      },
      deep: true
    }
  },
  mounted() {
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    // 移除事件监听器
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 确保所有页面都显示（竖向排列）
    showAllPages(): void {
      this.$nextTick().then(() => {
        const pdfEmbed = document.querySelector(`.contract-section-${this.type} .vue-pdf-embed`) as HTMLElement;
        if (!pdfEmbed) {
          console.warn(`[${this.type}] 找不到 PDF 嵌入组件`);
          return;
        }

        const pdfPages = pdfEmbed.querySelectorAll('.vue-pdf-embed__page') as NodeListOf<HTMLElement>;
        if (pdfPages.length === 0) {
          console.warn(`[${this.type}] 找不到 PDF 页面元素`);
          return;
        }

        // 确保所有页面都显示
        pdfPages.forEach((page) => {
          page.style.display = 'block';
        });

        console.log(`[${this.type}] 显示所有页面，共 ${pdfPages.length} 页`);
      });
    },

    // 初始化叠加层画布用于绘制边框
    initOverlayCanvas(): void {
      this.$nextTick().then(() => {
        this.overlayCanvases = {};
        this.overlayCtxs = {};

        // 查找 PDF 嵌入组件
        const pdfEmbed = document.querySelector(`.contract-section-${this.type} .vue-pdf-embed`) as HTMLElement;
        if (!pdfEmbed) {
          console.warn(`[${this.type}] 找不到 PDF 嵌入组件`);
          return;
        }

        // 查找所有 PDF 页面元素
        const pdfPages = pdfEmbed.querySelectorAll('.vue-pdf-embed__page') as NodeListOf<HTMLElement>;
        if (pdfPages.length === 0) {
          console.warn(`[${this.type}] 找不到 PDF 页面元素`);
          return;
        }

        // 为每个 PDF 页面创建叠加层
        pdfPages.forEach((pdfPage, idx) => {
          const pageNum = idx + 1;

          // 移除现有的叠加层
          const existingOverlay = pdfPage.querySelector('.overlay-canvas');
          if (existingOverlay) {
            existingOverlay.remove();
          }

          // 获取 PDF 页面的尺寸
          const rect = pdfPage.getBoundingClientRect();

          // 创建叠加层画布
          const overlay = document.createElement('canvas');
          overlay.className = 'overlay-canvas';
          overlay.style.position = 'absolute';
          overlay.style.top = '0';
          overlay.style.left = '0';
          overlay.style.width = '100%';
          overlay.style.height = '100%';
          overlay.style.pointerEvents = 'none';
          overlay.style.zIndex = '100';

          // 设置画布尺寸与 PDF 页面相匹配
          overlay.width = rect.width;
          overlay.height = rect.height;

          // 存储画布和上下文引用
          this.overlayCanvases[pageNum] = overlay;
          this.overlayCtxs[pageNum] = overlay.getContext('2d');

          // 将点击处理程序添加到 PDF 页面上
          pdfPage.addEventListener('click', (event: Event) => {
            if (event instanceof MouseEvent) {
              this.handleCanvasClick(event, pageNum);
            }
          });

          // 确保 PDF 页面使用相对定位
          pdfPage.style.position = 'relative';
          pdfPage.appendChild(overlay);
        });

        // 初始化后绘制差异框
        setTimeout(() => {
          this.drawDiffBoxes();
        }, 300);
      });
    },

    // 自适应宽度：根据容器宽度自动调整 scale
    fitWidth(): void {
      this.$nextTick().then(() => {
        const container = this.$el.querySelector('.pages-container') as HTMLElement | null;
        const pdfPage = this.$el.querySelector('.vue-pdf-embed__page') as HTMLElement | null;
        if (!container || !pdfPage) return;

        const containerWidth = container.clientWidth - 32; // 预留少量内边距
        const pageRect = pdfPage.getBoundingClientRect();
        if (!pageRect.width || containerWidth <= 0) return;

        const currentDisplayedWidth = pageRect.width;
        const ratio = containerWidth / currentDisplayedWidth;
        const nextScale = Number((this.scale * ratio).toFixed(2));
        if (Math.abs(nextScale - this.scale) > 0.01) {
          this.scale = nextScale;
          // 缩放后重建叠加层，确保标注对齐
          setTimeout(() => {
            this.initOverlayCanvas();
            this.drawDiffBoxes();
            if (this.selectedDiff) this.drawSelectedUnderline();
          }, 200);
        }
      });
    },

    // 处理窗口大小变化
    handleResize(): void {
      if (this.resizeTimer !== null) {
        clearTimeout(this.resizeTimer);
      }
      this.resizeTimer = window.setTimeout(() => {
        this.initOverlayCanvas();
        // 容器变化后适当重算叠加并可选地自适应宽度
        // 不强制调用 fitWidth，避免用户缩放被覆盖
      }, 200);
    },

    // 清除所有叠加层
    clearOverlays(): void {
      for (const pageNum in this.overlayCtxs) {
        if (Object.hasOwn(this.overlayCtxs, pageNum)) {
          const ctx = this.overlayCtxs[pageNum];
          const canvas = this.overlayCanvases[pageNum];
          if (ctx && canvas) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
          }
        }
      }
    },

    // 绘制所有页的所有差异框
    drawDiffBoxes(): void {
      this.clearOverlays(); // 保证每次都先清空

      // 绘制所有页面的差异框
      // eslint-disable-next-line no-plusplus
      for (let pageNum = 1; pageNum <= this.totalPages; pageNum++) {
        const pageDiffs = this.compareResults.filter(item => {
          if (this.type === 'original') {
            return item.basePageNum === pageNum;
          }
          return item.comparePageNum === pageNum;
        });
        const uniqueDiffs = uniqBy(pageDiffs, diff =>
          this.type === 'original' ? diff.baseBoxArea : diff.compareBoxArea
        );
        uniqueDiffs.forEach(diff => {
          const boxArea = this.type === 'original' ? diff.baseBoxArea : diff.compareBoxArea;
          if (boxArea && boxArea !== '[0, 0, 0, 0]') {
            this.drawBox(pageNum, boxArea, this.type === 'original' ? diff.baseDiffType : diff.compareDiffType);
          }
        });
      }
    },

    // 解析 bbox 坐标
    parseBboxCoordinates(boxArea: string | number[]): number[] | null {
      if (!boxArea || boxArea === '[0, 0, 0, 0]') {
        return null;
      }

      try {
        // 处理不同可能的格式
        let coords: number[];
        if (typeof boxArea === 'string') {
          // 移除括号和空格，然后按逗号分割
          const cleanStr = boxArea.replace(/^\[|\]$/g, '').replace(/\s+/g, '');
          coords = cleanStr.split(',').map(num => Number.parseFloat(num.trim()));
        } else if (Array.isArray(boxArea)) {
          coords = boxArea.map(num => Number.parseFloat(String(num)));
        } else {
          console.error('无效的bbox格式:', boxArea);
          return null;
        }

        // 验证4个有效数字
        if (coords.length !== 4 || coords.some(num => Number.isNaN(num))) {
          console.error('无效的bbox坐标:', coords);
          return null;
        }

        return coords;
      } catch (error) {
        console.error('解析bbox坐标失败:', error, boxArea);
        return null;
      }
    },

    // 确保 bbox 具有最小尺寸
    ensureMinimumBboxSize(coords: number[] | null, minWidth = 5, minHeight = 5): number[] | null {
      if (!coords || !Array.isArray(coords) || coords.length !== 4) {
        return null;
      }

      const [x, y, width, height] = coords;

      // 设置最小宽度和高度
      const adjustedWidth = width <= 0 || width < minWidth ? minWidth : width;
      const adjustedHeight = height <= 0 || height < minHeight ? minHeight : height;

      return [x, y, adjustedWidth, adjustedHeight];
    },

    // 在指定页面上绘制一个 bbox
    drawBox(pageNum: number, boxArea: string, diffType: string): void {
      const ctx = this.overlayCtxs[pageNum];
      const canvas = this.overlayCanvases[pageNum];

      if (!ctx || !canvas) return;

      // 解析坐标
      const coords = this.parseBboxCoordinates(boxArea);
      if (!coords) return;

      // 确保最小尺寸
      const adjustedCoords = this.ensureMinimumBboxSize(coords);
      if (!adjustedCoords) return;

      // PDF 大小标准 (单位为pt)
      const PDF_WIDTH = 595; // A4宽度
      const PDF_HEIGHT = 842; // A4高度

      // 计算缩放比例 (PDF 点到像素的转换)
      const scaleX = canvas.width / PDF_WIDTH;
      const scaleY = canvas.height / PDF_HEIGHT;

      // 自动适配 boxArea 单位
      const [xInit, yInit, widthInit, heightInit] = adjustedCoords;
      let x = xInit;
      let y = yInit;
      let width = widthInit;
      let height = heightInit;
      // 如果 boxArea 是 px（150dpi），先转 pt
      const isPx = Math.max(x, y, width, height) > 900; // 粗略判断
      if (isPx) {
        const dpi = 150;
        const pxToPt = (px: number) => (px * 72) / dpi;
        x = pxToPt(x);
        y = pxToPt(y);
        width = pxToPt(width);
        height = pxToPt(height);
      }
      // 重要：PDF 坐标系原点在左下角，Y 轴向上
      // Canvas 坐标系原点在左上角，Y 轴向下
      // 因此需要转换 Y 坐标
      const scaledX = x * scaleX;
      const scaledWidth = width * scaleX;
      const scaledHeight = height * scaleY;
      const scaledY = y * scaleY - scaledHeight;

      // 设置虚线样式
      ctx.setLineDash([5, 5]);
      ctx.lineWidth = 1;

      // 根据差异类型设置颜色
      switch (diffType) {
        case 'insert':
          ctx.strokeStyle = '#52c41a'; // 绿色
          break;
        case 'delete':
          ctx.strokeStyle = '#ff4d4f'; // 红色
          break;
        case 'modify':
          ctx.strokeStyle = '#faad14'; // 黄色
          break;
        default:
          ctx.strokeStyle = '#1890ff'; // 蓝色
      }

      // 绘制矩形框
      ctx.strokeRect(scaledX, scaledY, scaledWidth, scaledHeight);

      // 添加半透明填充效果
      ctx.fillStyle = `${ctx.strokeStyle}40`; // 25% 透明度
      ctx.fillRect(scaledX, scaledY, scaledWidth, scaledHeight);

      // 重置虚线样式
      ctx.setLineDash([]);
    },

    // 绘制选中的差异下划线
    drawSelectedUnderline(): void {
      if (!this.selectedDiff) return;

      // 检查选中的差异是否在当前页
      const isCurrentPage =
        this.type === 'original'
          ? this.selectedDiff.basePageNum === this.currentPage
          : this.selectedDiff.comparePageNum === this.currentPage;

      if (!isCurrentPage) return;

      const pageNum = this.currentPage;
      const ctx = this.overlayCtxs[pageNum];
      const canvas = this.overlayCanvases[pageNum];

      if (!ctx || !canvas) return;

      // 获取 bbox 区域
      const boxArea = this.type === 'original' ? this.selectedDiff.baseBoxArea : this.selectedDiff.compareBoxArea;

      const coords = this.parseBboxCoordinates(boxArea);
      if (!coords) return;

      const adjustedCoords = this.ensureMinimumBboxSize(coords);
      if (!adjustedCoords) return;

      let [x, y, width, height] = adjustedCoords;

      // PDF 大小标准 (单位为pt)
      const PDF_WIDTH = 595;
      const PDF_HEIGHT = 842;

      // 计算缩放比例
      const scaleY = canvas.height / PDF_HEIGHT;

      // 单位转换（如有必要）
      const isPx = Math.max(x, y, width, height) > 900;
      if (isPx) {
        const dpi = 150;
        const pxToPt = (px: number) => (px * 72) / dpi;
        x = pxToPt(x);
        y = pxToPt(y);
        width = pxToPt(width);
        height = pxToPt(height);
      }

      // 重要：PDF 坐标系原点在左下角，Canvas 在左上角
      const scaledHeight = height * scaleY;
      const scaledY = y * scaleY - scaledHeight;

      // 在 bbox 下方绘制下划线
      ctx.save();
      ctx.setLineDash([8, 4]);
      ctx.lineWidth = 3;
      ctx.strokeStyle = '#1890ff';

      ctx.beginPath();
      ctx.moveTo(0, scaledY + scaledHeight);
      ctx.lineTo(canvas.width, scaledY + scaledHeight);
      ctx.stroke();

      ctx.restore();
    },

    // 滚动到指定页
    scrollToPage(pageNum: number): void {
      this.$nextTick().then(() => {
        const pdfEmbed = document.querySelector(`.contract-section-${this.type} .vue-pdf-embed`) as HTMLElement;
        if (!pdfEmbed) {
          console.warn(`[${this.type}] 找不到 PDF 嵌入组件`);
          return;
        }

        const pdfPages = pdfEmbed.querySelectorAll('.vue-pdf-embed__page') as NodeListOf<HTMLElement>;
        if (pdfPages.length === 0 || pageNum > pdfPages.length) {
          console.warn(`[${this.type}] 页面 ${pageNum} 不存在`);
          return;
        }

        const targetPage = pdfPages[pageNum - 1]; // 数组从0开始，页面从1开始
        if (targetPage) {
          targetPage.scrollIntoView({ behavior: 'smooth', block: 'start' });
          console.log(`[${this.type}] 滚动到页面 ${pageNum}`);
        }
      });
    },

    // 处理画布点击
    handleCanvasClick(event: MouseEvent, pageNum: number): void {
      const canvas = this.overlayCanvases[pageNum];
      if (!canvas) return;

      const rect = canvas.getBoundingClientRect();
      const clickX = event.clientX - rect.left;
      const clickY = event.clientY - rect.top;

      // 查找点击的差异
      const clickedDiff = this.findClickedDiff(clickX, clickY, pageNum);
      if (clickedDiff) {
        this.$emit('select-diff', clickedDiff);
      }
    },

    // 查找点击的是哪个差异
    findClickedDiff(x: number, y: number, pageNum: number): CompareResult | undefined {
      const pageDiffs = this.compareResults.filter(item => {
        if (this.type === 'original') {
          return item.basePageNum === pageNum;
        }
        return item.comparePageNum === pageNum;
      });

      const canvas = this.overlayCanvases[pageNum];
      if (!canvas) return undefined;

      // PDF 大小标准 (单位为pt)
      const PDF_WIDTH = 595;
      const PDF_HEIGHT = 842;

      // 计算缩放比例
      const scaleX = canvas.width / PDF_WIDTH;
      const scaleY = canvas.height / PDF_HEIGHT;

      return pageDiffs.find(diff => {
        const boxArea = this.type === 'original' ? diff.baseBoxArea : diff.compareBoxArea;
        if (boxArea && boxArea !== '[0, 0, 0, 0]') {
          const coords = this.parseBboxCoordinates(boxArea);
          if (!coords) return false;

          const [boxX, boxY, width, height] = coords;

          // 转换坐标
          const scaledBoxX = boxX * scaleX;
          const scaledBoxY = canvas.height - boxY * scaleY - height * scaleY;
          const scaledWidth = width * scaleX;
          const scaledHeight = height * scaleY;

          return x >= scaledBoxX && x <= scaledBoxX + scaledWidth && y >= scaledBoxY && y <= scaledBoxY + scaledHeight;
        }
        return false;
      });
    },

    // 切换页
    changePage(pageNum: number): void {
      this.$emit('update:currentPage', pageNum);
    },

    // 更新PDF加载事件处理
    onPdfLoaded(): void {
      this.pdfLoaded = true;
      console.log(`[${this.type}] PDF 文档加载完成`);
    },

    // 更新Page Rendered处理
    onPageRendered(): void {
      // 使用延时确保PDF渲染完成后再绘制框框
      setTimeout(() => {
        // 确保所有页面都显示
        this.showAllPages();
        // 初始化叠加层
        this.initOverlayCanvas();
        // 绘制所有差异框
        this.drawDiffBoxes();
        if (this.selectedDiff) {
          this.drawSelectedUnderline();
        }
        console.log(`[${this.type}] 完成PDF渲染`);
        // 初始时如出现横向溢出，尝试适配宽度
        this.$nextTick(() => {
          const container = this.$el.querySelector('.pages-container') as HTMLElement | null;
          const content = this.$el.querySelector('.vue-pdf-embed__page') as HTMLElement | null;
          if (container && content && content.getBoundingClientRect().width > container.clientWidth) {
            this.fitWidth();
          }
        });
      }, 500);
    },

    // 添加一个手动触发差异框绘制的方法
    redrawBoxes(): void {
      // 重绘框框
      this.clearOverlays();
      this.initOverlayCanvas();

      setTimeout(() => {
        this.drawDiffBoxes();
        if (this.selectedDiff) {
          this.drawSelectedUnderline();
        }
      }, 200);
    }
  }
});
</script>

<template>
  <div
    class="contract-section"
    :class="[type === 'original' ? 'contract-section-original' : 'contract-section-compare']"
  >
    <div class="contract-header">
      <div class="section-title">
        <div class="title-icon" :class="[type]">{{ type === 'original' ? '📄' : '📋' }}</div>
        <h3>{{ type === 'original' ? '原合同' : '对比合同' }}</h3>
      </div>
      <PaginationControl :current-page="currentPage" :total-pages="totalPages" @page-change="changePage" />
    </div>
    <div class="pages-container">
      <!-- 使用单个 PDF 组件加载整个文档 -->
      <div v-if="pdfUrl && !isLoading" class="pdf-viewer">
        <VuePdfEmbed
          :source="pdfUrl"
          class="pdf-document"
          :scale="scale"
          @rendered="onPageRendered"
          @loaded="onPdfLoaded"
        />
      </div>

      <!-- 加载状态 -->
      <div v-else-if="isLoading" class="canvas-container">
        <div class="pdf-placeholder">
          <div class="loading-message">正在加载 PDF...</div>
        </div>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="loadError" class="canvas-container">
        <div class="pdf-placeholder">
          <div class="error-message">{{ loadError }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.contract-section {
  flex: 1;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: 1px solid #e8e8e8;

  .contract-header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.section-title {
  display: flex;
  align-items: center;
  gap: 12px;
  .title-icon {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: white;
    font-weight: bold;
    &.original {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    &.compare {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }
  }
  h3 {
    margin: 0;
    color: #262626;
    font-size: 18px;
    font-weight: 600;
  }
}

.pages-container {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: auto; /* 超大屏或缩放导致的横向溢出时可横向滚动 */
  gap: 24px;
}

.page-item {
  display: flex;
  flex-direction: column;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  flex-shrink: 0;
}

.page-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background: #fafafa;
  position: relative;
  width: 100%;
  box-sizing: border-box;
  min-height: auto;
}

.pdf-viewer-container {
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
}

.pdf-viewer {
  width: 100%;
  display: flex;
  justify-content: center;
  position: relative;
  overflow: visible; /* 允许内容根据缩放溢出 */
}

.page-display-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* PDF 文档样式 */
:deep(.pdf-document) {
  width: 100% !important;
}

:deep(.vue-pdf-embed) {
  width: 100% !important;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

:deep(.vue-pdf-embed__page) {
  position: relative !important;
  width: auto !important; /* 由 scale 控制显示宽度 */
  max-width: none; /* 取消固定 800px 限制，避免大屏放大时被限制 */
  height: auto !important;
  margin-bottom: 24px !important;
  display: block !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
}



/* 叠加层样式 */
:deep(.overlay-canvas) {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  z-index: 10;
  pointer-events: none;
}

.pdf-placeholder {
  width: 100%;
  height: 500px;
  background: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  color: #666;
  font-size: 14px;
}

.loading-message {
  color: #1890ff;
}

.error-message {
  color: #ff4d4f;
}

.page-number {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  z-index: 10;
}

.canvas-container {
  position: relative;
  width: 100%;
}

/* 删除缩放工具条相关样式 */

/* Scrollbar styles */
.pages-container::-webkit-scrollbar {
  width: 8px;
}

.pages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.pages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.pages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

@media (max-width: 1200px) {
  .contract-section {
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .contract-section {
    width: 100%;
  }
}
</style>
