import { View } from "@tarojs/components";
import {
  Button,
  Input,
  Popup,
  Radio,
  SafeArea,
  Toast,
} from "@nutui/nutui-react-taro";
import { Icon } from "@/components";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { validatePrice } from "@/utils";
import { business } from "@/services";
import { globalStore } from "@/store/global-store";

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

interface IStallWeighProps {
  index: number;
  value: BusinessAPI.OrderVO;
  onChange: (orderVO: BusinessAPI.OrderVO) => void;
}

export default forwardRef<StallWeighRef, IStallWeighProps>(
  function StallWeigh(props, ref) {
    const { value, onChange, index } = props;

    const { orderSupplierList } = value;
    const { setLoading } = globalStore((state: any) => state);

    const setOrderSupplierList = (
      orderSupplierList: BusinessAPI.OrderSupplier[],
    ) => {
      onChange({
        ...value,
        orderSupplierList,
      });
    };

    const setSupplierVO = (orderSupplierVO: BusinessAPI.OrderSupplier) => {
      setOrderSupplierList([
        ...orderSupplierList.map((item: BusinessAPI.OrderSupplier) => {
          if (item.orderSupplierId === orderSupplierVO.orderSupplierId) {
            return orderSupplierVO;
          }
          return item;
        }),
      ]);
    };

    const supplierVO = orderSupplierList[index];

    useEffect(() => {
      setLoading(true);
      // 获取产品列表
      business.product
        .listProduct({
          productListQry: {
            status: true,
          },
        })
        .then(({ data }) => {
          if (data.success) {
            const products = data.data || [];
            setProductList(products);
          }
          setLoading(false);
        });
    }, []);

    const [isProductIdError, setProductIdError] = useState<{
      [key: string]: boolean;
    }>({}); // 添加瓜农是否选择西瓜品牌的错误状态

    const [productPopupVisible, setProductPopupVisible] = useState(false);
    const [selectedProduct, setSelectedProduct] = useState("");
    const [customProduct, setCustomProduct] = useState("");
    const [productList, setProductList] = useState<BusinessAPI.ProductVO[]>([]);

    // 添加三个字段的错误状态
    const [grossWeightError, setGrossWeightError] = useState<{
      [key: string]: boolean;
    }>({});
    const [priceError, setPriceError] = useState<{
      [key: string]: boolean;
    }>({});

    // 将校验方法暴露给父组件
    useImperativeHandle(ref, () => ({
      validate,
    }));

    if (!supplierVO) {
      return;
    }

    // 校验西瓜品种
    const validateProductId = (productId: any) => {
      if (productId === "" || productId === undefined || productId === null) {
        setProductIdError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

      setProductIdError((prev) => ({
        ...prev,
        [supplierVO.orderSupplierId]: false,
      }));
      return true;
    };

    // 校验空磅重量
    const validateGrossWeight = (value: any) => {
      if (value === "" || value === undefined || value === null) {
        setGrossWeightError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

      const numValue = Number(value);
      if (Number.isNaN(numValue) || numValue < 0) {
        setGrossWeightError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

      setGrossWeightError((prev) => ({
        ...prev,
        [supplierVO.orderSupplierId]: false,
      }));
      return true;
    };

    // 校验采购单价
    const validatePurchasePrice = (value: any) => {
      if (value === "" || value === undefined || value === null) {
        setPriceError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

      const numValue = Number(value);
      if (Number.isNaN(numValue) || numValue < 0) {
        setPriceError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

      setPriceError((prev) => ({
        ...prev,
        [supplierVO.orderSupplierId]: false,
      }));
      return true;
    };

    // 对外暴露的校验方法
    const validate = () => {
      const id = supplierVO?.orderSupplierId;
      if (!id) return false;

      const isGrossWeightValid = validateGrossWeight(supplierVO.grossWeight);
      const isPurchasePriceValid = validatePurchasePrice(
        supplierVO.purchasePrice,
      );
      const isProductIdValid = validateProductId(supplierVO.productId);

      // 更新错误状态
      setProductIdError((prev) => ({
        ...prev,
        [id]: !isProductIdValid,
      }));

      setPriceError((prev) => ({
        ...prev,
        [id]: !isPurchasePriceValid,
      }));

      const isValid =
        isPurchasePriceValid && isProductIdValid && isGrossWeightValid;

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

      return isValid;
    };

    return (
      <View className="flex flex-1 flex-col gap-2.5 p-2.5">
        {/* 西瓜品种选择弹窗 */}
        <Popup
          duration={150}
          style={{
            minHeight: "auto",
          }}
          visible={productPopupVisible}
          position="bottom"
          title="请选择具体品种"
          description={"请选择具体品种，选择其他时请注明"}
          onClose={() => setProductPopupVisible(false)}
          round
          closeable
        >
          <View className={"flex flex-col gap-2.5 p-2.5"}>
            <View className="flex flex-col gap-2.5">
              <View className="grid grid-cols-2 gap-2">
                {productList.map((product) => (
                  <View
                    className={`cursor-pointer rounded-lg border p-3 text-center hover:bg-gray-50 ${selectedProduct === product.name ? "border-primary border-2" : "border-gray-200"}`}
                    key={product.productId}
                    onClick={() => setSelectedProduct(product.name)}
                  >
                    <View
                      className={
                        selectedProduct === product.name
                          ? "text-primary font-medium"
                          : ""
                      }
                    >
                      {product.name}
                    </View>
                  </View>
                ))}
              </View>
              {selectedProduct === "其他（请注明）" && (
                <View
                  className={`flex h-10 w-full items-center rounded-md ${selectedProduct === "其他（请注明）" && customProduct ? "border-primary border-4" : "border-4 border-gray-300"}`}
                >
                  <Input
                    clearable
                    placeholder="请输入品种"
                    type="text"
                    value={customProduct}
                    onChange={(value) => {
                      setCustomProduct(value);
                    }}
                  />
                </View>
              )}
            </View>

            <View className={"flex w-full flex-row gap-2.5 bg-white"}>
              <View className={"flex-1"}>
                <Button
                  size="xlarge"
                  block
                  type="default"
                  onClick={() => {
                    setProductPopupVisible(false);
                    setSelectedProduct("");
                    setCustomProduct("");
                  }}
                >
                  关闭
                </Button>
              </View>
              <View className={"flex-1"}>
                <Button
                  size="xlarge"
                  block
                  type="primary"
                  onClick={() => {
                    let finalProduct = "";
                    if (selectedProduct === "其他（请注明）") {
                      finalProduct = customProduct;
                    } else if (selectedProduct) {
                      // 从产品列表中找到选中产品的ID
                      const selectedProductObj = productList.find(
                        (p) => p.name === selectedProduct,
                      );
                      if (selectedProductObj) {
                        finalProduct = selectedProductObj.productId;
                      }
                    }

                    if (finalProduct) {
                      // 找到选中的产品对象
                      const productObj = productList.find(
                        (p) => p.name === selectedProduct,
                      );

                      if (productObj) {
                        setSupplierVO({
                          ...supplierVO,
                          productId: productObj.productId,
                          productName:
                            selectedProduct === "其他（请注明）"
                              ? customProduct
                              : productObj.name,
                        });
                      }

                      setProductPopupVisible(false);
                      setSelectedProduct("");
                      setCustomProduct("");
                    }
                  }}
                >
                  确定
                </Button>
              </View>
            </View>
            <SafeArea position={"bottom"} />
          </View>
        </Popup>

        {productList.length > 0 && (
          <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={"flex items-center justify-between gap-2.5"}>
                <View className="text-sm">装的西瓜品种是？</View>
                <View className="text-neutral-darkest text-sm font-medium">
                  <Radio.Group
                    direction="horizontal"
                    value={supplierVO.productId}
                    onChange={(value) => {
                      // 清除错误状态
                      setProductIdError((prev) => ({
                        ...prev,
                        [supplierVO.orderSupplierId]: false,
                      }));

                      if (value === "other") {
                        // 点击"其他"时打开弹窗
                        setProductPopupVisible(true);
                      } else {
                        // 根据用户选择设置西瓜品种
                        const productId = value as string;
                        const productVO = productList.find(
                          (p) => p.productId === productId,
                        );

                        if (productVO) {
                          setSupplierVO({
                            ...supplierVO,
                            productId: productVO?.productId,
                            productName: productVO?.name,
                            loadingMode:
                              productVO?.name !== "硒砂瓜"
                                ? "BOX_WITH_TAPE"
                                : undefined,
                          });
                        }
                      }
                    }}
                  >
                    <Radio
                      value={supplierVO.productId || productList?.[0].productId}
                    >
                      {supplierVO.productName || productList?.[0].name}
                    </Radio>
                    <Radio value="other">其他</Radio>
                  </Radio.Group>
                </View>
              </View>
              {isProductIdError[supplierVO.orderSupplierId] && (
                <View className="mt-1 text-xs text-red-500">
                  请选择西瓜品种
                </View>
              )}
            </View>
          </View>
        )}

        {/*/!* 瓜农包纸箱吗，包纸箱按照毛重报价，不包按照净重报价 *!/*/}
        {/*<View className="border-primary rounded-lg border-4 bg-white p-2.5 shadow-sm">*/}
        {/*  <View className={"flex items-center justify-between gap-2.5"}>*/}
        {/*    <View className="text-sm">{supplierVO.name}包纸箱吗？</View>*/}
        {/*    <View className="text-neutral-darkest text-sm font-medium">*/}
        {/*      <Radio.Group*/}
        {/*        direction="horizontal"*/}
        {/*        value={supplierVO.pricingMethod}*/}
        {/*        onChange={(value) => {*/}
        {/*          setSupplierVO({*/}
        {/*            ...supplierVO,*/}
        {/*            pricingMethod: value as any,*/}
        {/*          });*/}
        {/*        }}*/}
        {/*      >*/}
        {/*        <Radio value="BY_GROSS_WEIGHT">包</Radio>*/}
        {/*        <Radio value="BY_NET_WEIGHT">不包</Radio>*/}
        {/*      </Radio.Group>*/}
        {/*    </View>*/}
        {/*  </View>*/}
        {/*</View>*/}
        {/* 采购单价区域 */}
        <View className="border-primary rounded-lg border-4 bg-white p-2.5 shadow-sm">
          <View className="mb-2.5 flex items-center">
            <Icon
              name={"money-bill"}
              className="mr-2"
              size={20}
              color={"var(--color-yellow-500)"}
            />
            <View className="text-primary text-base font-bold">
              采购单价设置 (元/斤)
            </View>
          </View>

          <View
            className={`flex h-10 w-full items-center rounded-md ${priceError[supplierVO.orderSupplierId] ? "border-4 border-red-500" : "border-4 border-yellow-300"}`}
          >
            <Input
              clearable
              placeholder="0.00"
              type="digit"
              value={supplierVO.purchasePrice?.toString()}
              onChange={(value) => {
                const numValue = validatePrice(value);
                if (numValue !== undefined) {
                  setSupplierVO({
                    ...supplierVO,
                    purchasePrice: numValue as any,
                  });
                  // 校验输入值
                  validatePurchasePrice(numValue);
                }
              }}
              onBlur={() => {
                // 失去焦点时进行校验
                validatePurchasePrice(supplierVO.purchasePrice);
              }}
            />
            <View
              className="text-gray-500"
              style={{
                padding: `var(--nutui-input-padding)`,
              }}
            >
              元/斤
            </View>
          </View>
          {priceError[supplierVO.orderSupplierId] && (
            <View className="mt-1 text-xs text-red-500">
              请输入有效的采购单价
            </View>
          )}
        </View>

        {/* 称重信息和照片整合区域 */}
        <View className="border-primary rounded-lg border-4 bg-white p-2.5 shadow-sm">
          <View className="text-primary mb-2.5 text-base font-bold">
            {supplierVO.name}的称重信息
          </View>

          <View className="flex flex-col gap-2.5">
            {/* 重量输入区域 */}
            <View className="flex flex-row gap-2.5">
              <View className="flex-1 rounded-lg bg-blue-50 p-2.5">
                <View className="mb-2.5 flex items-center">
                  <Icon
                    name={"truck"}
                    className="mr-2"
                    size={20}
                    color={"var(--color-blue-500)"}
                  />
                  <View className="text-sm text-gray-700">毛重重量 (斤)</View>
                </View>

                <View
                  className={`flex h-10 w-full items-center rounded-md ${grossWeightError[supplierVO.orderSupplierId] ? "border-4 border-red-500" : "border-4 border-blue-300"}`}
                >
                  <Input
                    clearable
                    placeholder="0"
                    type="digit"
                    value={supplierVO.grossWeight?.toString()}
                    onChange={(value) => {
                      const numValue = validatePrice(value);
                      if (numValue !== undefined) {
                        setSupplierVO({
                          ...supplierVO,
                          grossWeight: numValue as any,
                        });
                        // 校验输入值
                        validateGrossWeight(numValue);
                      }
                    }}
                    onBlur={() => {
                      // 失去焦点时进行校验
                      validateGrossWeight(supplierVO.grossWeight);
                    }}
                  />
                  <View
                    className="text-gray-500"
                    style={{
                      padding: `var(--nutui-input-padding)`,
                    }}
                  >
                    斤
                  </View>
                </View>
                {grossWeightError[supplierVO.orderSupplierId] && (
                  <View className="mt-1 text-xs text-red-500">
                    请输入有效的毛重重量
                  </View>
                )}
              </View>
            </View>
          </View>
        </View>
      </View>
    );
  },
);
