<template>
  <div class="batch-task-panel">
    <!-- 面板标题 -->
    <div class="panel-header">
      <h2>
        <n-icon><Flash /></n-icon>
        批量自动化任务
      </h2>
      <n-space>
        <n-tag
          v-if="batchStore.isExecuting"
          type="info"
          :bordered="false"
        >
          <template #icon>
            <n-icon><Refresh /></n-icon>
          </template>
          执行中...
        </n-tag>
        <n-tag
          type="success"
          :bordered="false"
        >
          并发数: {{ batchStore.maxConcurrency }}
        </n-tag>
        <!-- 定时任务状态指示器 -->
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-tag
              :type="schedulerStatusType"
              :bordered="false"
              class="scheduler-status-tag"
            >
              <template #icon>
                <n-icon><Time /></n-icon>
              </template>
              {{ schedulerStatusText }}
            </n-tag>
          </template>
          <div class="scheduler-tooltip">
            <div v-if="batchStore.schedulerConfig.enabled">
              <p><strong>定时任务已启用</strong></p>
              <p v-if="batchStore.schedulerConfig.type === 'interval'">
                间隔执行：每 {{ formatInterval(batchStore.schedulerConfig.interval) }}
              </p>
              <p v-else>
                每日定时：{{ batchStore.schedulerConfig.dailyTimes.join(', ') }}
              </p>
              <p v-if="batchStore.schedulerConfig.lastExecutionTime">
                上次执行：{{ formatLastExecutionTime }}
              </p>
              <p v-else>
                尚未执行过
              </p>
            </div>
            <p v-else>定时任务未启用</p>
          </div>
        </n-tooltip>
      </n-space>
    </div>
    
    <!-- 定时任务快速控制栏 -->
    <div v-if="batchStore.schedulerConfig.enabled" class="scheduler-quick-control">
      <div class="control-info">
        <n-icon size="18"><Time /></n-icon>
        <span class="info-text">
          <strong>定时任务运行中</strong>
          <span v-if="batchStore.schedulerConfig.type === 'interval'">
            - 每 {{ formatInterval(batchStore.schedulerConfig.interval) }} 自动执行
          </span>
          <span v-else>
            - 每日 {{ batchStore.schedulerConfig.dailyTimes.join(', ') }} 执行
          </span>
        </span>
      </div>
      <n-space>
        <n-button
          size="small"
          @click="showScheduler = true"
        >
          <template #icon>
            <n-icon><Settings /></n-icon>
          </template>
          配置
        </n-button>
        <n-button
          size="small"
          type="warning"
          @click="handleQuickToggleScheduler(false)"
        >
          <template #icon>
            <n-icon><Pause /></n-icon>
          </template>
          停用
        </n-button>
      </n-space>
    </div>

    <!-- 任务模板选择 -->
    <div class="template-section">
      <n-space vertical :size="16">
        <!-- 模板选择器和并发数设置 -->
        <n-grid cols="1 s:2 m:3" :x-gap="16">
          <n-grid-item>
            <div class="template-selector">
              <label>选择任务模板：</label>
              <n-select
                v-model:value="batchStore.selectedTemplate"
                :options="templateOptions"
                :disabled="batchStore.isExecuting"
                size="large"
              />
            </div>
          </n-grid-item>
          
          <!-- 🆕 v3.13.0 连接池模式开关 -->
          <n-grid-item>
            <div class="connection-pool-toggle">
              <n-space justify="space-between" align="center">
                <div class="toggle-label">
                  <n-space align="center">
                    <n-icon size="20" :color="batchStore.USE_CONNECTION_POOL ? '#18a058' : '#999'">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                        <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                      </svg>
                    </n-icon>
                    <span :style="{ fontWeight: 'bold', color: batchStore.USE_CONNECTION_POOL ? '#18a058' : '#666' }">
                      🏊 连接池模式
                    </span>
                    <n-tooltip trigger="hover" placement="right">
                      <template #trigger>
                        <n-icon size="16" color="#999">
                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                            <path fill="currentColor" d="M11 17h2v-6h-2v6zm1-8q.425 0 .713-.288Q13 8.425 13 8t-.287-.713Q12.425 7 12 7t-.712.287Q11 7.575 11 8t.288.712Q11.575 9 12 9zm0 13q-2.075 0-3.9-.788-1.825-.787-3.175-2.137-1.35-1.35-2.137-3.175Q2 14.075 2 12t.788-3.9q.787-1.825 2.137-3.175 1.35-1.35 3.175-2.138Q9.925 2 12 2t3.9.787q1.825.788 3.175 2.138 1.35 1.35 2.137 3.175Q22 9.925 22 12t-.788 3.9q-.787 1.825-2.137 3.175-1.35 1.35-3.175 2.137Q14.075 22 12 22Z"/>
                          </svg>
                        </n-icon>
                      </template>
                      <div style="max-width: 300px;">
                        <p><strong>连接池模式（推荐用于100并发）</strong></p>
                        <p>✅ 突破浏览器WebSocket连接数限制（10-20个）</p>
                        <p>✅ 100个Token复用20个连接，稳定高效</p>
                        <p>✅ 连接复用，节省建立时间</p>
                        <p>✅ 内存占用更低（20连接 vs 100连接）</p>
                        <p style="margin-top: 8px; color: #999;">
                          ⚠️ 传统模式：并发数超过20容易连接失败<br/>
                          ✨ 连接池模式：支持100+并发稳定运行
                        </p>
                      </div>
                    </n-tooltip>
                  </n-space>
                </div>
                <n-switch
                  v-model:value="batchStore.USE_CONNECTION_POOL"
                  :disabled="batchStore.isExecuting"
                  @update:value="handlePoolModeChange"
                  size="medium"
                >
                  <template #checked>
                    启用
                  </template>
                  <template #unchecked>
                    禁用
                  </template>
                </n-switch>
              </n-space>
            </div>
          </n-grid-item>
          
          <!-- 🆕 v3.13.0 连接池大小（仅在连接池模式启用时显示） -->
          <n-grid-item v-if="batchStore.USE_CONNECTION_POOL">
            <div class="pool-size-selector">
              <div class="selector-header">
                <label>连接池大小：</label>
                <n-input-number
                  v-model:value="batchStore.POOL_SIZE"
                  :min="1"
                  :max="100"
                  :step="1"
                  :disabled="batchStore.isExecuting"
                  size="medium"
                  :show-button="true"
                  class="number-input"
                  @update:value="handlePoolSizeChange"
                >
                  <template #suffix>
                    <span style="margin-left: 4px;">个</span>
                  </template>
                </n-input-number>
              </div>
              <n-slider
                v-model:value="batchStore.POOL_SIZE"
                :min="1"
                :max="100"
                :step="1"
                :marks="{1: '1', 10: '10', 20: '20 (推荐)', 30: '30', 50: '50', 70: '70', 100: '100'}"
                :disabled="batchStore.isExecuting"
                :tooltip="true"
                @update:value="handlePoolSizeChange"
              />
              <div class="pool-size-hint">
                <n-alert type="info" :bordered="false" size="small">
                  <template #icon>
                    <n-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="currentColor" d="M11 17h2v-6h-2v6zm1-8q.425 0 .713-.288Q13 8.425 13 8t-.287-.713Q12.425 7 12 7t-.712.287Q11 7.575 11 8t.288.712Q11.575 9 12 9zm0 13q-2.075 0-3.9-.788-1.825-.787-3.175-2.137-1.35-1.35-2.137-3.175Q2 14.075 2 12t.788-3.9q.787-1.825 2.137-3.175 1.35-1.35 3.175-2.138Q9.925 2 12 2t3.9.787q1.825.788 3.175 2.138 1.35 1.35 2.137 3.175Q22 9.925 22 12t-.788 3.9q-.787 1.825-2.137 3.175-1.35 1.35-3.175 2.137Q14.075 22 12 22Z"/></svg></n-icon>
                  </template>
                  <span v-if="batchStore.POOL_SIZE <= 10">适用：网络一般，追求稳定</span>
                  <span v-else-if="batchStore.POOL_SIZE <= 20">适用：网络良好，平衡性能与稳定性（推荐）</span>
                  <span v-else>适用：网络极好（企业/专线），追求极致性能</span>
                </n-alert>
              </div>
            </div>
          </n-grid-item>
          
          <!-- 🆕 v3.13.2 最大并发请求数（仅在连接池模式启用时显示） -->
          <n-grid-item v-if="batchStore.USE_CONNECTION_POOL">
            <div class="concurrent-requests-selector">
              <div class="selector-header">
                <label>同时执行数：</label>
                <n-input-number
                  v-model:value="batchStore.MAX_CONCURRENT_REQUESTS"
                  :min="1"
                  :max="100"
                  :step="1"
                  :disabled="batchStore.isExecuting"
                  size="medium"
                  :show-button="true"
                  class="number-input"
                  @update:value="handleConcurrentRequestsChange"
                >
                  <template #suffix>
                    <span style="margin-left: 4px;">个</span>
                  </template>
                </n-input-number>
              </div>
              <n-slider
                v-model:value="batchStore.MAX_CONCURRENT_REQUESTS"
                :min="1"
                :max="100"
                :step="1"
                :marks="{1: '1', 5: '5 (推荐)', 10: '10', 20: '20', 40: '40', 70: '70', 100: '100'}"
                :disabled="batchStore.isExecuting"
                :tooltip="true"
                @update:value="handleConcurrentRequestsChange"
              />
              <div class="concurrent-requests-hint">
                <n-alert type="info" :bordered="false" size="small">
                  <template #icon>
                    <n-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="currentColor" d="M11 17h2v-6h-2v6zm1-8q.425 0 .713-.288Q13 8.425 13 8t-.287-.713Q12.425 7 12 7t-.712.287Q11 7.575 11 8t.288.712Q11.575 9 12 9zm0 13q-2.075 0-3.9-.788-1.825-.787-3.175-2.137-1.35-1.35-2.137-3.175Q2 14.075 2 12t.788-3.9q.787-1.825 2.137-3.175 1.35-1.35 3.175-2.138Q9.925 2 12 2t3.9.787q1.825.788 3.175 2.138 1.35 1.35 2.137 3.175Q22 9.925 22 12t-.788 3.9q-.787 1.825-2.137 3.175-1.35 1.35-3.175 2.137Q14.075 22 12 22Z"/></svg></n-icon>
                  </template>
                  <strong>关键参数！</strong> 控制同时执行任务的Token数量，避免请求拥堵。
                  <span v-if="batchStore.MAX_CONCURRENT_REQUESTS <= 3">极度保守，适合网络很差</span>
                  <span v-else-if="batchStore.MAX_CONCURRENT_REQUESTS <= 6">推荐配置，平衡稳定性和效率</span>
                  <span v-else-if="batchStore.MAX_CONCURRENT_REQUESTS <= 10">激进配置，适合网络很好</span>
                  <span v-else>不推荐，可能导致请求拥堵</span>
                </n-alert>
                <n-alert type="warning" :bordered="false" size="small" style="margin-top: 8px;">
                  <template #icon>
                    <n-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="currentColor" d="M12 17q.425 0 .713-.288Q13 16.425 13 16t-.287-.713Q12.425 15 12 15t-.712.287Q11 15.575 11 16t.288.712Q11.575 17 12 17Zm-1-4h2V7h-2v6Zm1 9q-2.075 0-3.9-.788-1.825-.787-3.175-2.137-1.35-1.35-2.137-3.175Q2 14.075 2 12t.788-3.9q.787-1.825 2.137-3.175 1.35-1.35 3.175-2.138Q9.925 2 12 2t3.9.787q1.825.788 3.175 2.138 1.35 1.35 2.137 3.175Q22 9.925 22 12t-.788 3.9q-.787 1.825-2.137 3.175-1.35 1.35-3.175 2.137Q14.075 22 12 22Z"/></svg></n-icon>
                  </template>
                  如果任务超时频繁，请降低此数值！推荐从5开始测试。
                </n-alert>
              </div>
            </div>
          </n-grid-item>
          
          <!-- 🆕 连接间隔时间（仅在连接池模式启用时显示） -->
          <n-grid-item v-if="batchStore.USE_CONNECTION_POOL">
            <div class="connection-interval-selector">
              <div class="selector-header">
                <label>连接间隔：</label>
                <n-input-number
                  v-model:value="batchStore.CONNECTION_INTERVAL"
                  :min="100"
                  :max="1000"
                  :step="50"
                  :disabled="batchStore.isExecuting"
                  size="medium"
                  :show-button="true"
                  class="number-input"
                  @update:value="handleConnectionIntervalChange"
                >
                  <template #suffix>
                    <span style="margin-left: 4px;">ms</span>
                  </template>
                </n-input-number>
              </div>
              <n-slider
                v-model:value="batchStore.CONNECTION_INTERVAL"
                :min="100"
                :max="1000"
                :step="50"
                :marks="{100: '100', 300: '300 (推荐)', 500: '500', 700: '700', 1000: '1000'}"
                :disabled="batchStore.isExecuting"
                :tooltip="true"
                @update:value="handleConnectionIntervalChange"
              />
              <div class="connection-interval-hint">
                <n-alert type="info" :bordered="false" size="small">
                  <template #icon>
                    <n-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="currentColor" d="M11 17h2v-6h-2v6zm1-8q.425 0 .713-.288Q13 8.425 13 8t-.287-.713Q12.425 7 12 7t-.712.287Q11 7.575 11 8t.288.712Q11.575 9 12 9zm0 13q-2.075 0-3.9-.788-1.825-.787-3.175-2.137-1.35-1.35-2.137-3.175Q2 14.075 2 12t.788-3.9q.787-1.825 2.137-3.175 1.35-1.35 3.175-2.138Q9.925 2 12 2t3.9.787q1.825.788 3.175 2.138 1.35 1.35 2.137 3.175Q22 9.925 22 12t-.788 3.9q-.787 1.825-2.137 3.175-1.35 1.35-3.175 2.137Q14.075 22 12 22Z"/></svg></n-icon>
                  </template>
                  控制每个Token建立连接的间隔时间，避免瞬间大量连接。
                  <span v-if="batchStore.CONNECTION_INTERVAL <= 200">快速模式</span>
                  <span v-else-if="batchStore.CONNECTION_INTERVAL <= 400">推荐配置</span>
                  <span v-else>保守模式</span>
                </n-alert>
              </div>
            </div>
          </n-grid-item>
          
          <!-- 并发数量（仅在传统模式显示） -->
          <n-grid-item v-if="!batchStore.USE_CONNECTION_POOL">
            <div class="concurrency-selector">
              <div class="selector-header">
                <label>并发数量：</label>
                <n-input-number
                  v-model:value="batchStore.maxConcurrency"
                  :min="1"
                  :max="100"
                  :step="1"
                  :disabled="batchStore.isExecuting"
                  size="medium"
                  :show-button="true"
                  class="number-input"
                  @update:value="handleConcurrencyChange"
                >
                  <template #suffix>
                    <span style="margin-left: 4px;">个</span>
                  </template>
                </n-input-number>
              </div>
              <n-slider
                v-model:value="batchStore.maxConcurrency"
                :min="1"
                :max="100"
                :step="1"
                :marks="{1: '1', 10: '10', 20: '20', 30: '30', 40: '40', 50: '50', 60: '60', 70: '70', 80: '80', 90: '90', 100: '100'}"
                :disabled="batchStore.isExecuting"
                :tooltip="true"
                @update:value="handleConcurrencyChange"
              />
              <div class="concurrency-hint" v-if="batchStore.maxConcurrency > 20">
                <n-alert type="warning" :bordered="false" size="small">
                  <template #icon>
                    <n-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="currentColor" d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/></svg></n-icon>
                  </template>
                  并发数超过20容易导致WSS连接失败，建议启用连接池模式
                </n-alert>
              </div>
            </div>
          </n-grid-item>
          <n-grid-item>
            <div class="tower-count-selector">
              <div class="selector-header">
                <label>爬塔次数：</label>
                <n-input-number
                  v-model:value="batchStore.climbTowerCount"
                  :min="0"
                  :max="100"
                  :step="1"
                  :disabled="batchStore.isExecuting"
                  size="medium"
                  :show-button="true"
                  class="number-input"
                  @update:value="handleTowerCountChange"
                >
                  <template #suffix>
                    <span style="margin-left: 4px;">次</span>
                  </template>
                </n-input-number>
              </div>
              <n-slider
                v-model:value="batchStore.climbTowerCount"
                :min="0"
                :max="100"
                :step="1"
                :marks="{0: '0', 10: '10', 20: '20', 30: '30', 40: '40', 50: '50', 60: '60', 70: '70', 80: '80', 90: '90', 100: '100'}"
                :disabled="batchStore.isExecuting"
                :tooltip="true"
                @update:value="handleTowerCountChange"
              />
            </div>
          </n-grid-item>
          <n-grid-item>
            <div class="tower-count-selector">
              <div class="selector-header">
                <label>发车刷新次数：</label>
                <n-input-number
                  v-model:value="batchStore.carRefreshCount"
                  :min="0"
                  :max="10"
                  :step="1"
                  :disabled="batchStore.isExecuting"
                  size="medium"
                  :show-button="true"
                  class="number-input"
                  @update:value="handleCarRefreshCountChange"
                >
                  <template #suffix>
                    <span style="margin-left: 4px;">次</span>
                  </template>
                </n-input-number>
              </div>
              <n-slider
                v-model:value="batchStore.carRefreshCount"
                :min="0"
                :max="10"
                :step="1"
                :marks="{0: '0', 2: '2', 4: '4', 6: '6', 8: '8', 10: '10'}"
                :disabled="batchStore.isExecuting"
                :tooltip="true"
                @update:value="handleCarRefreshCountChange"
              />
            </div>
          </n-grid-item>
        </n-grid>

        <!-- 自动重试配置 -->
        <div class="auto-retry-config">
          <div class="config-header">
            <n-space align="center">
              <n-switch
                v-model:value="batchStore.autoRetryConfig.enabled"
                @update:value="handleAutoRetryToggle"
              />
              <span class="config-title">自动重试失败任务</span>
              <n-tag
                v-if="batchStore.autoRetryConfig.enabled"
                type="success"
                size="small"
                :bordered="false"
              >
                已启用
              </n-tag>
            </n-space>
          </div>
          <div v-if="batchStore.autoRetryConfig.enabled" class="config-details">
            <n-space vertical :size="12">
              <div class="config-item">
                <span class="label">最大重试轮数：</span>
                <n-input-number
                  v-model:value="batchStore.autoRetryConfig.maxRetries"
                  :min="1"
                  :max="10"
                  :step="1"
                  size="small"
                  style="width: 100px;"
                  @update:value="handleAutoRetryConfigChange"
                >
                  <template #suffix>轮</template>
                </n-input-number>
                <n-text depth="3" style="margin-left: 8px; font-size: 12px;">
                  ({{ batchStore.currentRetryRound }}/{{ batchStore.autoRetryConfig.maxRetries }})
                </n-text>
              </div>
              <div class="config-item">
                <span class="label">重试间隔时间：</span>
                <n-input-number
                  v-model:value="retryDelaySeconds"
                  :min="1"
                  :max="60"
                  :step="1"
                  size="small"
                  style="width: 100px;"
                  @update:value="handleRetryDelayChange"
                >
                  <template #suffix>秒</template>
                </n-input-number>
              </div>
              <n-alert type="info" size="small" :bordered="false">
                开启后，批量任务完成时如有失败的token，会自动重试最多{{ batchStore.autoRetryConfig.maxRetries }}轮
              </n-alert>
            </n-space>
          </div>
        </div>

        <!-- 🆕 日志控制面板 -->
        <div class="log-control-panel">
          <div class="log-control-header" @click="showLogControl = !showLogControl" style="cursor: pointer;">
            <n-icon size="18"><DocumentText /></n-icon>
            <span>日志打印控制</span>
            <n-space style="margin-left: auto;">
              <n-button
                text
                size="small"
                @click.stop="enableAllLogs"
              >
                全部启用
              </n-button>
              <n-button
                text
                size="small"
                @click.stop="disableAllLogs"
              >
                全部禁用
              </n-button>
              <n-icon size="20" style="transition: transform 0.3s ease;" :style="{ transform: showLogControl ? 'rotate(180deg)' : 'rotate(0deg)' }">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path fill="currentColor" d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6l-6-6l1.41-1.41z"/>
                </svg>
              </n-icon>
            </n-space>
          </div>
          
          <div v-show="showLogControl" class="log-control-body">
            <div class="log-section">
              <div class="section-title">任务日志</div>
              <div class="log-switches">
                <n-space>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.dailyFix" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>一键补差</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.climbTower" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>爬塔</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.restartBottle" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>重启盐罐</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.legionSignIn" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>俱乐部签到</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.autoStudy" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>一键答题</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.claimHangupReward" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>挂机奖励</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.addClock" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>加钟</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.sendCar" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>发车</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.monthlyTask" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>月度任务</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.blackMarket" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>小号黑市购买</span>
                  </div>
                </n-space>
              </div>
            </div>
            
            <div class="log-section">
              <div class="section-title">系统日志</div>
              <div class="log-switches">
                <n-space>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.batch" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>批量执行</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.heartbeat" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>心跳机制</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.websocket" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>WebSocket</span>
                  </div>
                  <div class="log-switch-item">
                    <n-switch v-model:value="batchStore.logConfig.gameMessage" size="small" @update:value="batchStore.saveLogConfig" />
                    <span>游戏消息跳过</span>
                  </div>
                </n-space>
              </div>
            </div>
          </div>
        </div>

        <!-- 任务列表预览 -->
        <div class="tasks-preview">
          <div class="preview-header">
            <span>包含任务 ({{ currentTasks.length }}个)：</span>
            <n-button
              text
              size="small"
              @click="showTemplateEditor = true"
            >
              <template #icon>
                <n-icon><Settings /></n-icon>
              </template>
              自定义模板
            </n-button>
          </div>
          <div class="task-tags">
            <n-tag
              v-for="task in currentTasks"
              :key="task.id"
              :color="task.color ? { color: task.color, textColor: '#fff', borderColor: task.color } : undefined"
              :type="task.color ? undefined : task.type"
              size="small"
              :class="{ 'clickable-tag': task.id === 'dailyFix' || task.id === 'blackMarket' }"
              :style="{ cursor: (task.id === 'dailyFix' || task.id === 'blackMarket') ? 'pointer' : 'default' }"
              @click="handleTaskClick(task.id)"
            >
              {{ task.label }}
              <span v-if="task.id === 'dailyFix'" style="margin-left: 4px;">
                ({{ dailyTaskStateStore.dailyFixTaskDefinitions.length }}个子任务)
              </span>
            </n-tag>
          </div>
        </div>

        <!-- 执行控制按钮 -->
        <div class="control-buttons">
          <n-space>
            <n-button
              v-if="!batchStore.isExecuting"
              type="primary"
              size="large"
              :disabled="!batchStore.canExecute"
              @click="handleStart"
            >
              <template #icon>
                <n-icon><PlayCircle /></n-icon>
              </template>
              开始执行 ({{ tokenStore.gameTokens.length }}个角色)
            </n-button>

            <n-button
              v-if="!batchStore.isExecuting && failedTaskCount > 0"
              type="warning"
              size="large"
              @click="handleRetryFailed"
            >
              <template #icon>
                <n-icon><Refresh /></n-icon>
              </template>
              重试失败 ({{ failedTaskCount }}个)
            </n-button>

            <n-button
              v-if="batchStore.isExecuting && !batchStore.isPaused"
              type="warning"
              size="large"
              @click="batchStore.pauseExecution()"
            >
              <template #icon>
                <n-icon><Pause /></n-icon>
              </template>
              暂停
            </n-button>

            <n-button
              v-if="batchStore.isExecuting && batchStore.isPaused"
              type="success"
              size="large"
              @click="batchStore.resumeExecution()"
            >
              <template #icon>
                <n-icon><Play /></n-icon>
              </template>
              继续
            </n-button>

            <n-button
              v-if="batchStore.isExecuting"
              type="error"
              size="large"
              @click="handleStop"
            >
              <template #icon>
                <n-icon><Stop /></n-icon>
              </template>
              停止
            </n-button>

            <n-button
              size="large"
              @click="showScheduler = true"
            >
              <template #icon>
                <n-icon><Time /></n-icon>
              </template>
              定时设置
            </n-button>

            <n-button
              size="large"
              @click="showHistory = true"
            >
              <template #icon>
                <n-icon><List /></n-icon>
              </template>
              执行历史
            </n-button>
          </n-space>
        </div>

        <!-- 执行进度 -->
        <div
          v-if="batchStore.isExecuting"
          class="execution-progress"
        >
          <div class="progress-header">
            <n-space align="center" :size="8">
              <span>总体进度</span>
              <n-tag
                v-if="batchStore.currentRetryRound > 0"
                type="warning"
                size="small"
                :bordered="false"
              >
                🔄 第{{ batchStore.currentRetryRound }}轮重试
              </n-tag>
            </n-space>
            <span>{{ batchStore.overallProgress }}%</span>
          </div>
          <n-progress
            type="line"
            :percentage="batchStore.overallProgress"
            :status="batchStore.isPaused ? 'warning' : 'info'"
            :show-indicator="false"
          />
        </div>

        <!-- 统计信息 -->
        <div
          v-if="batchStore.isExecuting || batchStore.executionStats.endTime"
          class="stats-panel"
        >
          <n-space justify="space-around">
            <n-statistic label="总计" :value="batchStore.executionStats.total" />
            <n-statistic
              label="成功"
              :value="batchStore.executionStats.success"
              class="success"
            />
            <n-statistic
              label="失败"
              :value="batchStore.executionStats.failed"
              class="failed"
            />
            <n-statistic
              label="跳过"
              :value="batchStore.executionStats.skipped"
              class="skipped"
            />
            <n-statistic
              v-if="batchStore.autoRetryConfig.enabled"
              label="重试轮数"
              :value="`${batchStore.currentRetryRound}/${batchStore.autoRetryConfig.maxRetries}`"
              class="retry-round"
            />
            <n-statistic
              label="耗时"
              :value="executionDuration"
            />
          </n-space>
        </div>
        
        <!-- 🆕 失败原因统计 -->
        <div
          v-if="hasFailureReasons"
          class="failure-reasons-panel"
        >
          <n-card title="📋 失败原因统计" size="small" :bordered="false">
            <div class="failure-reasons-list">
              <div
                v-for="([reason, count], index) in failureReasonsList"
                :key="index"
                class="failure-reason-item"
              >
                <span class="reason-text">{{ reason }}</span>
                <n-tag type="error" size="small">{{ count }}个Token</n-tag>
              </div>
            </div>
          </n-card>
        </div>
      </n-space>
    </div>

    <!-- 任务模板编辑器弹窗 -->
    <n-modal
      v-model:show="showTemplateEditor"
      preset="card"
      title="自定义任务模板"
      :style="{ width: '600px' }"
      :bordered="false"
      :segmented="true"
    >
      <TemplateEditor
        :templates="batchStore.taskTemplates"
        @save="handleSaveTemplate"
        @delete="handleDeleteTemplate"
        @close="showTemplateEditor = false"
      />
    </n-modal>

    <!-- 定时设置弹窗 -->
    <n-modal
      v-model:show="showScheduler"
      preset="card"
      title="定时任务设置"
      :style="{ width: '600px' }"
      :bordered="false"
      :segmented="true"
    >
      <SchedulerConfig
        :config="batchStore.schedulerConfig"
        @save="handleSaveScheduler"
        @close="showScheduler = false"
      />
    </n-modal>

    <!-- 执行历史弹窗 -->
    <n-modal
      v-model:show="showHistory"
      preset="card"
      title="执行历史"
      :style="{ width: '700px' }"
      :bordered="false"
      :segmented="true"
    >
      <ExecutionHistory
        :history="batchStore.executionHistory"
        @clear="handleClearHistory"
        @close="showHistory = false"
      />
    </n-modal>

    <!-- 一键补差子任务详情弹窗 -->
    <n-modal
      v-model:show="showDailyFixDetail"
      preset="card"
      title="一键补差 - 子任务详情"
      :style="{ width: '700px', maxHeight: '80vh' }"
      :bordered="false"
      :segmented="true"
    >
      <div class="daily-fix-detail">
        <n-alert type="info" :bordered="false" style="margin-bottom: 16px;">
          <template #header>
            <strong>任务说明</strong>
          </template>
          "一键补差"会自动执行以下 {{ dailyTaskStateStore.dailyFixTaskDefinitions.length }} 个子任务，
          标记为 <n-tag type="error" size="tiny" :bordered="false">消耗资源</n-tag> 的任务在已完成后会自动跳过。
        </n-alert>

        <n-scrollbar style="max-height: 500px;">
          <n-list bordered>
            <n-list-item
              v-for="(task, index) in dailyTaskStateStore.dailyFixTaskDefinitions"
              :key="task.id"
            >
              <template #prefix>
                <n-tag :bordered="false" size="small" type="default">
                  {{ index + 1 }}
                </n-tag>
              </template>
              <div class="task-item">
                <span class="task-name">{{ task.name }}</span>
                <n-tag
                  v-if="task.consumesResources"
                  type="error"
                  size="tiny"
                  :bordered="false"
                  style="margin-left: 8px;"
                >
                  消耗资源
                </n-tag>
              </div>
            </n-list-item>
          </n-list>
        </n-scrollbar>

        <n-divider style="margin: 16px 0;" />

        <div class="task-summary">
          <n-space vertical>
            <n-statistic label="任务总数" :value="dailyTaskStateStore.dailyFixTaskDefinitions.length" />
            <n-statistic 
              label="消耗资源任务" 
              :value="dailyTaskStateStore.resourceConsumingTasks.filter(t => dailyTaskStateStore.dailyFixTaskDefinitions.find(dt => dt.id === t.id)).length"
            >
              <template #suffix>
                <span style="font-size: 14px; color: #999;">个（已完成会跳过）</span>
              </template>
            </n-statistic>
            <n-statistic 
              label="预计执行时间" 
              :value="Math.ceil(dailyTaskStateStore.dailyFixTaskDefinitions.length * 1.2)"
            >
              <template #suffix>
                <span style="font-size: 14px; color: #999;">秒（单个角色）</span>
              </template>
            </n-statistic>
          </n-space>
        </div>

        <div style="margin-top: 16px; text-align: right;">
          <n-button type="primary" @click="showDailyFixDetail = false">
            知道了
          </n-button>
        </div>
      </div>
    </n-modal>

    <!-- 小号黑市购买详情弹窗 -->
    <n-modal
      v-model:show="showBlackMarketDetail"
      preset="card"
      title="小号黑市购买 - 任务说明"
      :style="{ width: '600px' }"
      :bordered="false"
      :segmented="true"
    >
      <div class="blackmarket-detail">
        <n-alert type="warning" :bordered="false" style="margin-bottom: 16px;">
          <template #header>
            <strong>固定购买配置</strong>
          </template>
          此任务使用固定购买策略，不可自定义配置
        </n-alert>

        <n-card title="购买策略" :bordered="false" size="small" style="margin-bottom: 16px;">
          <n-list bordered>
            <n-list-item>
              <template #prefix>
                <n-tag type="success" :bordered="false">✓</n-tag>
              </template>
              <div class="purchase-item">
                <span class="item-name">青铜宝箱</span>
                <n-tag type="error" size="small" :bordered="false">必买</n-tag>
                <span class="item-price">原价: 400金砖</span>
              </div>
            </n-list-item>
            <n-list-item>
              <template #prefix>
                <n-tag type="warning" :bordered="false">~</n-tag>
              </template>
              <div class="purchase-item">
                <span class="item-name">黄金宝箱</span>
                <n-tag type="warning" size="small" :bordered="false">≤5折购买</n-tag>
                <span class="item-price">原价: 375金砖</span>
              </div>
            </n-list-item>
            <n-list-item>
              <template #prefix>
                <n-tag type="success" :bordered="false">✓</n-tag>
              </template>
              <div class="purchase-item">
                <span class="item-name">铂金宝箱</span>
                <n-tag type="error" size="small" :bordered="false">必买</n-tag>
                <span class="item-price">原价: 625金砖</span>
              </div>
            </n-list-item>
          </n-list>
        </n-card>

        <n-card title="执行流程" :bordered="false" size="small" style="margin-bottom: 16px;">
          <n-steps vertical :current="4" :status="'finish'">
            <n-step title="获取黑市信息" description="发送store_goodslist命令" />
            <n-step title="第一轮购买" description="按策略购买青铜、黄金(≤5折)、铂金宝箱" />
            <n-step title="刷新黑市" description="发送store_refresh命令(消耗100金砖)" />
            <n-step title="第二轮购买" description="再次按策略购买宝箱" />
          </n-steps>
        </n-card>

        <n-alert type="info" :bordered="false" style="margin-bottom: 16px;">
          <template #header>
            <strong>智能跳过</strong>
          </template>
          ✓ 如果"黑市购买1次物品"每日任务已完成，自动跳过<br/>
          ✓ 第一次刷新免费，后续刷新需要100金砖
        </n-alert>

        <div class="task-summary">
          <n-space vertical>
            <n-statistic label="预计消耗" value="~1400-2900">
              <template #suffix>
                <span style="font-size: 14px; color: #999;">金砖（含刷新费用）</span>
              </template>
            </n-statistic>
            <n-statistic label="预计执行时间" value="~5-8">
              <template #suffix>
                <span style="font-size: 14px; color: #999;">秒（单个角色）</span>
              </template>
            </n-statistic>
          </n-space>
        </div>

        <div style="margin-top: 16px; text-align: right;">
          <n-button type="primary" @click="showBlackMarketDetail = false">
            知道了
          </n-button>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, h } from 'vue'
