<template>
  <div class="upload-container">
    <h2>多文件分片上传 (Vue3 + Element Plus)</h2>
    
    <el-card shadow="hover">
      <el-upload
        ref="uploadRef"
        class="multi-uploader"
        action="#" 
        :auto-upload="false" 
        multiple
        :limit="10"
        :on-change="handleFileChange"
        :on-remove="handleRemove"
        :file-list="fileList"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        
        <!-- 自定义文件列表项 -->
        <template #file="{ file }">
          <div class="el-upload-list__item-custom">
            <div class="file-info">
              <el-icon><Document /></el-icon>
              <span class="file-name">{{ file.name }}</span>
              <span class="file-size">{{ formatSize(file.size) }}</span>
            </div>

            <!-- 状态与进度区域 -->
            <div class="file-action-area">
              <!-- 等待上传状态 -->
              <div v-if="getTaskStatus(file.uid)?.status === 'idle' || !getTaskStatus(file.uid)" class="status-wait">
                <el-tag size="small">待上传</el-tag>
                <el-button link type="primary" @click="startSingleUpload(file)">开始</el-button>
              </div>

              <!-- 进行中/暂停/合并状态 -->
              <div v-else-if="['checking', 'uploading', 'merging', 'paused'].includes(getTaskStatus(file.uid)?.status)" class="status-progress">
                <el-progress 
                  :percentage="getTaskStatus(file.uid)?.progress || 0" 
                  :status="getTaskStatus(file.uid)?.status === 'paused' ? 'exception' : undefined"
                  :format="(percent) => getTaskStatus(file.uid)?.message || `${percent}%`"
                />
                <div class="btn-group">
                  <el-button 
                    v-if="getTaskStatus(file.uid)?.status !== 'paused'"
                    link type="warning" 
                    @click="handlePause(file.uid)"
                  >暂停</el-button>
                  <el-button 
                    v-else
                    link type="success" 
                    @click="handleResume(file.uid)"
                  >继续</el-button>
                  <el-button link type="danger" @click="handleCancel(file.uid)">取消</el-button>
                </div>
              </div>

              <!-- 成功状态 -->
              <div v-else-if="getTaskStatus(file.uid)?.status === 'success'" class="status-success">
                <el-tag type="success" effect="plain">完成</el-tag>
                <span class="success-text">✓ {{ getTaskStatus(file.uid)?.message }}</span>
              </div>

              <!-- 失败状态 -->
              <div v-else-if="getTaskStatus(file.uid)?.status === 'error'" class="status-error">
                <el-tag type="danger" effect="plain">失败</el-tag>
                <span class="error-text">{{ getTaskStatus(file.uid)?.message }}</span>
                <el-button link type="primary" @click="startSingleUpload(file)">重试</el-button>
              </div>
            </div>
          </div>
        </template>
      </el-upload>

      <div class="global-actions" v-if="fileList.length > 0">
        <el-button type="success" @click="startAllUploads" :disabled="isUploadingAny">全部开始</el-button>
        <el-button type="info" @click="clearAll">清空列表</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { Document } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useMultiFileUpload } from '@/composables/useMultiFileUpload';

const uploadRef = ref(null);
const fileList = ref([]); // Element Plus 管理的文件列表

// 引入我们的逻辑钩子
const { startUpload, pauseFile, resumeFile, cancelFile, getTaskStatus } = useMultiFileUpload();

// 格式化大小
const formatSize = (bytes) => {
  if (!bytes) return '';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 当用户选择文件时
const handleFileChange = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles;
  // 初始化状态为 idle (实际上 useMultiFileUpload 会在 start 时初始化)
};

// 移除文件
const handleRemove = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles;
  cancelFile(uploadFile.uid); // 如果正在传，先取消
};

// 单个开始上传
const startSingleUpload = (file) => {
  // 这里的 file 是 element-plus 的 UploadFile 对象，raw 才是原生 File 对象
  if (!file.raw) return;
  
  // 定义回调，用于强制刷新视图（虽然 uploadTasks 是响应式的，但有时 EL 的 slot 更新不及时，可加 forceUpdate 逻辑，此处依赖响应式）
  const updateCallback = (uid, status, progress, msg) => {
    // 如果需要更激进的 UI 更新，可以在这里操作 fileList 中的对应项
    // 但通常响应式对象足够
  };

  startUpload(file.raw, updateCallback);
};

// 全部开始 (简单实现：遍历所有未成功的文件)
const startAllUploads = () => {
  fileList.value.forEach(file => {
    const status = getTaskStatus(file.uid)?.status;
    if (!status || status === 'error' || status === 'idle' || status === 'paused') {
      // 如果是 paused，调用 resume 逻辑可能需要特殊处理，这里简化为重新触发 start (我们的 logic 支持断点)
      if (status === 'paused') {
        resumeFile(file.uid);
      } else {
        startSingleUpload(file);
      }
    }
  });
};

const handlePause = (uid) => pauseFile(uid);
const handleResume = (uid) => resumeFile(uid);
const handleCancel = (uid) => {
  cancelFile(uid);
  // 从列表中移除视觉上的文件（可选，看需求是保留记录还是直接删掉）
  // fileList.value = fileList.value.filter(f => f.uid !== uid); 
};

const clearAll = () => {
  fileList.value = [];
  // 清理内部状态逻辑略
};

const isUploadingAny = computed(() => {
  return fileList.value.some(f => {
    const s = getTaskStatus(f.uid)?.status;
    return s === 'uploading' || s === 'checking' || s === 'merging';
  });
});
</script>

<style scoped>
.upload-container {
  max-width: 800px;
  margin: 20px auto;
}

.el-upload-list__item-custom {
  display: flex;
  flex-direction: column;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.2s;
}

.el-upload-list__item-custom:hover {
  background-color: #f5f7fa;
}

.file-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.file-info .el-icon {
  margin-right: 8px;
  color: #409eff;
  font-size: 20px;
}

.file-name {
  font-weight: bold;
  color: #606266;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 10px;
}

.file-size {
  font-size: 12px;
  color: #909399;
}

.file-action-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.status-wait, .status-success, .status-error {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.status-progress {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-progress .el-progress {
  flex: 1;
}

.btn-group {
  display: flex;
  gap: 5px;
}

.global-actions {
  margin-top: 20px;
  text-align: right;
  border-top: 1px solid #eee;
  padding-top: 15px;
}
</style>