import { View } from "@tarojs/components";
import { ExpenseCostCard, ExpenseCostCreate, Icon } from "@/components";
import { Button } from "@nutui/nutui-react-taro";
import { useEffect, useState } from "react";
import { business } from "@/services";

interface IExpenseCostProps {
  expenseRecord?: BusinessAPI.ExpenseRecordVO;
  onChange?: (expenseRecord: BusinessAPI.ExpenseRecordVO) => void;
}

export default function ExpenseCostList(props: IExpenseCostProps) {
  const { expenseRecord, onChange } = props;

  const expenseCosts = expenseRecord?.expenseCostList || [];

  const [costList, setCostList] = useState<BusinessAPI.CostVO[]>();

  const [visible, setVisible] = useState(false);

  const getCostList = async () => {
    const {
      data: { data: costList },
    } = await business.cost.listCost({
      costListQry: {
        status: true,
        type: "EXPENSE_TYPE",
      },
    });

    setCostList(costList);
  };

  // 获取显示的费用列表：isDefault=true 或已录入的费用
  const getDisplayCostList = () => {
    if (!costList) return [];

    return costList.filter((cost) => {
      // 如果已录入，则显示
      const isRecorded = expenseCosts.some(
        (item) => item.costId === cost.costId,
      );
      // 如果是默认费用，则显示
      const isDefault = cost.isDefault === true;

      return isRecorded || isDefault;
    });
  };

  // 获取可添加的费用列表：未显示的费用
  const getAvailableCostList = () => {
    if (!costList) return [];

    const displayedCostIds = getDisplayCostList().map((cost) => cost.costId);

    return costList.filter((cost) => !displayedCostIds.includes(cost.costId));
  };

  useEffect(() => {
    getCostList();
  }, []);

  return (
    <View className="overflow-hidden rounded-md bg-white shadow-md">
      <View className="border-b border-gray-100 p-2.5">
        <View className="text-neutral-darkest text-base font-medium">
          已录入费用
        </View>
      </View>
      {expenseRecord?.expenseCostList?.length === 0 && (
        <View className="py-2 text-center text-sm text-gray-500">
          暂无费用数据
        </View>
      )}
      <View className="divide-y divide-gray-100">
        {getDisplayCostList().map((cost) => {
          // 查找该费用类型对应的已录入费用
          const expenseCost = expenseCosts.find(
            (item) => item.costId === cost.costId,
          );
          return (
            <ExpenseCostCard
              key={cost.costId}
              cost={cost}
              expenseCost={expenseCost}
              onUpdate={(expenseCost) => {
                // 如果是更新已存在的费用
                const updatedList = expenseCosts.some(
                  (item) => item.costId === cost.costId,
                )
                  ? expenseCosts.map((item) =>
                      item.costId === cost.costId ? expenseCost : item,
                    )
                  : [...expenseCosts, expenseCost];
                onChange?.({
                  ...expenseRecord!,
                  expenseCostList: updatedList,
                });
              }}
              onDelete={() => {
                onChange?.({
                  ...expenseRecord!,
                  expenseCostList: expenseCosts.filter(
                    (item) => item.costId !== cost.costId,
                  ),
                });
              }}
            />
          );
        })}
      </View>
      <View className="border-t border-gray-100 bg-gray-50 p-2.5">
        <View className="flex items-center justify-between">
          <View className="text-neutral-darker text-sm">合计</View>
          <View className="text-neutral-darkest text-sm font-medium">
            ¥
            {expenseCosts
              .reduce((sum, expense) => sum + (expense.expenseAmount || 0), 0)
              .toFixed(2)}
          </View>
        </View>
      </View>

      {/* 只有当有可添加的费用时才显示添加按钮 */}
      {getAvailableCostList().length > 0 && (
        <View className={"bg-gray-50 p-2.5"}>
          <Button
            type="primary"
            size={"large"}
            block
            icon={<Icon name="plus" color={"white"} size={16} />}
            onClick={() => {
              setVisible(true);
            }}
          >
            添加费用
          </Button>
        </View>
      )}

      <ExpenseCostCreate
        visible={visible}
        onClose={() => setVisible(false)}
        onFinish={(expressCost) => {
          onChange?.({
            ...expenseRecord!,
            expenseCostList: [...expenseCosts, expressCost],
          });
        }}
      />
    </View>
  );
}