import { useMessage, useDialog } from 'naive-ui'
import { 
  Flash, 
  Refresh, 
  Settings, 
  PlayCircle, 
  Pause, 
  Play, 
  Stop, 
  Time, 
  List,
  DocumentText
} from '@vicons/ionicons5'
import { useBatchTaskStore } from '@/stores/batchTaskStore'
import { useTokenStore } from '@/stores/tokenStore'
import { useDailyTaskStateStore } from '@/stores/dailyTaskState'
import { taskScheduler } from '@/utils/taskScheduler'
import TemplateEditor from './TemplateEditor.vue'
import SchedulerConfig from './SchedulerConfig.vue'
import ExecutionHistory from './ExecutionHistory.vue'

const batchStore = useBatchTaskStore()
const tokenStore = useTokenStore()
const dailyTaskStateStore = useDailyTaskStateStore()
const message = useMessage()
const dialog = useDialog()

// 弹窗状态
const showTemplateEditor = ref(false)
const showScheduler = ref(false)
const showHistory = ref(false)
const showDailyFixDetail = ref(false)
const showBlackMarketDetail = ref(false) // 黑市购买说明
const showLogControl = ref(false) // 日志控制面板折叠状态，默认折叠

// 任务定义（可扩展）
const taskDefinitions = {
  dailyFix: { label: '一键补差', type: 'warning', color: '#f0a020' },          // 金橙色
  restartBottle: { label: '重启盐罐机器人', type: 'success', color: '#18a058' }, // 绿色
  legionSignIn: { label: '俱乐部签到', type: 'primary', color: '#2080f0' },     // 蓝色
  autoStudy: { label: '一键答题', type: 'error', color: '#d03050' },           // 红色
  claimHangupReward: { label: '领取挂机奖励', type: 'info', color: '#70c0e8' }, // 浅蓝色
  addClock: { label: '加钟', type: 'default', color: '#909399' },              // 灰色
  sendCar: { label: '发车', type: 'warning', color: '#9333ea' },               // 紫色
  climbTower: { label: '爬塔', type: 'error', color: '#ec4899' },              // 粉红色
  blackMarket: { label: '小号黑市购买', type: 'info', color: '#f59e0b' }        // 橙色
}

