<template>
  <div class="course-upload">
    <h2>上传课程资料</h2>
    
    <el-upload
      multiple
      :limit="5"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :http-request="uploadFiles"
    >
      <el-button type="primary">选择文件</el-button>
      <template #tip>
        <div class="el-upload__tip">
          支持 PDF、Word、PPT 等格式文件，单个文件不超过 50MB
        </div>
      </template>
    </el-upload>
    
    <div v-if="uploadingFiles.length > 0" class="upload-progress">
      <div v-for="(file, index) in uploadingFiles" :key="index" class="file-item">
        <span>{{ file.name }}</span>
        <el-progress :percentage="file.progress" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { upload } from '../../utils/request'

const courseId = ref('123') // 假设已知课程ID
const uploadingFiles = ref([])

const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件')
}

const beforeUpload = (file) => {
  const validTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation']
  const isValidType = validTypes.includes(file.type)
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isValidType) {
    ElMessage.error('只能上传PDF、Word、PPT等格式文件!')
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB!')
  }
  
  if (isValidType && isLt50M) {
    // 添加到上传列表
    uploadingFiles.value.push({
      name: file.name,
      progress: 0
    })
  }
  
  return isValidType && isLt50M
}

const uploadFiles = async (options) => {
  const fileIndex = uploadingFiles.value.findIndex(item => item.name === options.file.name)
  
  try {
    const res = await upload(`/courses/${courseId.value}/materials`, options.file, (progress) => {
      if (fileIndex !== -1) {
        uploadingFiles.value[fileIndex].progress = progress
      }
    })
    
    ElMessage.success(`${options.file.name} 上传成功`)
    
    // 上传完成后从列表中移除
    if (fileIndex !== -1 && uploadingFiles.value[fileIndex].progress === 100) {
      setTimeout(() => {
        uploadingFiles.value.splice(fileIndex, 1)
      }, 1000)
    }
    
    return res
  } catch (error) {
    console.error('文件上传失败:', error)
    if (fileIndex !== -1) {
      uploadingFiles.value[fileIndex].progress = 0
    }
    ElMessage.error(`${options.file.name} 上传失败`)
  }
}
</script> 