<template>
  <div class="task-status-page">
    <div class="page-header">
      <h1>{{ $t('taskMonitor.title') }}</h1>
      <div class="header-actions">
        <button @click="refreshAll" class="btn-refresh" :disabled="loading">
          {{ loading ? $t('taskMonitor.refreshing') : $t('taskMonitor.refreshAll') }}
        </button>
        <button @click="triggerPolling" class="btn-poll" v-if="isAdmin">
          {{ $t('taskMonitor.manualPolling') }}
        </button>
      </div>
    </div>
    
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon pending">⏳</div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.pending }}</div>
          <div class="stat-label">{{ $t('taskMonitor.pending') }}</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon processing">🔄</div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.processing }}</div>
          <div class="stat-label">{{ $t('taskMonitor.processing') }}</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon completed">✅</div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.completed }}</div>
          <div class="stat-label">{{ $t('taskMonitor.completed') }}</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon failed">❌</div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.failed }}</div>
          <div class="stat-label">{{ $t('taskMonitor.failed') }}</div>
        </div>
      </div>
    </div>
    
    <div class="task-list">
      <div class="list-header">
        <h2>{{ $t('taskMonitor.taskList') }}</h2>
        <div class="filter-controls">
          <select v-model="statusFilter" @change="filterTasks">
            <option value="">{{ $t('taskMonitor.allStatus') }}</option>
            <option value="PENDING">{{ $t('taskMonitor.pending') }}</option>
            <option value="PROCESSING">{{ $t('taskMonitor.processing') }}</option>
            <option value="COMPLETED">{{ $t('taskMonitor.completed') }}</option>
            <option value="FAILED">{{ $t('taskMonitor.failed') }}</option>
            <option value="CANCELLED">{{ $t('taskMonitor.cancelled') }}</option>
            <option value="TIMEOUT">{{ $t('taskMonitor.timeout') }}</option>
          </select>
        </div>
      </div>
      
      <div class="task-items">
        <div 
          v-for="task in filteredTasks" 
          :key="task.taskId"
          class="task-item"
          :class="getTaskItemClass(task.status)"
        >
          <div class="task-main">
            <div class="task-info">
              <div class="task-id">{{ task.taskId }}</div>
              <div class="task-type">{{ task.taskType?.description || task.taskType }}</div>
              <div class="task-time">{{ formatDate(task.createdAt) }}</div>
            </div>
            
            <div class="task-status">
              <div class="status-badge" :class="getStatusClass(task.status)">
                {{ task.statusDescription || task.status }}
              </div>
              <div class="progress-info" v-if="task.status === 'PROCESSING'">
                <div class="progress-bar">
                  <div 
                    class="progress-fill" 
                    :style="{ width: task.progress + '%' }"
                  ></div>
                </div>
                <span class="progress-text">{{ task.progress }}%</span>
              </div>
            </div>
          </div>
          
          <div class="task-actions">
            <button 
              v-if="task.resultUrl" 
              @click="viewResult(task.resultUrl)"
              class="btn-view"
            >
              {{ $t('taskMonitor.viewResult') }}
            </button>
            <button 
              v-if="['FAILED', 'TIMEOUT'].includes(task.status)" 
              @click="retryTask(task.taskId)"
              class="btn-retry"
            >
              {{ $t('taskMonitor.retry') }}
            </button>
          </div>
        </div>
      </div>
      
      <div v-if="filteredTasks.length === 0" class="empty-state">
        <div class="empty-icon">📋</div>
        <div class="empty-text">{{ $t('taskMonitor.noTasks') }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { taskStatusApi } from '@/api/taskStatus'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const userStore = useUserStore()

const tasks = ref([])
const loading = ref(false)
const statusFilter = ref('')
const refreshTimer = ref(null)

// 计算属性
const isAdmin = computed(() => userStore.isAdmin)

const stats = computed(() => {
  const stats = {
    pending: 0,
    processing: 0,
    completed: 0,
    failed: 0
  }
  
  tasks.value.forEach(task => {
    switch (task.status) {
      case 'PENDING':
        stats.pending++
        break
      case 'PROCESSING':
        stats.processing++
        break
      case 'COMPLETED':
        stats.completed++
        break
      case 'FAILED':
      case 'CANCELLED':
      case 'TIMEOUT':
        stats.failed++
        break
    }
  })
  
  return stats
})

const filteredTasks = computed(() => {
  if (!statusFilter.value) {
    return tasks.value
  }
  return tasks.value.filter(task => task.status === statusFilter.value)
})

// 方法
const fetchTasks = async () => {
  try {
    loading.value = true
    const response = await taskStatusApi.getUserTaskStatuses(userStore.user?.username)
    tasks.value = response.data
  } catch (error) {
    console.error('获取任务列表失败:', error)
    message.error(t('common.loadTaskListFailed'))
  } finally {
    loading.value = false
  }
}

const refreshAll = async () => {
  await fetchTasks()
  message.success(t('common.taskListRefreshed'))
}

const filterTasks = () => {
  // 过滤逻辑在计算属性中处理
}

const viewResult = (resultUrl) => {
  window.open(resultUrl, '_blank')
}

const retryTask = (taskId) => {
  // 重试逻辑，可以导航到相应的创建页面
  message.info(t('common.retryFeatureInDev'))
}

const triggerPolling = async () => {
  try {
    const response = await taskStatusApi.triggerPolling()
    if (response.data.success) {
      message.success(t('common.pollingTriggered'))
    }
  } catch (error) {
    console.error('触发轮询失败:', error)
    message.error(t('common.triggerPollingFailed'))
  }
}

const getTaskItemClass = (status) => {
  return `task-item-${status.toLowerCase()}`
}

const getStatusClass = (status) => {
  return `status-${status.toLowerCase()}`
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

const startAutoRefresh = () => {
  refreshTimer.value = setInterval(fetchTasks, 30000) // 30秒刷新一次
}

const stopAutoRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
    refreshTimer.value = null
  }
}

