<template>
  <!-- 🚀 v3.13.5.5: 简化卡片结构，减少组件嵌套 -->
  <div
    class="task-progress-card"
    :class="statusClass"
  >
    <div class="card-header">
      <div class="token-info">
        <n-icon
          class="status-icon"
          :component="statusIcon"
        />
        <span class="token-name">{{ tokenName }}</span>
      </div>
      <div class="card-actions">
        <n-tag
          :type="statusTagType"
          size="small"
          :bordered="false"
        >
          {{ statusText }}
        </n-tag>
        <n-button
          v-if="hasTaskResults"
          text
          size="small"
          @click="showDetail = true"
          class="action-btn"
        >
          <template #icon>
            <n-icon><InformationCircle /></n-icon>
          </template>
          <span class="btn-text">详情</span>
        </n-button>
        <n-button
          text
          size="small"
          @click="showSubTaskDetail = true"
          class="action-btn"
        >
          <template #icon>
            <n-icon><List /></n-icon>
          </template>
          <span class="btn-text">子任务</span>
        </n-button>
      </div>
    </div>

    <!-- 🚀 使用v-show替代v-if，避免频繁的DOM创建销毁 -->
    <div
      v-show="progress && progress.status !== 'pending'"
      class="card-body"
    >
      <!-- 进度显示（数字方式） -->
      <div
        v-show="progress?.status === 'executing'"
        class="progress-section"
      >
        <div class="progress-content">
          <span class="progress-percent">{{ progress?.progress || 0 }}%</span>
          <span class="progress-task">{{ currentTaskLabel }}</span>
          <span class="progress-count">{{ progress?.tasksCompleted || 0 }}/{{ progress?.tasksTotal || 0 }}</span>
        </div>
      </div>

      <!-- 结果统计 -->
      <div
        v-show="progress?.status === 'completed' || progress?.status === 'failed'"
        class="result-section"
      >
        <span v-if="successCount > 0" class="result-tag result-success">
          成功: {{ successCount }}
        </span>
        <span v-if="failedCount > 0" class="result-tag result-error">
          失败: {{ failedCount }}
        </span>
      </div>

      <!-- 🚀 发车状态：简化为纯HTML+CSS，移除n-space -->
      <div class="car-status-section">
        <span class="car-icon">🚗</span>
        <span class="car-count" :class="'car-' + carStatusType">
          {{ dailyCarSendCount }}/4
        </span>
        <span class="car-text">{{ carStatusText }}</span>
      </div>

      <!-- 错误信息 -->
      <div
        v-show="progress?.error"
        class="error-section"
      >
        <div class="error-alert">
          ⚠️ {{ progress?.error }}
        </div>
      </div>
    </div>

    <!-- 🚀 性能优化：使用v-if延迟渲染modal，只在打开时才创建DOM -->
    <n-modal
      v-if="showSubTaskDetail"
      v-model:show="showSubTaskDetail"
      preset="card"
      :title="`${tokenName} - 批量任务详情`"
      :style="{ width: '750px', maxHeight: '85vh' }"
      :bordered="false"
      :segmented="true"
    >
      <template #header-extra>
        <n-space size="small">
          <n-button-group size="small">
            <n-button
              :type="taskViewMode === 'all' ? 'primary' : 'default'"
              @click="taskViewMode = 'all'"
            >
              全部任务
            </n-button>
            <n-button
              :type="taskViewMode === 'dailyFix' ? 'primary' : 'default'"
              @click="taskViewMode = 'dailyFix'"
            >
              一键补差
            </n-button>
            <n-button
              :type="taskViewMode === 'other' ? 'primary' : 'default'"
              @click="taskViewMode = 'other'"
            >
              其他任务
            </n-button>
          </n-button-group>
          <n-button
            size="small"
            @click="handleResetSubTasks"
          >
            重置所有
          </n-button>
        </n-space>
      </template>

      <div class="subtask-detail">
        <!-- 统计信息 -->
        <div class="subtask-stats">
          <n-space>
            <n-tag type="default" :bordered="false">
              总计: {{ subTaskStats.total }}
            </n-tag>
            <n-tag type="success" :bordered="false">
              已完成: {{ subTaskStats.success }}
            </n-tag>
            <n-tag type="error" :bordered="false">
              失败: {{ subTaskStats.failed }}
            </n-tag>
            <n-tag type="info" :bordered="false">
              待执行: {{ subTaskStats.pending }}
            </n-tag>
          </n-space>
        </div>

        <!-- 任务列表 -->
        <n-scrollbar style="max-height: 500px;">
          <n-list bordered style="margin-top: 16px;">
            <n-list-item
              v-for="task in subTaskList"
              :key="task.id"
            >
              <template #prefix>
                <n-icon
                  :color="task.state.completed ? (task.state.success ? '#18a058' : '#d03050') : '#999'"
                  size="20"
                >
                  <CheckmarkCircle v-if="task.state.success" />
                  <CloseCircle v-else-if="task.state.completed && !task.state.success" />
                  <HourglassOutline v-else />
                </n-icon>
              </template>
              
              <div class="subtask-item">
                <div class="subtask-header">
                  <div class="subtask-name-row">
                    <strong>{{ task.name }}</strong>
                    <n-space size="small">
                      <n-tag
                        v-if="task.consumesResources"
                        type="warning"
                        size="small"
                        :bordered="false"
                      >
                        消耗资源
                      </n-tag>
                      <n-tag
                        v-if="task.state.completed"
                        :type="task.state.success ? 'success' : 'error'"
                        size="small"
                        :bordered="false"
                      >
                        {{ task.state.success ? '已完成' : '失败' }}
                      </n-tag>
                      <n-tag
                        v-else
                        type="default"
                        size="small"
                        :bordered="false"
                      >
                        未执行
                      </n-tag>
                    </n-space>
                  </div>
                </div>
                
                <div
                  v-if="task.state.completed && task.state.completedAt"
                  class="subtask-time"
                >
                  <n-text depth="3" style="font-size: 12px;">
                    完成时间: {{ new Date(task.state.completedAt).toLocaleString() }}
                  </n-text>
                </div>
                
                <div
                  v-if="task.state.error"
                  class="subtask-error"
                >
                  <n-alert
                    type="error"
                    size="small"
                    :show-icon="false"
                  >
                    {{ task.state.error }}
                  </n-alert>
                </div>
              </div>
            </n-list-item>
          </n-list>
        </n-scrollbar>

        <!-- 说明文字 -->
        <n-alert
          type="info"
          style="margin-top: 16px;"
          :show-icon="false"
        >
          <template #header>
            <strong>💡 提示</strong>
          </template>
          <ul style="margin: 8px 0; padding-left: 20px;">
            <li><strong>消耗资源任务</strong>：付费招募、免费点金、开宝箱、免费钓鱼、黑市购买、竞技场战斗等，
              完成后下次运行时会自动跳过</li>
            <li><strong>其他任务</strong>：俱乐部签到、一键答题、领取挂机奖励、加钟等，
              每次都会执行，但会记录状态</li>
            <li><strong>发车任务</strong>：自动查询、刷新、收获和发送俱乐部赛车，每个账号每天最多发送4辆车</li>
            <li><strong>爬塔任务</strong>：根据设置的次数执行，设置为0时跳过</li>
            <li><strong>状态重置</strong>：每天0点自动重置，或手动点击"重置所有"按钮</li>
          </ul>
        </n-alert>
      </div>
    </n-modal>

    <!-- 🚀 性能优化：使用v-if延迟渲染modal，只在打开时才创建DOM -->
    <n-modal
      v-if="showDetail"
      v-model:show="showDetail"
      preset="card"
      :title="`${tokenName} - 任务执行详情`"
      :style="{ width: '600px' }"
      :bordered="false"
      :segmented="true"
    >
      <div class="task-detail">
        <!-- 整体错误信息（如WebSocket连接失败） -->
        <n-alert
          v-if="progress?.error && Object.keys(taskResults).length === 0"
          type="error"
          title="任务执行失败"
          style="margin-bottom: 16px;"
        >
          {{ progress.error }}
        </n-alert>
        
        <n-list v-if="Object.keys(taskResults).length > 0" bordered>
          <n-list-item
            v-for="(result, taskId) in taskResults"
            :key="taskId"
          >
            <template #prefix>
              <n-icon
                :color="result.success ? '#18a058' : '#d03050'"
                size="20"
              >
                <component :is="result.success ? CheckmarkCircle : CloseCircle" />
              </n-icon>
            </template>
            
            <div class="task-item">
              <div class="task-name">
                <strong>{{ taskLabels[taskId] || taskId }}</strong>
                <n-tag
                  :type="result.success ? 'success' : 'error'"
                  size="small"
                  :bordered="false"
                >
                  {{ result.success ? '成功' : '失败' }}
                </n-tag>
              </div>
              
              <div
                v-if="!result.success && result.error"
                class="task-error"
              >
                <n-alert
                  type="error"
                  size="small"
                  :show-icon="false"
                >
                  {{ result.error }}
                </n-alert>
              </div>
              
              <div
                v-if="result.success && result.data"
                class="task-data"
              >
                <n-text depth="3" style="font-size: 12px;">
                  执行成功
                </n-text>
              </div>
            </div>
          </n-list-item>
        </n-list>
        
        <!-- 无数据提示 -->
        <n-empty
          v-if="!hasTaskResults"
          description="暂无任务执行详情"
          style="padding: 40px 0;"
        />

        <!-- 统计信息 -->
        <div v-if="hasTaskResults" class="task-summary">
          <n-space justify="space-around">
            <n-statistic
              label="总任务数"
              :value="Object.keys(taskResults).length"
            />
            <n-statistic
              label="成功"
              :value="successCount"
              class="success"
            />
            <n-statistic
              label="失败"
              :value="failedCount"
              class="failed"
            />
          </n-space>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { 
  CheckmarkCircle, 
  CloseCircle, 
  Time, 
  Refresh, 
  Remove,
  InformationCircle,
  List,
  HourglassOutline,
  CarSportSharp
} from '@vicons/ionicons5'
import { useDailyTaskStateStore } from '@/stores/dailyTaskState'

