<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="400px" append-to-body :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-item label="选择文件">
            <el-upload
              ref="uploadRef"
              :action="uploadUrl"
              :data="{ fileCate: 'UNIT-' + unitId, fileTitle: fileTitle }"
              :headers="uploadHeaders"
              :limit="1"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :on-change="handleUploadFileChange"
              :on-remove="handleUploadFileRemove"
              :before-upload="beforeUpload"
              :auto-upload="false"
              :show-file-list="true">
              <el-button type="primary" size="small" icon="Upload">选择文件</el-button>
              <template #tip><div class="el-upload__tip">支持PDF、Word等常见文件</div></template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" :loading="isUploading" @click="submitUpload">{{ isUploading ? '上传中...' : '上 传' }}</el-button>
          <el-button @click="uploadDialogVisible = false">取 消</el-button>
        </template>
      </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="javascript:void(0)" class="file-name" @click="handleDownloadFile(file)">{{ 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 { ElMessage, ElMessageBox } from 'element-plus'
import { getDocFileList, delDocFile } from '@/api/slgc/doc/index'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

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(import.meta.env.VITE_SERVICE_BASE_TITLE + '/slgc/doc-file/upload')
const uploadHeaders = { Authorization: 'Bearer ' + getToken() }
const isUploading = ref(false)
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 handleDownloadFile(file) {
  if (!file.filePath) return
  request({ url: '/common/download/resource', method: 'get', params: { resource: file.filePath }, responseType: 'blob' }).then(res => {
    const blob = new Blob([res])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = file.fileName || '下载文件'
    link.click()
    window.URL.revokeObjectURL(url)
  }).catch(() => { ElMessage.error('下载失败') })
}

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) {
  isUploading.value = false
  uploadDialogVisible.value = false
  if (res.code === 200) {
    ElMessage.success('上传成功')
    fileTitle.value = ''
    loadFiles()
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

function handleUploadFileChange(file) {
  if (!fileTitle.value) fileTitle.value = file.name || file.raw?.name || ''
}

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

function resetUploadForm() {
  fileTitle.value = ''
  isUploading.value = false
  uploadRef.value?.clearFiles()
}

function handleUploadError() {
  isUploading.value = false
  ElMessage.error('上传失败')
}
function submitUpload() {
  if (!uploadRef.value) return
  isUploading.value = true
  try {
    uploadRef.value.submit()
  } catch (e) {
    isUploading.value = false
  }
}

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>
