<template>
  <div class="vtk-pdf-container">
    <v-card 
      :class="['vtk-pdf-card', { 'vtk-pdf-card--preview': preview }]"
      @click="openPreview"
    >
      <!-- PDF封面或默认图标 -->
      <div class="vtk-pdf-cover" :style="{ aspectRatio: aspectRatio }">
        <v-icon size="48" color="red">mdi-file-pdf-box</v-icon>
        <div class="vtk-pdf-label">PDF</div>
      </div>
      
      <!-- PDF标题和描述 -->
      <div class="vtk-pdf-info" v-if="showTitle || showDescription">
        <v-card-title v-if="showTitle" class="vtk-pdf-title text-subtitle-2 pa-2">
          {{ title }}
        </v-card-title>
        <v-card-subtitle v-if="showDescription" class="vtk-pdf-description text-caption pa-2">
          {{ description }}
        </v-card-subtitle>
      </div>
    </v-card>
    
    <!-- 使用 v-dialog 的PDF预览 -->
    <v-dialog 
      v-model="showPreview" 
      max-width="90%" 
      fullscreen
      @click:outside="closePreview"
    >
      <v-card class="pdf-viewer-card">
        <v-toolbar dark color="red darken-1">
          <v-btn icon dark @click="closePreview">
            <v-icon>mdi-close</v-icon>
          </v-btn>
          <v-toolbar-title>{{ title }}</v-toolbar-title>
          <v-spacer></v-spacer>
          <v-toolbar-items>
            <v-btn icon dark @click="downloadPdf">
              <v-icon>mdi-download</v-icon>
            </v-btn>
          </v-toolbar-items>
        </v-toolbar>
        
        <div class="pdf-viewer-content">
          <div class="pdf-container" ref="pdfContainer">
            <!-- PDF内容将通过PDF.js渲染 -->
            <div id="pdf-viewer"></div>
          </div>
        </div>
        
        <div class="pdf-viewer-footer" v-if="pdfLoaded">
          <v-row align="center" justify="center">
            <v-col cols="12" sm="6" class="d-flex justify-center">
              <v-btn icon @click="prevPage" :disabled="currentPage <= 1">
                <v-icon>mdi-chevron-left</v-icon>
              </v-btn>
              <div class="mx-4">
                <span>第 {{ currentPage }} 页 / 共 {{ pageCount }} 页</span>
              </div>
              <v-btn icon @click="nextPage" :disabled="currentPage >= pageCount">
                <v-icon>mdi-chevron-right</v-icon>
              </v-btn>
            </v-col>
            <v-col cols="12" sm="6" class="d-flex justify-center">
              <v-slider
                v-model="currentPage"
                :min="1"
                :max="pageCount"
                hide-details
                class="mx-4"
              ></v-slider>
            </v-col>
          </v-row>
        </div>
        
        <div class="pdf-loading" v-if="loading">
          <v-progress-circular indeterminate color="red"></v-progress-circular>
          <p class="mt-2">正在加载PDF...</p>
        </div>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
// import * as pdfjsLib from 'pdfjs-dist';
// 注意：在实际项目中，您需要安装 pdfjs-dist 库
// npm install pdfjs-dist
// import * as pdfjsLib from 'pdfjs-dist';

defineOptions({
  name: 'VtkPdf',
  inheritAttrs: true
});

const props = defineProps({
  src: {
    type: String,
    default: null,
  },
  preview: {
    type: Boolean,
    default: true
  },
  title: {
    type: String,
    default: ''
  },
  description: {
    type: String,
    default: ''
  },
  // 是否显示标题
  showTitle: {
    type: Boolean,
    default: true
  },
  // 是否显示描述
  showDescription: {
    type: Boolean,
    default: true
  },
  // 封面宽高比
  aspectRatio: {
    type: [String, Number],
    default: 16/9
  }
});

// 预览状态
const showPreview = ref(false);
// PDF相关状态
const loading = ref(false);
const pdfLoaded = ref(false);
const currentPage = ref(1);
const pageCount = ref(0);
const pdfContainer = ref(null);

// PDF对象（实际使用时需要引入pdfjsLib）
let pdfDoc = null;

// 使用计算属性处理带token的URL
const srcWithToken = computed(() => {
  if (!props.src) return props.src;
  
  try {
    // 首先尝试使用 $vtk.storage
    if (window.$vtk && typeof window.$vtk.storage?.get === 'function') {
      const token = window.$vtk.storage.get('token');
      return token ? `${props.src}?stoken=${token}` : props.src;
    }
    // 如果 $vtk 不存在，尝试从 localStorage 获取 token
    else {
      const token = localStorage.getItem('token');
      return token ? `${props.src}?stoken=${token}` : props.src;
    }
  } catch (error) {
    // 发生错误时返回原始src
    console.warn('VtkPdf: Failed to get token, using src without token', error);
    return props.src;
  }
});

