// 调试打印任务创建问题
const { DataSource } = require('typeorm');

async function debugPrintTask() {
  console.log('=== 调试打印任务创建问题 ===\n');

  // 创建数据源
  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 tenantId = 1;
    const orderId = 25;

    // 1. 检查订单是否存在
    console.log('1. 检查订单是否存在...');
    const order = await dataSource.query(
      'SELECT id, order_no, amount, pay_state, state FROM orders_mt WHERE id = $1 AND tenant_id = $2',
      [orderId, tenantId]
    );

    if (order.length === 0) {
      console.log('❌ 订单不存在');
      return;
    }

    console.log('✅ 订单存在:', order[0]);
    console.log(`   订单号: ${order[0].order_no}`);
    console.log(`   金额: ${order[0].amount}`);
    console.log(`   支付状态: ${order[0].pay_state}`);
    console.log(`   订单状态: ${order[0].state}\n`);

    // 2. 检查打印机配置
    console.log('2. 检查打印机配置...');
    const printer = await dataSource.query(
      'SELECT * FROM feie_printer_mt WHERE tenant_id = $1 AND is_default = 1',
      [tenantId]
    );

    if (printer.length === 0) {
      console.log('❌ 没有默认打印机');
      return;
    }

    console.log('✅ 默认打印机存在:', printer[0].printer_name);
    console.log(`   打印机SN: ${printer[0].printer_sn}`);
    console.log(`   打印机状态: ${printer[0].printer_status}\n`);

    // 3. 检查防退款延迟配置
    console.log('3. 检查防退款延迟配置...');
    const delayConfig = await dataSource.query(
      'SELECT config_value FROM system_config_mt WHERE tenant_id = $1 AND config_key = $2',
      [tenantId, 'feie.anti_refund_delay']
    );

    const delaySeconds = delayConfig.length > 0 ? parseInt(delayConfig[0].config_value) : 120;
    console.log(`✅ 防退款延迟时间: ${delaySeconds}秒\n`);

    // 4. 检查飞鹅API配置
    console.log('4. 检查飞鹅API配置...');
    const apiConfigs = await dataSource.query(
      'SELECT config_key, config_value FROM system_config_mt WHERE tenant_id = $1 AND config_key LIKE $2',
      [tenantId, 'feie.api.%']
    );

    if (apiConfigs.length === 0) {
      console.log('❌ 飞鹅API配置不存在');
    } else {
      console.log('✅ 飞鹅API配置存在:');
      apiConfigs.forEach(config => {
        console.log(`   ${config.config_key}: ${config.config_value}`);
      });
      console.log();
    }

    // 5. 手动创建打印任务（模拟代码逻辑）
    console.log('5. 手动创建打印任务...');
    const taskId = `FEIE_${Date.now()}_${Math.floor(Math.random() * 10000)}`;
    const scheduledAt = new Date(Date.now() + delaySeconds * 1000);

    try {
      await dataSource.query(`
        INSERT INTO feie_print_task_mt
        (tenant_id, task_id, order_id, printer_sn, content, print_type, print_status, scheduled_at, retry_count, max_retries, created_at, updated_at)
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW(), NOW())
      `, [
        tenantId,
        taskId,
        orderId,
        printer[0].printer_sn,
        `测试打印内容\n订单号: ${order[0].order_no}\n时间: ${new Date().toLocaleString()}`,
        'RECEIPT',
        'DELAYED',
        scheduledAt,
        0,
        3
      ]);

      console.log('✅ 手动创建打印任务成功');
      console.log(`   任务ID: ${taskId}`);
      console.log(`   计划时间: ${scheduledAt}\n`);

      // 6. 验证任务是否创建成功
      console.log('6. 验证任务是否创建成功...');
      const createdTask = await dataSource.query(
        'SELECT * FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
        [tenantId, taskId]
      );

      if (createdTask.length > 0) {
        console.log('✅ 任务验证成功:');
        console.log(`   任务ID: ${createdTask[0].task_id}`);
        console.log(`   订单ID: ${createdTask[0].order_id}`);
        console.log(`   状态: ${createdTask[0].print_status}`);
        console.log(`   创建时间: ${createdTask[0].created_at}`);
      } else {
        console.log('❌ 任务验证失败 - 任务未找到');
      }

      // 7. 清理测试数据
      console.log('\n7. 清理测试数据...');
      await dataSource.query(
        'DELETE FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
        [tenantId, taskId]
      );
      console.log('✅ 测试数据已清理');

    } catch (error) {
      console.error('❌ 手动创建打印任务失败:', error.message);
      console.error('错误堆栈:', error.stack);
    }

  } catch (error) {
    console.error('调试失败:', error);
  } finally {
    try {
      await dataSource.destroy();
      console.log('\n🔌 数据库连接已关闭');
    } catch (error) {
      console.error('关闭数据库连接失败:', error);
    }
  }
}

// 运行调试
debugPrintTask().catch(error => {
  console.error('调试脚本执行失败:', error);
  process.exit(1);
});