<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <el-space>
            <el-button text @click="$router.back()">← 返回</el-button>
            <span>单位档案</span>
          </el-space>
          <el-button type="primary" size="small" @click="uploadDialogVisible = true">上传文件</el-button>
        </div>
      </template>
      <el-dialog v-model="uploadDialogVisible" title="上传文件" width="480px" :close-on-click-modal="false" @closed="resetUploadForm">
        <el-form label-width="80px">
          <el-form-item label="标题">
            <el-input v-model="fileTitle" placeholder="请输入文件标题" maxlength="100" />
          </el-form-item>
        </el-form>
        <el-upload
          ref="uploadRef"
          :action="uploadUrl"
          :data="{ fileCate: 'UNIT-' + unitId, fileTitle: fileTitle }"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError">
          <el-button type="primary" size="small">选择文件</el-button>
        </el-upload>
      </el-dialog>
      <div v-if="fileList.length === 0">
        <el-empty description="暂无档案文件" />
      </div>
      <div v-else class="file-list">
        <div v-for="file in fileList" :key="file.fileId" class="file-item" @mouseover="hoverId = file.fileId" @mouseout="hoverId = ''">
          <el-icon size="16" color="#409EFF"><Document /></el-icon>
          <a :href="getDownloadUrl(file)" target="_blank" class="file-name">{{ file.fileName }}</a>
          <span class="file-size">{{ formatSize(file.fileSize) }}</span>
          <span class="file-time">{{ file.createTime }}</span>
          <el-button v-show="hoverId === file.fileId" type="danger" link size="small" @click.stop="handleDeleteFile(file)">删除</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="UnitFile">
import { getDocFileList, delDocFile } from '@/api/slgc/doc/index'

const route = useRoute()
const { proxy } = getCurrentInstance()
const uploadRef = ref(null)
const unitId = ref(route.query.id || '')
const fileList = ref([])
const hoverId = ref('')
const uploadUrl = ref('/slgc/doc-file/upload')
const uploadDialogVisible = ref(false)
const fileTitle = ref('')

function loadFiles() {
  if (!unitId.value) return
  getDocFileList({ fileCate: 'UNIT-' + unitId.value }).then(r => {
    fileList.value = r.rows || []
  })
}

function getDownloadUrl(file) {
  return `/common/download?fileName=${encodeURIComponent(file.filePath)}`
}

function formatSize(size) {
  if (!size) return ''
  const s = Number(size)
  if (s < 1024) return s + ' B'
  if (s < 1048576) return (s / 1024).toFixed(1) + ' KB'
  return (s / 1048576).toFixed(1) + ' MB'
}

function beforeUpload(file) {
  const maxSize = 50 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过 50MB')
    return false
  }
  return true
}

function handleUploadSuccess(res) {
  if (res.code === 200) {
    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    fileTitle.value = ''
    loadFiles()
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

function resetUploadForm() {
  fileTitle.value = ''
}

function handleUploadError() {
  ElMessage.error('上传失败')
}

function handleDeleteFile(file) {
  proxy.$modal.confirm('确认删除"' + file.fileName + '"？').then(() => {
    delDocFile(file.fileId).then(() => {
      ElMessage.success('删除成功')
      loadFiles()
    })
  })
}

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

<style scoped>
.card-header { font-weight: 600; font-size: 16px; display: flex; justify-content: space-between; align-items: center; }
.file-list { padding: 8px 0; }
.file-item { display: flex; align-items: center; padding: 8px 12px; border-bottom: 1px solid #f0f0f0; }
.file-item:hover { background: #fafafa; }
.file-name { margin-left: 8px; flex: 1; color: #409EFF; text-decoration: none; font-size: 14px; }
.file-name:hover { text-decoration: underline; }
.file-size { color: #999; font-size: 12px; margin-right: 12px; }
.file-time { color: #999; font-size: 12px; margin-right: 12px; }
</style>
