import { Table, TableColumnProps } from "@nutui/nutui-react-taro";
import { OrderCalculator } from "@/utils";
import { useState } from "react";
import { DecimalUtils } from "@/utils/classes/calculators/core/DecimalUtils";

export default function CostSummarySection(props: {
  orderVO: BusinessAPI.OrderVO;
  onChange?: (orderVO: BusinessAPI.OrderVO) => void;
  readOnly?: boolean;
  calculator: OrderCalculator;
}) {
  const { calculator } = props;

  // 计算总净重
  const totalWeight = calculator.getTotalWeight();

  // 计算运费
  const freightCost = calculator.getDeliveryFee();

  let costWithoutFreight: number;
  let costWithFreight: number;

  // 判断采购成本是否包含运费,包含运费说明已经加过一次了
  if (calculator.getRules().shouldIncludeFreightCost()) {
    costWithFreight = calculator
      .getCostCalculator()
      .calculateTotalPurchaseCost(true);
    costWithoutFreight = costWithFreight - freightCost;
  } else {
    costWithoutFreight = calculator
      .getCostCalculator()
      .calculateTotalPurchaseCost();
    costWithFreight = costWithoutFreight + freightCost;
  }

  // 计算单斤成本(不含运费)
  const unitCostWithoutFreight =
    totalWeight > 0
      ? DecimalUtils.toDecimalPlaces(
          DecimalUtils.divide(costWithoutFreight, totalWeight),
          2,
        )
      : 0;

  // 计算单斤成本(含运费)
  const unitCostWithFreight =
    totalWeight > 0
      ? DecimalUtils.toDecimalPlaces(
          DecimalUtils.divide(costWithFreight, totalWeight),
          2,
        )
      : 0;

  // 准备表格数据
  const tableData = [
    {
      id: 1,
      costType: "成本合计(不含运费)",
      unitCost: unitCostWithoutFreight,
      amount: costWithoutFreight,
    },
    {
      id: 2,
      costType: "成本合计(含运费)",
      unitCost: unitCostWithFreight,
      amount: costWithFreight,
    },
  ];

  // 定义表格列
  const [columns] = useState<Array<TableColumnProps>>([
    {
      title: "成本合计",
      key: "costType",
      fixed: "left",
    },
    {
      title: "金额（元）",
      key: "amount",
    },
    {
      title: "单斤成本（元/斤）",
      key: "unitCost",
    },
  ]);

  return <Table columns={columns} data={tableData} striped />;
}
