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

/**
 * 飞鹅打印模块测试数据工厂类
 */
export class FeieTestDataFactory {
  /**
   * 创建测试用户数据
   */
  static createUserData(overrides: Partial<UserEntityMt> = {}): Partial<UserEntityMt> {
    const timestamp = Math.floor(Math.random() * 100000);
    return {
      username: `test_user_${timestamp}`,
      password: 'test_password',
      nickname: '测试用户',
      registrationSource: 'web',
      isDisabled: 0,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试用户
   */
  static async createTestUser(dataSource: DataSource, tenantId: number, overrides: Partial<UserEntityMt> = {}): Promise<UserEntityMt> {
    const userData = this.createUserData({ tenantId, ...overrides });
    const userRepository = dataSource.getRepository(UserEntityMt);
    const user = userRepository.create(userData);
    return await userRepository.save(user);
  }

  /**
   * 创建测试打印机
   */
  static async createTestPrinter(dataSource: DataSource, tenantId: number, overrides: Partial<FeiePrinterMt> = {}): Promise<FeiePrinterMt> {
    const printerRepository = dataSource.getRepository(FeiePrinterMt);
    const timestamp = Math.floor(Math.random() * 100000);

    const printer = printerRepository.create({
      tenantId,
      printerSn: `TEST_SN_${timestamp}`,
      printerKey: `TEST_KEY_${timestamp}`,
      printerName: '测试打印机',
      printerType: '58mm',
      printerStatus: 'ACTIVE',
      isDefault: 0,
      ...overrides
    });

    return await printerRepository.save(printer);
  }

  /**
   * 创建特定序列号的测试打印机（用于特定测试场景）
   */
  static async createSpecificTestPrinter(
    dataSource: DataSource,
    tenantId: number,
    printerSn: string,
    printerKey: string,
    isDefault: number = 1,
    overrides: Partial<FeiePrinterMt> = {}
  ): Promise<FeiePrinterMt> {
    const printerRepository = dataSource.getRepository(FeiePrinterMt);

    const printer = printerRepository.create({
      tenantId,
      printerSn,
      printerKey,
      printerName: `打印机 ${printerSn}`,
      printerType: '58mm',
      printerStatus: 'ACTIVE',
      isDefault,
      ...overrides
    });

    return await printerRepository.save(printer);
  }

  /**
   * 创建测试打印任务
   */
  static async createTestPrintTask(dataSource: DataSource, tenantId: number, printerSn: string, overrides: Partial<FeiePrintTaskMt> = {}): Promise<FeiePrintTaskMt> {
    const taskRepository = dataSource.getRepository(FeiePrintTaskMt);
    const timestamp = Date.now();

    const task = taskRepository.create({
      tenantId,
      taskId: `TASK_${timestamp}`,
      printerSn,
      content: '<CB>测试打印内容</CB><BR>',
      printType: 'RECEIPT',
      printStatus: 'PENDING',
      retryCount: 0,
      ...overrides
    });

    return await taskRepository.save(task);
  }

  /**
   * 创建测试飞鹅配置
   */
  static async createTestFeieConfig(dataSource: DataSource, tenantId: number, overrides: Partial<FeieConfigMt> = {}): Promise<FeieConfigMt> {
    const configRepository = 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配置
   */
  static async createFullFeieConfig(dataSource: DataSource, tenantId: number): Promise<void> {
    const configRepository = 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));
    }
  }

  /**
   * 创建完整的测试环境数据
   */
  static async createCompleteTestData(dataSource: DataSource, tenantId: number = 1): Promise<{
    user: UserEntityMt;
    printer: FeiePrinterMt;
    task: FeiePrintTaskMt;
  }> {
    // 创建用户
    const user = await this.createTestUser(dataSource, tenantId);

    // 创建打印机
    const printer = await this.createTestPrinter(dataSource, tenantId);

    // 创建打印任务
    const task = await this.createTestPrintTask(dataSource, tenantId, printer.printerSn);

    // 创建配置
    await this.createFullFeieConfig(dataSource, tenantId);

    return {
      user,
      printer,
      task
    };
  }

  /**
   * 为测试用户生成JWT token
   */
  static generateUserToken(user: UserEntityMt): string {
    return JWTUtil.generateToken({
      id: user.id,
      username: user.username,
      tenantId: user.tenantId
    });
  }

  /**
   * 为管理员生成JWT token
   */
  static generateAdminToken(tenantId: number): string {
    return JWTUtil.generateToken({
      id: 1,
      username: 'admin',
      tenantId
    });
  }
}