<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="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
    }
  },
  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 '[无法解码内容]'
      }
    }
  }
}
</script>

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