#!/usr/bin/env node

/**
 * 修复延迟调度器脚本
 * 1. 检查当前延迟任务状态
 * 2. 手动执行超时任务
 * 3. 提供修复建议
 */

const { DataSource } = require('typeorm');
const { DelaySchedulerService } = require('./packages/feie-printer-module-mt/build-simple.cjs');

async function main() {
  console.log('=== 延迟调度器修复脚本 ===\n');

  // 1. 检查数据库中的延迟任务
  console.log('1. 检查数据库中的延迟任务...');
  const dataSource = new DataSource({
    type: 'postgres',
    host: '127.0.0.1',
    port: 5432,
    username: 'postgres',
    password: '',
    database: 'postgres',
    synchronize: false,
    logging: false
  });

  try {
    await dataSource.initialize();
    console.log('数据库连接成功\n');

    // 查询延迟任务
    const tasks = await dataSource.query(`
      SELECT
        task_id,
        order_id,
        print_status,
        scheduled_at,
        created_at,
        EXTRACT(EPOCH FROM (NOW() - scheduled_at)) as seconds_late
      FROM feie_print_task_mt
      WHERE print_status IN ('DELAYED', 'PENDING')
      ORDER BY scheduled_at
    `);

    console.log(`找到 ${tasks.length} 个延迟任务:`);
    tasks.forEach((task, index) => {
      console.log(`  ${index + 1}. ${task.task_id} - 订单: ${task.order_id}`);
      console.log(`     状态: ${task.print_status}, 计划时间: ${task.scheduled_at}`);
      console.log(`     已超时: ${Math.round(task.seconds_late)} 秒\n`);
    });

    if (tasks.length === 0) {
      console.log('没有找到延迟任务，无需修复');
      return;
    }

    // 2. 创建调度器并手动处理任务
    console.log('2. 创建调度器并手动处理任务...');
    const feieConfig = {
      baseUrl: 'https://api.feieyun.cn/Api/Open/',
      user: '',
      ukey: '',
      timeout: 10000,
      maxRetries: 3
    };

    // 获取所有租户ID
    const tenantIds = await dataSource.query(`
      SELECT DISTINCT tenant_id
      FROM feie_print_task_mt
      WHERE print_status IN ('DELAYED', 'PENDING')
      ORDER BY tenant_id
    `);

    for (const row of tenantIds) {
      const tenantId = row.tenant_id;
      console.log(`\n处理租户 ${tenantId} 的任务:`);

      const scheduler = new DelaySchedulerService(dataSource, feieConfig, tenantId);

      // 手动处理任务
      const result = await scheduler.triggerManualProcess(tenantId);
      console.log(`  结果: ${result.message}`);

      // 启动调度器（如果未运行）
      try {
        await scheduler.start();
        console.log(`  调度器已启动`);
      } catch (error) {
        if (error.message.includes('已经在运行中')) {
          console.log(`  调度器已在运行中`);
        } else {
          console.log(`  启动调度器失败: ${error.message}`);
        }
      }
    }

    // 3. 验证修复结果
    console.log('\n3. 验证修复结果...');
    const remainingTasks = await dataSource.query(`
      SELECT COUNT(*) as count
      FROM feie_print_task_mt
      WHERE print_status IN ('DELAYED', 'PENDING')
        AND scheduled_at <= NOW()
    `);

    console.log(`剩余未处理的延迟任务: ${remainingTasks[0].count} 个`);

    if (remainingTasks[0].count > 0) {
      console.log('\n⚠️  警告: 仍有未处理的延迟任务');
      console.log('可能原因:');
      console.log('  1. 打印机配置问题');
      console.log('  2. 飞鹅API连接失败');
      console.log('  3. 订单状态检查失败');
    } else {
      console.log('\n✅ 所有延迟任务已处理完成');
    }

  } catch (error) {
    console.error('修复过程中发生错误:', error);
  } finally {
    if (dataSource.isInitialized) {
      await dataSource.destroy();
    }
  }

  console.log('\n=== 修复脚本执行完成 ===');
}

// 执行修复
main().catch(console.error);