// 简单调试脚本
const { exec } = require('child_process');
const util = require('util');
const execPromise = util.promisify(exec);

async function debugSimple() {
  console.log('=== 简单调试打印任务问题 ===\n');

  try {
    // 1. 检查订单ID 25
    console.log('1. 检查订单ID 25...');
    const { stdout: orderStdout } = await execPromise(
      'psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT id, order_no, amount, pay_state, state FROM orders_mt WHERE id = 25"'
    );
    console.log(orderStdout);

    // 2. 检查飞鹅配置
    console.log('\n2. 检查飞鹅配置...');
    const { stdout: configStdout } = await execPromise(
      'psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT config_key, config_value FROM feie_config_mt WHERE tenant_id = 1 AND config_key LIKE \'feie.%\'"'
    );
    console.log(configStdout);

    // 3. 检查打印机
    console.log('\n3. 检查打印机...');
    const { stdout: printerStdout } = await execPromise(
      'psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT id, printer_sn, printer_name, is_default FROM feie_printer_mt WHERE tenant_id = 1"'
    );
    console.log(printerStdout);

    // 4. 检查打印任务
    console.log('\n4. 检查打印任务...');
    const { stdout: taskStdout } = await execPromise(
      'psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT id, tenant_id, task_id, order_id, print_status, scheduled_at, created_at FROM feie_print_task_mt WHERE order_id = 25 OR order_id = 999 ORDER BY created_at DESC"'
    );
    console.log(taskStdout);

    // 5. 检查系统配置
    console.log('\n5. 检查系统配置...');
    const { stdout: systemConfigStdout } = await execPromise(
      'psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT config_key, config_value FROM system_config_mt WHERE tenant_id = 1 AND config_key LIKE \'feie.%\'"'
    );
    console.log(systemConfigStdout);

    // 6. 分析问题
    console.log('\n6. 问题分析...');
    const configLines = configStdout.trim().split('\n');
    const hasFeieConfig = configLines.length > 2; // 超过标题行和空行

    const printerLines = printerStdout.trim().split('\n');
    const hasPrinter = printerLines.length > 2;

    const taskLines = taskStdout.trim().split('\n');
    const hasTaskFor25 = taskStdout.includes('25');

    console.log(`  飞鹅配置: ${hasFeieConfig ? '✅ 存在' : '❌ 缺失'}`);
    console.log(`  打印机: ${hasPrinter ? '✅ 存在' : '❌ 缺失'}`);
    console.log(`  订单25的打印任务: ${hasTaskFor25 ? '✅ 存在' : '❌ 缺失'}`);

    if (!hasFeieConfig) {
      console.log('\n  问题: 缺少飞鹅配置');
      console.log('  解决方案: 在feie_config_mt表中添加配置');
    }

    if (!hasPrinter) {
      console.log('\n  问题: 缺少打印机');
      console.log('  解决方案: 在feie_printer_mt表中添加打印机');
    }

  } catch (error) {
    console.error('调试失败:', error.message);
  }
}

debugSimple().catch(console.error);