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 { DeliveryAddressMt } from '@d8d/delivery-address-module-mt';
import { FileMt } from '@d8d/file-module-mt';
import { GoodsMt, GoodsCategoryMt } from '@d8d/goods-module-mt';
import { AreaEntityMt } from '@d8d/geo-areas-mt';
import { OrderMt, OrderGoodsMt, OrderRefundMt } from '../../src/entities/index';

export class OrdersTestFactory {
  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 createTestArea(overrides: Partial<AreaEntityMt> = {}): Promise<AreaEntityMt> {
    const areaRepository = this.dataSource.getRepository(AreaEntityMt);
    const area = areaRepository.create({
      tenantId: 1,
      name: '测试地区',
      code: `AREA_${Math.floor(Math.random() * 100000)}`,
      level: 1,
      ...overrides
    });
    return await areaRepository.save(area);
  }

  /**
   * 创建测试配送地址
   */
  async createTestDeliveryAddress(userId: number, overrides: Partial<DeliveryAddressMt> = {}): Promise<DeliveryAddressMt> {
    const addressRepository = this.dataSource.getRepository(DeliveryAddressMt);

    // 创建测试地区数据
    const testProvince = await this.createTestArea({ id: 110000, level: 1 });
    const testCity = await this.createTestArea({ id: 110100, level: 2 });
    const testDistrict = await this.createTestArea({ id: 110105, level: 3 });
    const testTown = await this.createTestArea({ id: 110105, level: 4 });

    const address = addressRepository.create({
      tenantId: 1,
      name: '测试收货人',
      phone: '13800138000',
      receiverProvince: testProvince.id,
      receiverCity: testCity.id,
      receiverDistrict: testDistrict.id,
      receiverTown: testTown.id,
      address: '测试地址',
      userId,
      ...overrides
    });
    return await addressRepository.save(address);
  }

  /**
   * 创建测试商品分类
   */
  async createTestGoodsCategory(overrides: Partial<GoodsCategoryMt> = {}): Promise<GoodsCategoryMt> {
    const categoryRepository = this.dataSource.getRepository(GoodsCategoryMt);
    const tenantId = overrides.tenantId || 1;

    const category = categoryRepository.create({
      tenantId,
      name: `测试分类_${Math.floor(Math.random() * 100000)}`,
      parentId: 0,
      level: 1,
      state: 1,
      ...overrides
    });
    return await categoryRepository.save(category);
  }

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

    // 创建测试商品分类
    const testCategory = await this.createTestGoodsCategory({ tenantId });

    const goods = goodsRepository.create({
      tenantId,
      name: `测试商品_${Math.floor(Math.random() * 100000)}`,
      price: 100.00,
      costPrice: 80.00,
      goodsType: 1,
      state: 1,
      stock: 100,
      lowestBuy: 1,
      createdBy,
      categoryId1: testCategory.id, // 使用真实创建的分类ID
      categoryId2: testCategory.id,
      categoryId3: testCategory.id,
      ...overrides
    });
    return await goodsRepository.save(goods);
  }

  /**
   * 创建测试订单
   */
  async createTestOrder(
    userId: number,
    overrides: Partial<OrderMt> = {}
  ): Promise<OrderMt> {
    const orderRepository = this.dataSource.getRepository(OrderMt);
    const tenantId = overrides.tenantId || 1;

    // 创建必要的关联实体
    const testSupplier = await this.createTestSupplier(userId, { tenantId });
    const testMerchant = await this.createTestMerchant(userId, { tenantId });
    const testDeliveryAddress = await this.createTestDeliveryAddress(userId, { tenantId });

    const order = orderRepository.create({
      tenantId,
      orderNo: `ORD_${Date.now()}`,
      userId: userId,
      amount: 100.00,
      payAmount: 95.00,
      discountAmount: 5.00,
      merchantId: testMerchant.id,
      supplierId: testSupplier.id,
      addressId: testDeliveryAddress.id,
      state: 0,
      payState: 0,
      orderType: 1,
      payType: 1,
      ...overrides
    });
    return await orderRepository.save(order);
  }

  /**
   * 创建测试订单商品
   */
  async createTestOrderGoods(
    orderId: number,
    goodsId: number,
    overrides: Partial<OrderGoodsMt> = {}
  ): Promise<OrderGoodsMt> {
    const orderGoodsRepository = this.dataSource.getRepository(OrderGoodsMt);
    const tenantId = overrides.tenantId || 1;

    const orderGoods = orderGoodsRepository.create({
      tenantId,
      orderId,
      goodsId,
      goodsName: '测试商品',
      price: 100.00,
      costPrice: 80.00,
      num: 1,
      freightAmount: 0.00,
      goodsType: 1,
      state: 1,
      ...overrides
    });
    return await orderGoodsRepository.save(orderGoods);
  }

  /**
   * 创建测试退款记录
   */
  async createTestOrderRefund(
    orderId: number,
    overrides: Partial<OrderRefundMt> = {}
  ): Promise<OrderRefundMt> {
    const refundRepository = this.dataSource.getRepository(OrderRefundMt);
    const tenantId = overrides.tenantId || 1;

    const refund = refundRepository.create({
      tenantId,
      orderNo: `ORD_${Date.now()}`,
      refundOrderNo: `REFUND_${Date.now()}`,
      refundAmount: 100.00,
      remark: '测试退款原因',
      state: 0,
      ...overrides
    });
    return await refundRepository.save(refund);
  }

  /**
   * 创建完整的测试订单环境
   */
  async createFullOrderTestEnvironment(tenantId: number = 1) {
    const testUser = await this.createTestUser(tenantId);
    const testOrder = await this.createTestOrder(testUser.id, { tenantId });
    const testGoods = await this.createTestGoods(testUser.id, { tenantId });
    const testOrderGoods = await this.createTestOrderGoods(testOrder.id, testGoods.id, { tenantId });

    return {
      testUser,
      testOrder,
      testGoods,
      testOrderGoods
    };
  }

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

    const tenant1Order = await this.createTestOrder(tenant1User.id, { tenantId: 1 });
    const tenant2Order = await this.createTestOrder(tenant2User.id, { tenantId: 2 });

    return {
      tenant1User,
      tenant2User,
      tenant1Order,
      tenant2Order
    };
  }

  /**
   * 清理测试数据
   */
  async cleanup() {
    const repositories = {
      orderRefund: this.dataSource.getRepository(OrderRefundMt),
      orderGoods: this.dataSource.getRepository(OrderGoodsMt),
      order: this.dataSource.getRepository(OrderMt),
      goods: this.dataSource.getRepository(GoodsMt),
      deliveryAddress: this.dataSource.getRepository(DeliveryAddressMt),
      supplier: this.dataSource.getRepository(SupplierMt),
      merchant: this.dataSource.getRepository(MerchantMt),
      user: this.dataSource.getRepository(UserEntityMt),
      area: this.dataSource.getRepository(AreaEntityMt)
    };

    // 按依赖关系顺序删除数据
    await repositories.orderRefund.delete({});
    await repositories.orderGoods.delete({});
    await repositories.order.delete({});
    await repositories.goods.delete({});
    await repositories.deliveryAddress.delete({});
    await repositories.supplier.delete({});
    await repositories.merchant.delete({});
    await repositories.user.delete({});
    await repositories.area.delete({});
  }
}