// 模板选项
const templateOptions = computed(() => {
  return Object.keys(batchStore.taskTemplates).map(key => ({
    label: batchStore.taskTemplates[key].name,
    value: key
  }))
})

// 当前选中模板的任务列表
const currentTasks = computed(() => {
  return batchStore.currentTemplateTasks.map(taskId => ({
    id: taskId,
    ...taskDefinitions[taskId]
  }))
})

// 执行耗时
const executionDuration = computed(() => {
  const stats = batchStore.executionStats
  if (!stats.startTime) return '0秒'
  
  const endTime = stats.endTime || Date.now()
  const duration = Math.round((endTime - stats.startTime) / 1000)
  
  if (duration < 60) return `${duration}秒`
  
  const minutes = Math.floor(duration / 60)
  const seconds = duration % 60
  return `${minutes}分${seconds}秒`
})

// 🆕 失败原因统计
const hasFailureReasons = computed(() => {
  return Object.keys(batchStore.failureReasonsStats).length > 0
})

const failureReasonsList = computed(() => {
  return Object.entries(batchStore.failureReasonsStats)
    .sort((a, b) => b[1] - a[1]) // 按数量降序排列
})

// 格式化时间间隔
const formatInterval = (minutes) => {
  if (minutes < 60) {
    return `${minutes}分钟`
  } else if (minutes % 60 === 0) {
    return `${minutes / 60}小时`
  } else {
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    return `${hours}小时${mins}分钟`
  }
}

