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

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

export type IOrderCost = BusinessAPI.OrderCost;

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

export default forwardRef<OrderCostRef, IOrderCostProps>(
  function OrderCost(props, ref) {
    const { value, onChange } = props;

    const { orderSupplierList, orderCostList } = value;
    const supplierVO = orderSupplierList[orderSupplierList.length - 1];
    const costTemplate = supplierVO?.costTemplate;
    const costIds = supplierVO?.costIds;
    // 解析costTemplate为JSON对象
    const parsedCostTemplate = JSON.parse(costTemplate || "[]");

    // 初始化函数
    const init = async (costIds: string[]) => {
      // 创建一个映射，用于快速查找orderCostItemList中的项目
      const orderCostMap = new Map<string, BusinessAPI.OrderCost>();

      orderCostList?.forEach((item) => {
        if (item.costId && costIds?.includes(item.costId)) {
          orderCostMap.set(item.costId, item);
        }
      });

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

      // 遍历costList，将costList中的项目添加到orderCostList中
      parsedCostTemplate.productionTypeList?.forEach((item) => {
        const existingItem = orderCostMap.get(item.costId);

        if (existingItem) {
          newOrderCostList.push({
            ...existingItem,
            selected: existingItem?.selected || false,
          });
        } else {
          newOrderCostList.push({
            orderCostId: generateShortId(),
            costItemIds: item.costItemIds,
            costId: item.costId,
            name: item.name,
            type: item.type,
            selected: false,
            count: 1,
            price: item.price || 0,
            unit: item.unit || "元",
            belong: item.belong,
          });

          orderCostMap.set(item.costId, {
            orderCostId: generateShortId(),
            costItemIds: item.costItemIds,
            costId: item.costId,
            name: item.name,
            type: item.type,
            selected: false,
            count: 1,
            price: item.price || 0,
            unit: item.unit || "元",
            belong: item.belong,
          });
        }
      });

      const { data } = await business.cost.listCost({
        costListQry: {
          status: true,
        },
      });

      data.data?.forEach((item) => {
        if (
          item.costId &&
          costIds?.includes(item.costId) &&
          !newOrderCostList.some((cost) => cost.costId === item.costId)
        ) {
          newOrderCostList.push({
            orderCostId: generateShortId(),
            costItemIds: item.costItemIds,
            costId: item.costId,
            name: item.name,
            type: item.type,
            selected: false,
            count: 1,
            price: item.price || 0,
            unit: item.unit || "元",
            belong: item.belong,
          });
        }
      });

      onChange?.({
        ...value,
        orderCostList: newOrderCostList,
      });
    };

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

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

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

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

      // 校验费用
      orderCostList.forEach((item) => {
        if (item.selected) {
          // 校验数量
          if (!validateCount(item.costId, item.count || 0)) {
            isValid = false;
          }
        }
      });

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

      return isValid;
    };

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

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

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

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

        const selected = currentItem?.selected || false;
        const price = currentItem?.price || 0;
        const orderCostId = currentItem?.orderCostId || generateShortId();

        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.costId, checked);
                }}
              >
                <View className={"text-sm font-normal text-[#000000]"}>
                  用了
                </View>
              </Checkbox>
            </View>

            {/* 只对生产费用类型显示金额输入框 */}
            {selected && (
              <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[orderCostId] && selected ? "border-red-500" : "border-gray-200"} bg-white`}
                    >
                      <Input
                        clearable
                        type="digit"
                        value={price.toString()}
                        align={"center"}
                        placeholder={"输入多少钱"}
                        onChange={(value) => {
                          updatePrice(item.costId, Number(value));
                        }}
                        onBlur={() => validateCount(orderCostId, price)}
                      />
                    </View>
                    <View className={"ml-2.5 text-sm text-gray-500"}>元</View>
                  </View>
                </View>

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

    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-1 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(parsedCostTemplate.productionTypeList)}
          </View>
        </View>
      </View>
    );
  },
);
