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

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

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

export default forwardRef<SupplierWeighRef, IWeightProps>(
  function SupplierWeigh(props, ref) {
    const { value, onChange, index } = props;

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

    const isFirst = index === 0;

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

    const changePaper = (isPaper: boolean) => {
      setOrderSupplierList([
        ...orderSupplierList.map((item: BusinessAPI.OrderSupplier) => {
          item.isPaper = isPaper;
          return item;
        }),
      ]);
    };

    const changeProduct = (productVO: BusinessAPI.ProductVO) => {
      setOrderSupplierList([
        ...orderSupplierList.map((item: BusinessAPI.OrderSupplier) => {
          item.productId = productVO.productId;
          item.productName = productVO.name;
          item.costIds = productVO.costIds;
          item.costTemplate = productVO.costTemplate;
          return item;
        }),
      ]);
    };

    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 [isPaperError, setIsPaperError] = useState<{
      [key: string]: boolean;
    }>({}); // 添加是否为最后一个瓜农的错误状态

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

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

    // 添加定金相关字段的错误状态
    const [depositError, setDepositError] = useState<{
      [key: string]: boolean;
    }>({});

    // 添加包纸箱字段的错误状态
    const [pricingMethodError, setPricingMethodError] = useState<{
      [key: string]: boolean;
    }>({});

    // 添加是否付定金字段的错误状态
    const [isDepositPaidError, setIsDepositPaidError] = useState<{
      [key: string]: boolean;
    }>({});

    // 装车方式切换确认状态
    const [loadingModeConfirmVisible, setLoadingModeConfirmVisible] =
      useState(false);
    const [pendingLoadingMode, setPendingLoadingMode] = useState<string>("");

    // 空磅照片上传处理函数
    const handleEmptyWeightImgUpload = async () => {
      await Taro.chooseImage({
        count: 1,
        sourceType: ["album", "camera"],
        success: (res) => {
          setLoading(true);
          const file = res.tempFiles[0];
          uploadFile(file.path)
            .then(({ url }) => {
              setSupplierVO({
                ...supplierVO!,
                emptyWeightImg: url,
              });
              setLoading(false);
              Toast.show("toast", {
                title: "上传成功",
                icon: "success",
                content: "空磅照片已上传",
              });
            })
            .catch((err) => {
              Toast.show("toast", {
                title: "上传失败",
                icon: "fail",
                content: err.message || "上传过程中发生错误",
              });
              setLoading(false);
            });
        },
        fail: (err) => {
          Toast.show("toast", {
            title: "选择图片失败",
            icon: "fail",
            content: err.errMsg,
          });
        },
      });
    };

    // 总磅照片上传处理函数
    const handleTotalWeightImgUpload = async () => {
      await Taro.chooseImage({
        count: 1,
        sourceType: ["album", "camera"],
        success: (res) => {
          setLoading(true);
          const file = res.tempFiles[0];
          uploadFile(file.path)
            .then(({ url }) => {
              setSupplierVO({
                ...supplierVO!,
                totalWeightImg: url,
              });
              setLoading(false);
              Toast.show("toast", {
                title: "上传成功",
                icon: "success",
                content: "总磅照片已上传",
              });
            })
            .catch((err) => {
              Toast.show("toast", {
                title: "上传失败",
                icon: "fail",
                content: err.message || "上传过程中发生错误",
              });
              setLoading(false);
            });
        },
        fail: (err) => {
          Toast.show("toast", {
            title: "选择图片失败",
            icon: "fail",
            content: err.errMsg,
          });
        },
      });
    };

    // 检查是否有包装信息
    const hasPackageInfo = () => {
      return (
        supplierVO.orderPackageList && supplierVO.orderPackageList.length > 0
      );
    };

    // 处理装车方式切换
    const handleLoadingModeChange = (newLoadingMode: string) => {
      // 如果切换到"搭架子+网垫"且有包装信息，需要确认
      if (newLoadingMode === "FRAME_WITH_NET" && hasPackageInfo()) {
        setPendingLoadingMode(newLoadingMode);
        setLoadingModeConfirmVisible(true);
      } else {
        // 直接切换
        setSupplierVO({
          ...supplierVO,
          loadingMode: newLoadingMode as any,
        });
      }
    };

    // 确认切换装车方式并清空包装信息
    const confirmLoadingModeChange = () => {
      setLoadingModeConfirmVisible(false);
      setSupplierVO({
        ...supplierVO,
        loadingMode: pendingLoadingMode as any,
        orderPackageList: [], // 清空包装信息
      });
      Toast.show("toast", {
        title: "提示",
        icon: "success",
        content: "已切换装车方式并清空包装信息",
      });
    };

    // 取消切换装车方式
    const cancelLoadingModeChange = () => {
      setLoadingModeConfirmVisible(false);
      setPendingLoadingMode("");
    };

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

    if (!supplierVO) {
      return;
    }
    // 校验是否为最后一个瓜农函数
    const validateIsPaper = (isPaper: any) => {
      // 必须选择是或否
      return isPaper !== undefined && isPaper !== null;
    };

    // 校验西瓜品种
    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 validateEmptyWeight = (value: any) => {
      if (value === "" || value === undefined || value === null) {
        setEmptyWeightError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

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

      // 检查空磅重量是否小于总磅重量
      const totalWeight = Number(supplierVO.totalWeight);
      if (
        !Number.isNaN(totalWeight) &&
        totalWeight >= 0 &&
        numValue >= totalWeight
      ) {
        setEmptyWeightError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

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

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

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

      // 检查总磅重量是否大于空磅重量
      const emptyWeight = Number(supplierVO.emptyWeight);
      if (
        !Number.isNaN(emptyWeight) &&
        emptyWeight >= 0 &&
        numValue <= emptyWeight
      ) {
        setTotalWeightError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

      setTotalWeightError((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 validateDepositAmount = (
      isDepositPaid: boolean | undefined,
      depositAmount: number | undefined,
    ) => {
      // 如果选择了有定金，则必须填写定金金额且不能为0
      if (isDepositPaid === true) {
        if (
          depositAmount === undefined ||
          depositAmount === null ||
          depositAmount <= 0
        ) {
          setDepositError((prev) => ({
            ...prev,
            [supplierVO.orderSupplierId]: true,
          }));
          return false;
        }
      }

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

    // 校验是否选择包纸箱
    const validatePricingMethod = (pricingMethod: any) => {
      if (
        pricingMethod === undefined ||
        pricingMethod === null ||
        pricingMethod === ""
      ) {
        setPricingMethodError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

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

    // 校验是否选择是否付定金
    const validateIsDepositPaid = (isDepositPaid: any) => {
      if (isDepositPaid === undefined || isDepositPaid === null) {
        setIsDepositPaidError((prev) => ({
          ...prev,
          [supplierVO.orderSupplierId]: true,
        }));
        return false;
      }

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

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

      validateEmptyWeight(supplierVO.emptyWeight);
      const isTotalWeightValid = validateTotalWeight(supplierVO.totalWeight);
      const isPurchasePriceValid = validatePurchasePrice(
        supplierVO.purchasePrice,
      );
      const isPaperValid = validateIsPaper(supplierVO.isPaper);
      const isProductIdValid = validateProductId(supplierVO.productId);
      const isDepositAmountValid = validateDepositAmount(
        supplierVO.isDepositPaid,
        supplierVO.depositAmount,
      );
      const isPricingMethodValid = validatePricingMethod(
        supplierVO.pricingMethod,
      );
      const isDepositPaidValid = validateIsDepositPaid(
        supplierVO.isDepositPaid,
      );

      // 再次校验空磅重量（因为总磅重量可能影响空磅重量的校验结果）
      const isEmptyWeightValidAgain = validateEmptyWeight(
        supplierVO.emptyWeight,
      );

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

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

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

      setTotalWeightError((prev) => ({
        ...prev,
        [id]: !isTotalWeightValid,
      }));

      setEmptyWeightError((prev) => ({
        ...prev,
        [id]: !isEmptyWeightValidAgain,
      }));

      setDepositError((prev) => ({
        ...prev,
        [id]: !isDepositAmountValid,
      }));

      setPricingMethodError((prev) => ({
        ...prev,
        [id]: !isPricingMethodValid,
      }));

      setIsDepositPaidError((prev) => ({
        ...prev,
        [id]: !isDepositPaidValid,
      }));

      const isValid =
        isEmptyWeightValidAgain &&
        isTotalWeightValid &&
        isPurchasePriceValid &&
        isProductIdValid &&
        isPaperValid &&
        isDepositAmountValid &&
        isPricingMethodValid &&
        isDepositPaidValid;

      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,
                        });

                        changeProduct({
                          ...productObj,
                          name:
                            selectedProduct === "其他（请注明）"
                              ? customProduct
                              : productObj.name,
                        });
                      }

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

        {isFirst && (
          <>
            <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">空车过磅时带纸箱了吗？</View>
                <View className="text-neutral-darkest text-sm font-medium">
                  <Radio.Group
                    direction="horizontal"
                    value={
                      supplierVO.isPaper === true
                        ? "true"
                        : supplierVO.isPaper === false
                          ? "false"
                          : undefined
                    }
                    onChange={(value) => {
                      // 清除错误状态
                      setIsPaperError((prev) => ({
                        ...prev,
                        [supplierVO.orderSupplierId]: false,
                      }));

                      // 根据用户选择设置是否包含空纸箱
                      const isPaperValue =
                        value === "true"
                          ? true
                          : value === "false"
                            ? false
                            : undefined;
                      setSupplierVO({
                        ...supplierVO,
                        // @ts-ignore
                        isPaper: isPaperValue,
                      });

                      changePaper(isPaperValue!);
                    }}
                  >
                    <Radio value="true">带了</Radio>
                    <Radio value="false">没带</Radio>
                  </Radio.Group>
                </View>
              </View>
              {isPaperError[supplierVO.orderSupplierId] && (
                <View className="mt-1 text-xs text-red-500">
                  请选择空车过磅时有没有带纸箱
                </View>
              )}
            </View>

            {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,
                              });

                              changeProduct(productVO);
                            }
                          }
                        }}
                      >
                        <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>
                  )}
                  {/*装车方式 */}
                  {supplierVO.productName === "硒砂瓜" && (
                    <>
                      <View className="text-neutral-darkest text-sm font-medium">
                        装车方式
                      </View>
                      <View className="flex flex-row gap-4">
                        <View
                          className={`flex flex-1 flex-row items-center justify-center rounded-md py-2 ${
                            supplierVO.loadingMode === "FRAME_WITH_NET"
                              ? "bg-blue-100 text-blue-600"
                              : "border border-gray-300"
                          }`}
                          onClick={() => {
                            handleLoadingModeChange("FRAME_WITH_NET");
                          }}
                        >
                          搭架子+网垫
                        </View>
                        <View
                          className={`flex flex-1 flex-row items-center justify-center rounded-md py-2 ${
                            supplierVO.loadingMode === "BOX_WITH_TAPE"
                              ? "bg-blue-100 text-blue-600"
                              : "border border-gray-300"
                          }`}
                          onClick={() => {
                            handleLoadingModeChange("BOX_WITH_TAPE");
                          }}
                        >
                          纸箱+胶带+木隔板
                        </View>
                      </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) => {
                  // 清除错误状态
                  setPricingMethodError((prev) => ({
                    ...prev,
                    [supplierVO.orderSupplierId]: false,
                  }));

                  setSupplierVO({
                    ...supplierVO,
                    pricingMethod: value as any,
                  });
                }}
              >
                <Radio value="BY_GROSS_WEIGHT">包</Radio>
                <Radio value="BY_NET_WEIGHT">不包</Radio>
              </Radio.Group>
            </View>
          </View>
          {pricingMethodError[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={"flex flex-col gap-2.5"}>
            <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.isDepositPaid === true
                      ? "true"
                      : supplierVO.isDepositPaid === false
                        ? "false"
                        : undefined
                  }
                  onChange={(value) => {
                    // 清除错误状态
                    setIsDepositPaidError((prev) => ({
                      ...prev,
                      [supplierVO.orderSupplierId]: false,
                    }));

                    const isDepositPaidValue =
                      value === "true"
                        ? true
                        : value === "false"
                          ? false
                          : undefined;

                    setSupplierVO({
                      ...supplierVO,
                      // @ts-ignore
                      isDepositPaid: isDepositPaidValue,
                      // 如果选择了"有定金"，默认定金金额为0
                      ...(isDepositPaidValue === true && {
                        depositAmount: supplierVO.depositAmount ?? 0,
                      }),
                    });
                  }}
                >
                  <Radio value="true">付了</Radio>
                  <Radio value="false">没付</Radio>
                </Radio.Group>
              </View>
            </View>
            {isDepositPaidError[supplierVO.orderSupplierId] && (
              <View className="mt-1 text-xs text-red-500">
                请选择是否付定金
              </View>
            )}

            {supplierVO.isDepositPaid === true && (
              <>
                <View className="text-neutral-darkest text-sm font-medium">
                  本车需付多少订金
                </View>
                <View
                  className={`flex h-10 w-full items-center rounded-md ${depositError[supplierVO.orderSupplierId] ? "border-4 border-red-500" : "border-4 border-gray-300"}`}
                >
                  <Input
                    clearable
                    placeholder="0"
                    type="digit"
                    value={supplierVO.depositAmount?.toString()}
                    onChange={(value) => {
                      const numValue = validatePrice(value);
                      if (numValue !== undefined) {
                        setSupplierVO({
                          ...supplierVO,
                          depositAmount: numValue as any,
                        });
                        // 校验输入值
                        validateDepositAmount(true, numValue as any);
                      }
                    }}
                    onBlur={() => {
                      // 失去焦点时进行校验
                      validateDepositAmount(
                        supplierVO.isDepositPaid,
                        supplierVO.depositAmount,
                      );
                    }}
                  />
                  <View
                    className="text-gray-500"
                    style={{
                      padding: `var(--nutui-input-padding)`,
                    }}
                  >
                    元
                  </View>
                </View>
                {depositError[supplierVO.orderSupplierId] && (
                  <View className="mt-1 text-xs text-red-500">
                    请输入有效的定金金额(必须大于0)
                  </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">空磅重量 (kg)</View>
                </View>

                <View
                  className={`flex h-10 w-full items-center rounded-md ${emptyWeightError[supplierVO.orderSupplierId] ? "border-4 border-red-500" : "border-4 border-blue-300"}`}
                >
                  <Input
                    clearable
                    placeholder="0"
                    type="digit"
                    value={supplierVO.emptyWeight?.toString()}
                    onChange={(value) => {
                      const numValue = validatePrice(value);
                      if (numValue !== undefined) {
                        setSupplierVO({
                          ...supplierVO,
                          emptyWeight: numValue as any,
                        });
                        // 校验输入值
                        validateEmptyWeight(numValue);
                      }
                    }}
                    onBlur={() => {
                      // 失去焦点时进行校验
                      validateEmptyWeight(supplierVO.emptyWeight);
                    }}
                  />
                  <View
                    className="text-gray-500"
                    style={{
                      padding: `var(--nutui-input-padding)`,
                    }}
                  >
                    kg
                  </View>
                </View>
                {emptyWeightError[supplierVO.orderSupplierId] && (
                  <View className="mt-1 text-xs text-red-500">
                    请输入有效的空磅重量，必须小于总磅重量
                  </View>
                )}
                <View className="mt-2.5 flex flex-row text-xs text-blue-600">
                  <Icon
                    name={"circle-info"}
                    className="mr-1"
                    color={"rgb(--color-blue-600)"}
                    size={12}
                  />
                  <View>自动带入上一个瓜农的总磅重量</View>
                </View>
              </View>

              <View className="flex-1 rounded-lg bg-green-50 p-2.5">
                <View className="mb-2.5 flex items-center">
                  <Icon
                    name={"weight-scale"}
                    className="mr-2"
                    size={20}
                    color={"var(--color-green-300)"}
                  />
                  <View className="text-sm text-gray-700">总磅重量 (kg)</View>
                </View>

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

            {/* 照片上传区域 */}
            <View className="flex flex-row gap-2.5">
              {/* 空磅照片上传 */}
              <View className="flex-1">
                {supplierVO.emptyWeightImg ? (
                  <View className="flex flex-col gap-2.5 rounded-lg bg-blue-50 p-2.5">
                    <View className="flex items-center">
                      <View className="relative mr-3 h-16 w-16 overflow-hidden rounded-lg">
                        <Image
                          className="h-full w-full object-cover"
                          src={supplierVO.emptyWeightImg}
                        />
                      </View>
                      <View className="flex-1">
                        <View className="text-sm font-medium text-blue-700">
                          空磅照片
                        </View>
                        <View className="text-xs text-blue-600">
                          已拍摄完成
                        </View>
                      </View>
                    </View>
                    <View className="flex flex-row gap-2.5">
                      <View className={"flex-1"}>
                        <Button
                          type={"primary"}
                          size={"small"}
                          fill={"outline"}
                          block
                          onClick={handleEmptyWeightImgUpload}
                        >
                          <View className="text-xs">重新拍摄</View>
                        </Button>
                      </View>
                    </View>
                  </View>
                ) : (
                  <View
                    className={
                      "flex h-24 flex-1 flex-col items-center justify-center rounded-md border-2 border-dashed border-blue-300 bg-blue-50 p-2.5"
                    }
                    onClick={handleEmptyWeightImgUpload}
                  >
                    <Icon name={"camera"} size={24} />
                    <View className="text-xs font-medium text-blue-700">
                      拍照上传
                    </View>
                    <View className="text-neutral-darker mt-1 text-xs">
                      空磅照片
                    </View>
                  </View>
                )}
              </View>

              {/* 总磅照片上传 */}
              <View className="flex-1">
                {supplierVO.totalWeightImg ? (
                  <View className="flex flex-col gap-2.5 rounded-lg bg-green-50 p-2.5">
                    <View className="flex items-center">
                      <View className="relative mr-3 h-16 w-16 overflow-hidden rounded-lg">
                        <Image
                          className="h-full w-full object-cover"
                          src={supplierVO.totalWeightImg}
                        />
                      </View>
                      <View className="flex-1">
                        <View className="text-sm font-medium text-green-700">
                          总磅照片
                        </View>
                        <View className="text-xs text-green-600">
                          已拍摄完成
                        </View>
                      </View>
                    </View>
                    <View className="flex flex-row gap-2.5">
                      <View className={"flex-1"}>
                        <Button
                          type={"primary"}
                          size={"small"}
                          fill={"outline"}
                          block
                          onClick={handleTotalWeightImgUpload}
                        >
                          <View className="text-xs">重新拍摄</View>
                        </Button>
                      </View>
                    </View>
                  </View>
                ) : (
                  <View
                    className={
                      "flex h-24 flex-1 flex-col items-center justify-center rounded-md border-2 border-dashed border-green-300 bg-green-50 p-2.5"
                    }
                    onClick={handleTotalWeightImgUpload}
                  >
                    <Icon name={"camera"} size={24} />
                    <View className="text-xs font-medium text-green-700">
                      拍照上传
                    </View>
                    <View className="text-neutral-darker mt-1 text-xs">
                      总磅照片
                    </View>
                  </View>
                )}
              </View>
            </View>
          </View>
        </View>

        {/* 装车方式切换确认对话框 */}
        <Dialog
          visible={loadingModeConfirmVisible}
          title="装车方式切换确认"
          content="检测到已经录入包装信息，切换到搭架子+网垫将会清空所有包装信息，是否确认切换？"
          onCancel={cancelLoadingModeChange}
          onConfirm={confirmLoadingModeChange}
        />
      </View>
    );
  },
);
