// 将OrderVO转换为OrderShipVO
import { generateShortId, OrderCalculator } from "@/utils";
import { DecimalUtils } from "@/utils/classes/calculators/core/DecimalUtils";

/**
 * 将OrderVO转换为OrderShipVO
 * @param orderVO 采购订单对象
 * @returns 发货单对象
 */
export const convertOrderToOrderShip = (
  orderVO: BusinessAPI.OrderVO,
): BusinessAPI.OrderShip => {
  const oldOrderShip = orderVO.orderShipList[0];

  // 添加一个辅助函数用于分组
  const groupBy = <T>(
    array: T[],
    keyFn: (item: T) => string,
  ): Record<string, T[]> => {
    return array.reduce(
      (groups, item) => {
        const key = keyFn(item);
        if (!groups[key]) {
          groups[key] = [];
        }
        groups[key].push(item);
        return groups;
      },
      {} as Record<string, T[]>,
    );
  };

  // 转换供应商列表为发货单项列表，根据 purchasePrice 分组
  const suppliersByPrice = groupBy(
    orderVO.orderSupplierList || [],
    (supplier) => String(supplier.salePrice || "0"),
  );

  const orderShipId = oldOrderShip?.orderShipId || generateShortId();

  const orderShipItemList: BusinessAPI.OrderShipItem[] = Object.entries(
    suppliersByPrice,
  ).map(([price, suppliers]) => {
    // 计算该价格下的总毛重、总净重等
    const totalGrossWeight = DecimalUtils.toDecimalPlaces(
      suppliers.reduce(
        (sum, supplier) => DecimalUtils.add(sum, supplier.grossWeight || 0),
        0,
      ),
    );

    const totalNetWeight = DecimalUtils.toDecimalPlaces(
      suppliers.reduce(
        (sum, supplier) => DecimalUtils.add(sum, supplier.netWeight || 0),
        0,
      ),
    );

    const totalAmount = DecimalUtils.toDecimalPlaces(
      suppliers.reduce((sum, supplier) => {
        const amount = DecimalUtils.multiply(
          orderVO.pricingMethod === "BY_GROSS_WEIGHT"
            ? supplier.grossWeight
            : supplier.netWeight,
          supplier.salePrice || 0,
        );
        return DecimalUtils.add(sum, amount || 0);
      }, 0),
    );

    const totalBoxCount = DecimalUtils.toDecimalPlaces(
      suppliers.reduce(
        (sum, supplier) =>
          DecimalUtils.add(
            sum,
            supplier.orderPackageList?.reduce(
              (sum, item) => DecimalUtils.add(sum, item.boxCount || 0),
              0,
            ) || 0,
          ),
        0,
      ),
    );

    const oldOrderShipItem = oldOrderShip?.orderShipItemList?.find(
      (item) => item.unitPrice == parseFloat(price),
    );

    return {
      orderShipItemId: oldOrderShipItem?.orderShipItemId || generateShortId(),
      orderShipId: orderShipId, // 将在创建发货单时填充
      orderId: orderVO.orderId,
      boxCount: totalBoxCount,
      grossWeight: totalGrossWeight,
      boxWeight: totalGrossWeight - totalNetWeight,
      netWeight: totalNetWeight,
      unitPrice: price ? parseFloat(price) : 0,
      totalAmount: totalAmount,
      watermelonGrade: oldOrderShipItem?.watermelonGrade || "", // 需要手动填写
    };
  });

  const calculator = new OrderCalculator(orderVO);
  // 构建orderShip对象，不转换费用信息
  return {
    orderShipId: orderShipId,
    orderId: orderVO.orderId,
    orderSn: oldOrderShip?.orderSn,
    watermelonGrade: oldOrderShip?.watermelonGrade || "",
    dealerId: orderVO.orderVehicle?.dealerId!,
    dealerName: orderVO.orderVehicle?.dealerName!,
    companyId: orderVO.orderCompany?.companyId,
    companyName: orderVO.orderCompany?.fullName,
    shippingAddress:
      oldOrderShip?.shippingAddress || orderVO.orderVehicle?.origin,
    receivingAddress: orderVO.orderVehicle?.destination,
    shippingDate: orderVO.orderVehicle?.deliveryTime,
    estimatedArrivalDate: oldOrderShip?.estimatedArrivalDate || "",
    pdfUrl: oldOrderShip?.pdfUrl || "",
    picUrl: oldOrderShip?.picUrl || "",
    state: "WAIT_PAYMENT",
    receivableAmount: calculator.getMarketPrice(),
    orderShipItemList,
    remark: oldOrderShip?.remark || "",
  };
};
