<template>
  <div class="document-preview">
    <div class="preview-container">
      <!-- 文档列表 -->
    <!--   <div class="document-list">
        <div v-if="documents.length === 0" class="empty-state">
          <FileOutlined class="empty-icon" />
          <p>暂无文档</p>
        </div>
        <div v-else v-for="doc in documents" :key="doc.name" class="document-item" 
          :class="{ 'active': currentDoc?.name === doc.name }">
          <div class="document-info">
            
            <div class="doc-icon">
              <img 
                v-if="isImageFile(doc)"
                :src="doc.url" 
                class="preview-thumbnail"
                alt="preview"
              />
              <video
                v-else-if="isVideoFile(doc)"
                :src="doc.url"
                class="preview-thumbnail"
                preload="metadata"
              />
              <img 
                v-else 
                :src="getFileIcon(doc)" 
                alt="file"
                class="file-icon"
              />
            </div>
            
            
            <div class="info">
              <div class="name" :title="doc.name">{{ doc.name }}</div>
              <div class="size">{{ doc.sizeFormatted || formatFileSize(doc.size) }}</div>
            </div>
          </div>

          
          <div class="actions">
            <button class="action-btn" @click.stop="handleDownload(doc)" title="下载">
              <DownloadOutlined />
            </button>
          </div>
        </div>
      </div> -->
      <vue-office-docx
            src="https://501351981.github.io/vue-office/examples/dist/static/test-files/test.docx"
            style="height: 100vh;"
            @rendered="renderedHandler"
            @error="errorHandler"
        /> 
      <!-- 直接预览区域 -->
      <div v-if="currentDoc" class="direct-preview">
        <div class="preview-header">
          <span>{{ currentDoc.name }}</span>
          <button class="close-btn" @click="closePreview">
            <CloseOutlined />
          </button>
        </div>
        <div class="preview-body">
          <!-- 图片预览 -->
          <img 
            v-if="isImageFile(currentDoc)"
            :src="currentDoc.url" 
            class="preview-image"
            alt="preview"
          />
          <!-- 视频预览 -->
          <video
            v-else-if="isVideoFile(currentDoc)"
            :src="currentDoc.url"
            controls
            class="preview-video"
          />
          <!-- Word文档预览 -->
           <div v-else-if="isWordFile(currentDoc)">
            <vue-office-docx
              :src="currentDoc.url"
              class="doc-preview"
            />      
           </div>
          <!-- Excel文档预览 -->
          <div v-else-if="isExcelFile(currentDoc)">
            <vue-office-excel
              :options="excelOptions"
              @rendered="handleRendered"
              @error="handleExcelError"
              :src="currentDoc.url"
              class="doc-preview"
            />
          </div>
          <!-- PDF预览-->
           <iframe v-else-if="isPdfFile(currentDoc)" :src="currentDoc.url" style="width: 100%; height: 100%;" frameborder="0"></iframe>
          <!-- <vue-office-pdf
            v-else-if="isPdfFile(currentDoc)"
            @rendered="renderedHandler"
             @error="errorHandler"
            :src="currentDoc.url"
            class="doc-preview"
          /> -->
          <!-- 其他文件预览 -->
          <div v-else class="file-preview">
            <FileOutlined class="large-icon" />
            <p>该文件类型暂不支持预览</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, watch, onMounted } from 'vue';
import { 
  FileOutlined, 
  DownloadOutlined,
  CloseOutlined
} from '@ant-design/icons-vue';
/* import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css';
import '@vue-office/pdf/lib/index.css'; */
// 导入 vue-office 组件
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf  from '@vue-office/pdf';