// 打开预览
const openPreview = () => {
  if (props.preview) {
    showPreview.value = true;
    // 延迟加载PDF以确保DOM已准备好
    setTimeout(() => {
      loadPdf();
    }, 300);
  }
};

// 关闭预览
const closePreview = () => {
  showPreview.value = false;
  // 清理PDF对象
  pdfDoc = null;
  pdfLoaded.value = false;
  currentPage.value = 1;
  pageCount.value = 0;
};

// 加载PDF（示例实现，实际使用需要PDF.js库）
const loadPdf = async () => {
  if (!srcWithToken.value) return;
  
  loading.value = true;
  
  try {
    // 模拟PDF加载（实际实现需要使用PDF.js）
    /*
    // 实际使用时的代码示例：
    pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js';
    
    const loadingTask = pdfjsLib.getDocument(srcWithToken.value);
    pdfDoc = await loadingTask.promise;
    pageCount.value = pdfDoc.numPages;
    pdfLoaded.value = true;
    
    // 渲染第一页
    renderPage(currentPage.value);
    */
    
    // 模拟加载过程
    await new Promise(resolve => setTimeout(resolve, 1000));
    pageCount.value = 10; // 模拟10页PDF
    pdfLoaded.value = true;
  } catch (error) {
    console.error('加载PDF失败:', error);
  } finally {
    loading.value = false;
  }
};

// 渲染PDF页面（示例实现）
const renderPage = async (pageNum) => {
  if (!pdfDoc || !pdfContainer.value) return;
  
  try {
    /*
    // 实际使用时的代码示例：
    const page = await pdfDoc.getPage(pageNum);
    const viewport = page.getViewport({ scale: 1.5 });
    
    // 准备canvas
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    
    // 清空容器
    pdfContainer.value.innerHTML = '';
    pdfContainer.value.appendChild(canvas);
    
    // 渲染页面
    const renderContext = {
      canvasContext: context,
      viewport: viewport
    };
    await page.render(renderContext).promise;
    */
  } catch (error) {
    console.error('渲染PDF页面失败:', error);
  }
};

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    renderPage(currentPage.value);
  }
};

// 下一页
const nextPage = () => {
  if (currentPage.value < pageCount.value) {
    currentPage.value++;
    renderPage(currentPage.value);
  }
};

// 下载PDF
const downloadPdf = async () => {
  if (!srcWithToken.value) return;
  
  try {
    // 获取PDF文件的二进制数据
    const response = await fetch(srcWithToken.value);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const blob = await response.blob();
    const fileName = props.title && props.title.trim() !== '' 
      ? `${props.title}.pdf` 
      : 'document.pdf';
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('下载PDF失败:', error);
    // 备用方案：在新窗口打开
    window.open(srcWithToken.value, '_blank');
  }
};

// 监听页码变化
const handlePageChange = (newPage) => {
  if (newPage >= 1 && newPage <= pageCount.value) {
    renderPage(newPage);
  }
};

// 监听 currentPage 变化
// 在实际实现中，您需要使用 watch 监听 currentPage 变化
// watch(currentPage, handlePageChange);

// 组件销毁前清理
onBeforeUnmount(() => {
  pdfDoc = null;
});
</script>

<style lang="scss" scoped>
.vtk-pdf-container {
  position: relative;
  display: inline-block;
  width: 100%;
  height: 100%;
}

.vtk-pdf-card {
  height: 100%;
}

.vtk-pdf-card--preview {
  cursor: pointer;
  transition: transform 0.2s ease-in-out;
}

.vtk-pdf-card--preview:hover {
  transform: translateY(-5px);
}

.vtk-pdf-cover {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  width: 100%;
}

.vtk-pdf-label {
  margin-top: 8px;
  font-weight: 500;
  color: #666;
}

.vtk-pdf-info {
  padding: 0;
}

.vtk-pdf-title {
  word-break: break-word;
}

.vtk-pdf-description {
  word-break: break-word;
}

/* PDF查看器样式 */
.pdf-viewer-card {
  background-color: #e0e0e0;
  color: #333;
}

.pdf-viewer-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 150px);
  position: relative;
  background-color: #555;
  overflow: auto;
}

.pdf-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

#pdf-viewer {
  max-width: 100%;
  max-height: 100%;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  background-color: white;
  /* 实际PDF内容将在此处渲染 */
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 500px;
  min-width: 400px;
}

.pdf-viewer-footer {
  padding: 16px;
  background-color: #f5f5f5;
  border-top: 1px solid #ddd;
}

.pdf-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 8px;
  z-index: 100;
}
</style>