const dailyTaskStateStore = useDailyTaskStateStore()

const props = defineProps({
  tokenId: {
    type: String,
    required: true
  },
  tokenName: {
    type: String,
    required: true
  },
  progress: {
    type: Object,
    default: null
  }
})

// 弹窗状态
const showDetail = ref(false)
const showSubTaskDetail = ref(false)
const taskViewMode = ref('all') // 'all' | 'dailyFix' | 'other'

// 任务标签映射
const taskLabels = {
  dailyFix: '一键补差',
  restartBottle: '重启盐罐机器人',
  legionSignIn: '俱乐部签到',
  autoStudy: '一键答题',
  claimHangupReward: '领取挂机奖励',
  addClock: '加钟',
  sendCar: '发车',
  climbTower: '爬塔'
}

// 🚀 性能优化：使用ref + watch代替computed，减少重复计算
const currentTaskLabel = ref('准备中...')

watch(() => props.progress?.currentTask, (task) => {
  if (!task) {
    currentTaskLabel.value = '准备中...'
    return
  }
  
  // 检查是否是一键补差的子任务（格式：dailyFix_数字）
  if (task.startsWith('dailyFix_')) {
    const subTaskIndex = task.replace('dailyFix_', '')
    currentTaskLabel.value = `一键补差 ${subTaskIndex}/44`
  } else {
    // 普通任务直接返回映射名称
    currentTaskLabel.value = taskLabels[task] || task
  }
}, { immediate: true })

