<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="uploadVisible = true">上传文件</el-button>
        </div>
      </template>
      <el-dialog v-model="uploadVisible" title="上传文件" width="400px" append-to-body @closed="resetUploadForm">
        <el-form label-width="80px">
          <el-form-item label="选择文件">
            <el-upload
              ref="uploadRef"
              :action="uploadUrl"
              :data="{ fileCate: stcd }"
              :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等常见文件，大小不超过50MB</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="uploadVisible = false">取 消</el-button>
        </template>
      </el-dialog>
      <div v-if="fileList.length === 0" class="empty-tip">
        <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>
          <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="StationFile">
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 stcd = ref(route.query.stcd || '')
const fileList = ref([])
const hoverId = ref('')
const uploadUrl = ref(import.meta.env.VITE_SERVICE_BASE_TITLE + '/slgc/doc-file/upload')
const uploadVisible = ref(false)
const uploadHeaders = { Authorization: 'Bearer ' + getToken() }
const isUploading = ref(false)

function loadFiles() {
  getDocFileList({ fileCate: stcd.value }).then(r => { fileList.value = r.rows || [] })
}
function handleDownloadFile(file) {
  if (!file.filePath) return
  request({ url: '/common/download', method: 'get', params: { fileName: 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
  uploadVisible.value = false
  if (res.code === 200) {
    ElMessage.success('上传成功')
    loadFiles()
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}
function handleUploadError() { isUploading.value = false; ElMessage.error('上传失败') }
function handleUploadFileChange(file) { }
function handleUploadFileRemove() { }
function resetUploadForm() { isUploading.value = false; uploadRef.value?.clearFiles() }
function handleDeleteFile(file) {
  proxy.$modal.confirm('确认删除"' + file.fileName + '"？').then(() => {
    delDocFile(file.fileId).then(() => { ElMessage.success('删除成功'); loadFiles() })
  })
}
function submitUpload() {
  if (!uploadRef.value) return
  isUploading.value = true
  try {
    uploadRef.value.submit()
  } catch (e) {
    isUploading.value = false
  }
}
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; }
</style>
