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

// 设置模块路径
const projectRoot = path.resolve(__dirname);
const sharedUtilsPath = path.join(projectRoot, 'packages/shared-utils/dist/index.js');

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

  try {
    // 1. 检查数据源连接
    console.log('1. 检查数据源连接...');
    if (!AppDataSource.isInitialized) {
      console.log('  数据源未初始化，正在初始化...');
      await AppDataSource.initialize();
      console.log('  数据源初始化成功');
    } else {
      console.log('  数据源已初始化');
    }

    // 2. 检查订单ID 25是否存在
    console.log('\n2. 检查订单ID 25...');
    const orderRepository = AppDataSource.getRepository('OrderMt');
    const order = await orderRepository.findOne({
      where: { id: 25, tenantId: 1 }
    });

    if (!order) {
      console.log('  ❌ 订单ID 25不存在');
      return;
    }
    console.log(`  ✅ 订单存在: ${order.orderNo}, 支付状态: ${order.payState}, 订单状态: ${order.state}`);

    // 3. 检查飞鹅配置
    console.log('\n3. 检查飞鹅配置...');
    const configRepository = AppDataSource.getRepository('FeieConfigMt');
    const configKeys = [
      'feie.api.user',
      'feie.api.ukey',
      'feie.api.base_url',
      'feie.anti_refund_delay'
    ];

    for (const key of configKeys) {
      const config = await configRepository.findOne({
        where: { tenantId: 1, configKey: key }
      });
      console.log(`  ${key}: ${config ? config.configValue : '未配置'}`);
    }

    // 4. 检查默认打印机
    console.log('\n4. 检查默认打印机...');
    const printerRepository = AppDataSource.getRepository('FeiePrinterMt');
    const defaultPrinter = await printerRepository.findOne({
      where: { tenantId: 1, isDefault: true }
    });

    if (!defaultPrinter) {
      console.log('  ❌ 未找到默认打印机');
      // 检查是否有任何打印机
      const printers = await printerRepository.find({
        where: { tenantId: 1 }
      });
      console.log(`  租户1共有 ${printers.length} 台打印机`);
    } else {
      console.log(`  ✅ 默认打印机: ${defaultPrinter.printerSn} (${defaultPrinter.printerName})`);
    }

    // 5. 检查打印任务表结构
    console.log('\n5. 检查打印任务表结构...');
    const printTaskRepository = AppDataSource.getRepository('FeiePrintTaskMt');
    const tableMetadata = printTaskRepository.metadata;
    console.log(`  表名: ${tableMetadata.tableName}`);
    console.log(`  列数: ${tableMetadata.columns.length}`);

    // 6. 尝试手动创建打印任务
    console.log('\n6. 尝试手动创建打印任务...');
    try {
      // 动态导入飞鹅打印模块
      const { PrintTriggerService } = await import('@d8d/feie-printer-module-mt');

      // 创建配置
      const feieConfig = {
        user: 'test',
        ukey: 'test',
        baseUrl: 'http://api.feieyun.cn/Api/Open/',
        timeout: 10000,
        maxRetries: 3
      };

      // 创建服务实例
      const printTriggerService = new PrintTriggerService(AppDataSource, feieConfig);

      // 调用处理支付成功事件
      console.log('  调用handleOrderPaymentSuccess...');
      await printTriggerService.handleOrderPaymentSuccess(1, 25);
      console.log('  ✅ 调用成功');

    } catch (error) {
      console.log(`  ❌ 调用失败: ${error.message}`);
      console.log(`  错误堆栈: ${error.stack}`);
    }

    // 7. 检查是否创建了记录
    console.log('\n7. 检查是否创建了记录...');
    const tasks = await printTaskRepository.find({
      where: { tenantId: 1, orderId: 25 }
    });

    if (tasks.length === 0) {
      console.log('  ❌ 未找到订单ID 25的打印任务');
    } else {
      console.log(`  ✅ 找到 ${tasks.length} 个打印任务`);
      tasks.forEach(task => {
        console.log(`    - 任务ID: ${task.taskId}, 状态: ${task.printStatus}, 创建时间: ${task.createdAt}`);
      });
    }

  } catch (error) {
    console.error('调试过程中发生错误:', error);
    console.error('错误堆栈:', error.stack);
  }
}

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