// 🚀 性能优化：缓存日期和key，避免每次都重新计算
const carSendCountCache = (() => {
  const today = new Date().toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit' 
  })
  const key = `car_daily_send_count_${today}_${props.tokenId}`
  const count = parseInt(localStorage.getItem(key) || '0')
  return { today, key, count }
})()

// 获取今日发车次数的 key
const getCarSendCountKey = () => carSendCountCache.key

// 使用 ref 而不是 computed，以便手动刷新
const dailyCarSendCount = ref(carSendCountCache.count)

// 日志配置检查
const shouldLog = (type) => {
  try {
    const config = JSON.parse(localStorage.getItem('batchTaskLogConfig') || '{}')
    return config[type] === true
  } catch {
    return false
  }
}

// 🚀 性能优化：使用防抖减少localStorage读取频率
let refreshTimer = null
const refreshCarSendCount = () => {
  // 清除之前的定时器，避免频繁刷新
  if (refreshTimer) {
    clearTimeout(refreshTimer)
  }
  
  refreshTimer = setTimeout(() => {
    const key = getCarSendCountKey()
    const newCount = parseInt(localStorage.getItem(key) || '0')
    // 只在数值真正变化时才更新
    if (dailyCarSendCount.value !== newCount) {
      dailyCarSendCount.value = newCount
      if (shouldLog('sendCar')) console.log(`🔄 [${props.tokenId}] 刷新发车次数显示: ${newCount}/4`)
    }
    refreshTimer = null
  }, 200) // 200ms防抖，减少刷新频率
}