// 生命周期
onMounted(() => {
  fetchTasks()
  startAutoRefresh()
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.task-status-page {
  padding: var(--space-6);
  background: var(--bg-base);
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-8);
}

.page-header h1 {
  color: var(--text-primary);
  font-size: var(--text-3xl);
  font-weight: var(--font-bold);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: var(--space-3);
}

.btn-refresh,
.btn-poll {
  padding: var(--space-3) var(--space-5);
  border: none;
  border-radius: var(--radius-md);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  cursor: pointer;
  transition: var(--transition-all);
}

.btn-refresh {
  background: var(--primary-500);
  color: var(--text-primary);
}

.btn-refresh:hover:not(:disabled) {
  background: var(--primary-600);
}

.btn-refresh:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-poll {
  background: var(--success-500);
  color: var(--text-primary);
}

.btn-poll:hover {
  background: var(--success-600);
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--space-5);
  margin-bottom: var(--space-8);
}

.stat-card {
  background: var(--bg-surface);
  border-radius: var(--radius-lg);
  padding: var(--space-5);
  display: flex;
  align-items: center;
  gap: var(--space-4);
}

.stat-icon {
  font-size: var(--text-4xl);
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-lg);
}

.stat-icon.pending {
  background: var(--warning-400);
}

.stat-icon.processing {
  background: var(--primary-600);
}

.stat-icon.completed {
  background: var(--success-500);
}

.stat-icon.failed {
  background: var(--error-500);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: var(--text-2xl);
  font-weight: var(--font-bold);
  color: var(--text-primary);
  margin-bottom: var(--space-1);
}

.stat-label {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
}

.task-list {
  background: var(--bg-surface);
  border-radius: var(--radius-lg);
  padding: var(--space-6);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-5);
}

.list-header h2 {
  color: var(--text-primary);
  font-size: var(--text-xl);
  font-weight: var(--font-semibold);
  margin: 0;
}

.filter-controls select {
  padding: var(--space-2) var(--space-3);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-sm);
  background: var(--bg-surface);
  color: var(--text-primary);
  font-size: var(--text-sm);
}

.task-items {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
}

.task-item {
  background: var(--bg-base);
  border-radius: var(--radius-md);
  padding: var(--space-4);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 4px solid var(--border-default);
}

.task-item-pending {
  border-left-color: var(--warning-400);
}

.task-item-processing {
  border-left-color: var(--primary-600);
}

.task-item-completed {
  border-left-color: var(--success-500);
}

.task-item-failed,
.task-item-cancelled,
.task-item-timeout {
  border-left-color: var(--error-500);
}

.task-main {
  display: flex;
  align-items: center;
  gap: var(--space-5);
  flex: 1;
}

.task-info {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}

.task-id {
  color: var(--text-primary);
  font-weight: var(--font-semibold);
  font-size: var(--text-sm);
}

.task-type {
  color: var(--text-tertiary);
  font-size: var(--text-xs);
}

.task-time {
  color: var(--text-disabled);
  font-size: var(--text-xs);
}

.task-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-2);
}

.status-badge {
  padding: var(--space-1) var(--space-2);
  border-radius: var(--radius-lg);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
  text-transform: uppercase;
}

.status-pending {
  background: var(--warning-400);
  color: #92400e;
}

.status-processing {
  background: var(--primary-600);
  color: #1e40af;
}

.status-completed {
  background: var(--success-500);
  color: #064e3b;
}

.status-failed,
.status-cancelled,
.status-timeout {
  background: var(--error-500);
  color: #7f1d1d;
}

.progress-info {
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.progress-bar {
  width: 100px;
  height: 4px;
  background: var(--border-default);
  border-radius: 2px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: var(--primary-500);
  transition: width var(--duration-normal) var(--ease-default);
}

.progress-text {
  color: var(--text-tertiary);
  font-size: var(--text-xs);
}

.task-actions {
  display: flex;
  gap: var(--space-2);
}

.btn-view,
.btn-retry {
  padding: var(--space-1) var(--space-3);
  border: none;
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
  cursor: pointer;
  transition: var(--transition-all);
}

.btn-view {
  background: var(--primary-500);
  color: var(--text-primary);
}

.btn-view:hover {
  background: var(--primary-600);
}

.btn-retry {
  background: var(--success-500);
  color: var(--text-primary);
}

.btn-retry:hover {
  background: var(--success-600);
}

.empty-state {
  text-align: center;
  padding: var(--space-10);
  color: var(--text-disabled);
}

.empty-icon {
  font-size: var(--text-5xl);
  margin-bottom: var(--space-4);
}

.empty-text {
  font-size: var(--text-base);
}
</style>


