import { DataSource } from 'typeorm';
import { UserEntity } from '@d8d/user-module';
import { AreaEntity } from '@d8d/geo-areas';
import { DeliveryAddress } from '@d8d/delivery-address-module';
import { Merchant } from '@d8d/merchant-module';
import { Supplier } from '@d8d/supplier-module';
import { Order, OrderRefund } from '../../src/entities';
import { JWTUtil } from '@d8d/shared-utils';

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

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

  /**
   * 为测试用户生成JWT token
   */
  static generateUserToken(user: UserEntity): string {
    return JWTUtil.generateToken({
      id: user.id,
      username: user.username,
      roles: [{ name: 'user' }]
    });
  }

  /**
   * 创建测试地区数据
   */
  static createAreaData(overrides: Partial<AreaEntity> = {}): Partial<AreaEntity> {
    const timestamp = Math.floor(Math.random() * 100000);
    return {
      name: '广东省',
      level: 1,
      code: `44${timestamp.toString().padStart(4, '0')}`,
      state: 1,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试地区
   */
  static async createTestArea(dataSource: DataSource, overrides: Partial<AreaEntity> = {}): Promise<AreaEntity> {
    const areaData = this.createAreaData(overrides);
    const areaRepository = dataSource.getRepository(AreaEntity);
    const area = areaRepository.create(areaData);
    return await areaRepository.save(area);
  }

  /**
   * 创建完整的地区层级（省、市、区、街道）
   */
  static async createCompleteAreaHierarchy(dataSource: DataSource): Promise<{
    province: AreaEntity;
    city: AreaEntity;
    district: AreaEntity;
    town: AreaEntity;
  }> {
    const timestamp = Math.floor(Math.random() * 100000);

    const province = await this.createTestArea(dataSource, {
      name: '广东省',
      level: 1,
      code: `44${timestamp.toString().padStart(4, '0')}`
    });

    const city = await this.createTestArea(dataSource, {
      name: '深圳市',
      level: 2,
      code: `44${(timestamp + 1).toString().padStart(4, '0')}`,
      parentId: province.id
    });

    const district = await this.createTestArea(dataSource, {
      name: '南山区',
      level: 3,
      code: `44${(timestamp + 2).toString().padStart(4, '0')}`,
      parentId: city.id
    });

    const town = await this.createTestArea(dataSource, {
      name: '粤海街道',
      level: 4,
      code: `44${(timestamp + 3).toString().padStart(4, '0')}`,
      parentId: district.id
    });

    return { province, city, district, town };
  }

  /**
   * 创建测试配送地址数据
   */
  static createDeliveryAddressData(
    userId: number,
    areaHierarchy: { province: AreaEntity; city: AreaEntity; district: AreaEntity; town: AreaEntity },
    overrides: Partial<DeliveryAddress> = {}
  ): Partial<DeliveryAddress> {
    return {
      userId,
      name: '收货人姓名',
      phone: '13800138000',
      receiverProvince: areaHierarchy.province.id,
      receiverCity: areaHierarchy.city.id,
      receiverDistrict: areaHierarchy.district.id,
      receiverTown: areaHierarchy.town.id,
      address: '测试地址',
      isDefault: 1,
      state: 1,
      createdBy: userId,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试配送地址
   */
  static async createTestDeliveryAddress(
    dataSource: DataSource,
    userId: number,
    areaHierarchy: { province: AreaEntity; city: AreaEntity; district: AreaEntity; town: AreaEntity },
    overrides: Partial<DeliveryAddress> = {}
  ): Promise<DeliveryAddress> {
    const addressData = this.createDeliveryAddressData(userId, areaHierarchy, overrides);
    const addressRepository = dataSource.getRepository(DeliveryAddress);
    const address = addressRepository.create(addressData);
    return await addressRepository.save(address);
  }

  /**
   * 创建测试商户数据
   */
  static createMerchantData(overrides: Partial<Merchant> = {}): Partial<Merchant> {
    const timestamp = Math.floor(Math.random() * 100000);
    return {
      name: '测试商户',
      username: `merchant_${timestamp}`,
      password: 'test_password',
      state: 1,
      createdBy: 1,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试商户
   */
  static async createTestMerchant(dataSource: DataSource, overrides: Partial<Merchant> = {}): Promise<Merchant> {
    const merchantData = this.createMerchantData(overrides);
    const merchantRepository = dataSource.getRepository(Merchant);
    const merchant = merchantRepository.create(merchantData);
    return await merchantRepository.save(merchant);
  }

  /**
   * 创建测试供应商数据
   */
  static createSupplierData(overrides: Partial<Supplier> = {}): Partial<Supplier> {
    const timestamp = Math.floor(Math.random() * 100000);
    return {
      name: '测试供应商',
      username: `supplier_${timestamp}`,
      password: 'test_password',
      state: 1,
      createdBy: 1,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试供应商
   */
  static async createTestSupplier(dataSource: DataSource, overrides: Partial<Supplier> = {}): Promise<Supplier> {
    const supplierData = this.createSupplierData(overrides);
    const supplierRepository = dataSource.getRepository(Supplier);
    const supplier = supplierRepository.create(supplierData);
    return await supplierRepository.save(supplier);
  }

  /**
   * 创建测试订单数据
   */
  static createOrderData(
    userId: number,
    deliveryAddressId: number,
    merchantId: number,
    supplierId: number,
    areaHierarchy: { province: AreaEntity; city: AreaEntity; district: AreaEntity; town: AreaEntity },
    overrides: Partial<Order> = {}
  ): Partial<Order> {
    const timestamp = Math.floor(Math.random() * 100000);
    return {
      orderNo: `ORDER_${timestamp}`,
      userId,
      amount: 100.00,
      costAmount: 80.00,
      payAmount: 100.00,
      orderType: 1,
      payType: 1,
      payState: 2,
      state: 0,
      deliveryAddressId,
      addressId: deliveryAddressId,
      merchantId,
      supplierId,
      recevierProvince: areaHierarchy.province.id,
      recevierCity: areaHierarchy.city.id,
      recevierDistrict: areaHierarchy.district.id,
      recevierTown: areaHierarchy.town.id,
      createdBy: userId,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试订单
   */
  static async createTestOrder(
    dataSource: DataSource,
    userId: number,
    deliveryAddressId: number,
    merchantId: number,
    supplierId: number,
    areaHierarchy: { province: AreaEntity; city: AreaEntity; district: AreaEntity; town: AreaEntity },
    overrides: Partial<Order> = {}
  ): Promise<Order> {
    const orderData = this.createOrderData(userId, deliveryAddressId, merchantId, supplierId, areaHierarchy, overrides);
    const orderRepository = dataSource.getRepository(Order);
    const order = orderRepository.create(orderData);
    return await orderRepository.save(order);
  }

  /**
   * 创建完整的测试订单环境（包含所有依赖实体）
   */
  static async createCompleteOrderEnvironment(dataSource: DataSource, userId?: number): Promise<{
    user: UserEntity;
    areaHierarchy: { province: AreaEntity; city: AreaEntity; district: AreaEntity; town: AreaEntity };
    deliveryAddress: DeliveryAddress;
    merchant: Merchant;
    supplier: Supplier;
    order: Order;
  }> {
    // 创建用户
    const user = await this.createTestUser(dataSource, userId ? { id: userId } : {});

    // 创建地区层级
    const areaHierarchy = await this.createCompleteAreaHierarchy(dataSource);

    // 创建商户和供应商
    const merchant = await this.createTestMerchant(dataSource, { createdBy: user.id });
    const supplier = await this.createTestSupplier(dataSource, { createdBy: user.id });

    // 创建配送地址
    const deliveryAddress = await this.createTestDeliveryAddress(dataSource, user.id, areaHierarchy);

    // 创建订单
    const order = await this.createTestOrder(dataSource, user.id, deliveryAddress.id, merchant.id, supplier.id, areaHierarchy);

    return { user, areaHierarchy, deliveryAddress, merchant, supplier, order };
  }

  /**
   * 创建测试退款数据
   */
  static createRefundData(orderNo: string, overrides: Partial<OrderRefund> = {}): Partial<OrderRefund> {
    const timestamp = Math.floor(Math.random() * 100000);
    return {
      orderNo,
      refundOrderNo: `REFUND_${timestamp}`,
      refundAmount: 50.00,
      state: 0,
      createdBy: 1,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试退款
   */
  static async createTestRefund(
    dataSource: DataSource,
    orderNo: string,
    overrides: Partial<OrderRefund> = {}
  ): Promise<OrderRefund> {
    const refundData = this.createRefundData(orderNo, overrides);
    const refundRepository = dataSource.getRepository(OrderRefund);
    const refund = refundRepository.create(refundData);
    return await refundRepository.save(refund);
  }
}