// 定时任务状态文本
const schedulerStatusText = computed(() => {
  if (!batchStore.schedulerConfig.enabled) return '定时任务：未启用'
  
  if (batchStore.schedulerConfig.type === 'interval') {
    return `定时任务：每${formatInterval(batchStore.schedulerConfig.interval)}`
  } else {
    return `定时任务：每日${batchStore.schedulerConfig.dailyTimes.length}次`
  }
})

// 定时任务状态标签类型
const schedulerStatusType = computed(() => {
  return batchStore.schedulerConfig.enabled ? 'warning' : 'default'
})

// 格式化最后执行时间
const formatLastExecutionTime = computed(() => {
  if (!batchStore.schedulerConfig.lastExecutionTime) return '从未执行'
  
  const date = new Date(batchStore.schedulerConfig.lastExecutionTime)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
})

// 失败任务数量
const failedTaskCount = computed(() => {
  return Object.values(batchStore.taskProgress).filter(
    progress => progress.status === 'failed'
  ).length
})

// 重试延迟（秒转换）
const retryDelaySeconds = computed({
  get: () => batchStore.autoRetryConfig.retryDelay / 1000,
  set: (value) => {
    batchStore.autoRetryConfig.retryDelay = value * 1000
    handleAutoRetryConfigChange()
  }
})

