/**
 * 批量任务测试工具
 * 用于在浏览器控制台中测试批量任务功能
 */

// 测试配置
const testConfig = {
  concurrency: 3, // 测试并发数设为3（而不是5）
  mockTokens: [
    { id: 'token_1', name: '测试账号1' },
    { id: 'token_2', name: '测试账号2' },
    { id: 'token_3', name: '测试账号3' },
    { id: 'token_4', name: '测试账号4' },
    { id: 'token_5', name: '测试账号5' }
  ],
  mockTasks: ['task1', 'task2', 'task3']
}

/**
 * 模拟任务执行（异步）
 */
const mockExecuteTask = async (tokenId, taskName, delay = 1000) => {
  console.log(`[${new Date().toISOString()}] 开始执行: ${tokenId} - ${taskName}`)
  
  // 模拟延迟
  await new Promise(resolve => setTimeout(resolve, delay))
  
  // 随机成功/失败（90%成功率）
  const success = Math.random() > 0.1
  
  console.log(`[${new Date().toISOString()}] ${success ? '✅' : '❌'} 完成: ${tokenId} - ${taskName}`)
  
  if (!success) {
    throw new Error(`任务失败: ${taskName}`)
  }
  
  return { success: true, data: `${taskName} result` }
}

/**
 * 测试并发控制
 */
const testConcurrencyControl = async () => {
  console.log('========== 测试并发控制 ==========')
  console.log(`最大并发数: ${testConfig.concurrency}`)
  console.log(`Token数量: ${testConfig.mockTokens.length}`)
  console.log(`任务数量: ${testConfig.mockTasks.length}`)
  
  const startTime = Date.now()
  const queue = [...testConfig.mockTokens]
  const executing = []
  const results = []
  
  while (queue.length > 0 || executing.length > 0) {
    // 填充执行队列
    while (executing.length < testConfig.concurrency && queue.length > 0) {
      const token = queue.shift()
      
      const promise = (async () => {
        const tokenResults = {}
        
        for (const task of testConfig.mockTasks) {
          try {
            const result = await mockExecuteTask(token.id, task, 500)
            tokenResults[task] = result
          } catch (error) {
            tokenResults[task] = { success: false, error: error.message }
          }
        }
        
        return { tokenId: token.id, tokenName: token.name, results: tokenResults }
      })()
      
      promise.then(() => {
        const index = executing.indexOf(promise)
        if (index > -1) {
          executing.splice(index, 1)
        }
      })
      
      executing.push(promise)
    }
    
    // 等待至少一个完成
    if (executing.length > 0) {
      const result = await Promise.race(executing)
      results.push(result)
      console.log(`✓ Token完成: ${result.tokenName}`)
    }
  }
  
  const endTime = Date.now()
  const duration = Math.round((endTime - startTime) / 1000)
  
  console.log('\n========== 测试结果 ==========')
  console.log(`总耗时: ${duration}秒`)
  console.log(`完成Token数: ${results.length}`)
  console.log(`平均耗时: ${Math.round(duration / results.length)}秒/Token`)
  
  // 统计成功/失败
  let totalSuccess = 0
  let totalFailed = 0
  
  results.forEach(r => {
    Object.values(r.results).forEach(taskResult => {
      if (taskResult.success) {
        totalSuccess++
      } else {
        totalFailed++
      }
    })
  })
  
  console.log(`成功任务: ${totalSuccess}`)
  console.log(`失败任务: ${totalFailed}`)
  console.log(`成功率: ${Math.round((totalSuccess / (totalSuccess + totalFailed)) * 100)}%`)
  
  return results
}

/**
 * 测试任务调度器（间隔定时）
 */
const testIntervalScheduler = () => {
  console.log('========== 测试间隔调度器 ==========')
  
  let executionCount = 0
  const interval = 5000 // 5秒间隔
  
  const scheduler = {
    timer: null,
    start() {
      console.log(`启动调度器，间隔: ${interval}ms`)
      
      this.timer = setInterval(() => {
        executionCount++
        console.log(`[${new Date().toISOString()}] 第${executionCount}次执行`)
        
        // 执行3次后自动停止
        if (executionCount >= 3) {
          this.stop()
        }
      }, interval)
    },
    stop() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
        console.log('调度器已停止')
      }
    }
  }
  
  scheduler.start()
  
  return scheduler
}

