import { DataSource } from 'typeorm';
import { UserEntityMt } from '@d8d/user-module-mt';
import { SupplierMt } from '@d8d/supplier-module-mt';
import { MerchantMt } from '@d8d/merchant-module-mt';
import { FileMt } from '@d8d/file-module-mt';
import { GoodsMt, GoodsCategoryMt } from '../../src/entities/index.mt';

export class GoodsTestFactory {
  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 createTestAdmin(overrides: Partial<UserEntityMt> = {}): Promise<UserEntityMt> {
    const userRepository = this.dataSource.getRepository(UserEntityMt);
    const admin = userRepository.create({
      tenantId: 1,
      username: `test_admin_${Math.floor(Math.random() * 100000)}`,
      password: 'admin_password',
      nickname: '测试管理员',
      registrationSource: 'web',
      ...overrides
    });
    return await userRepository.save(admin);
  }

  /**
   * 创建测试供应商
   */
  async createTestSupplier(createdBy: number, overrides: Partial<SupplierMt> = {}): Promise<SupplierMt> {
    const supplierRepository = this.dataSource.getRepository(SupplierMt);
    const supplier = supplierRepository.create({
      tenantId: 1,
      name: '测试供应商',
      username: `test_supplier_${Math.floor(Math.random() * 100000)}`,
      password: 'password123',
      phone: '13800138000',
      realname: '测试供应商',
      state: 1,
      createdBy,
      ...overrides
    });
    return await supplierRepository.save(supplier);
  }

  /**
   * 创建测试商户
   */
  async createTestMerchant(createdBy: number, overrides: Partial<MerchantMt> = {}): Promise<MerchantMt> {
    const merchantRepository = this.dataSource.getRepository(MerchantMt);
    const merchant = merchantRepository.create({
      tenantId: 1,
      name: '测试商户',
      username: `test_merchant_${Math.floor(Math.random() * 100000)}`,
      password: 'password123',
      phone: '13800138001',
      realname: '测试商户',
      state: 1,
      createdBy,
      ...overrides
    });
    return await merchantRepository.save(merchant);
  }

  /**
   * 创建测试商品分类
   */
  async createTestCategory(createdBy: number, overrides: Partial<GoodsCategoryMt> = {}): Promise<GoodsCategoryMt> {
    const categoryRepository = this.dataSource.getRepository(GoodsCategoryMt);
    const category = categoryRepository.create({
      tenantId: 1,
      name: `测试分类_${Math.floor(Math.random() * 100000)}`,
      parentId: 0,
      level: 1,
      state: 1,
      createdBy,
      ...overrides
    });
    return await categoryRepository.save(category);
  }

  /**
   * 创建测试商品
   */
  async createTestGoods(
    createdBy: number,
    overrides: Partial<GoodsMt> = {}
  ): Promise<GoodsMt> {
    const goodsRepository = this.dataSource.getRepository(GoodsMt);

    // 从overrides中获取tenantId，默认为1
    const tenantId = overrides.tenantId || 1;

    // 创建默认的分类、供应商、商户用于测试
    const testCategory = await this.createTestCategory(createdBy, { tenantId });
    const testSupplier = await this.createTestSupplier(createdBy, { tenantId });
    const testMerchant = await this.createTestMerchant(createdBy, { tenantId });

    const goods = goodsRepository.create({
      tenantId,
      name: `测试商品_${Math.floor(Math.random() * 100000)}`,
      price: 100.00,
      costPrice: 80.00,
      categoryId1: testCategory.id,
      categoryId2: testCategory.id,
      categoryId3: testCategory.id,
      goodsType: 1,
      supplierId: testSupplier.id,
      merchantId: testMerchant.id,
      state: 1,
      stock: 100,
      lowestBuy: 1,
      createdBy,
      ...overrides
    });
    return await goodsRepository.save(goods);
  }

  /**
   * 创建测试文件
   */
  async createTestFile(uploadUserId: number, overrides: Partial<FileMt> = {}): Promise<FileMt> {
    const fileRepository = this.dataSource.getRepository(FileMt);
    const file = fileRepository.create({
      tenantId: 1,
      name: `test_file_${Math.floor(Math.random() * 100000)}.jpg`,
      originalName: 'test.jpg',
      path: '/uploads/test.jpg',
      mimeType: 'image/jpeg',
      size: 1024,
      uploadUserId,
      uploadTime: new Date(),
      ...overrides
    });
    return await fileRepository.save(file);
  }

  /**
   * 创建完整的测试环境（用户、供应商、商户、分类、商品）
   */
  async createFullTestEnvironment() {
    const testUser = await this.createTestUser();
    const testSupplier = await this.createTestSupplier(testUser.id);
    const testMerchant = await this.createTestMerchant(testUser.id);
    const testCategory = await this.createTestCategory(testUser.id);
    const testGoods = await this.createTestGoods(testUser.id);

    return {
      testUser,
      testSupplier,
      testMerchant,
      testCategory,
      testGoods
    };
  }

  /**
   * 清理测试数据
   */
  async cleanup() {
    const repositories = {
      goods: this.dataSource.getRepository(GoodsMt),
      category: this.dataSource.getRepository(GoodsCategoryMt),
      supplier: this.dataSource.getRepository(SupplierMt),
      merchant: this.dataSource.getRepository(MerchantMt),
      user: this.dataSource.getRepository(UserEntityMt),
      file: this.dataSource.getRepository(FileMt)
    };

    // 按依赖关系顺序删除数据
    await repositories.goods.delete({});
    await repositories.category.delete({});
    await repositories.supplier.delete({});
    await repositories.merchant.delete({});
    await repositories.file.delete({});
    await repositories.user.delete({});
  }
}