<template>
  <div class="file-preview">
    <div v-if="fileInfo && fileInfo.type === 'file'" style="margin-bottom: 10px;display:flex;align-items:center;">
      <el-button
        icon="el-icon-download"
        type="primary"
        size="mini"
        @click="$emit('download', fileInfo)"
      >下载</el-button>
      <span v-if="fileInfo.name" style="margin-left: 12px;font-weight:bold;">{{ fileInfo.name }}</span>
    </div>
    <el-alert v-if="fileInfo && fileInfo.errorMsg" :title="fileInfo.errorMsg" type="error" show-icon />
    <template v-else-if="loading">
      <div class="loading-container">
        <el-progress type="circle" :percentage="50" status="exception" :indeterminate="true"></el-progress>
        <div style="margin-top: 10px;">正在加载中，请稍候...</div>
      </div>
    </template>
    <template v-else-if="fileInfo">
      <div v-if="fileInfo.type === 'file'">
        <template v-if="fileInfo.isPreviewable">
          <div v-if="fileInfo.contentType.startsWith('image/')">
            <el-image
              style="max-width:90%;max-height:800px;display:block;object-fit:contain;"
              :src="fileInfo.dataUrl"
              :preview-src-list="[fileInfo.dataUrl]"
              :initial-index="0"
              fit="contain"
              :alt="fileInfo.name"
              :preview-on-click="false"
            />
          </div>
          <div v-else-if="isPdf(fileInfo)">
            <!-- 使用官方 PDF.js 在线viewer（CORS 已在后端放开），功能齐全 -->
            <iframe v-if="pdfViewerUrl" :src="pdfViewerUrl" style="width:100%;height:80vh;border:none;" title="PDF预览"></iframe>
            <!-- 兜底：如果viewerUrl不可用，回退到浏览器原生object/iframe -->
            <template v-else>
              <object :data="pdfUrl" type="application/pdf" style="width:100%;height:80vh;">
                <iframe :src="pdfUrl" style="width:100%;height:80vh;border:none;" title="PDF预览"></iframe>
              </object>
            </template>
            <div style="margin-top:6px;">
              <el-link type="primary" :href="pdfUrl" target="_blank">在新窗口打开 PDF</el-link>
            </div>
          </div>
          <div v-else-if="fileInfo.contentType.startsWith('text/')">
            <pre style="max-height:400px;overflow:auto;background:#f5f5f5;padding:10px;">
              <code>{{ decodeBase64(fileInfo.base64Data) }}</code>
            </pre>
          </div>
          <div v-else>
            <el-alert title="暂不支持该类型预览" type="info" show-icon />
          </div>
        </template>
        <template v-else>
          <el-alert title="该文件类型不支持在线预览，可下载查看" type="warning" show-icon />
        </template>
      </div>
      <div v-else-if="fileInfo.type === 'directory'">
        <el-alert title="请选择文件进行预览" type="info" show-icon />
      </div>
    </template>
    <template v-else>
      <el-empty description="暂无预览内容" />
    </template>
  </div>
</template>

<script>
export default {
  name: 'FilePreview',
  props: {
    fileInfo: {
      type: Object,
      default: null
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      pdfUrl: '',
      pdfViewerUrl: ''
    }
  },
  watch: {
    fileInfo: {
      handler(val) {
        // 释放旧的 blob url
        try { if (this.pdfUrl && this.pdfUrl.startsWith('blob:')) URL.revokeObjectURL(this.pdfUrl) } catch(e) {}
        this.pdfUrl = ''
        this.pdfViewerUrl = ''
        if (val && this.isPdf(val)) {
          const du = (val.dataUrl || '')
          if (du.startsWith('http') || du.startsWith('blob:') || du.startsWith('data:application/pdf')) {
            this.pdfUrl = du
          } else if (val.base64Data) {
            // base64 -> blob url
            try {
              const bin = window.atob(val.base64Data)
              const len = bin.length
              const bytes = new Uint8Array(len)
              for (let i = 0; i < len; i++) bytes[i] = bin.charCodeAt(i)
              const blob = new Blob([bytes], { type: 'application/pdf' })
              this.pdfUrl = URL.createObjectURL(blob)
            } catch (e) {
              this.pdfUrl = du
            }
          } else {
            this.pdfUrl = du
          }
          // 生成 PDF.js viewer 地址（优先使用直链/Blob）
          if (this.pdfUrl) {
            // 这里假设 pdfjs 放在 /static/pdfjs/web/viewer.html （如需改路径请调整）
            this.pdfViewerUrl = `/static/pdfjs/web/viewer.html?file=${encodeURIComponent(this.pdfUrl)}`
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    decodeBase64(base64Str) {
      try {
        // 更好地支持utf-8文本
        const binary = window.atob(base64Str)
        const bytes = new Uint8Array([...binary].map(char => char.charCodeAt(0)))
        const decoder = new TextDecoder('utf-8')
        return decoder.decode(bytes)
      } catch (e) {
        return '[无法解码内容]'
      }
    },
    isPdf(info) {
      if (!info) return false
      const ct = (info.contentType || '').toLowerCase()
      const name = (info.name || '').toLowerCase()
      return ct === 'application/pdf' || ct.endsWith('/pdf') || name.endsWith('.pdf')
    }
  }
}
</script>

<style scoped>
.file-preview {
  margin: 10px 0;
}
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}
</style>