import { View } from "@tarojs/components";
import { Icon, OrderPackage } from "@/components";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { Button, Checkbox, Input, Toast } from "@nutui/nutui-react-taro";
import { generateShortId, OrderCalculator } from "@/utils";

// 定义ref暴露的方法接口
export interface OrderCostItemRef {
  validate: () => boolean;
}

export type IOrderCostItem = BusinessAPI.OrderCostItem;

export interface IOrderCostItemProps {
  value: BusinessAPI.OrderVO;
  onChange?: (data: Partial<BusinessAPI.OrderVO>) => void;
}

export default forwardRef<OrderCostItemRef, IOrderCostItemProps>(
  function OrderCostItem(props, ref) {
    const { value, onChange } = props;

    const calculator = new OrderCalculator(value as any);

    const {
      orderId,
      orderSupplierList,
      foreman,
      orderPackageList,
      orderCostItemList,
    } = value;
    const supplierVO = orderSupplierList[orderSupplierList.length - 1];
    const costTemplate = supplierVO?.costTemplate;

    // 解析costTemplate为JSON对象
    const parsedCostTemplate = JSON.parse(costTemplate || "[]");

    // 工头姓名错误状态
    const [foremanError, setForemanError] = useState<boolean>(false);

    // 初始化函数
    const init = () => {
      // 创建一个映射，用于快速查找orderCostItemList中的项目
      const orderCostItemMap = new Map<string, BusinessAPI.OrderCostItem>();
      orderCostItemList?.forEach((item) => {
        if (item.costItemId) {
          orderCostItemMap.set(item.costItemId, {
            ...item,
            selected: item.selected || false,
          });
        }
      });

      // 构建初始列表，基于costTemplate中的项目
      const newOrderCostItemList: IOrderCostItem[] = [];

      // 处理人工费用项
      parsedCostTemplate.artificialTypeList?.forEach((item: any) => {
        const existingItem = orderCostItemMap.get(item.costItemId);
        newOrderCostItemList.push({
          orderCostItemId: existingItem?.orderCostItemId || generateShortId(),
          orderId: orderId,
          costItemId: item.costItemId,
          name: item.name,
          price: item.price,
          unit: item.unit,
          selected: existingItem?.selected || false,
          count: existingItem?.count || 1,
          payerType: existingItem?.payerType,
          type: item.type,
          rule: item.rule,
        });
      });

      // 处理辅料费用项（排除纸箱）
      parsedCostTemplate.materialTypeList
        ?.filter((item: any) => item.name !== "纸箱")
        .forEach((item: any) => {
          const existingItem = orderCostItemMap.get(item.costItemId);
          newOrderCostItemList.push({
            orderCostItemId: existingItem?.orderCostItemId || generateShortId(),
            orderId: orderId,
            costItemId: item.costItemId,
            name: item.name,
            price: item.price,
            unit: item.unit,
            selected: existingItem?.selected || false,
            count: existingItem?.count || 1,
            payerType: existingItem?.payerType,
            type: item.type,
            rule: item.rule,
          });
        });

      // 自动把纸箱加进去
      const boxCostItem = parsedCostTemplate.materialTypeList?.find(
        (item: any) => item.name === "纸箱",
      );

      if (boxCostItem) {
        newOrderCostItemList.push({
          orderCostItemId: boxCostItem?.orderCostItemId || generateShortId(),
          orderId: orderId,
          costItemId: boxCostItem.costItemId,
          name: boxCostItem.name,
          price:
            value.type === "PRODUCTION_PURCHASE" ? calculator.getBoxSale() : 0,
          unit: boxCostItem.unit,
          selected: true,
          count: boxCostItem?.count || 1,
          payerType: boxCostItem?.payerType,
          type: boxCostItem.type,
          rule: boxCostItem.rule,
        });
      }

      onChange?.({
        ...value,
        orderCostItemList: newOrderCostItemList,
      });
    };

    // 当传入的orderCostItemList发生变化时，重新初始化列表
    useEffect(() => {
      init();
    }, []);

    // 错误状态
    const [countError, setCountError] = useState<{ [key: string]: boolean }>(
      {},
    );
    const [payerTypeError, setPayerTypeError] = useState<{
      [key: string]: boolean;
    }>({});

    // 校验数量
    const validateCount = (id: string, value: number) => {
      const isValid = value > 0;
      setCountError((prev) => ({
        ...prev,
        [id]: !isValid,
      }));
      return isValid;
    };

    // 校验费用承担方
    const validatePayerType = (
      id: string,
      value: BusinessAPI.OrderCostItem["payerType"],
    ) => {
      const isValid = value === "US" || value === "OTHER";
      setPayerTypeError((prev) => ({
        ...prev,
        [id]: !isValid,
      }));
      return isValid;
    };

    // 校验工头姓名
    const validatePrincipal = (principal: string) => {
      const isValid = principal?.trim().length > 0;
      setForemanError(!isValid);
      return isValid;
    };

    // 处理工头姓名变化
    const handleForemanChange = (foreman: string) => {
      // 更新所有启用且费用承担方为"我方"的人工费用项的工头姓名
      const updatedList = orderCostItemList?.map((item) => {
        if (
          item.type === "ARTIFICIAL_TYPE" &&
          item.selected &&
          item.payerType === "US"
        ) {
          return { ...item, principal: foreman };
        }
        return item;
      });

      onChange?.({
        ...value,
        foreman: foreman,
        orderCostItemList: updatedList,
      });

      // 如果有启用且费用承担方为"我方"的项目，则校验工头姓名
      const enabledUsItems = orderCostItemList?.filter(
        (item) =>
          item.type === "ARTIFICIAL_TYPE" &&
          item.selected &&
          item.payerType === "US",
      );
      if (enabledUsItems && enabledUsItems.length > 0) {
        validatePrincipal(foreman);
      }
    };

    // 失去焦点时校验工头姓名
    const handlePrincipalBlur = (foreman: string) => {
      validatePrincipal(foreman);
    };

    // 对外暴露的校验方法
    const validate = () => {
      let isValid = true;

      // 校验人工和辅料费用
      orderCostItemList.forEach((item) => {
        if (item.selected) {
          // 校验数量
          if (!validateCount(item.orderCostItemId, item.count || 0)) {
            isValid = false;
          }

          if (item.type === "ARTIFICIAL_TYPE") {
            // 校验费用承担方
            if (!validatePayerType(item.orderCostItemId, item.payerType)) {
              isValid = false;
            }
          }
        }
      });

      // 校验总的工头姓名（如果有启用且费用承担方为"我方"的项目）
      const enabledUsItems = orderCostItemList.filter(
        (item) =>
          item.type === "ARTIFICIAL_TYPE" &&
          item.selected &&
          item.payerType === "US",
      );

      if (enabledUsItems.length > 0) {
        if (!validatePrincipal(foreman!)) {
          isValid = false;
        }
      }

      if (!isValid) {
        Toast.show("toast", {
          icon: "fail",
          title: "提示",
          content: "请完善人工和辅料信息后再进行下一步操作",
        });
      }

      return isValid;
    };

    useImperativeHandle(ref, () => ({
      validate,
    }));

    // 获取指定类型的项目列表
    const getItemsByCostType = (type: string) => {
      // 根据类型从parsedCostTemplate中获取数据
      if (type === "ARTIFICIAL_TYPE") {
        return parsedCostTemplate.artificialTypeList || [];
      } else if (type === "MATERIAL_TYPE") {
        // 过滤掉"纸箱"项
        return (parsedCostTemplate.materialTypeList || []).filter(
          (item: any) => item.name !== "纸箱",
        );
      }
      return [];
    };

    // 切换项目选择状态
    const toggleItemSelected = (costItemId: string, selected: boolean) => {
      onChange?.({
        ...value,
        orderCostItemList: orderCostItemList?.map((item) =>
          item.costItemId === costItemId ? { ...item, selected } : item,
        ),
      });
    };

    // 更新项目计数
    const updateItemCount = (costItemId: string, count: number) => {
      onChange?.({
        ...value,
        orderCostItemList: orderCostItemList?.map((item) =>
          item.costItemId === costItemId ? { ...item, count } : item,
        ),
      });
    };

    // 更新付款方类型
    const updatePayerType = (costItemId: string, payerType: "US" | "OTHER") => {
      onChange?.({
        ...value,
        orderCostItemList: orderCostItemList?.map((item) =>
          item.costItemId === costItemId ? { ...item, payerType } : item,
        ),
      });
    };

    // 更新价格
    const updatePrice = (costItemId: string, price: number) => {
      onChange?.({
        ...value,
        orderCostItemList: orderCostItemList?.map((item) =>
          item.costItemId === costItemId ? { ...item, price } : item,
        ),
      });
    };

    // 渲染项目列表
    const renderItemList = (items: any[], type: string) => {
      return items?.map((item, index) => {
        // 查找当前项目在costItemList中的状态
        const currentItem = orderCostItemList?.find(
          (costItem) => costItem.costItemId === item.costItemId,
        );

        const selected = currentItem?.selected || false;
        const count = currentItem?.count || 1;
        const payerType = currentItem?.payerType;
        const price = currentItem?.price || 0;
        const orderCostItemId =
          currentItem?.orderCostItemId || generateShortId();

        if (item.name === "带空箱") {
          return (
            <OrderPackage
              key={index}
              orderPackageList={orderPackageList}
              onChange={(orderPackageList) => {
                onChange?.({
                  ...value,
                  orderPackageList,
                  orderCostItemList: orderCostItemList?.map((item1) =>
                    item1.costItemId === item.costItemId
                      ? {
                          ...item1,
                          selected,
                          price: orderPackageList.reduce(
                            (sum, item) =>
                              sum + (item.boxSalePrice || 0) * item.boxCount,
                            0,
                          ),
                        }
                      : item1,
                  ),
                });
              }}
            />
          );
        }

        return (
          <View
            key={index}
            className={
              "bg-primary/10 flex flex-col gap-2.5 rounded-lg p-2.5 text-sm text-gray-600"
            }
          >
            <View className={"flex flex-row justify-between"}>
              <View className="block text-sm font-normal text-[#000000]">
                {item.name}
              </View>
              <Checkbox
                className={"flex flex-row items-center"}
                checked={selected}
                onChange={(checked) => {
                  toggleItemSelected(item.costItemId, checked);
                }}
              >
                <View className={"text-sm font-normal text-[#000000]"}>
                  用了
                </View>
              </Checkbox>
            </View>

            {selected && type === "ARTIFICIAL_TYPE" && (
              <View>
                {/* 费用承担方改为按钮形式，参考OrderPackage中的样式 */}
                <View className="flex items-center justify-between">
                  <View className="flex-shrink-0 text-sm">谁出钱:</View>
                  <View className="flex gap-2">
                    <Button
                      size="small"
                      type={payerType === "US" ? "primary" : "default"}
                      onClick={() => {
                        updatePayerType(item.costItemId, "US");
                      }}
                    >
                      我们出
                    </Button>
                    <Button
                      size="small"
                      type={payerType === "OTHER" ? "primary" : "default"}
                      onClick={() => {
                        updatePayerType(item.costItemId, "OTHER");
                      }}
                    >
                      对方出
                    </Button>
                  </View>
                </View>

                {payerTypeError[item.costItemId] && selected && (
                  <View className="mt-1 text-xs text-red-500">
                    请选择谁出这笔钱
                  </View>
                )}
              </View>
            )}

            {/* 根据rule值判断是否显示数量输入 */}
            {selected &&
              (type === "ARTIFICIAL_TYPE" || type === "MATERIAL_TYPE") &&
              (item.rule === "INPUT_QUANTITY" ||
                item.rule === "INPUT_QUANTITY_AND_AMOUNT") && (
                <View>
                  <View className="flex items-center justify-between gap-2">
                    <View className="flex-shrink-0 text-sm">用多少:</View>
                    <View className="flex flex-1 items-center">
                      <View
                        className="flex !size-12 flex-none items-center justify-center bg-gray-200 text-sm"
                        onClick={() => {
                          const currentCount = count || 1;
                          const newCount = Math.max(1, currentCount - 1);
                          updateItemCount(item.costItemId, newCount);

                          // 校验数量
                          if (selected) {
                            validateCount(orderCostItemId, newCount);
                          }
                        }}
                      >
                        <Icon name="minus" size={20} />
                      </View>
                      <View
                        className={`flex h-12 w-full shrink items-center border-4 border-gray-200`}
                      >
                        <Input
                          clearable
                          type="number"
                          value={count?.toString()}
                          align={"center"}
                          placeholder={"用了多少"}
                          onChange={(value) => {
                            updateItemCount(item.costItemId, Number(value));
                          }}
                          formatter={(value) =>
                            Math.max(1, Number(value)).toString()
                          }
                          onBlur={() => validateCount(orderCostItemId, count)}
                        />
                      </View>
                      <View
                        className="flex !size-12 flex-none items-center justify-center bg-gray-200 text-sm"
                        onClick={() => {
                          const currentCount = count || 1;
                          const newCount = currentCount + 1;
                          updateItemCount(item.costItemId, newCount);

                          // 校验数量
                          if (selected) {
                            validateCount(orderCostItemId, newCount);
                          }
                        }}
                      >
                        <Icon name="plus" size={20} />
                      </View>

                      <View className={"ml-2.5 text-sm text-gray-500"}>
                        {item.unit}
                      </View>
                    </View>
                  </View>

                  {countError[orderCostItemId] && selected && (
                    <View className="mt-1 text-xs text-red-500">
                      请填写正确的数量
                    </View>
                  )}
                </View>
              )}

            {/* 根据rule值判断是否显示金额输入 */}
            {selected &&
              (type === "ARTIFICIAL_TYPE" || type === "MATERIAL_TYPE") &&
              item.rule === "INPUT_QUANTITY_AND_AMOUNT" && (
                <View>
                  <View className="flex items-center justify-between gap-2">
                    <View className="flex-shrink-0 text-sm">多少钱:</View>
                    <View className="flex flex-1 items-center">
                      <View
                        className={`flex h-12 w-full shrink items-center border-4 ${countError[orderCostItemId] && selected ? "border-red-500" : "border-gray-200"} bg-white`}
                      >
                        <Input
                          clearable
                          type="digit"
                          value={price.toString()}
                          align={"center"}
                          placeholder={"输入多少钱"}
                          onChange={(value) => {
                            updatePrice(item.costItemId, Number(value));
                          }}
                          onBlur={() => validateCount(orderCostItemId, price)}
                        />
                      </View>
                      <View className={"ml-2.5 text-sm text-gray-500"}>元</View>
                    </View>
                  </View>

                  {countError[orderCostItemId] && selected && (
                    <View className="mt-1 text-xs text-red-500">
                      请填写正确的金额
                    </View>
                  )}
                </View>
              )}
          </View>
        );
      });
    };

    // 检查是否有人工费用项被启用且费用承担方为"我方"
    const shouldShowPrincipalInput = () => {
      return (
        orderCostItemList?.some(
          (item) =>
            item.type === "ARTIFICIAL_TYPE" &&
            item.selected &&
            item.payerType === "US",
        ) || false
      );
    };

    return (
      <View className="flex flex-1 flex-col gap-2.5 bg-[#D1D5DB] p-2.5">
        <View className="border-primary rounded-lg border-4 bg-white p-2.5 shadow-sm">
          <View className={"flex flex-col gap-2.5"}>
            <View className="text-primary text-base font-bold">人工费用</View>
            <View className="flex items-center rounded-lg border border-blue-200 bg-blue-50 p-2.5">
              <Icon
                className={"mr-1 leading-4"}
                name="circle-info"
                color={"var(--color-blue-700)"}
                size={18}
              />
              <View className={"text-sm text-blue-700"}>
                对方出钱可以不勾选
              </View>
            </View>

            {/* 总的工头姓名输入框 */}
            {shouldShowPrincipalInput() && (
              <View className="flex flex-col gap-2.5">
                <View className="text-sm font-medium">工头叫什么名字</View>
                <View
                  className={`flex h-12 items-center rounded-md ${foremanError ? "border-2 border-red-500 bg-red-100" : "border-2 border-gray-300 bg-white"}`}
                >
                  <Input
                    clearable
                    className="text-base"
                    type="text"
                    placeholder={"工头的名字"}
                    value={foreman}
                    onChange={(value) => {
                      handleForemanChange(value);
                    }}
                    onBlur={() => handlePrincipalBlur(foreman!)}
                  />
                </View>
                {foremanError && (
                  <View className="mt-1 text-xs text-red-500">
                    工头叫啥子填一下
                  </View>
                )}
              </View>
            )}

            {renderItemList(
              getItemsByCostType("ARTIFICIAL_TYPE"),
              "ARTIFICIAL_TYPE",
            )}
          </View>
        </View>
        <View className="border-primary rounded-lg border-4 bg-white p-2.5 shadow-sm">
          <View className={"flex flex-col gap-2.5"}>
            <View className="text-primary text-base font-bold">辅料费用</View>
            <View className="flex items-center rounded-lg border border-blue-200 bg-blue-50 p-2.5">
              <Icon
                className={"mr-1 leading-4"}
                name="circle-info"
                color={"var(--color-blue-700)"}
                size={18}
              />
              <View className={"text-sm text-blue-700"}>用了几包就填几包</View>
            </View>
            {/* 渲染辅料费用项（不含纸箱） */}
            {renderItemList(
              getItemsByCostType("MATERIAL_TYPE"),
              "MATERIAL_TYPE",
            )}
          </View>
        </View>
      </View>
    );
  },
);
