<template>
  <div class="app-container viewer-container">
    <el-card>
      <template #header>
        <div class="viewer-header">
          <span class="viewer-title">{{ route.query.fileName || "文件预览" }}</span>
          <div class="viewer-actions">
            <el-button icon="Download" @click="handleDownload" v-hasPermi="['efinder:file:download']">下载</el-button>
            <el-button icon="Back" @click="handleBack">返回</el-button>
          </div>
        </div>
      </template>
      <div class="viewer-body">
        <el-empty v-if="!fileId" description="未获取到文件信息" />
        <el-result v-else-if="loading" icon="Loading" title="加载中..." />
        <el-result v-else-if="error" icon="Error" title="加载失败" :sub-title="errorMsg">
          <template #extra>
            <el-button type="primary" @click="loadFile">重新加载</el-button>
          </template>
        </el-result>
        <template v-else>
          <div v-if="fileType === 'image'" class="viewer-image">
            <el-image :src="fileUrl" :preview-src-list="[fileUrl]" fit="contain" style="max-width: 100%; max-height: 80vh;" />
          </div>
          <div v-else-if="fileType === 'pdf'" class="viewer-pdf">
            <iframe :src="pdfUrl" style="width: 100%; height: 80vh; border: none;" />
          </div>
          <div v-else-if="fileType === 'text'" class="viewer-text">
            <pre class="text-content">{{ textContent }}</pre>
          </div>
          <div v-else-if="fileType === 'video'" class="viewer-video">
            <video :src="fileUrl" controls style="max-width: 100%; max-height: 80vh;" />
          </div>
          <div v-else-if="fileType === 'audio'" class="viewer-audio">
            <audio :src="fileUrl" controls style="width: 100%;" />
          </div>
          <el-result v-else icon="InfoFilled" title="暂不支持该文件类型的预览" sub-title="请尝试下载后查看">
            <template #extra>
              <el-button type="primary" icon="Download" @click="handleDownload">下载文件</el-button>
            </template>
          </el-result>
        </template>
      </div>
    </el-card>
  </div>
</template>

<script setup name="EfinderViewer">
import { getFileInfo, downloadFile } from "@/api/efinder/finder"

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const fileId = ref(route.query.fileId)
const fileType = ref(route.query.fileType)
const fileName = ref(route.query.fileName)
const fileUrl = ref("")
const textContent = ref("")
const loading = ref(true)
const error = ref(false)
const errorMsg = ref("")

const baseUrl = import.meta.env.VITE_SERVICE_BASE_TITLE

const pdfUrl = computed(() => {
  return baseUrl + "/efinder/file/preview/" + fileId.value
})

function loadFile() {
  loading.value = true
  error.value = false
  if (!fileId.value) {
    loading.value = false
    error.value = true
    errorMsg.value = "缺少文件ID"
    return
  }
  if (fileType.value === "text") {
    loadTextContent()
  } else {
    getFileInfo(fileId.value).then(response => {
      fileUrl.value = baseUrl + "/efinder/file/preview/" + fileId.value
      if (!fileType.value) {
        fileType.value = response.data.type
      }
      loading.value = false
    }).catch(err => {
      error.value = true
      errorMsg.value = err.msg || "文件加载失败"
      loading.value = false
    })
  }
}

function loadTextContent() {
  downloadFile(fileId.value).then(res => {
    const reader = new FileReader()
    reader.onload = (e) => {
      textContent.value = e.target.result
      loading.value = false
    }
    reader.onerror = () => {
      error.value = true
      errorMsg.value = "文本内容读取失败"
      loading.value = false
    }
    reader.readAsText(res)
  }).catch(err => {
    error.value = true
    errorMsg.value = err.msg || "文件加载失败"
    loading.value = false
  })
}

function handleDownload() {
  downloadFile(fileId.value).then(res => {
    const blob = new Blob([res])
    const link = document.createElement("a")
    link.href = URL.createObjectURL(blob)
    link.download = fileName.value || fileId.value
    link.click()
    URL.revokeObjectURL(link.href)
    proxy.$modal.msgSuccess("下载成功")
  })
}

function handleBack() {
  router.back()
}

onMounted(() => {
  loadFile()
})
</script>

<style lang="scss" scoped>
.viewer-container {
  height: calc(100vh - 84px);
}
.viewer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.viewer-title {
  font-size: 16px;
  font-weight: 600;
}
.viewer-actions {
  display: flex;
  gap: 8px;
}
.viewer-body {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.viewer-image,
.viewer-video {
  text-align: center;
  width: 100%;
}
.viewer-audio {
  width: 100%;
  max-width: 600px;
}
.viewer-pdf {
  width: 100%;
}
.text-content {
  width: 100%;
  max-height: 80vh;
  overflow: auto;
  background: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}
</style>