// 处理任务标签点击
const handleTaskClick = (taskId) => {
  if (taskId === 'dailyFix') {
    showDailyFixDetail.value = true
  } else if (taskId === 'blackMarket') {
    showBlackMarketDetail.value = true
  }
}

// 开始执行
const handleStart = () => {
  // 🆕 检查是否有保存的进度
  if (batchStore.hasSavedProgress && batchStore.savedProgress) {
    const completed = batchStore.savedProgress.completedTokenIds.length
    const total = batchStore.savedProgress.allTokenIds.length
    const remaining = total - completed
    
    dialog.warning({
      title: '发现未完成的任务',
      content: () => {
        return h('div', [
          h('p', `检测到上次有未完成的批量任务：`),
          h('ul', { style: 'margin: 12px 0; padding-left: 24px;' }, [
            h('li', `总计：${total} 个Token`),
            h('li', `已完成：${completed} 个`),
            h('li', { style: 'color: #ff6b6b; font-weight: bold;' }, `剩余：${remaining} 个`)
          ]),
          h('p', { style: 'margin-top: 16px; font-weight: bold;' }, '您想要：')
        ])
      },
      positiveText: '继续上次进度',
      negativeText: '重新开始',
      onPositiveClick: () => {
        batchStore.startBatchExecution(null, null, false, true)
        message.success(`继续执行剩余 ${remaining} 个Token`)
      },
      onNegativeClick: () => {
        dialog.warning({
          title: '确认重新开始',
          content: `确定要重新开始执行所有 ${tokenStore.gameTokens.length} 个角色的任务吗？\n\n已完成的 ${completed} 个Token将会重新执行。`,
          positiveText: '确定重新开始',
          negativeText: '取消',
          onPositiveClick: () => {
            batchStore.clearSavedProgress()
            batchStore.startBatchExecution()
            message.success('批量任务已启动（重新开始）')
          }
        })
      }
    })
  } else {
    // 没有保存的进度，正常开始
    dialog.warning({
      title: '确认执行',
      content: `即将对 ${tokenStore.gameTokens.length} 个角色执行批量任务，是否继续？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        batchStore.startBatchExecution()
        message.success('批量任务已启动')
      }
    })
  }
}

// 停止执行
const handleStop = () => {
  dialog.warning({
    title: '确认停止',
    content: '是否停止当前批量任务？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      batchStore.stopExecution()
      message.warning('批量任务已停止')
    }
  })
}

// 重试失败任务
const handleRetryFailed = () => {
  const count = failedTaskCount.value
  dialog.warning({
    title: '重试失败任务',
    content: `即将重新执行 ${count} 个失败的任务，是否继续？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      await batchStore.retryFailedTasks()
      message.success(`已重新执行 ${count} 个失败的任务`)
    }
  })
}

