import { DataSource } from 'typeorm';
import { UserEntityMt } from '@d8d/user-module-mt';
import { FeiePrinterMt, FeiePrintTaskMt, FeieConfigMt } from '../../src/entities';

export class FeieTestFactory {
  private dataSource: DataSource;

  constructor(dataSource: DataSource) {
    this.dataSource = dataSource;
  }

  /**
   * 创建测试用户
   */
  async createTestUser(tenantId: number = 1, overrides: Partial<UserEntityMt> = {}): Promise<UserEntityMt> {
    const userRepository = this.dataSource.getRepository(UserEntityMt);
    const user = userRepository.create({
      tenantId,
      username: `test_user_${Math.floor(Math.random() * 100000)}`,
      password: 'test_password',
      nickname: '测试用户',
      registrationSource: 'web',
      ...overrides
    });
    return await userRepository.save(user);
  }

  /**
   * 创建测试打印机
   */
  async createTestPrinter(tenantId: number = 1, overrides: Partial<FeiePrinterMt> = {}): Promise<FeiePrinterMt> {
    const printerRepository = this.dataSource.getRepository(FeiePrinterMt);
    const printer = printerRepository.create({
      tenantId,
      printerSn: `TEST_SN_${Math.floor(Math.random() * 100000)}`,
      printerKey: `TEST_KEY_${Math.floor(Math.random() * 100000)}`,
      printerName: '测试打印机',
      printerType: '58mm',
      printerStatus: 'ACTIVE',
      isDefault: 0,
      ...overrides
    });
    return await printerRepository.save(printer);
  }

  /**
   * 创建特定序列号的测试打印机（用于特定测试场景）
   */
  async createSpecificTestPrinter(
    tenantId: number = 1,
    printerSn: string,
    printerKey: string,
    isDefault: number = 1,
    overrides: Partial<FeiePrinterMt> = {}
  ): Promise<FeiePrinterMt> {
    const printerRepository = this.dataSource.getRepository(FeiePrinterMt);
    const printer = printerRepository.create({
      tenantId,
      printerSn,
      printerKey,
      printerName: `打印机 ${printerSn}`,
      printerType: '58mm',
      printerStatus: 'ACTIVE',
      isDefault,
      ...overrides
    });
    return await printerRepository.save(printer);
  }

  /**
   * 创建测试打印任务
   */
  async createTestPrintTask(tenantId: number = 1, printerSn: string, overrides: Partial<FeiePrintTaskMt> = {}): Promise<FeiePrintTaskMt> {
    const taskRepository = this.dataSource.getRepository(FeiePrintTaskMt);
    const task = taskRepository.create({
      tenantId,
      taskId: `TASK_${Date.now()}`,
      printerSn,
      content: '<CB>测试打印内容</CB><BR>',
      printType: 'RECEIPT',
      printStatus: 'PENDING',
      retryCount: 0,
      ...overrides
    });
    return await taskRepository.save(task);
  }

  /**
   * 创建测试飞鹅配置
   */
  async createTestFeieConfig(tenantId: number = 1, overrides: Partial<FeieConfigMt> = {}): Promise<FeieConfigMt> {
    const configRepository = this.dataSource.getRepository(FeieConfigMt);
    const config = configRepository.create({
      tenantId,
      configKey: 'feie.api.user',
      configValue: 'test_user',
      configType: 'STRING',
      description: '飞鹅API用户',
      ...overrides
    });
    return await configRepository.save(config);
  }

  /**
   * 创建完整的飞鹅API配置
   */
  async createFullFeieConfig(tenantId: number = 1): Promise<void> {
    const configRepository = this.dataSource.getRepository(FeieConfigMt);

    const configs = [
      {
        tenantId,
        configKey: 'feie.api.user',
        configValue: 'test_user',
        configType: 'STRING',
        description: '飞鹅API用户'
      },
      {
        tenantId,
        configKey: 'feie.api.ukey',
        configValue: 'test_ukey',
        configType: 'STRING',
        description: '飞鹅API密钥'
      },
      {
        tenantId,
        configKey: 'feie.api.base_url',
        configValue: 'https://api.feieyun.cn/Api/Open/',
        configType: 'STRING',
        description: '飞鹅API基础URL'
      },
      {
        tenantId,
        configKey: 'feie.api.timeout',
        configValue: '10000',
        configType: 'NUMBER',
        description: 'API超时时间'
      },
      {
        tenantId,
        configKey: 'feie.api.max_retries',
        configValue: '3',
        configType: 'NUMBER',
        description: '最大重试次数'
      }
    ];

    for (const config of configs) {
      await configRepository.save(configRepository.create(config));
    }
  }

  /**
   * 创建跨租户测试环境
   */
  async createCrossTenantTestEnvironment() {
    const tenant1User = await this.createTestUser(1);
    const tenant2User = await this.createTestUser(2);

    const tenant1Printer = await this.createTestPrinter(1);
    const tenant2Printer = await this.createTestPrinter(2);

    const tenant1Task = await this.createTestPrintTask(1, tenant1Printer.printerSn);
    const tenant2Task = await this.createTestPrintTask(2, tenant2Printer.printerSn);

    // 创建配置
    await this.createFullFeieConfig(1);
    await this.createFullFeieConfig(2);

    return {
      tenant1User,
      tenant2User,
      tenant1Printer,
      tenant2Printer,
      tenant1Task,
      tenant2Task
    };
  }

  /**
   * 清理测试数据
   */
  async cleanup() {
    const repositories = {
      printTask: this.dataSource.getRepository(FeiePrintTaskMt),
      printer: this.dataSource.getRepository(FeiePrinterMt),
      config: this.dataSource.getRepository(FeieConfigMt),
      user: this.dataSource.getRepository(UserEntityMt)
    };

    // 按依赖关系顺序删除数据
    await repositories.printTask.delete({});
    await repositories.printer.delete({});
    await repositories.config.delete({});
    await repositories.user.delete({});
  }
}