<template>
  <div class="generate-task-record admin-theme">
    <AdminSidebar active="tasks" />

    <!-- 主内容区域 -->
    <main class="main-content">
      <AdminHeader :title="$t('nav.taskRecord')" />

      <!-- 任务记录内容 -->
      <section class="task-content">
        <div class="content-header">
          <h2>{{ $t('tasks.title') }}</h2>
          <div class="selection-info" v-if="selectedTasks.length > 0">
            {{ $t('orders.selected', { count: selectedTasks.length }) }}
          </div>
        </div>

        <div class="table-toolbar">
          <div class="toolbar-left">
            <a-select v-model:value="statusFilter" :placeholder="$t('tasks.allStatus')" size="small" @change="handleStatusFilter">
              <a-select-option value="all">{{ $t('tasks.allStatus') }}</a-select-option>
              <a-select-option value="completed">{{ $t('tasks.completed') }}</a-select-option>
              <a-select-option value="processing">{{ $t('tasks.processing') }}</a-select-option>
              <a-select-option value="failed">{{ $t('tasks.failed') }}</a-select-option>
            </a-select>
          </div>
          <div class="toolbar-right">
            <a-button type="danger" size="small" @click="handleBatchDelete" :disabled="selectedTasks.length === 0">
              <DeleteOutlined />
              {{ $t('common.delete') }}
            </a-button>
          </div>
        </div>

        <div class="table-container">
          <table class="task-table">
            <thead>
              <tr>
                <th class="checkbox-col">
                  <input type="checkbox" @change="toggleAllSelection" :checked="isAllSelected" />
                </th>
                <th>{{ $t('tasks.taskId') }}</th>
                <th>{{ $t('tasks.username') }}</th>
                <th>{{ $t('tasks.type') }}</th>
                <th>{{ $t('tasks.resources') }}</th>
                <th>{{ $t('tasks.status') }}</th>
                <th>{{ $t('tasks.createTime') }}</th>
                <th>{{ $t('tasks.operation') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="task in filteredTaskRecords" :key="task.id" class="table-row">
                <td class="checkbox-col">
                  <input
                    type="checkbox"
                    :checked="selectedTasks.some(t => t.id === task.id)"
                    @change="toggleTaskSelection(task)" />
                </td>
                <td>{{ task.taskId || task.id }}</td>
                <td>{{ task.username || $t('tasks.unknown') }}</td>
                <td>{{ getTaskTypeText(task.type) }}</td>
                <td>{{ task.resources || '0' + $t('tasks.pointsUnit') }}</td>
                <td>
                  <span class="status-tag" :class="getStatusClass(task.status)">
                    {{ getStatusText(task.status) }}
                  </span>
                </td>
                <td>{{ formatDate(task.createTime || task.createdAt) }}</td>
                <td>
                  <a type="primary" class="action-link" @click="handleView(task)">{{ $t('common.view') }}</a>
                  <a type="danger" class="action-link" @click="handleDelete(task)">{{ $t('common.delete') }}</a>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <div class="pagination">
            <span class="page-arrow" @click="prevPage" :class="{ disabled: currentPage === 1 }"><LeftOutlined /></span>
            <button 
              v-for="page in visiblePages" 
              :key="page"
              class="page-btn"
              :class="{ active: page === currentPage }"
              @click="goToPage(page)">
              {{ page }}
            </button>
            <template v-if="totalPages > 7 && currentPage < totalPages - 2">
              <span class="page-ellipsis">...</span>
              <button 
                class="page-btn"
                :class="{ active: totalPages === currentPage }"
                @click="goToPage(totalPages)">
                {{ totalPages }}
              </button>
            </template>
            <span class="page-arrow" @click="nextPage" :class="{ disabled: currentPage === totalPages }"><RightOutlined /></span>
          </div>
        </div>
      </section>
    </main>

    <!-- 任务详情弹窗 -->
    <a-modal
      v-model:open="detailDialogVisible"
      :title="$t('tasks.taskDetail')"
      width="600px"
      class="task-detail-dialog"
    >
      <div class="task-detail-content" v-if="currentTask">
        <div class="detail-section">
          <h4>{{ $t('tasks.basicInfo') }}</h4>
          <div class="detail-row">
            <span class="detail-label">{{ $t('tasks.taskId') }}：</span>
            <span class="detail-value">{{ currentTask.taskId || currentTask.id }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">{{ $t('tasks.username') }}：</span>
            <span class="detail-value">{{ currentTask.username || $t('tasks.unknown') }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">{{ $t('tasks.taskType') }}：</span>
            <span class="detail-value">{{ getTaskTypeText(currentTask.type || currentTask.taskType) }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">{{ $t('tasks.resourcesConsumed') }}：</span>
            <span class="detail-value">{{ currentTask.resources || $t('tasks.defaultPoints') }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">{{ $t('tasks.status') }}：</span>
            <span class="status-tag" :class="getStatusClass(currentTask.status)">
              {{ getStatusText(currentTask.status) }}
            </span>
          </div>
        </div>

        <div class="detail-section">
          <h4>{{ $t('tasks.timeInfo') }}</h4>
          <div class="detail-row">
            <span class="detail-label">{{ $t('tasks.createTime') }}：</span>
            <span class="detail-value">{{ formatDate(currentTask.createdAt || currentTask.createTime) }}</span>
          </div>
          <div class="detail-row" v-if="currentTask.updatedAt">
            <span class="detail-label">{{ $t('tasks.updateTime') }}：</span>
            <span class="detail-value">{{ formatDate(currentTask.updatedAt) }}</span>
          </div>
          <div class="detail-row" v-if="currentTask.completedAt">
            <span class="detail-label">{{ $t('tasks.completeTime') }}：</span>
            <span class="detail-value">{{ formatDate(currentTask.completedAt) }}</span>
          </div>
        </div>

        <div class="detail-section" v-if="currentTask.progress !== undefined">
          <h4>{{ $t('tasks.progressInfo') }}</h4>
          <div class="detail-row">
            <span class="detail-label">{{ $t('tasks.progress') }}：</span>
            <a-progress :percentage="currentTask.progress || 0" :status="getProgressStatus(currentTask.status)" />
          </div>
        </div>

        <div class="detail-section" v-if="currentTask.resultUrl">
          <h4>{{ $t('tasks.result') }}</h4>
          <div class="detail-row">
            <span class="detail-label">{{ $t('tasks.resultLink') }}：</span>
            <a :href="currentTask.resultUrl" target="_blank" class="result-link">{{ $t('tasks.viewResult') }}</a>
          </div>
          <div class="result-preview" v-if="isVideoUrl(currentTask.resultUrl)">
            <video :src="currentTask.resultUrl" controls class="preview-video"></video>
          </div>
          <div class="result-preview" v-else-if="isImageUrl(currentTask.resultUrl)">
            <img :src="currentTask.resultUrl" class="preview-image" />
          </div>
        </div>

        <div class="detail-section" v-if="currentTask.errorMessage">
          <h4>{{ $t('tasks.errorInfo') }}</h4>
          <div class="error-message">{{ currentTask.errorMessage }}</div>
        </div>
      </div>

      <template #footer>
        <a-button @click="detailDialogVisible = false">{{ $t('tasks.close') }}</a-button>
        <a-button 
          v-if="currentTask?.resultUrl" 
          type="primary" 
          @click="openResult(currentTask.resultUrl)"
        >
          {{ $t('tasks.viewResult') }}
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { message, Modal } from 'ant-design-vue'
import {
  LeftOutlined,
  RightOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { taskStatusApi } from '@/api/taskStatus'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'

const { t } = useI18n()

// 响应式数据
const statusFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedTasks = ref([])
const loading = ref(false)
const searchText = ref('')

// 任务详情弹窗相关
const detailDialogVisible = ref(false)
const currentTask = ref(null)

// 任务记录数据
const taskRecords = ref([])

// 表格操作
const isAllSelected = computed(() => {
  return taskRecords.value.length > 0 && selectedTasks.value.length === taskRecords.value.length
})

const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

const visiblePages = computed(() => {
  const pages = []
  const total = totalPages.value
  const current = currentPage.value
  
  if (total <= 7) {
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    if (current <= 3) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
    } else if (current >= total - 2) {
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      for (let i = current - 2; i <= current + 2; i++) {
        pages.push(i)
      }
    }
  }
  return pages
})

const toggleAllSelection = () => {
  if (isAllSelected.value) {
    selectedTasks.value = []
  } else {
    selectedTasks.value = [...taskRecords.value]
  }
}

const toggleTaskSelection = (task) => {
  const index = selectedTasks.value.findIndex(t => t.id === task.id)
  if (index > -1) {
    selectedTasks.value.splice(index, 1)
  } else {
    selectedTasks.value.push(task)
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    loadTaskRecords()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    loadTaskRecords()
  }
}

const goToPage = (page) => {
  currentPage.value = page
  loadTaskRecords()
}

// 计算属性：过滤后的任务记录
const filteredTaskRecords = computed(() => {
  let filtered = taskRecords.value

  // 只在前端进行搜索筛选（如果需要实时搜索）
  if (searchText.value) {
    const SearchOutlined = searchText.value.toLowerCase()
    filtered = filtered.filter(record => {
      return (record.taskId && record.taskId.toLowerCase().includes(search)) ||
             (record.username && record.username.toLowerCase().includes(search)) ||
             (record.type && record.type.toLowerCase().includes(search))
    })
  }

  return filtered
})

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    '已完成': 'completed',
    'COMPLETED': 'completed',
    '已取消': 'cancelled',
    'CANCELLED': 'cancelled',
    '处理中': 'processing',
    'PROCESSING': 'processing',
    '失败': 'failed',
    'FAILED': 'failed'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'COMPLETED': t('tasks.completed'),
    'PROCESSING': t('tasks.processing'),
    'CANCELLED': t('tasks.cancelled'),
    'FAILED': t('tasks.failed'),
    'PENDING': t('tasks.pending')
  }
  return statusMap[status] || status || t('tasks.unknown')
}

// 获取任务类型文本
const getTaskTypeText = (type) => {
  if (!type) return t('tasks.unknown')
  const typeMap = {
    'TEXT_TO_VIDEO': t('tasks.textToVideo'),
    'IMAGE_TO_VIDEO': t('tasks.imageToVideo'),
    'STORYBOARD': t('tasks.storyboardVideo'),
    '文生视频': t('tasks.textToVideo'),
    '图生视频': t('tasks.imageToVideo'),
    '分镜视频': t('tasks.storyboardVideo')
  }
  return typeMap[type] || type
}

// 状态筛选
const handleStatusFilter = () => {
  currentPage.value = 1
  loadTaskRecords() // 调用API重新加载数据
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return t('tasks.unknown')
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return '未知'

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('日期格式化失败:', error)
    return '未知'
  }
}

// 查看任务详情
const handleView = (task) => {
  currentTask.value = task
  detailDialogVisible.value = true
}

// 获取进度条状态
const getProgressStatus = (status) => {
  switch (status) {
    case 'COMPLETED':
      return 'success'
    case 'FAILED':
    case 'TIMEOUT':
      return 'exception'
    default:
      return null
  }
}

// 判断是否是视频URL
const isVideoUrl = (url) => {
  if (!url) return false
  const videoExtensions = ['.mp4', '.webm', '.ogg', '.mov', '.avi']
  return videoExtensions.some(ext => url.toLowerCase().includes(ext))
}

// 判断是否是图片URL
const isImageUrl = (url) => {
  if (!url) return false
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']
  return imageExtensions.some(ext => url.toLowerCase().includes(ext))
}

// 打开结果
const openResult = (url) => {
  if (url) {
    window.open(url, '_blank')
  }
}

// 删除单个任务
const handleDelete = async (task) => {
  try {
    await new Promise((resolve, reject) => {
      Modal.confirm({
        title: t('common.confirmDeleteTitle'),
        content: t('common.confirmDeleteTask', { taskId: task.taskId || task.id }),
        okText: t('common.confirm'),
        cancelText: t('common.cancel'),
        onOk() { resolve() },
        onCancel() { reject('cancel') }
      })
    })
    
    // 调用后端API删除
    const token = localStorage.getItem('token')
    if (!token) {
      message.error(t('common.pleaseLoginFirst'))
      return
    }
    const deleteUrl = `/api/admin/tasks/${task.taskId || task.id}`
    const response = await fetch(deleteUrl, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    if (result.success) {
      // 从前端数据中移除
      const index = taskRecords.value.findIndex(item => item.id === task.id)
      if (index > -1) {
        taskRecords.value.splice(index, 1)
        total.value--
      }
      message.success(t('common.taskDeleteSuccess'))
    } else {
      message.error(result.message || t('common.taskDeleteFailed'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      message.error(t('common.taskDeleteFailed') + ': ' + error.message)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedTasks.value.length === 0) {
    message.warning(t('common.pleaseSelectTasksFirst'))
    return
  }
  
  try {
    await new Promise((resolve, reject) => {
      Modal.confirm({
        title: t('common.confirmBatchDeleteTitle'),
        content: t('common.confirmBatchDeleteTasks', { count: selectedTasks.value.length }),
        okText: t('common.confirm'),
        cancelText: t('common.cancel'),
        onOk() { resolve() },
        onCancel() { reject('cancel') }
      })
    })
    
    // 调用后端API批量删除
    const token = localStorage.getItem('token')
    if (!token) {
      message.error(t('common.pleaseLoginFirst'))
      return
    }
    const taskIds = selectedTasks.value.map(item => item.taskId || item.id)
    
    const response = await fetch('/api/admin/tasks/batch', {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(taskIds)
    })
    
    const result = await response.json()
    if (result.success) {
      // 从前端数据中移除
      const selectedIds = selectedTasks.value.map(item => item.id)
      taskRecords.value = taskRecords.value.filter(item => !selectedIds.includes(item.id))
      total.value -= result.deletedCount || selectedIds.length
      selectedTasks.value = []
      message.success(result.message || t('common.batchDeleteSuccess', { count: result.deletedCount }))
    } else {
      message.error(result.message || t('common.batchDeleteFailed'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      message.error(t('common.batchDeleteFailed') + ': ' + error.message)
    }
  }
}

// 加载数据
const loadTaskRecords = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value - 1, // 后端从0开始
      size: pageSize.value
    }

    // 添加状态筛选
    if (statusFilter.value && statusFilter.value !== 'all') {
      params.status = statusFilter.value.toUpperCase()
    }

    // 添加搜索参数
    if (searchText.value) {
      params.search = searchText.value
    }

    // 尝试调用API获取数据
    try {
      const response = await taskStatusApi.getAllTaskRecords(params)

      if (response.data && response.data.success) {
        const realData = response.data.data || []
        taskRecords.value = realData
        total.value = response.data.totalElements || realData.length
        console.log('成功加载任务记录:', taskRecords.value.length)
      } else {
        console.warn('API返回失败:', response.data?.message)
        taskRecords.value = []
        total.value = 0
        message.warning(response.data?.message || t('common.loadDataFailed'))
      }
    } catch (apiError) {
      console.error('API调用失败:', apiError)
      taskRecords.value = []
      total.value = 0
      message.error(t('common.apiCallFailed') + ': ' + (apiError.message || t('common.checkNetwork')))
    }
  } catch (error) {
    console.error('加载任务记录失败:', error)
    message.error(t('common.dataLoadFailed'))
    taskRecords.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 加载模拟数据（用于演示或API不可用时）
const loadMockData = () => {
  const now = new Date()
  taskRecords.value = [
    {
      id: 1,
      taskId: 'TASK-2025-001',
      username: '张三',
      type: '图生视频',
      resources: '5积分',
      status: 'COMPLETED',
      statusText: '已完成',
      createdAt: new Date(now.getTime() - 2 * 60 * 60 * 1000).toISOString() // 2小时前
    },
    {
      id: 2,
      taskId: 'TASK-2025-002',
      username: '李四',
      type: '文生视频',
      resources: '10积分',
      status: 'PROCESSING',
      statusText: '处理中',
      createdAt: new Date(now.getTime() - 1 * 60 * 60 * 1000).toISOString() // 1小时前
    },
    {
      id: 3,
      taskId: 'TASK-2025-003',
      username: '王五',
      type: '分镜视频',
      resources: '15积分',
      status: 'COMPLETED',
      statusText: '已完成',
      createdAt: new Date(now.getTime() - 30 * 60 * 1000).toISOString() // 30分钟前
    },
    {
      id: 4,
      taskId: 'TASK-2025-004',
      username: '赵六',
      type: '图生视频',
      resources: '5积分',
      status: 'FAILED',
      statusText: '失败',
      createdAt: new Date(now.getTime() - 15 * 60 * 1000).toISOString() // 15分钟前
    },
    {
      id: 5,
      taskId: 'TASK-2025-005',
      username: '孙七',
      type: '文生视频',
      resources: '10积分',
      status: 'COMPLETED',
      statusText: '已完成',
      createdAt: new Date(now.getTime() - 10 * 60 * 1000).toISOString() // 10分钟前
    },
    {
      id: 6,
      taskId: 'TASK-2025-006',
      username: '周八',
      type: '图生视频',
      resources: '5积分',
      status: 'PROCESSING',
      statusText: '处理中',
      createdAt: new Date(now.getTime() - 5 * 60 * 1000).toISOString() // 5分钟前
    },
    {
      id: 7,
      taskId: 'TASK-2025-007',
      username: '吴九',
      type: '分镜视频',
      resources: '15积分',
      status: 'CANCELLED',
      statusText: '已取消',
      createdAt: new Date(now.getTime() - 3 * 60 * 1000).toISOString() // 3分钟前
    },
    {
      id: 8,
      taskId: 'TASK-2025-008',
      username: '郑十',
      type: '文生视频',
      resources: '10积分',
      status: 'COMPLETED',
      statusText: '已完成',
      createdAt: new Date(now.getTime() - 1 * 60 * 1000).toISOString() // 1分钟前
    }
  ]
  total.value = taskRecords.value.length
  console.log('使用模拟数据，共', taskRecords.value.length, '条记录')
}

// 页面加载时初始化数据
onMounted(() => {
  loadTaskRecords()
})
</script>

<style scoped>
.generate-task-record {
  display: flex;
  min-height: 100vh;
  background: var(--bg-base);
  font-family: var(--font-sans);
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--bg-base);
}

/* 任务内容区域 */
.task-content {
  padding: var(--space-6);
  flex: 1;
  background: var(--bg-surface);
  margin: var(--space-6);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-sm);
}

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

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

.selection-info {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  background: var(--bg-glass);
  padding: var(--space-2) var(--space-4);
  border-radius: var(--radius-sm);
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 确保下拉框选中值可见 */
.toolbar-left :deep(.ant-select) {
  min-width: 120px;
}

.toolbar-left :deep(.ant-select-selector) {
  color: var(--text-primary) !important;
  font-size: var(--text-sm);
  min-height: 32px;
}

.toolbar-left :deep(.ant-select-selector *) {
  color: var(--text-primary) !important;
}

.toolbar-left :deep(.ant-select-selector) {
  display: flex !important;
  align-items: center !important;
}

.toolbar-left :deep(.ant-select-selection-item) {
  color: var(--text-primary) !important;
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
}

.toolbar-left :deep(.ant-select-selection-placeholder) {
  color: var(--text-disabled) !important;
  opacity: 1 !important;
  visibility: visible !important;
}

.table-container {
  background: var(--bg-surface);
  border-radius: var(--radius-md);
  overflow: hidden;
  border: 1px solid var(--border-subtle);
  margin-bottom: var(--space-6);
}

.task-table {
  width: 100%;
  border-collapse: collapse;
  font-size: var(--text-sm);
}

.task-table thead {
  background: var(--bg-elevated);
}

.task-table th {
  padding: var(--space-3) var(--space-4);
  text-align: left;
  font-weight: var(--font-semibold);
  color: var(--text-secondary);
  border-bottom: 1px solid var(--border-subtle);
}

.task-table td {
  padding: var(--space-3) var(--space-4);
  border-bottom: 1px solid var(--border-subtle);
  color: var(--text-primary);
}

.table-row:hover {
  background: var(--bg-hover);
}

.checkbox-col {
  width: 50px;
  text-align: center;
}

.checkbox-col input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.status-tag {
  display: inline-block;
  padding: var(--space-1) var(--space-3);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
  color: var(--text-inverse);
}

.status-tag.completed {
  background: var(--accent-500);
}

.status-tag.cancelled {
  background: var(--error-500);
}

.status-tag.processing {
  background: var(--primary-600);
}

.status-tag.failed {
  background: var(--warning-500);
}

.action-link {
  margin-right: var(--space-3);
  font-size: var(--text-sm);
  text-decoration: none;
}

.action-link:last-child {
  margin-right: 0;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--space-6);
}

.pagination {
  display: flex;
  align-items: center;
  gap: 4px;
}

.page-arrow {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--border-default);
  background: var(--bg-surface);
  color: var(--text-primary);
  cursor: pointer;
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  transition: var(--transition-all);
}

.page-arrow:hover:not(.disabled) {
  background: var(--bg-hover);
  border-color: var(--border-strong);
}

.page-arrow.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn {
  min-width: 32px;
  height: 32px;
  padding: 0 var(--space-3);
  border: 1px solid var(--border-default);
  background: var(--bg-surface);
  color: var(--text-primary);
  cursor: pointer;
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  transition: var(--transition-all);
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-btn:hover:not(:disabled) {
  background: var(--bg-hover);
  border-color: var(--border-strong);
}

.page-btn.active {
  background: var(--primary-500);
  color: var(--text-inverse);
  border-color: var(--primary-500);
}

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

.page-ellipsis {
  padding: 0 var(--space-2);
  color: var(--text-tertiary);
  font-size: var(--text-sm);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .generate-task-record {
    flex-direction: column;
  }
  
  .task-content {
    padding: 16px;
  }
}

/* 任务详情弹窗样式 */
.task-detail-content {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: var(--space-6);
  padding-bottom: var(--space-4);
  border-bottom: 1px solid var(--border-subtle);
}

.detail-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.detail-section h4 {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
  margin-bottom: var(--space-3);
}

.detail-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.detail-label {
  width: 100px;
  flex-shrink: 0;
  color: var(--text-tertiary);
  font-size: var(--text-sm);
}

.detail-value {
  color: var(--text-primary);
  font-size: var(--text-sm);
  word-break: break-all;
}

.result-link {
  color: var(--primary-500);
  text-decoration: none;
}

.result-link:hover {
  text-decoration: underline;
}

.result-preview {
  margin-top: 12px;
}

.preview-video {
  max-width: 100%;
  max-height: 300px;
  border-radius: var(--radius-md);
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: var(--radius-md);
  object-fit: contain;
}

.error-message {
  background: var(--error-glow);
  border: 1px solid var(--error-500);
  color: var(--error-400);
  padding: var(--space-3);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  line-height: var(--leading-normal);
}
</style>