// 自动重试开关切换
const handleAutoRetryToggle = (value) => {
  batchStore.saveAutoRetryConfig({ enabled: value })
  if (value) {
    message.success('已启用自动重试失败任务')
  } else {
    message.info('已关闭自动重试')
  }
}

// 自动重试配置变更
const handleAutoRetryConfigChange = () => {
  batchStore.saveAutoRetryConfig(batchStore.autoRetryConfig)
  message.success('自动重试配置已更新')
}

// 重试延迟变更
const handleRetryDelayChange = (value) => {
  batchStore.autoRetryConfig.retryDelay = value * 1000
  batchStore.saveAutoRetryConfig(batchStore.autoRetryConfig)
}

// 保存任务模板
const handleSaveTemplate = (name, tasks) => {
  batchStore.saveTaskTemplate(name, tasks)
  message.success('任务模板已保存')
}

// 删除任务模板
const handleDeleteTemplate = (name) => {
  batchStore.deleteTaskTemplate(name)
  message.success('任务模板已删除')
}

// 保存调度器配置
const handleSaveScheduler = (config) => {
  // 如果是首次启用，显示确认对话框
  if (config.enabled && !batchStore.schedulerConfig.enabled) {
    const scheduleDesc = config.type === 'interval' 
      ? `每 ${formatInterval(config.interval)} 自动执行一次`
      : `每天在 ${config.dailyTimes.join(', ')} 自动执行`
    
    dialog.warning({
      title: '⚠️ 首次启用定时任务',
      content: `您正在启用定时任务功能：\n\n${scheduleDesc}\n\n任务将在后台自动执行，请确认您已了解此功能。\n\n提示：您可以随时在此页面停用定时任务。`,
      positiveText: '确认启用',
      negativeText: '取消',
      onPositiveClick: () => {
        batchStore.saveSchedulerConfig(config)
        startScheduler()
        message.success('✅ 定时任务已启动')
        showScheduler.value = false
      }
    })
  } else {
    batchStore.saveSchedulerConfig(config)
    
    // 重启调度器
    if (config.enabled) {
      startScheduler()
      message.success('定时任务已更新')
    } else {
      stopScheduler()
      message.info('定时任务已停止')
    }
    
    showScheduler.value = false
  }
}