export default defineComponent({
  name: 'DocumentPreview',
  components: {
    FileOutlined,
    DownloadOutlined,
    CloseOutlined,
/*     VueOfficeDocx,
    VueOfficeExcel,
    VueOfficePdf */
  },
  props: {
    documents: {
      type: Array,
      default: () => []
    }
  },
  emits: ['select'],
  setup(props, { emit }) {
    const currentDoc = ref(null);

    // 监听文档列表变化，自动预览第一个文档
    watch(() => props.documents, (newDocs) => {
      console.log('文档列表变化:', newDocs);
      if (newDocs && newDocs.length > 0) {
        currentDoc.value = newDocs[newDocs.length - 1]; // 预览最新上传的文档
      } else {
        currentDoc.value = null;
      }
    }, { 
      immediate: true, 
      deep: true  // 添加深层监听
    });

    // 额外监听文档列表长度变化
    watch(() => props.documents.length, (newLength, oldLength) => {
      console.log('文档数量变化:', newLength, oldLength);
      if (newLength > oldLength && props.documents.length > 0) {
        // 当新增文档时，预览最新的文档
        currentDoc.value = props.documents[props.documents.length - 1];
      } else if (newLength === 0) {
        currentDoc.value = null;
      }
    });
// Excel预览配置选项
const excelOptions = ref({
  xls: false,       // 预览xlsx文件设为false；预览xls文件设为true
  minColLength: 0,  // excel最少渲染多少列，设为0表示根据实际内容渲染
  minRowLength: 0,  // excel最少渲染多少行，设为0表示根据实际内容渲染
  widthOffset: 10,  // 在默认渲染的列表宽度上再加10px宽
  heightOffset: 10, // 在默认渲染的列表高度上再加10px高
  forceRender: true, // 强制渲染，即使文件可能有问题
  maxSheetLength: 10, // 最多渲染10个工作表
  beforeTransformData: (workbookData) => {
    console.log('Excel数据预处理:', workbookData);
    return workbookData;
  }, 
  transformData: (workbookData) => {
    return workbookData;
  }
});

// 处理渲染完成事件
const handleRendered = () => {
 
  console.log('文件渲染完成');
};

// 处理渲染错误事件
const handleError = (error) => {

  console.error('文件渲染失败:', error);
  ElMessage.error('文件预览失败，请尝试下载查看');
};

    // 组件挂载时，如果有文档就预览第一个
    onMounted(() => {
      console.log('组件挂载，当前文档:', props.documents);
      if (props.documents && props.documents.length > 0) {
        currentDoc.value = props.documents[0];
      }
    });
    const renderedHandler = () => {
            console.log("渲染完成")
        }
    const errorHandler = () => {
            console.log("渲染失败")
        }
    const isImageFile = (file) => {
      if (!file) return false;
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
      const ext = file.name?.split('.')?.pop()?.toLowerCase() || '';
      return imageTypes.includes(ext);
    };

    const isVideoFile = (file) => {
      if (!file) return false;
      const videoTypes = ['mp4', 'webm', 'ogg'];
      const ext = file.name?.split('.')?.pop()?.toLowerCase() || '';
      return videoTypes.includes(ext);
    };

    const isWordFile = (file) => {
      if (!file) return false;
      const wordTypes = ['doc', 'docx'];
      const ext = file.name?.split('.')?.pop()?.toLowerCase() || '';
      return wordTypes.includes(ext);
    };

    const isExcelFile = (file) => {
      if (!file) return false;
      const excelTypes = ['xls', 'xlsx'];
      const ext = file.name?.split('.')?.pop()?.toLowerCase() || '';
      return excelTypes.includes(ext);
    };

    const isPdfFile = (file) => {
      if (!file) return false;
      return file.name?.toLowerCase()?.endsWith('.pdf') || false;
    };

    const getFileIcon = (file) => {
      // 根据文件类型返回对应的图标
      return '/src/assets/svg/word.svg'; // 默认文档图标
    };

    const formatFileSize = (bytes) => {
      if (!bytes || isNaN(bytes)) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    const handleDownload = (doc) => {
      if (doc.url) {
        const link = document.createElement('a');
        link.href = doc.url;
        link.download = doc.name;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    };

    const closePreview = () => {
      currentDoc.value = null;
    };

    return {
      currentDoc,
      isImageFile,
      isVideoFile,
      isWordFile,
      isExcelFile,
      isPdfFile,
      getFileIcon,
      formatFileSize,
      handleDownload,
      closePreview,
      renderedHandler,
      errorHandler
    };
  }
});
</script>

<style lang="less" scoped>
.document-preview {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.preview-container {
  display: flex;
  height: 100%;
  gap: 16px;
}

.document-list {
  width: 300px;
  flex-shrink: 0;
  overflow-y: auto;
  padding: 16px;
  border-right: 1px solid var(--border-color);
}

.direct-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--secondary-bg);
  border-radius: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  color: var(--primary-text);

  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
  }

  p {
    font-size: 14px;
    margin: 0;
  }
}

.document-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  background: var(--secondary-bg);
  transition: all 0.3s;
  color: var(--primary-color);

  &.active {
    background: var(--primary-bg);
    border: 1px solid var(--primary-color);
  }
}

.document-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.doc-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.file-icon {
  width: 24px;
  height: 24px;
}

.info {
  flex: 1;
  min-width: 0;

  .name {
    font-size: 14px;
    color: var(--primary-text);
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .size {
    font-size: 12px;
    color: var(--primary-text);
  }
}

.actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary-text);
  transition: all 0.3s;

  &:hover {
    background: rgba(0, 0, 0, 0.04);
    color: #1677ff;
  }
}

.preview-header {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    font-size: 16px;
    font-weight: 500;
    color: var(--primary-text);
  }

  .close-btn {
    border: none;
    background: transparent;
    cursor: pointer;
    color: var(--primary-text);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      background: rgba(0, 0, 0, 0.04);
      color: var(--primary-color);
    }
  }
}

.preview-body {
  flex: 1;
  overflow: auto;
  padding: 24px;
  display: flex;
  align-items: flex-start;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.preview-video {
  max-width: 100%;
  max-height: 70vh;
}

.doc-preview {
  width: 100%;
  height: 100%;
  min-height: 500px;
}

.file-preview {
  text-align: center;
  color: var(--primary-text);

  .large-icon {
    font-size: 64px;
    margin-bottom: 16px;
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .preview-container {
    flex-direction: column;
  }

  .document-list {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid var(--border-color);
  }
}
</style> 