// 🚀 性能优化：简化watch，只在关键状态变化时刷新
watch(() => props.progress?.status, (newStatus) => {
  // 只在任务完成或失败时刷新一次
  if (newStatus === 'completed' || newStatus === 'failed') {
    refreshCarSendCount()
  }
})

// 组件挂载时刷新发车次数
onMounted(() => {
  refreshCarSendCount()
})

// 发车状态类型
const carStatusType = computed(() => {
  const count = dailyCarSendCount.value
  if (count >= 4) return 'error'
  if (count >= 3) return 'warning'
  return 'success'
})

// 发车状态文本
const carStatusText = computed(() => {
  const count = dailyCarSendCount.value
  if (count >= 4) return '今日已达上限'
  if (count === 0) return '今日未发车'
  return `剩余${4 - count}次`
})

// 任务执行结果
const taskResults = computed(() => {
  if (!props.progress || !props.progress.result) return {}
  return props.progress.result
})

// 是否有任务结果（包括有错误信息的情况）
const hasTaskResults = computed(() => {
  return Object.keys(taskResults.value).length > 0 || !!props.progress?.error
})

// 状态图标
const statusIcon = computed(() => {
  if (!props.progress) return Time
  
  switch (props.progress.status) {
    case 'completed':
      return CheckmarkCircle
    case 'failed':
      return CloseCircle
    case 'executing':
      return Refresh
    case 'skipped':
      return Remove
    default:
      return Time
  }
})

// 状态标签类型
const statusTagType = computed(() => {
  if (!props.progress) return 'default'
  
  switch (props.progress.status) {
    case 'completed':
      return 'success'
    case 'failed':
      return 'error'
    case 'executing':
      return 'info'
    case 'skipped':
      return 'warning'
    default:
      return 'default'
  }
})

// 状态文本
const statusText = computed(() => {
  if (!props.progress) return '等待中'
  
  switch (props.progress.status) {
    case 'completed':
      return '已完成'
    case 'failed':
      return '失败'
    case 'executing':
      return '执行中'
    case 'skipped':
      return '已跳过'
    default:
      return '等待中'
  }
})

// 状态样式类
const statusClass = computed(() => {
  if (!props.progress) return ''
  return `status-${props.progress.status}`
})