// 快速切换调度器（用于快速控制栏）
const handleQuickToggleScheduler = (enabled) => {
  if (!enabled) {
    // 停用确认
    dialog.warning({
      title: '停用定时任务',
      content: '确定要停用定时任务吗？您可以随时重新启用。',
      positiveText: '确定停用',
      negativeText: '取消',
      onPositiveClick: () => {
        batchStore.saveSchedulerConfig({ enabled: false })
        stopScheduler()
        message.info('✅ 定时任务已停用')
      }
    })
  } else {
    // 快速启用（使用现有配置）
    batchStore.saveSchedulerConfig({ enabled: true })
    startScheduler()
    message.success('✅ 定时任务已启用')
  }
}

// 清空历史
const handleClearHistory = () => {
  batchStore.clearHistory()
  message.success('执行历史已清空')
}

// 并发数改变
const handleConcurrencyChange = (value) => {
  batchStore.setMaxConcurrency(value)
  message.success(`并发数已设置为 ${value}`)
}

// 🆕 v3.13.0 连接池模式切换
const handlePoolModeChange = (enabled) => {
  batchStore.setUseConnectionPool(enabled)
  if (enabled) {
    message.success('🏊 连接池模式已启用 - 支持100+并发稳定运行', {
      duration: 3000
    })
  } else {
    message.info('⚙️ 连接池模式已禁用 - 使用传统模式', {
      duration: 3000
    })
  }
}

// 🆕 v3.13.0 连接池大小改变
const handlePoolSizeChange = (value) => {
  batchStore.setPoolSize(value)
  message.success(`连接池大小已设置为 ${value}`)
}

// 🆕 v3.13.2 最大并发请求数改变
const handleConcurrentRequestsChange = (value) => {
  batchStore.setMaxConcurrentRequests(value)
  message.success(`同时执行数已设置为 ${value}`, {
    duration: 3000
  })
}

// 🆕 连接间隔改变
const handleConnectionIntervalChange = (value) => {
  batchStore.setConnectionInterval(value)
  message.success(`连接间隔已设置为 ${value}ms`, {
    duration: 3000
  })
}

// 爬塔次数改变
const handleTowerCountChange = (value) => {
  batchStore.setClimbTowerCount(value)
  if (value === 0) {
    message.info('爬塔次数设置为0，将跳过爬塔任务')
  } else {
    message.success(`爬塔次数已设置为 ${value}`)
  }
}

// 发车刷新次数改变
const handleCarRefreshCountChange = (value) => {
  batchStore.setCarRefreshCount(value)
  if (value === 0) {
    message.info('发车刷新次数设置为0，将跳过刷新步骤')
  } else {
    message.success(`发车刷新次数已设置为 ${value}`)
  }
}

// 🆕 日志控制
const enableAllLogs = () => {
  const keys = Object.keys(batchStore.logConfig)
  keys.forEach(key => {
    batchStore.logConfig[key] = true
  })
  batchStore.saveLogConfig()
  message.success('已启用所有日志')
}

const disableAllLogs = () => {
  const keys = Object.keys(batchStore.logConfig)
  keys.forEach(key => {
    batchStore.logConfig[key] = false
  })
  batchStore.saveLogConfig()
  message.success('已禁用所有日志')
}

// 启动调度器
const startScheduler = () => {
  const config = batchStore.schedulerConfig
  
  if (!config.enabled) return
  
  taskScheduler.start(config, async (tasks) => {
    // tasks参数：每日定时模式下会传递指定的任务列表，间隔模式下为null
    const tasksInfo = tasks ? ` [${tasks.length}个任务]` : ''
    console.log(`🤖 调度器触发批量任务${tasksInfo}`)
    
    // 如果指定了任务列表，直接使用这些任务
    if (tasks) {
      await batchStore.startBatchExecution(null, tasks)
    } else {
      // 否则使用当前选中的模板
      await batchStore.startBatchExecution()
    }
    
    // 更新最后执行时间
    batchStore.saveSchedulerConfig({
      lastExecutionTime: Date.now()
    })
  })
}

// 停止调度器
const stopScheduler = () => {
  taskScheduler.stop()
}

// 组件挂载时
onMounted(() => {
  // 如果启用了定时任务，显示提醒并启动调度器
  if (batchStore.schedulerConfig.enabled) {
    const config = batchStore.schedulerConfig
    const scheduleDesc = config.type === 'interval' 
      ? `每 ${formatInterval(config.interval)}`
      : `每天 ${config.dailyTimes.join(', ')}`
    
    // 显示通知提醒用户定时任务正在运行
    message.warning(
      `⏰ 定时任务已自动启动（${scheduleDesc}）`,
      {
        duration: 5000,
        closable: true
      }
    )
    
    startScheduler()
  }
})

// 组件卸载时
onUnmounted(() => {
  stopScheduler()
})
</script>

