import { View } from "@tarojs/components";
import { useEffect, useState } from "react";
import { Table, TableColumnProps } from "@nutui/nutui-react-taro";
import { formatCurrency, OrderCalculator } from "@/utils";
import { Icon } from "@/components";
import { Decimal } from "decimal.js";
import { previewImage } from "@tarojs/taro";

interface IPurchasePreviewProps {
  orderVO: BusinessAPI.OrderVO;
}

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

export default function MadePreview(props: IPurchasePreviewProps) {
  const { orderVO } = props;
  const [orderSupplierList, setOrderSupplierList] = useState<
    BusinessAPI.OrderSupplier[]
  >([]);
  const [expandedBrands, setExpandedBrands] = useState<Record<string, boolean>>(
    {},
  );
  const [expandedCalculation, setExpandedCalculation] = useState<
    Record<string, boolean>
  >({});
  const [expandedEmptyBoxBrands, setExpandedEmptyBoxBrands] = useState<
    Record<string, boolean>
  >({});
  const [expandedFarmerInfo, setExpandedFarmerInfo] = useState<
    Record<string, boolean>
  >({});

  const calculator = new OrderCalculator(orderVO as any);

  // 切换品牌展开/收起状态
  const toggleBrand = (brandName: string) => {
    setExpandedBrands((prev) => ({
      ...prev,
      [brandName]: !prev[brandName],
    }));
  };

  // 切换计算明细展开/收起状态
  const toggleCalculation = (supplierId: string) => {
    setExpandedCalculation((prev) => ({
      ...prev,
      [supplierId]: !prev[supplierId],
    }));
  };

  // 切换空箱品牌展开/收起状态
  const toggleEmptyBoxBrand = (brandName: string) => {
    setExpandedEmptyBoxBrands((prev) => ({
      ...prev,
      [brandName]: !prev[brandName],
    }));
  };

  // 切换瓜农信息展开/收起状态
  const toggleFarmerInfo = (supplierId: string) => {
    setExpandedFarmerInfo((prev) => ({
      ...prev,
      [supplierId]: !prev[supplierId],
    }));
  };

  // 查看图片
  const handlePreviewImage = (imageUrl: string) => {
    if (!imageUrl) return;
    previewImage({
      current: imageUrl,
      urls: [imageUrl],
    });
  };

  // 查看合同
  const handlePreviewContract = (supplier: BusinessAPI.OrderSupplier) => {
    if (!supplier.contractImg || supplier.contractImg.length === 0) return;

    const images = supplier.contractImg.map((img) => img?.filePath || "");
    previewImage({
      current: images[0],
      urls: images,
    });
  };

  useEffect(() => {
    if (orderVO.orderSupplierList) {
      setOrderSupplierList(orderVO.orderSupplierList as any);
    }
  }, [orderVO]);

  // 判断是否是拼车中（所有供应商的 isLast 都是 false）
  const isCarpooling =
    orderSupplierList.length > 0 &&
    orderSupplierList.every((supplier) => !supplier.isLast);

  const [columns] = useState<Array<TableColumnProps>>([
    {
      title: "规格",
      key: "boxSpecName",
      fixed: "left",
    },
    {
      title: "型号",
      key: "boxProductName",
    },
    {
      title: "数量（箱）",
      key: "boxCount",
    },
    {
      title: "重量（斤）",
      key: "boxProductWeight",
      render: (record: any) => {
        return new Decimal(record.boxProductWeight)
          .mul(new Decimal(record.boxCount))
          .toDecimalPlaces(0, Decimal.ROUND_HALF_UP)
          .toNumber();
      },
    },
  ]);

  return (
    <View className="flex flex-1 flex-col gap-2.5 p-2.5">
      {isCarpooling && (
        <View className="mt-2 flex items-center justify-center gap-1 rounded-full bg-orange-100 px-3 py-1">
          <Icon
            name={"truck"}
            size={14}
            color="var(--color-warning, #f59e0b)"
          />
          <View className="text-xs font-semibold text-orange-700">拼车中</View>
        </View>
      )}
      {orderVO.state === "DRAFT" && (
        <View className="rounded-lg bg-gradient-to-r from-blue-50 to-blue-100 p-4 text-center">
          <View className="mb-1 flex items-center justify-center">
            <Icon
              name="circle-info"
              size={20}
              color="var(--color-primary)"
              className="mr-2"
            />
            <View className="text-lg font-bold text-gray-800">信息确认</View>
          </View>
          <View className="text-xs text-gray-600">
            请仔细核对以下信息，确认无误后提交
          </View>
        </View>
      )}
      <View className="text-sm font-bold">车辆信息</View>
      <View className="flex flex-col gap-2.5 rounded-lg bg-white p-2.5 shadow-sm">
        <View className="flex items-center justify-between border-b border-gray-200 pb-2">
          <View className="text-lg font-semibold">
            经销商：{orderVO.orderVehicle.dealerName}
          </View>
        </View>
        <View className="grid grid-cols-2 gap-2.5">
          <View className="flex flex-col gap-1">
            <View className="text-sm font-normal text-gray-700">发货地</View>
            <View className="text-sm font-bold">
              {orderVO.orderVehicle?.origin || "未填写"}
            </View>
          </View>
          <View className="flex flex-col gap-1">
            <View className="text-sm font-normal text-gray-700">收货地</View>
            <View className="text-sm font-bold">
              {orderVO.orderVehicle?.destination || "未填写"}
            </View>
          </View>
          <View className="flex flex-col gap-1">
            <View className="text-sm font-normal text-gray-700">发货日期</View>
            <View className="text-sm font-bold">
              {orderVO.orderVehicle?.deliveryTime || "未填写"}
            </View>
          </View>
          <View className="flex flex-col gap-1">
            <View className="text-sm font-normal text-gray-700">车牌号</View>
            <View className="text-sm font-bold">
              {orderVO.orderVehicle?.plate || "未填写"}
            </View>
          </View>
          <View className="flex flex-col gap-1">
            <View className="text-sm font-normal text-gray-700">司机电话</View>
            <View className="text-sm font-bold">
              {orderVO.orderVehicle?.phone || "未填写"}
            </View>
          </View>
          <View className="flex flex-col gap-1">
            <View className="text-sm font-normal text-gray-700">运输费</View>
            <View className="text-sm font-bold">
              {orderVO.orderVehicle?.price
                ? `${orderVO.orderVehicle.price} 元`
                : "未填写"}
            </View>
          </View>
          <View className="flex flex-col gap-1">
            <View className="text-sm font-normal text-gray-700">毛重</View>
            <View className="text-sm font-bold">
              {formatCurrency(calculator.getTotalGrossWeight())} 斤
            </View>
          </View>
          <View className="flex flex-col gap-1">
            <View className="text-sm font-normal text-gray-700">净重</View>
            <View className="text-sm font-bold">
              {formatCurrency(calculator.getTotalNetWeight())} 斤
            </View>
          </View>
          <View className="flex flex-col gap-1">
            <View className="text-sm font-normal text-gray-700">箱重</View>
            <View className="text-sm font-bold">
              {formatCurrency(calculator.getBoxWeight())} 斤
            </View>
          </View>
        </View>
      </View>
      <View className="text-sm font-bold">瓜农明细</View>
      <View className="flex flex-col gap-2.5">
        {orderSupplierList.map((supplier, index) => {
          const calculator = new OrderCalculator(orderVO).getSupplierCalculator(
            supplier,
          );

          return (
            <View
              className="flex flex-col gap-2.5 rounded-lg bg-white p-2.5 shadow-sm"
              key={supplier.orderSupplierId}
            >
              {/* 瓜农基本信息 */}
              <View className="flex items-center justify-between border-b border-gray-200 pb-2">
                <View className="flex flex-1 flex-col gap-1">
                  <View className="flex items-center gap-2">
                    <View className="text-lg font-semibold">
                      瓜农{index + 1}：{supplier.name}
                    </View>
                    {supplier.contractUpload ? (
                      <View
                        className="flex cursor-pointer items-center gap-1 rounded-full bg-green-100 px-2 py-0.5"
                        onClick={() => handlePreviewContract(supplier)}
                      >
                        <Icon
                          name="check"
                          size={12}
                          color="var(--color-success, #10b981)"
                        />
                        <View className="text-xs font-medium text-green-700">
                          已传合同
                        </View>
                        <Icon
                          name="eye"
                          size={10}
                          color="var(--color-success, #10b981)"
                          className="ml-0.5"
                        />
                      </View>
                    ) : (
                      <View className="flex items-center gap-1 rounded-full bg-red-100 px-2 py-0.5">
                        <Icon
                          name="file-pdf"
                          size={12}
                          color="var(--color-danger, #ef4444)"
                        />
                        <View className="text-xs font-medium text-red-700">
                          未传合同
                        </View>
                      </View>
                    )}
                  </View>
                  {supplier.productName && (
                    <View className="text-sm text-gray-600">
                      西瓜品种：{supplier.productName}
                    </View>
                  )}
                </View>
                <View className="rounded bg-gray-100 px-2 py-1 text-xs font-medium">
                  {supplier.isLast ? "最后一个瓜农" : "不是最后一个"}
                </View>
              </View>

              {/* 瓜农联系信息 */}
              <View
                className="flex items-center justify-between"
                onClick={() => toggleFarmerInfo(supplier.orderSupplierId || "")}
              >
                <View className="text-neutral-darker text-sm">基础信息</View>
                <View className="flex items-center gap-2">
                  <Icon
                    name={
                      !expandedFarmerInfo[supplier.orderSupplierId || ""]
                        ? "chevron-up"
                        : "chevron-down"
                    }
                    size={16}
                    color="var(--color-primary)"
                  />
                </View>
              </View>

              {/* 瓜农信息详情 */}
              {!expandedFarmerInfo[supplier.orderSupplierId || ""] && (
                <View className="rounded-lg border border-gray-200 bg-gray-50 p-3">
                  <View className="mb-2 flex items-center">
                    <Icon name="user" className="mr-2 leading-4" size={20} />
                    <View className="text-sm font-medium text-gray-700">
                      瓜农信息
                    </View>
                  </View>
                  <View className="space-y-2">
                    {supplier.phone && (
                      <View className="flex items-center justify-between text-sm">
                        <View className="text-gray-600">手机号码</View>
                        <View className="font-medium text-gray-900">
                          {supplier.phone}
                        </View>
                      </View>
                    )}
                    {supplier.idCard && (
                      <View className="flex items-center justify-between text-sm">
                        <View className="text-gray-600">身份证号</View>
                        <View className="font-medium text-gray-900">
                          {supplier.idCard}
                        </View>
                      </View>
                    )}
                    {supplier.bankName && (
                      <View className="flex items-center justify-between text-sm">
                        <View className="text-gray-600">银行名称</View>
                        <View className="font-medium text-gray-900">
                          {supplier.bankName}
                        </View>
                      </View>
                    )}
                    {supplier.bankCard && (
                      <View className="flex items-center justify-between text-sm">
                        <View className="text-gray-600">银行卡号</View>
                        <View className="font-medium text-gray-900">
                          {supplier.bankCard}
                        </View>
                      </View>
                    )}
                    {supplier.payeeName && (
                      <View className="flex items-center justify-between text-sm">
                        <View className="text-gray-600">收款人姓名</View>
                        <View className="font-medium text-gray-900">
                          {supplier.payeeName}
                        </View>
                      </View>
                    )}
                    {supplier.wechatQr && (
                      <View className="flex items-center justify-between text-sm">
                        <View className="text-gray-600">个人收款码</View>
                        <View
                          className="flex cursor-pointer items-center gap-1 rounded bg-blue-50 px-3 py-1.5"
                          onClick={() => handlePreviewImage(supplier.wechatQr!)}
                        >
                          <Icon
                            name="eye"
                            size={14}
                            color="var(--color-primary)"
                          />
                          <View className="text-primary text-xs font-medium">
                            查看收款码
                          </View>
                        </View>
                      </View>
                    )}
                  </View>
                </View>
              )}

              <View className="flex flex-col gap-2">
                <View
                  className="flex items-center justify-between"
                  onClick={() =>
                    toggleCalculation(supplier.orderSupplierId || "")
                  }
                >
                  <View className="text-neutral-darker text-sm">合计金额</View>
                  <View className="flex items-center gap-2">
                    <View className="text-sm font-semibold text-gray-900">
                      {supplier.invoiceAmount} 元{" "}
                      {supplier.isDepositPaid
                        ? `（含定金：${calculator.getDepositPaidAmount()}元）`
                        : ""}
                    </View>
                    <Icon
                      name={
                        !expandedCalculation[supplier.orderSupplierId || ""]
                          ? "chevron-up"
                          : "chevron-down"
                      }
                      size={16}
                      color="var(--color-primary)"
                    />
                  </View>
                </View>
              </View>

              {/* 计算公式区域 */}
              {!expandedCalculation[supplier.orderSupplierId || ""] && (
                <View className="rounded-lg border border-gray-200 bg-gray-50 p-3">
                  <View className="mb-2 flex items-center">
                    <Icon
                      name="calculator"
                      className="mr-2 leading-4"
                      size={20}
                    />
                    <View className="text-sm font-medium text-gray-700">
                      计算明细
                    </View>
                  </View>
                  <View className="space-y-1">
                    <View className="flex justify-between text-sm">
                      <View className="text-neutral-darker text-sm">
                        总磅重量（kg）
                      </View>
                      <View className="flex items-center gap-2">
                        <View className="font-medium text-gray-800">
                          {supplier.totalWeight || 0}
                        </View>
                        {supplier.totalWeightImg && (
                          <Icon
                            name="eye"
                            size={16}
                            color="var(--color-primary)"
                            onClick={() =>
                              handlePreviewImage(supplier.totalWeightImg!)
                            }
                            className="cursor-pointer"
                          />
                        )}
                      </View>
                    </View>
                    <View className="flex justify-between text-sm">
                      <View className="text-neutral-darker text-sm">
                        空磅重量（kg）
                      </View>
                      <View className="flex items-center gap-2">
                        <View className="font-medium text-gray-800">
                          {supplier.emptyWeight || 0}
                        </View>
                        {supplier.emptyWeightImg && (
                          <Icon
                            name="eye"
                            size={16}
                            color="var(--color-primary)"
                            onClick={() =>
                              handlePreviewImage(supplier.emptyWeightImg!)
                            }
                            className="cursor-pointer"
                          />
                        )}
                      </View>
                    </View>
                    <View className="flex justify-between text-sm">
                      <View className="text-neutral-darker text-sm">
                        箱重量（斤）
                      </View>
                      <View className="font-medium text-gray-800">
                        {calculator.calculateBoxesTotalWeight("USED") || 0}
                      </View>
                    </View>
                    <View className="flex justify-between text-sm">
                      <View className="text-neutral-darker text-sm">
                        净重量（斤）
                      </View>
                      <View className="font-medium text-gray-800">
                        {supplier.netWeight || 0}
                      </View>
                    </View>
                    <View className="flex justify-between text-sm">
                      <View className="text-neutral-darker text-sm">
                        毛重量（斤）
                      </View>
                      <View className="font-medium text-gray-800">
                        {supplier.grossWeight || 0}
                      </View>
                    </View>
                    <View className="flex justify-between text-sm">
                      <View className="text-neutral-darker text-sm">
                        采购单价（元/斤）
                      </View>
                      <View className="font-medium text-gray-800">
                        {supplier.purchasePrice || 0}
                      </View>
                    </View>
                    <View className="flex justify-between text-sm">
                      <View className="text-neutral-darker text-sm">
                        报价方式
                      </View>
                      <View className="font-medium text-gray-800">
                        {supplier.pricingMethod === "BY_GROSS_WEIGHT"
                          ? "毛重"
                          : "净重"}
                      </View>
                    </View>
                    <View className="my-2 h-px bg-gray-300"></View>
                    <View className="text-neutral-darker text-center text-xs">
                      计算公式：
                      {supplier.pricingMethod === "BY_GROSS_WEIGHT"
                        ? "毛重"
                        : "净重"}
                      量 × 采购单价
                    </View>
                  </View>
                </View>
              )}

              {/* 根据boxBrandName对packageInfoList进行分组显示 */}
              {(() => {
                const groupedPackageInfo = groupBy(
                  supplier.orderPackageList?.filter(
                    (item) => item.boxType === "USED",
                  ) || [],
                  (item) => item?.boxBrandName || "",
                );

                return Object.entries(groupedPackageInfo).map(
                  ([brandName, packageInfos]) => {
                    // 计算该品牌的统计数据
                    const brandBoxCount = packageInfos.reduce(
                      (sum, item) => sum + (item.boxCount || 0),
                      0,
                    );
                    const brandBoxWeight = packageInfos.reduce(
                      (sum, item) =>
                        sum +
                        new Decimal(item.boxProductWeight || 0)
                          .mul(new Decimal(item.boxCount || 0))
                          .toDecimalPlaces(0)
                          .toNumber(),
                      0,
                    );

                    return (
                      <View key={brandName} className="flex flex-col gap-2">
                        <View
                          className="flex items-center justify-between"
                          onClick={() => toggleBrand(brandName)}
                        >
                          <View className="flex-1">
                            <View className="text-sm font-medium text-gray-700">
                              纸箱品牌{index + 1}
                            </View>
                          </View>
                          <View className="flex items-center gap-3">
                            <View className="text-base font-semibold text-gray-900">
                              {brandName}
                            </View>
                            <Icon
                              name={
                                !expandedBrands[brandName]
                                  ? "chevron-up"
                                  : "chevron-down"
                              }
                              size={18}
                              color="var(--color-primary)"
                            />
                          </View>
                        </View>
                        {!expandedBrands[brandName] && (
                          <View className="flex flex-col gap-2">
                            <View className="overflow-x-auto">
                              <Table columns={columns} data={packageInfos} />
                            </View>
                            <View className="rounded bg-gray-50 p-2">
                              <View className="flex items-center justify-between text-sm">
                                <View className="font-medium text-gray-700">
                                  品牌小计
                                </View>
                                <View className="flex gap-4">
                                  <View className="text-gray-600">
                                    <View className="text-xs">箱数</View>
                                    <View className="font-semibold text-gray-900">
                                      {brandBoxCount} 箱
                                    </View>
                                  </View>
                                  <View className="text-gray-600">
                                    <View className="text-xs">箱重</View>
                                    <View className="font-semibold text-gray-900">
                                      {brandBoxWeight} 斤
                                    </View>
                                  </View>
                                </View>
                              </View>
                            </View>
                          </View>
                        )}
                      </View>
                    );
                  },
                );
              })()}
            </View>
          );
        })}
        <View className="text-sm font-bold">装箱统计</View>
        <View className="rounded-lg bg-white p-2.5 shadow-md">
          <View className="flex items-center justify-between text-sm font-bold">
            <View>总箱数</View>
            <View>{calculator.getBoxCount()} 箱</View>
          </View>
          <View className="mt-2 flex items-center justify-between text-sm font-bold">
            <View>总箱重</View>
            <View>{calculator.getBoxWeight()} 斤</View>
          </View>
        </View>
      </View>

      {orderVO.orderPackageList?.length > 0 && (
        <>
          <View className="text-sm font-bold">空箱使用明细</View>
          <View className="flex flex-col gap-2.5">
            <View className="flex flex-col gap-2.5 rounded-lg bg-white p-2.5 shadow-sm">
              {/* 根据boxBrandName对packageInfoList进行分组显示 */}
              {(() => {
                const groupedPackageInfo = groupBy(
                  orderVO.orderPackageList || [],
                  (item) => item?.boxBrandName || "",
                );

                return Object.entries(groupedPackageInfo).map(
                  ([brandName, packageInfos]) => {
                    // 计算该品牌的统计数据
                    const brandBoxCount = packageInfos.reduce(
                      (sum, item) => sum + (item.boxCount || 0),
                      0,
                    );
                    const brandBoxWeight = packageInfos.reduce(
                      (sum, item) =>
                        sum +
                        new Decimal(item.boxProductWeight || 0)
                          .mul(new Decimal(item.boxCount || 0))
                          .toDecimalPlaces(0)
                          .toNumber(),
                      0,
                    );

                    return (
                      <View key={brandName} className="mb-2.5">
                        <View
                          className="flex items-center justify-between"
                          onClick={() => toggleEmptyBoxBrand(brandName)}
                        >
                          <View className="flex-1">
                            <View className="text-sm font-medium text-gray-700">
                              纸箱品牌
                            </View>
                          </View>
                          <View className="flex items-center gap-3">
                            <View className="text-base font-semibold text-gray-900">
                              {brandName}
                            </View>
                            <Icon
                              name={
                                !expandedEmptyBoxBrands[brandName]
                                  ? "chevron-up"
                                  : "chevron-down"
                              }
                              size={18}
                              color="var(--color-primary)"
                            />
                          </View>
                        </View>
                        {!expandedEmptyBoxBrands[brandName] && (
                          <View className="mt-2 flex flex-col gap-2">
                            <View className="overflow-x-auto">
                              <Table columns={columns} data={packageInfos} />
                            </View>
                            <View className="rounded bg-gray-50 p-2">
                              <View className="flex items-center justify-between text-sm">
                                <View className="font-medium text-gray-700">
                                  品牌小计
                                </View>
                                <View className="flex gap-4">
                                  <View className="text-gray-600">
                                    <View className="text-xs">箱数</View>
                                    <View className="font-semibold text-gray-900">
                                      {brandBoxCount} 箱
                                    </View>
                                  </View>
                                  <View className="text-gray-600">
                                    <View className="text-xs">箱重</View>
                                    <View className="font-semibold text-gray-900">
                                      {brandBoxWeight} 斤
                                    </View>
                                  </View>
                                </View>
                              </View>
                            </View>
                          </View>
                        )}
                      </View>
                    );
                  },
                );
              })()}
            </View>
            <View className="flex flex-col gap-2.5 rounded-lg bg-white p-2.5 shadow-md">
              <View className="flex items-center justify-between text-sm font-bold">
                <View>总箱数</View>
                <View>
                  {orderVO.orderPackageList.reduce(
                    (sum, item) => sum + item.boxCount,
                    0,
                  )}
                  箱
                </View>
              </View>
              <View className="mt-2 flex items-center justify-between text-sm font-bold">
                <View>总箱重</View>
                <View>
                  {formatCurrency(
                    orderVO.orderPackageList.reduce(
                      (sum, item) =>
                        sum +
                        new Decimal(item.boxProductWeight)
                          .mul(new Decimal(item.boxCount))
                          .toNumber(),
                      0,
                    ),
                  )}{" "}
                  斤
                </View>
              </View>
            </View>
          </View>
        </>
      )}

      {orderVO.orderCostItemList?.filter(
        (orderCostItem: BusinessAPI.OrderCostItem) =>
          orderCostItem.type === "ARTIFICIAL_TYPE",
      ).length > 0 && (
        <>
          <View className="text-sm font-bold">用工信息</View>
          <View className="flex flex-col gap-2.5 rounded-lg bg-white p-2.5 shadow-sm">
            {orderVO.orderCostItemList?.some(
              (costItem: BusinessAPI.OrderCostItem) =>
                costItem.type === "ARTIFICIAL_TYPE" &&
                costItem.payerType === "US",
            ) && (
              <View className="flex items-center justify-between border-b border-gray-200 pb-2">
                <View className="text-lg font-semibold">
                  工头：{orderVO.foreman}
                </View>
              </View>
            )}
            <View className="flex flex-col gap-2.5">
              {orderVO.orderCostItemList
                ?.filter(
                  (orderCostItem: BusinessAPI.OrderCostItem) =>
                    orderCostItem.type === "ARTIFICIAL_TYPE",
                )
                .map((orderCostItem) => (
                  <View
                    className="flex items-center justify-between"
                    key={orderCostItem.orderCostItemId}
                  >
                    <View className="text-neutral-darker text-sm">
                      {orderCostItem.name}
                    </View>
                    <View className="flex flex-1 items-center justify-end gap-1">
                      <View className="text-sm font-normal text-gray-400">
                        {orderCostItem.payerType === "US"
                          ? "我方承担费用"
                          : orderCostItem.payerType === "OTHER"
                            ? "瓜农承担费用"
                            : "未指定"}
                      </View>
                      <View className="mr-2 text-sm font-medium">
                        共 {orderCostItem.count} {orderCostItem.unit}
                      </View>
                    </View>
                  </View>
                ))}
              <View className="rounded bg-gray-50 p-2">
                <View className="flex items-center justify-between text-sm">
                  <View className="font-medium text-gray-700">人工小计</View>

                  <View className="flex gap-4">
                    <View className="text-gray-600">
                      <View className="text-xs">我方</View>
                      <View className="font-semibold text-gray-900">
                        {orderVO.orderCostItemList
                          ?.filter(
                            (costItem: BusinessAPI.OrderCostItem) =>
                              costItem.type === "ARTIFICIAL_TYPE" &&
                              costItem.payerType === "US",
                          )
                          .reduce(
                            (sum, costItem) => sum + (costItem.count || 0),
                            0,
                          ) || 0}{" "}
                        人
                      </View>
                    </View>
                    <View className="text-gray-600">
                      <View className="text-xs">瓜农</View>
                      <View className="font-semibold text-gray-900">
                        {orderVO.orderCostItemList
                          ?.filter(
                            (costItem: BusinessAPI.OrderCostItem) =>
                              costItem.type === "ARTIFICIAL_TYPE" &&
                              costItem.payerType === "OTHER",
                          )
                          .reduce(
                            (sum, costItem) => sum + (costItem.count || 0),
                            0,
                          ) || 0}{" "}
                        人
                      </View>
                    </View>
                    <View className="text-gray-600">
                      <View className="text-xs">总人数</View>
                      <View className="font-semibold text-gray-900">
                        {orderVO.orderCostItemList
                          ?.filter(
                            (costItem: BusinessAPI.OrderCostItem) =>
                              costItem.type === "ARTIFICIAL_TYPE",
                          )
                          .reduce(
                            (sum, costItem) => sum + (costItem.count || 0),
                            0,
                          ) || 0}{" "}
                        人
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            </View>
          </View>
        </>
      )}

      {orderVO.orderCostItemList?.filter(
        (orderCostItem: BusinessAPI.OrderCostItem) =>
          orderCostItem.type === "MATERIAL_TYPE" &&
          orderCostItem.name !== "带空箱" &&
          orderCostItem.name !== "纸箱",
      ).length > 0 && (
        <>
          <View className="text-sm font-bold">辅料明细</View>
          <View className="rounded-lg bg-white p-2.5 shadow-sm">
            <View className="flex flex-col gap-2.5">
              {orderVO.orderCostItemList
                ?.filter(
                  (orderCostItem: BusinessAPI.OrderCostItem) =>
                    orderCostItem.type === "MATERIAL_TYPE" &&
                    orderCostItem.name !== "带空箱" &&
                    orderCostItem.name !== "纸箱",
                )
                .map((orderCostItem) => (
                  <View
                    className="flex items-center justify-between"
                    key={orderCostItem.orderCostItemId}
                  >
                    <View className="text-neutral-darker text-sm">
                      {orderCostItem.name}
                    </View>
                    <View className="text-sm font-medium">
                      {orderCostItem.count} {orderCostItem.unit}
                    </View>
                  </View>
                ))}
            </View>
          </View>
        </>
      )}

      {orderVO.orderCostList?.filter(
        (costItem: BusinessAPI.OrderCost) =>
          costItem.type === "PRODUCTION_TYPE",
      ).length > 0 && (
        <>
          <View className="text-sm font-bold">费用明细</View>
          <View className="rounded-lg bg-white p-2.5 shadow-sm">
            <View className="flex flex-col gap-2.5">
              {orderVO.orderCostList
                ?.filter(
                  (orderCost: BusinessAPI.OrderCost) =>
                    orderCost.type === "PRODUCTION_TYPE",
                )
                .map((orderCost) => (
                  <View
                    className="flex items-center justify-between"
                    key={orderCost.orderCostId}
                  >
                    <View className="text-neutral-darker text-sm">
                      {orderCost.name}
                    </View>
                    <View className="flex flex-1 items-center justify-end gap-1">
                      <View className="mr-2 text-sm font-medium">
                        {orderCost.price} {orderCost.unit || "元"}
                      </View>
                    </View>
                  </View>
                ))}
            </View>
          </View>
        </>
      )}
    </View>
  );
}