// 成功任务数
const successCount = computed(() => {
  if (!props.progress || !props.progress.result) return 0
  return Object.values(props.progress.result).filter(r => r.success).length
})

// 失败任务数
const failedCount = computed(() => {
  if (!props.progress || !props.progress.result) return 0
  return Object.values(props.progress.result).filter(r => !r.success).length
})

// 子任务列表（根据视图模式显示不同任务）
const subTaskList = computed(() => {
  return dailyTaskStateStore.getDetailedTaskList(props.tokenId, taskViewMode.value)
})

// 子任务统计
const subTaskStats = computed(() => {
  return dailyTaskStateStore.getTaskStatistics(props.tokenId)
})

// 重置子任务状态
const handleResetSubTasks = () => {
  dailyTaskStateStore.resetTokenTasks(props.tokenId)
  showSubTaskDetail.value = false
}
</script>

<style scoped lang="scss">
.task-progress-card {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  padding: 12px; /* 减小内边距 */
  border: 2px solid transparent;
  transition: all 0.3s ease;
  overflow: hidden; /* 防止内容溢出 */

  &.status-executing {
    border-color: #2080f0;
    box-shadow: 0 0 12px rgba(32, 128, 240, 0.2);
  }

  &.status-completed {
    border-color: #18a058;
  }

  &.status-failed {
    border-color: #d03050;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    gap: 8px; /* 添加间距 */
    min-height: 28px; /* 确保最小高度 */

    .token-info {
      display: flex;
      align-items: center;
      gap: 8px;
      flex-shrink: 1; /* 允许收缩 */
      min-width: 0; /* 允许收缩到0 */

      .status-icon {
        font-size: 20px;
        flex-shrink: 0; /* 图标不收缩 */
      }

      .token-name {
        font-weight: 500;
        color: #333;
        overflow: hidden; /* 隐藏溢出 */
        text-overflow: ellipsis; /* 显示省略号 */
        white-space: nowrap; /* 单行显示 */
        flex-shrink: 1; /* 允许收缩 */
      }
    }

    .card-actions {
      flex-shrink: 0; /* 按钮区域不收缩 */
      display: flex;
      align-items: center;
      gap: 8px; /* 🚀 使用gap替代n-space */
      flex-wrap: nowrap; /* 不换行 */

      .action-btn {
        padding: 2px 8px; /* 减小按钮内边距 */
        min-width: auto; /* 移除最小宽度限制 */

        .btn-text {
          font-size: 12px;
        }
      }
    }
  }

  /* 响应式：超过5列时隐藏按钮文字，只显示图标 */
  @media (min-width: 1800px) {
    .card-header .card-actions .action-btn .btn-text {
      display: none; /* 宽屏多列时只显示图标 */
    }
    
    .card-header .card-actions .action-btn {
      padding: 2px 4px; /* 进一步减小内边距 */
    }
  }

  .card-body {
    .progress-section {
      padding: 10px 12px;
      background: linear-gradient(135deg, rgba(32, 128, 240, 0.08) 0%, rgba(32, 128, 240, 0.03) 100%);
      border-radius: 8px;
      border-left: 3px solid #2080f0;
      
      /* 🚀 简化后的进度内容布局 */
      .progress-content {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 14px;
        
        .progress-percent {
          padding: 4px 10px;
          background: rgba(32, 128, 240, 0.15);
          border-radius: 4px;
          color: #2080f0;
          font-weight: 600;
        }
        
        .progress-task {
          flex: 1;
          color: #666;
        }
        
        .progress-count {
          padding: 4px 10px;
          background: rgba(0, 0, 0, 0.05);
          border-radius: 4px;
          font-weight: 600;
          color: #333;
        }
      }
    }

    .result-section {
      margin-top: 8px;
      display: flex;
      gap: 8px;
      
      /* 🚀 简化后的结果标签样式 */
      .result-tag {
        padding: 4px 12px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: 500;
        
        &.result-success {
          background: rgba(24, 160, 88, 0.1);
          color: #18a058;
        }
        
        &.result-error {
          background: rgba(208, 48, 80, 0.1);
          color: #d03050;
        }
      }
    }

    .car-status-section {
      margin-top: 8px;
      padding: 8px 12px;
      background: rgba(102, 126, 234, 0.05);
      border-radius: 8px;
      border: 1px solid rgba(102, 126, 234, 0.1);
      display: flex;
      align-items: center;
      gap: 8px;
      
      /* 🚀 简化后的发车状态样式 */
      .car-icon {
        font-size: 16px;
      }
      
      .car-count {
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: 500;
        
        &.car-success {
          background: rgba(24, 160, 88, 0.1);
          color: #18a058;
        }
        
        &.car-warning {
          background: rgba(240, 138, 0, 0.1);
          color: #f08a00;
        }
        
        &.car-error {
          background: rgba(208, 48, 80, 0.1);
          color: #d03050;
        }
      }
      
      .car-text {
        font-size: 12px;
        color: #999;
      }
    }

    .error-section {
      margin-top: 8px;
      
      /* 🚀 简化后的错误提示样式 */
      .error-alert {
        padding: 8px 12px;
        background: rgba(208, 48, 80, 0.1);
        border-left: 3px solid #d03050;
        border-radius: 4px;
        color: #d03050;
        font-size: 13px;
      }
    }
  }
}