<style scoped lang="scss">
.batch-task-panel {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  margin-bottom: 24px;

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h2 {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 20px;
      font-weight: 600;
      margin: 0;
      color: #333;

      .n-icon {
        font-size: 24px;
        color: #667eea;
      }
    }
  }

  // 定时任务状态标签
  .scheduler-status-tag {
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }

  // 定时任务提示框
  .scheduler-tooltip {
    p {
      margin: 4px 0;
      line-height: 1.6;
      
      &:first-child {
        margin-top: 0;
      }
      
      &:last-child {
        margin-bottom: 0;
      }
      
      strong {
        color: #667eea;
      }
    }
  }

  // 定时任务快速控制栏
  .scheduler-quick-control {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    margin-bottom: 16px;
    background: linear-gradient(135deg, rgba(255, 193, 7, 0.1) 0%, rgba(255, 152, 0, 0.1) 100%);
    border: 1px solid rgba(255, 193, 7, 0.3);
    border-radius: 12px;
    animation: pulse-border 2s ease-in-out infinite;
    
    .control-info {
      display: flex;
      align-items: center;
      gap: 12px;
      flex: 1;
      
      .n-icon {
        color: #ff9800;
        flex-shrink: 0;
      }
      
      .info-text {
        color: #333;
        font-size: 14px;
        
        strong {
          color: #ff6f00;
          margin-right: 8px;
        }
        
        span {
          color: #666;
        }
      }
    }
  }

  @keyframes pulse-border {
    0%, 100% {
      border-color: rgba(255, 193, 7, 0.3);
      box-shadow: 0 0 0 0 rgba(255, 193, 7, 0);
    }
    50% {
      border-color: rgba(255, 193, 7, 0.6);
      box-shadow: 0 0 0 4px rgba(255, 193, 7, 0.1);
    }
  }

  .template-section {
    .template-selector,
    // 🆕 v3.13.0 连接池模式切换
    .connection-pool-toggle {
      padding: 16px;
      background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
      border: 1px solid #bae6fd;
      border-radius: 8px;
      margin-bottom: 4px;
      
      .toggle-label {
        span {
          font-size: 15px;
        }
      }
    }
    
    // 🆕 v3.13.0 连接池大小选择器
    .pool-size-selector {
      padding: 16px;
      background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
      border: 1px solid #bbf7d0;
      border-radius: 8px;
      
      .pool-size-hint {
        margin-top: 12px;
      }
      
      .selector-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        
        label {
          margin: 0;
          font-weight: 500;
          color: #15803d;
          white-space: nowrap;
        }
        
        .number-input {
          flex-shrink: 0;
          width: 140px !important;
          
          :deep(.n-input-number-input) {
            text-align: center;
          }
        }
      }
    }
    
    // 🆕 v3.13.2 最大并发请求数选择器
    .concurrent-requests-selector {
      padding: 16px;
      background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
      border: 1px solid #fcd34d;
      border-radius: 8px;
      
      .concurrent-requests-hint {
        margin-top: 12px;
      }
      
      .selector-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        
        label {
          margin: 0;
          font-weight: 500;
          color: #92400e;
          white-space: nowrap;
        }
        
        .number-input {
          flex-shrink: 0;
          width: 140px !important;
          
          :deep(.n-input-number-input) {
            text-align: center;
          }
        }
      }
    }
    
    // 🆕 连接间隔选择器
    .connection-interval-selector {
      padding: 16px;
      background: linear-gradient(135deg, #e0e7ff 0%, #c7d2fe 100%);
      border: 1px solid #a5b4fc;
      border-radius: 8px;
      
      .connection-interval-hint {
        margin-top: 12px;
      }
      
      .selector-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        
        label {
          margin: 0;
          font-weight: 500;
          color: #3730a3;
          white-space: nowrap;
        }
        
        .number-input {
          flex-shrink: 0;
          width: 140px !important;
          
          :deep(.n-input-number-input) {
            text-align: center;
          }
        }
      }
    }
    
    .concurrency-selector,
    .tower-count-selector {
      .concurrency-hint {
        margin-top: 12px;
      }
      
      .selector-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        
        label {
          margin: 0;
          font-weight: 500;
          color: #666;
          white-space: nowrap;
        }
        
        .number-input {
          flex-shrink: 0;
          width: 140px !important;
          
          :deep(.n-input-number-input) {
            text-align: center;
            font-size: 16px;
            font-weight: 600;
            cursor: text;
          }
          
          :deep(.n-input__input-el) {
            cursor: text !important;
          }
        }
      }
      
      :deep(.n-slider) {
        margin-top: 0;
      }
    }

    // 自动重试配置
    .auto-retry-config {
      background: rgba(16, 185, 129, 0.05);
      border: 1px solid rgba(16, 185, 129, 0.2);
      border-radius: 8px;
      padding: 16px;
      
      .config-header {
        margin-bottom: 12px;
        
        .config-title {
          font-weight: 500;
          font-size: 14px;
          color: #333;
        }
      }
      
      .config-details {
        margin-top: 12px;
        padding-top: 12px;
        border-top: 1px solid rgba(16, 185, 129, 0.1);
        
        .config-item {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .label {
            font-size: 14px;
            color: #666;
            min-width: 100px;
          }
        }
      }
    }

    .tasks-preview {
      background: rgba(102, 126, 234, 0.05);
      border-radius: 8px;
      padding: 16px;

      .preview-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        font-weight: 500;
        color: #666;
      }

      .task-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .clickable-tag {
          transition: all 0.3s ease;
          position: relative;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
          }
          
          &:active {
            transform: translateY(0);
          }
        }
      }
    }

    // 一键补差子任务详情弹窗样式
    .daily-fix-detail {
      .task-item {
        display: flex;
        align-items: center;
        
        .task-name {
          font-size: 14px;
          color: #333;
        }
      }

      .task-summary {
        padding: 16px;
        background: rgba(102, 126, 234, 0.05);
        border-radius: 8px;
      }
    }

    .control-buttons {
      margin-top: 8px;
    }

    .execution-progress {
      background: rgba(102, 126, 234, 0.05);
      border-radius: 8px;
      padding: 16px;

      .progress-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-weight: 500;
        color: #666;
      }
    }

    .stats-panel {
      background: rgba(102, 126, 234, 0.05);
      border-radius: 8px;
      padding: 16px;

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

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

        &.skipped .n-statistic-value__content {
          color: #f0a020;
        }
        
        &.retry-round .n-statistic-value__content {
          color: #ff9800;
          font-weight: 600;
        }
      }
    }
    
    // 🆕 失败原因统计面板
    .failure-reasons-panel {
      margin-top: 12px;
      
      .failure-reasons-list {
        display: flex;
        flex-direction: column;
        gap: 8px;
      }
      
      .failure-reason-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        background: rgba(208, 48, 80, 0.05);
        border-radius: 6px;
        border-left: 3px solid #d03050;
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(208, 48, 80, 0.1);
          transform: translateX(2px);
        }
        
        .reason-text {
          flex: 1;
          font-size: 13px;
          color: #333;
          font-weight: 500;
        }
      }
      
      :deep(.n-card__header) {
        padding: 12px 16px;
        font-weight: 600;
        font-size: 14px;
      }
      
      :deep(.n-card__content) {
        padding: 12px 16px;
      }
    }
  }
}

/* 深色主题适配 */
html.dark .batch-task-panel,
html[data-theme="dark"] .batch-task-panel {
  background: rgba(30, 30, 30, 0.95);

  .panel-header h2 {
    color: #ffffff;
  }

  .template-selector label,
  .concurrency-selector .selector-header label,
  .tower-count-selector .selector-header label,
  .preview-header,
  .progress-header {
    color: #cccccc;
  }

  .tasks-preview,
  .execution-progress,
  .stats-panel {
    background: rgba(255, 255, 255, 0.05);
  }
  
  // 🆕 深色主题下的失败原因统计
  .failure-reasons-panel {
    .failure-reason-item {
      background: rgba(208, 48, 80, 0.15);
      border-left-color: #e57373;
      
      &:hover {
        background: rgba(208, 48, 80, 0.25);
      }
      
      .reason-text {
        color: #e0e0e0;
      }
    }
  }

  // 深色主题下的定时任务控制栏
  .scheduler-quick-control {
    background: linear-gradient(135deg, rgba(255, 193, 7, 0.15) 0%, rgba(255, 152, 0, 0.15) 100%);
    border-color: rgba(255, 193, 7, 0.4);
    
    .control-info {
      .info-text {
        color: #e0e0e0;
        
        strong {
          color: #ffb74d;
        }
        
        span {
          color: #b0b0b0;
        }
      }
    }
  }

  // 深色主题下的提示框
  .scheduler-tooltip {
    p {
      color: #e0e0e0;
      
      strong {
        color: #8ea3f5;
      }
    }
  }
  
  // 🆕 日志控制面板
  .log-control-panel {
    margin-bottom: 20px;
    padding: 16px;
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border: 1px solid #f59e0b;
    border-radius: 8px;
    
    .log-control-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 16px;
      font-weight: 600;
      color: #92400e;
      
      .n-icon {
        color: #f59e0b;
      }
    }
    
    .log-control-body {
      display: flex;
      flex-direction: column;
      gap: 16px;
      
      .log-section {
        .section-title {
          font-size: 13px;
          font-weight: 600;
          color: #78350f;
          margin-bottom: 10px;
          padding-bottom: 6px;
          border-bottom: 1px solid rgba(245, 158, 11, 0.3);
        }
        
        .log-switches {
          .log-switch-item {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 12px;
            background: rgba(255, 255, 255, 0.6);
            border-radius: 6px;
            
            span {
              font-size: 13px;
              color: #92400e;
              white-space: nowrap;
            }
          }
        }
      }
    }
  }
}

// 黑市购买详情样式
.blackmarket-detail {
  .purchase-item {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .item-name {
      font-weight: 500;
      min-width: 80px;
    }
    
    .item-price {
      margin-left: auto;
      font-size: 12px;
      color: #999;
    }
  }
}
</style>

