import { View } from "@tarojs/components";
import { Button } from "@nutui/nutui-react-taro";
import { useState } from "react";
import CostCreate from "./CostCreate";
import CostCard from "./CostCard";

export default function CostList(props: {
  orderVO: BusinessAPI.OrderVO;
  onChange?: (orderVO: BusinessAPI.OrderVO) => void;
  costList: BusinessAPI.CostVO[];
  readOnly?: boolean;
  type: BusinessAPI.OrderCost["type"];
}) {
  const {
    orderVO,
    onChange,
    readOnly,
    costList: defaultCostList,
    type,
  } = props;

  const costIdList = orderVO.orderCostList
    .filter((orderCost) => orderCost.type === type)
    .map((orderCost) => orderCost.costId);

  const costList = defaultCostList.filter(
    (cost) => !costIdList.includes(cost.costId) && cost.type === type,
  );

  // 新增费弹窗状态
  const [showAddCostPopup, setShowAddCostPopup] = useState(false);

  // 费类型
  const orderCosts =
    orderVO.orderCostList?.filter((item) => item.type === type) || [];

  const handleSaveNewCost = (
    orderCost: BusinessAPI.OrderCost,
    orderCostItemList: BusinessAPI.OrderCostItem[],
  ) => {
    // 更新orderVO，将新费用添加到orderCostList中
    if (onChange) {
      const updatedOrderCostList = [
        ...(orderVO.orderCostList || []),
        orderCost,
      ];

      // 更新orderCostItemList
      // 首先过滤掉旧的费用项
      const filteredOrderCostItemList = (
        orderVO.orderCostItemList || []
      ).filter((item) => !orderCost.costItemIds?.includes(item.costItemId!));

      // 然后添加新的费用项
      const updatedOrderCostItemList = [
        ...filteredOrderCostItemList,
        ...orderCostItemList,
      ];

      const newOrderVO = {
        ...orderVO,
        orderCostList: updatedOrderCostList,
        orderCostItemList: updatedOrderCostItemList,
      };
      onChange(newOrderVO);
    }

    setShowAddCostPopup(false);
  };

  const handleEditCost = (
    editedItem: BusinessAPI.OrderCost,
    editedItemList: BusinessAPI.OrderCostItem[],
  ) => {
    // 更新orderVO，替换被编辑的费用项
    if (onChange) {
      // 更新orderCostList
      const updatedOrderCostList = (orderVO.orderCostList || []).map((item) => {
        if (item.orderCostId === editedItem.orderCostId) {
          return editedItem;
        }
        return item;
      });

      // 更新orderCostItemList
      // 首先过滤掉旧的费用项
      const filteredOrderCostItemList = (
        orderVO.orderCostItemList || []
      ).filter((item) => !editedItem.costItemIds?.includes(item.costItemId!));

      // 然后添加新的费用项
      const updatedOrderCostItemList = [
        ...filteredOrderCostItemList,
        ...editedItemList,
      ];

      const newOrderVO = {
        ...orderVO,
        orderCostList: updatedOrderCostList,
        orderCostItemList: updatedOrderCostItemList,
      };
      onChange(newOrderVO);
    }
  };

  const handleDeleteCost = (orderCostId: string) => {
    // 更新orderVO，移除被删除的费用项
    if (onChange) {
      // 删除orderCostList中的项
      const updatedOrderCostList = (orderVO.orderCostList || []).filter(
        (item) => item.orderCostId !== orderCostId,
      );

      // 找到要删除的费用项，以便同时删除orderCostItemList中的相关项
      const costToDelete = (orderVO.orderCostList || []).find(
        (item) => item.orderCostId === orderCostId,
      );

      // 删除orderCostItemList中的相关项
      let updatedOrderCostItemList = orderVO.orderCostItemList || [];
      if (costToDelete?.costItemIds) {
        updatedOrderCostItemList = updatedOrderCostItemList.filter(
          (item) => !costToDelete.costItemIds?.includes(item.costItemId!),
        );
      }

      const newOrderVO = {
        ...orderVO,
        orderCostList: updatedOrderCostList,
        orderCostItemList: updatedOrderCostItemList,
      };
      onChange(newOrderVO);
    }
  };

  return (
    <>
      <View className={"flex flex-col gap-2.5 divide-y divide-[#eaeaea]"}>
        <View className="flex flex-col gap-2.5">
          {type === "ARTIFICIAL_TYPE" && orderVO.foreman && (
            <View className={"flex flex-col gap-2.5"}>
              <View className={"text-sm font-bold"}>
                工头：{orderVO.foreman}
              </View>
            </View>
          )}

          {type === "PRODUCTION_TYPE" && orderVO.originPrincipal && (
            <View className={"flex flex-col gap-2.5"}>
              <View className={"text-sm font-bold"}>
                产地负责人：{orderVO.originPrincipal}
              </View>
            </View>
          )}

          {orderCosts.map((orderCost) => {
            if (
              orderCost.name === "空箱费" ||
              orderCost.name === "纸箱费" ||
              orderCost.name === "主运费" ||
              orderCost.name === "短驳费" ||
              orderCost.name === "付瓜农定金" ||
              (orderCost.name === "草帘费" &&
                orderCost.type === "LOGISTICS_TYPE") ||
              (orderCost.name === "人工费" &&
                orderCost.type === "ARTIFICIAL_TYPE" &&
                orderVO.orderCostItemList.filter(
                  (item) =>
                    item.payerType === "US" &&
                    orderCost.costItemIds?.includes(item.costItemId!),
                ).length === 0)
            ) {
              return <></>;
            }
            return (
              <CostCard
                costList={defaultCostList}
                key={orderCost.orderCostId}
                item={orderCost}
                orderVO={orderVO}
                readOnly={readOnly}
                onEdit={handleEditCost}
                onDelete={handleDeleteCost}
              />
            );
          })}
        </View>
        {!readOnly && (
          <Button
            type={"primary"}
            block
            size={"large"}
            onClick={() => setShowAddCostPopup(true)}
          >
            {type === "ARTIFICIAL_TYPE" && "新增其他人工类型费用"}
            {type === "MATERIAL_TYPE" && "新增其他辅料类型费用"}
            {type === "PRODUCTION_TYPE" && "新增其他产地类型费用"}
            {type === "OTHER_TYPE" && "新增其他类型费用"}
          </Button>
        )}
      </View>

      <CostCreate
        type={type}
        costList={costList}
        orderCostItemList={orderVO.orderCostItemList}
        visible={showAddCostPopup}
        onClose={() => setShowAddCostPopup(false)}
        onSave={handleSaveNewCost}
      />
    </>
  );
}