/* 子任务详情弹窗 */
.subtask-detail {
  .subtask-stats {
    padding: 12px;
    background: rgba(24, 160, 88, 0.05);
    border-radius: 8px;
  }

  .subtask-item {
    width: 100%;

    .subtask-header {
      .subtask-name-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        strong {
          font-size: 14px;
          color: #333;
        }
      }
    }

    .subtask-time {
      margin-top: 4px;
      margin-bottom: 4px;
    }

    .subtask-error {
      margin-top: 8px;
    }
  }
}

/* 任务详情弹窗 */
.task-detail {
  .task-item {
    width: 100%;

    .task-name {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      strong {
        font-size: 14px;
        color: #333;
      }
    }

    .task-error {
      margin-top: 8px;
    }

    .task-data {
      margin-top: 4px;
    }
  }

  .task-summary {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #e0e0e0;

    :deep(.n-statistic) {
      &.success .n-statistic-value__content {
        color: #18a058;
      }

      &.failed .n-statistic-value__content {
        color: #d03050;
      }
    }
  }
}

/* 深色主题 */
html.dark .task-progress-card,
html[data-theme="dark"] .task-progress-card {
  background: rgba(40, 40, 40, 0.8);

  .card-header .token-info .token-name {
    color: #ffffff;
  }

  .card-body {
    .progress-section {
      background: linear-gradient(135deg, rgba(32, 128, 240, 0.15) 0%, rgba(32, 128, 240, 0.08) 100%);
      
      .progress-content {
        .progress-task {
          color: #ccc;
        }
        
        .progress-count {
          background: rgba(255, 255, 255, 0.1);
          color: #fff;
        }
      }
    }
    
    .car-status-section {
      background: rgba(102, 126, 234, 0.1);
      border-color: rgba(102, 126, 234, 0.2);
      
      .car-text {
        color: #aaa;
      }
    }
  }
}

html.dark .subtask-detail,
html[data-theme="dark"] .subtask-detail {
  .subtask-stats {
    background: rgba(24, 160, 88, 0.1);
  }

  .subtask-item .subtask-header .subtask-name-row strong {
    color: #ffffff;
  }
}

html.dark .task-detail,
html[data-theme="dark"] .task-detail {
  .task-item .task-name strong {
    color: #ffffff;
  }

  .task-summary {
    border-top-color: #4a4a4a;
  }
}
</style>

