<template>
  <div class="contract-preview">
    <div class="preview-content">
      <iframe
        v-if="previewUrl"
        :src="previewUrl"
        class="preview-iframe"
        frameborder="0"
        width="100%"
        height="100%"
      ></iframe>
      <el-empty v-else description="文件地址无效">
        <el-button type="primary" @click="downloadFile">下载文档</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';

const route = useRoute();
const loading = ref(true);

const fileUrl = computed(() => route.query.file as string);

// 获取文件扩展名
const fileExtension = computed(() => {
  if (!fileUrl.value) return '';
  return fileUrl.value.split('.').pop()?.toLowerCase() || '';
});

// 根据文件类型生成预览URL
const previewUrl = computed(() => {
  if (!fileUrl.value) return '';
  
  // 对URL进行编码
  const encodedUrl = encodeURIComponent(fileUrl.value);
  
  switch (fileExtension.value) {
    case 'pdf':
      return fileUrl.value; // PDF直接使用原始URL
    case 'doc':
    case 'docx':
      // 使用Microsoft Office Online Viewer
      return `https://view.officeapps.live.com/op/embed.aspx?src=${encodedUrl}`;
      // 备选方案：使用Google Docs Viewer
      // return `https://docs.google.com/viewer?url=${encodedUrl}&embedded=true`;
    default:
      ElMessage.warning('不支持的文件类型，将尝试直接预览');
      return fileUrl.value;
  }
});

const downloadFile = () => {
  const url = fileUrl.value;
  if (url) {
    window.open(url, '_blank');
  } else {
    ElMessage.error('文件地址无效');
  }
};
</script>

<style scoped>
.contract-preview {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.preview-content {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  overflow: hidden;
  position: relative;
}

.preview-iframe {
  width: 100%;
  height: 100%;
  border: none;
}
</style> 