<template>
  <el-dialog 
    title="附件列表" 
    v-model="visible" 
    :width="800" 
    :close-on-click-modal="false" 
    draggable>
    <div v-loading="loading">
      <div v-if="fileList.length === 0" class="text-center text-gray-400 py-10">
        暂无附件
      </div>
      <div v-else>
        <div
          v-for="(file, index) in fileList"
          :key="index"
          class="flex items-center px-4 py-3 mb-2 rounded border border-gray-200 hover:bg-blue-50 transition-colors">
          <el-icon class="mr-3 text-blue-500 text-lg"><Document /></el-icon>
          <span class="flex-1 text-gray-700 truncate">{{ getFileName(file) }}</span>
          <el-button 
            icon="Download" 
            text 
            type="primary" 
            size="small"
            @click="handleDownload(file)">
            下载
          </el-button>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">关 闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="ClassConstructionFileListDialog">
import { ref } from 'vue'
import { Document, Download } from '@element-plus/icons-vue'
import { getDetail } from '/@/api/stuwork/classconstruction'
import { useMessage } from '/@/hooks/message'
import other from '/@/utils/other'

// 定义变量内容
const visible = ref(false)
const loading = ref(false)
const fileList = ref<string[]>([])
const currentRow = ref<any>(null)

// 获取文件名
const getFileName = (url: string): string => {
  if (!url) return '未知文件'
  return other.getQueryString(url, 'fileName') || other.getQueryString(url, 'originalFileName') || url.split('/').pop() || '未知文件'
}

// 下载文件
const handleDownload = (url: string) => {
  if (!url) {
    useMessage().warning('文件地址无效')
    return
  }
  window.open(url, '_blank')
}

// 打开弹窗
const openDialog = async (row: any) => {
  visible.value = true
  currentRow.value = row
  fileList.value = []
  
  if (!row.id) {
    useMessage().warning('数据异常')
    return
  }
  
  loading.value = true
  try {
    // API文档中没有单独的附件列表接口，直接从row中获取fileUrl
    if (row.fileUrl) {
      const urls = row.fileUrl
      fileList.value = typeof urls === 'string' ? urls.split(',').filter((url: string) => url.trim()) : []
    } else {
      // 如果没有fileUrl，尝试获取详情
      const res = await getDetail(row.id)
      if (res.data && res.data.fileUrl) {
        const urls = res.data.fileUrl
        fileList.value = typeof urls === 'string' ? urls.split(',').filter((url: string) => url.trim()) : []
      } else {
        fileList.value = []
      }
    }
  } catch (err: any) {
    useMessage().error(err.msg || '获取附件列表失败')
    fileList.value = []
  } finally {
    loading.value = false
  }
}

// 暴露方法
defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
</style>

