import { DecimalUtils } from "../core/DecimalUtils";

/**
 * 包装计算模块
 * 负责纸箱、包装相关的计算
 */
export class PackagingCalculator {
  constructor(private order: BusinessAPI.OrderVO) {}

  /**
   * 计算纸箱售卖费
   * 所有使用中的旧纸箱数量 × 售卖价格之和
   */
  calculateBoxSaleAmount(): number {
    return this.order.orderSupplierList.reduce((total, supplier) => {
      const supplierBoxSale = this.calculateSupplierBoxSale(supplier);
      return DecimalUtils.add(total, supplierBoxSale);
    }, 0);
  }

  /**
   * 计算总纸箱数量
   */
  calculateTotalBoxCount(): number {
    return this.order.orderSupplierList.reduce((total, supplier) => {
      const supplierBoxCount = this.calculateSupplierBoxCount(supplier);
      return DecimalUtils.add(total, supplierBoxCount);
    }, 0);
  }

  /**
   * 计算总箱重
   * 所有使用中的纸箱 × 单箱产品重量之和
   */
  calculateTotalBoxWeight(): number {
    return this.order.orderSupplierList.reduce((total, supplier) => {
      const supplierBoxWeight = this.calculateSupplierBoxWeight(supplier);
      return DecimalUtils.add(total, supplierBoxWeight);
    }, 0);
  }

  /**
   * 计算运费
   */
  calculateDeliveryFee(): number {
    return this.order.orderVehicle?.price || 0;
  }

  /**
   * 计算单个供应商的纸箱售卖费
   */
  private calculateSupplierBoxSale(
    supplier: BusinessAPI.OrderSupplier,
  ): number {
    if (!supplier.orderPackageList?.length) {
      return 0;
    }

    return supplier.orderPackageList
      .filter((pkg) => pkg.boxType === "USED")
      .reduce((total, pkg) => {
        const saleAmount = DecimalUtils.multiply(
          pkg.boxCount || 0,
          pkg.boxSalePrice || 0,
        );
        return DecimalUtils.add(total, saleAmount);
      }, 0);
  }

  /**
   * 计算单个供应商的纸箱数量
   */
  private calculateSupplierBoxCount(
    supplier: BusinessAPI.OrderSupplier,
  ): number {
    if (!supplier.orderPackageList?.length) {
      return 0;
    }

    return supplier.orderPackageList
      .filter((pkg) => pkg.boxType === "USED")
      .reduce((total, pkg) => {
        return DecimalUtils.add(total, pkg.boxCount || 0);
      }, 0);
  }

  /**
   * 计算单个供应商的纸箱重量
   */
  private calculateSupplierBoxWeight(
    supplier: BusinessAPI.OrderSupplier,
  ): number {
    if (!supplier.orderPackageList?.length) {
      return 0;
    }

    return supplier.orderPackageList
      .filter((pkg) => pkg.boxType === "USED")
      .reduce((total, pkg) => {
        const boxWeight = DecimalUtils.multiply(
          pkg.boxProductWeight || 0,
          pkg.boxCount || 0,
        );
        return DecimalUtils.add(total, boxWeight);
      }, 0);
  }
}