/**
 * 测试每日定时调度
 */
const testDailyScheduler = () => {
  console.log('========== 测试每日定时调度 ==========')
  
  const dailyTimes = ['08:00', '12:00', '18:00']
  
  const calculateNextExecution = (timeStr) => {
    const [hour, minute] = timeStr.split(':').map(Number)
    const now = new Date()
    const scheduled = new Date()
    scheduled.setHours(hour, minute, 0, 0)
    
    if (scheduled <= now) {
      scheduled.setDate(scheduled.getDate() + 1)
    }
    
    const delay = scheduled - now
    return {
      timeStr,
      scheduled: scheduled.toISOString(),
      delayMs: delay,
      delayMinutes: Math.round(delay / 1000 / 60)
    }
  }
  
  dailyTimes.forEach(time => {
    const next = calculateNextExecution(time)
    console.log(`时间点: ${next.timeStr}`)
    console.log(`  下次执行: ${next.scheduled}`)
    console.log(`  延迟: ${next.delayMinutes}分钟\n`)
  })
}

/**
 * 测试存储功能
 */
const testStorage = () => {
  console.log('========== 测试存储功能 ==========')
  
  // 测试数据
  const testData = {
    templates: {
      '测试模板': {
        name: '测试模板',
        tasks: ['task1', 'task2'],
        enabled: true
      }
    },
    history: [
      {
        id: 'batch_123',
        template: '测试模板',
        stats: { total: 5, success: 4, failed: 1 },
        timestamp: Date.now(),
        duration: 12000
      }
    ]
  }
  
  // 保存到localStorage
  try {
    localStorage.setItem('test_taskTemplates', JSON.stringify(testData.templates))
    localStorage.setItem('test_batchTaskHistory', JSON.stringify(testData.history))
    console.log('✓ 数据保存成功')
    
    // 读取验证
    const savedTemplates = JSON.parse(localStorage.getItem('test_taskTemplates'))
    const savedHistory = JSON.parse(localStorage.getItem('test_batchTaskHistory'))
    
    console.log('✓ 数据读取成功')
    console.log('模板数量:', Object.keys(savedTemplates).length)
    console.log('历史记录数:', savedHistory.length)
    
    // 清理测试数据
    localStorage.removeItem('test_taskTemplates')
    localStorage.removeItem('test_batchTaskHistory')
    console.log('✓ 测试数据已清理')
    
  } catch (error) {
    console.error('❌ 存储测试失败:', error)
  }
}

/**
 * 运行所有测试
 */
export const runAllTests = async () => {
  console.log('\n')
  console.log('╔═══════════════════════════════════╗')
  console.log('║   批量任务功能测试套件            ║')
  console.log('╚═══════════════════════════════════╝')
  console.log('\n')
  
  // 测试1: 并发控制
  await testConcurrencyControl()
  
  console.log('\n')
  
  // 测试2: 存储功能
  testStorage()
  
  console.log('\n')
  
  // 测试3: 每日调度
  testDailyScheduler()
  
  console.log('\n')
  console.log('✅ 所有测试完成')
  console.log('\n提示: 运行 testIntervalScheduler() 可以测试间隔调度器（会执行3次后自动停止）')
}

// 导出测试函数
export const batchTaskTests = {
  runAll: runAllTests,
  concurrency: testConcurrencyControl,
  intervalScheduler: testIntervalScheduler,
  dailyScheduler: testDailyScheduler,
  storage: testStorage
}

// 在浏览器控制台使用说明
console.log('批量任务测试工具已加载')
console.log('使用方法:')
console.log('  import { batchTaskTests } from "@/utils/batchTaskTest.js"')
console.log('  batchTaskTests.runAll()        - 运行所有测试')
console.log('  batchTaskTests.concurrency()   - 测试并发控制')
console.log('  batchTaskTests.intervalScheduler() - 测试间隔调度')
console.log('  batchTaskTests.dailyScheduler()    - 测试每日调度')
console.log('  batchTaskTests.storage()           - 测试存储功能')

