import dayjs from "dayjs";
import { DecimalUtils } from "@/utils/classes/calculators/core/DecimalUtils";
import { OrderCalculator } from "@/utils";

// 添加一个辅助函数用于分组
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[]>,
  );
};

/**
 * 将orderShip转换为示例数据格式
 * @param orderVO 采购订单对象
 * @returns 示例数据格式
 */
export const convertOrderShipVOToExamplesFormat = (
  orderVO: BusinessAPI.OrderVO,
) => {
  const calculator = new OrderCalculator(orderVO);

  const orderShip = orderVO.orderShipList[0]!;

  // 转换包装信息，根据 boxSpecId 分组
  const allPackages: BusinessAPI.OrderPackage[] = [];
  orderVO.orderSupplierList?.forEach((supplier) => {
    if (supplier.orderPackageList) {
      allPackages.push(
        ...supplier.orderPackageList.filter((pkg) => pkg.boxType === "USED"),
      );
    }
  });

  const packagesBySpec = groupBy(
    allPackages,
    (pkg) => pkg.boxSpecName + pkg.boxProductName,
  );

  const orderShipPackageList = Object.entries(packagesBySpec).map(
    ([specId, packages]) => {
      // 计算该规格下的总数量、总重量等
      const totalQuantity = packages.reduce(
        (sum, pkg) => DecimalUtils.add(sum, pkg.boxCount || 0),
        0,
      );

      const totalWeight = packages.reduce(
        (sum, pkg) =>
          DecimalUtils.toDecimalPlaces(
            DecimalUtils.add(
              sum,
              DecimalUtils.multiply(
                pkg.boxCount || 0,
                pkg.boxProductWeight || 0,
              ),
            ),
          ),
        0,
      );

      // 获取第一条记录的价格信息（假设同一规格价格一致）
      const firstPackage = packages[0];

      const totalPrice = DecimalUtils.toDecimalPlaces(
        DecimalUtils.multiply(totalQuantity, firstPackage.boxSalePrice || 0),
      );

      return {
        boxSpecId: specId,
        boxSpecName: firstPackage.boxSpecName,
        boxProduct: firstPackage.boxProductName,
        quantity: totalQuantity,
        unitPrice: firstPackage.boxSalePrice,
        itemAmount: totalPrice,
        singleWeight: firstPackage.boxProductWeight,
        totalWeight: totalWeight,
        boxBrandImage: firstPackage.boxBrandImage,
      };
    },
  );
  return {
    title: {
      title: "西瓜发货清单",
    },
    dealerInfo: {
      dealerName: orderVO.orderDealer?.shortName || "",
      vehicleNumber: `第 ${orderVO.orderVehicle?.vehicleNo || ""} 车`,
      destination: orderShip.shippingAddress || "",
      watermelonGrade: orderShip.watermelonGrade || "",
    },
    shippingInfo: {
      shippingFrom: orderShip.shippingAddress || "",
      date: orderShip.shippingDate || "",
    },
    weightInfo: {
      data: orderShip.orderShipItemList,
      accountCompany: orderShip.companyName || "",
      sumAmount:
        orderShip.orderShipItemList?.reduce(
          (acc, item) => DecimalUtils.add(acc, item?.totalAmount!),
          0,
        ) || "",
    },
    packingSpec: {
      data:
        orderShipPackageList?.map((item) => ({
          boxSpecId: item.boxSpecId || "",
          boxSpecName: item.boxSpecName || "",
          boxType: item.boxProduct || "",
          quantity: item.quantity?.toString() || "",
          unitPrice: item.unitPrice?.toString() || "",
          amount: item.itemAmount?.toString() || "",
          unitWeight: item.singleWeight?.toString() || "",
          weight: item.totalWeight?.toString() || "",
        })) || [],
    },
    vehicleInfo: {
      driverPhone: orderVO.orderVehicle?.phone || "",
      licensePlate: orderVO.orderVehicle.plate || "",
      estimatedArrivalTime: orderShip.estimatedArrivalDate
        ? dayjs(orderShip?.estimatedArrivalDate).format("YYYY年MM月DD日")
        : "",
      freightDebt: orderVO.orderVehicle.price?.toString() || "",
      strawMatDebt: orderVO.orderVehicle.strawCurtainPrice?.toString() || "",
      remarks: orderShip.remark || "",
    },
    otherFees: {},
    totalAmount: {
      amount: calculator.getMarketPrice(),
      farmer:
        orderShip.farmerInfo ||
        orderVO.orderSupplierList
          .map((item) => {
            return item.name;
          })
          .join("、"),
    },
    otherInfo: {
      data: orderShip.orderShipItemList,
      driverPhone: orderVO.orderVehicle?.phone || "",
      licensePlate: orderVO.orderVehicle.plate || "",
      accountCompany: orderShip.companyName || "",
      vehicleNumber: `第 ${orderVO.orderVehicle.vehicleNo || ""} 车`,
      destination: orderShip.receivingAddress || "",
      shippingFrom: orderShip.shippingAddress || "",
      estimatedArrivalTime: orderShip.estimatedArrivalDate
        ? dayjs(orderShip?.estimatedArrivalDate).format("YYYY年MM月DD日")
        : "1",
    },
  };
};
