<template>
  <div class="page-content">
    <div class="mb-5 flex justify-between">
      <div><h2 class="text-xl font-semibold">我的文件仓库</h2><p class="text-g-500 mt-1 text-sm">个人文件存储于平台对象存储，仅自己可见，可通过 API 下载引用</p></div>
      <ElUpload :show-file-list="false" :http-request="upload">
        <ElButton type="primary" :loading="uploading">上传文件</ElButton>
      </ElUpload>
    </div>
    <ElTable v-loading="loading" :data="files">
      <ElTableColumn prop="original_name" label="文件名" min-width="200" show-overflow-tooltip/>
      <ElTableColumn label="大小" width="120"><template #default="{row}">{{ formatBytes(row.size_bytes) }}</template></ElTableColumn>
      <ElTableColumn prop="content_type" label="类型" width="180" show-overflow-tooltip/>
      <ElTableColumn prop="created_at" label="上传时间" width="190"/>
      <ElTableColumn label="操作" width="160" fixed="right"><template #default="{row}">
        <ElButton link type="primary" @click="download(row)">下载</ElButton>
        <ElButton link type="danger" @click="remove(row)">删除</ElButton>
      </template></ElTableColumn>
    </ElTable>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { FileObject, deleteMyFile, downloadMyFile, fetchMyFiles, uploadMyFile } from '@/api/portal'
const loading = ref(false), uploading = ref(false)
const files = ref<FileObject[]>([])
function formatBytes(n: number) {
  if (n < 1024) return `${n} B`
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`
  if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MiB`
  return `${(n / 1024 / 1024 / 1024).toFixed(2)} GiB`
}
async function load() {
  loading.value = true
  try { files.value = await fetchMyFiles() } finally { loading.value = false }
}
async function upload({ file }: { file: File }) {
  uploading.value = true
  try {
    await uploadMyFile(file)
    ElMessage.success('上传成功')
    await load()
  } finally { uploading.value = false }
}
function download(row: FileObject) {
  downloadMyFile(row.id, row.original_name)
}
async function remove(row: FileObject) {
  await ElMessageBox.confirm(`确认删除文件「${row.original_name}」？`, '删除确认', { type: 'warning' })
  await deleteMyFile(row.id)
  ElMessage.success('已删除')
  await load()
}
onMounted(load)
</script>
