<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>参赛证生成任务</span>
          <el-button type="primary" size="small" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      
      <el-table v-loading="loading" :data="taskList" border>
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column label="任务名称" prop="taskName" />
        <el-table-column label="赛事名称" prop="eventName" width="150">
          <template #default="scope">
            {{ scope.row.eventName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180">
          <template #default="scope">
            {{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </template>
        </el-table-column>
        <el-table-column label="完成时间" prop="finishTime" width="180">
          <template #default="scope">
            {{ scope.row.finishTime ? parseTime(scope.row.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === '0'" 
              type="warning" 
              size="small" 
              @click="handleStopTask(scope.row.taskId)"
            >
              停止
            </el-button>
            <el-button 
              v-if="scope.row.status === '2'" 
              type="success" 
              size="small" 
              :loading="downloadingTasks.has(scope.row.taskId)"
              @click="handleDownload(scope.row.taskId)"
            >
              {{ downloadingTasks.has(scope.row.taskId) ? '下载中...' : '下载' }}
            </el-button>
            <el-button 
              v-if="scope.row.status === '2'" 
              type="primary" 
              size="small" 
              @click="handleCopyDownloadLink(scope.row.taskId)"
            >
              复制链接
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row.taskId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination 
        v-show="total > 0" 
        :total="total" 
        v-model:page="queryParams.pageNum" 
        v-model:limit="queryParams.pageSize" 
        @pagination="getList" 
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getTaskList, pauseTask, deleteTask, downloadTask, smartDownloadTask, getDownloadUrl } from '@/api/system/gameEvent/task';
import { BASE_URL } from '@/config/api';

const router = useRouter();

const loading = ref(false);
const taskList = ref([]);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
});

// 下载状态管理
const downloadingTasks = ref(new Set<number>());

// 轮询定时器
let pollingTimer: NodeJS.Timeout | null = null;

// 存储上次轮询时的任务状态，用于比较状态变化
const lastTaskStates = ref(new Map<number, string>());

// 获取任务列表
const getList = async () => {
  loading.value = true;
  try {
    const response = await getTaskList(queryParams.value);
    taskList.value = response.rows;
    total.value = response.total;
    
    // 记录当前任务状态，用于后续轮询比较
    const currentTaskStates = new Map<number, string>();
    response.rows.forEach(task => {
      currentTaskStates.set(task.taskId, task.status);
    });
    lastTaskStates.value = currentTaskStates;
  } finally {
    loading.value = false;
  }
};

// 新建任务
const handleCreateTask = () => {
  router.push('/system/gameEvent');
};

// 复制下载链接
const handleCopyDownloadLink = async (taskId: number) => {
  try {
    // 获取当前任务信息，检查是否有OSS文件ID
    const currentTask = taskList.value.find(task => task.taskId === taskId);
    let downloadUrl;
    
    if (currentTask && currentTask.ossId) {
      // 如果有OSS文件ID，获取预签名URL（最快下载方式）
      try {
        const response = await getDownloadUrl(taskId);
        downloadUrl = response.msg || response.data;
        if (!downloadUrl || downloadUrl === 'null' || downloadUrl === '') {
          // 如果获取预签名URL失败，回退到代理下载
          downloadUrl = `${BASE_URL}/system/number/public/downloadTask/${taskId}`;
        }
      } catch (error) {
        console.warn('获取预签名URL失败，使用代理下载:', error);
        downloadUrl = `${BASE_URL}/system/number/public/downloadTask/${taskId}`;
      }
    } else {
      // 否则使用原有的下载链接
      downloadUrl = `${BASE_URL}/system/number/public/downloadTask/${taskId}`;
    }
    
    // 复制到剪贴板
    await navigator.clipboard.writeText(downloadUrl);
    ElMessage.success('下载链接已复制到剪贴板');
  } catch (error) {
    console.error('复制失败:', error);
    // 降级方案：使用传统的复制方法
    const currentTask = taskList.value.find(task => task.taskId === taskId);
    let downloadUrl;
    
    if (currentTask && currentTask.ossId) {
      // 如果有OSS文件ID，获取预签名URL（最快下载方式）
      try {
        const response = await getDownloadUrl(taskId);
        downloadUrl = response.msg || response.data;
        if (!downloadUrl || downloadUrl === 'null' || downloadUrl === '') {
          // 如果获取预签名URL失败，回退到代理下载
          downloadUrl = `${BASE_URL}/system/number/public/downloadTask/${taskId}`;
        }
      } catch (error) {
        console.warn('获取预签名URL失败，使用代理下载:', error);
        downloadUrl = `${BASE_URL}/system/number/public/downloadTask/${taskId}`;
      }
    } else {
      // 否则使用原有的下载链接
      downloadUrl = `${BASE_URL}/system/number/public/downloadTask/${taskId}`;
    }
    
    const textArea = document.createElement('textarea');
    textArea.value = downloadUrl;
    document.body.appendChild(textArea);
    textArea.select();
    try {
      document.execCommand('copy');
      ElMessage.success('下载链接已复制到剪贴板');
    } catch (fallbackError) {
      ElMessage.error('复制失败，请手动复制链接');
    }
    document.body.removeChild(textArea);
  }
};

// 手动刷新
const handleRefresh = () => {
  getList();
  ElMessage.success('刷新成功');
};

// 停止任务
const handleStopTask = async (taskId: number) => {
  try {
    await ElMessageBox.confirm('确定要停止这个任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await pauseTask(taskId);
    ElMessage.success('任务已停止');
    getList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('停止失败');
    }
  }
};

// 下载任务结果（使用智能下载）
const handleDownload = async (taskId: number) => {
  downloadingTasks.value.add(taskId);
  try {
    await smartDownloadTask(taskId);
    // ElMessage.success('下载完成');
  } catch (error) {
    ElMessage.error('下载失败');
  } finally {
    downloadingTasks.value.delete(taskId);
  }
};

// 删除任务
const handleDelete = async (taskId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await deleteTask(taskId);
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 状态相关方法
const getStatusType = (status: string) => {
  const statusMap = {
    '0': 'warning',  // 运行中
    '1': 'info',     // 暂停
    '2': 'success',  // 完成
    '3': 'danger'    // 失败
  };
  return statusMap[status] || 'info';
};

const getStatusText = (status: string) => {
  const statusMap = {
    '0': '运行中',
    '1': '暂停',
    '2': '完成',
    '3': '失败'
  };
  return statusMap[status] || '未知';
};

// 开始轮询
const startPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer);
  }
  pollingTimer = setInterval(async () => {
    // 只轮询有运行中任务的情况
    const hasRunningTasks = taskList.value.some(task => task.status === '0');
    if (hasRunningTasks) {
      await checkTaskStatusChanges();
    }
  }, 15000); // 每15秒检查一次
};

// 检查任务状态变化
const checkTaskStatusChanges = async () => {
  try {
    const response = await getTaskList(queryParams.value);
    const currentTasks = response.rows;
    
    // 检查是否有任务状态发生变化
    let hasStatusChanged = false;
    const currentTaskStates = new Map<number, string>();
    
    currentTasks.forEach(task => {
      const taskId = task.taskId;
      const currentStatus = task.status;
      const lastStatus = lastTaskStates.value.get(taskId);
      
      currentTaskStates.set(taskId, currentStatus);
      
      // 如果状态发生变化，标记需要更新
      if (lastStatus && lastStatus !== currentStatus) {
        hasStatusChanged = true;
      }
    });
    
    // 只有当状态发生变化时才更新UI
    if (hasStatusChanged) {
      taskList.value = currentTasks;
      total.value = response.total;
    }
    
    // 更新状态记录
    lastTaskStates.value = currentTaskStates;
    
  } catch (error) {
  }
};

// 停止轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer);
    pollingTimer = null;
  }
};

onMounted(() => {
  getList();
  startPolling();
});

onUnmounted(() => {
  stopPolling();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
