#!/usr/bin/env node

/**
 * 简单修复延迟任务脚本
 * 直接使用数据库查询和更新
 */

const { Client } = require('pg');

async function main() {
  console.log('=== 延迟任务简单修复脚本 ===\n');

  const client = new Client({
    host: '127.0.0.1',
    port: 5432,
    user: 'postgres',
    password: '',
    database: 'postgres'
  });

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

    // 1. 检查延迟任务
    console.log('1. 检查延迟任务状态...');
    const tasksResult = await client.query(`
      SELECT
        task_id,
        order_id,
        print_status,
        scheduled_at,
        EXTRACT(EPOCH FROM (NOW() - scheduled_at)) as seconds_late
      FROM feie_print_task_mt
      WHERE print_status IN ('DELAYED', 'PENDING')
        AND scheduled_at <= NOW()
      ORDER BY scheduled_at
    `);

    const tasks = tasksResult.rows;
    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. 检查订单状态...');
    for (const task of tasks) {
      if (!task.order_id) continue;

      const orderResult = await client.query(`
        SELECT pay_state, state
        FROM order_mt
        WHERE id = $1 AND tenant_id = 1
      `, [task.order_id]);

      if (orderResult.rows.length === 0) {
        console.log(`  订单 ${task.order_id} 不存在，标记任务为取消`);
        await client.query(`
          UPDATE feie_print_task_mt
          SET print_status = 'CANCELLED',
              updated_at = NOW(),
              cancel_reason = 'ORDER_NOT_FOUND'
          WHERE task_id = $1
        `, [task.task_id]);
      } else {
        const order = orderResult.rows[0];
        console.log(`  订单 ${task.order_id}: 支付状态=${order.pay_state}, 订单状态=${order.state}`);

        // 检查是否已退款 (pay_state = 3) 或订单关闭 (state = 5)
        if (order.pay_state === 3 || order.state === 5) {
          console.log(`  订单 ${task.order_id} 已退款/关闭，取消打印任务`);
          await client.query(`
            UPDATE feie_print_task_mt
            SET print_status = 'CANCELLED',
                updated_at = NOW(),
                cancel_reason = 'REFUND'
            WHERE task_id = $1
          `, [task.task_id]);
        } else {
          console.log(`  订单 ${task.order_id} 正常，标记任务为失败（模拟打印失败）`);
          await client.query(`
            UPDATE feie_print_task_mt
            SET print_status = 'FAILED',
                updated_at = NOW(),
                error_message = '手动修复：任务超时未执行'
            WHERE task_id = $1
          `, [task.task_id]);
        }
      }
    }

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

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

    if (remainingResult.rows[0].count > 0) {
      console.log('\n⚠️  仍有未处理的延迟任务，建议：');
      console.log('  1. 检查调度器是否启动');
      console.log('  2. 检查飞鹅打印机配置');
      console.log('  3. 检查网络连接');
    } else {
      console.log('\n✅ 所有超时延迟任务已处理');
    }

  } catch (error) {
    console.error('修复过程中发生错误:', error);
  } finally {
    await client.end();
  }

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

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