import { View } from "@tarojs/components";
import { Toast } from "@nutui/nutui-react-taro";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { business } from "@/services";
import { BoxBrand, BoxProduct, BoxSpec } from "@/types/typings";
import { generateShortId } from "@/utils";
import { PackageList } from "@/components";
import { globalStore } from "@/store/global-store";

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

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

export default forwardRef<StallPackageRef, IStallPackageProps>(
  function StallPackage(props, ref) {
    const { value, onChange, index } = props;

    const { setLoading } = globalStore((state: any) => state);
    const { orderSupplierList } = value;
    const supplierVO = orderSupplierList[index];
    const orderPackageList =
      supplierVO.orderPackageList as BusinessAPI.OrderPackage[];

    const setOrderPackageList = (
      orderPackageList: BusinessAPI.OrderPackage[],
    ) => {
      onChange?.({
        ...value,
        orderSupplierList: orderSupplierList.map((item, index1) => {
          if (index1 === index) {
            return {
              ...item,
              orderPackageList,
            };
          }
          return item;
        }),
      });
    };

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

    // 校验函数
    const validate = () => {
      // 根据当前供应商确定需要检查的纸箱类型
      const hasPackagesOfType = orderPackageList.some(
        (item) => item.boxType === "USED",
      );

      if (!hasPackagesOfType) {
        Toast.show("toast", {
          icon: "fail",
          title: "提示",
          content: `已选择使用记录装车用的纸箱，请添加对应的纸箱信息`,
        });
        return false;
      }

      return true;
    };

    // 纸箱品牌数据
    const [boxBrandList, setBoxBrandList] = useState<BoxBrand[]>();

    const initBoxBrandList = async () => {
      setLoading(true);
      const { data } = await business.boxBrand.listBoxBrand({
        boxBrandListQry: {
          status: true,
          withProduct: true,
        },
      });

      const boxBrandList =
        data.data
          ?.filter(
            (boxBrand) =>
              boxBrand.status &&
              boxBrand.boxProductVOList &&
              boxBrand.boxProductVOList.length > 0,
          )
          .map((boxBrand) => {
            // 将产品按规格分类
            const boxSpecList: BoxSpec[] =
              boxBrand.boxSpecVOList?.map((item) => {
                return {
                  id: generateShortId(),
                  boxSpecId: item.specId,
                  boxSpecName: item.name,
                  boxProductList: [],
                };
              }) || [];
            const boxProductList = boxBrand.boxProductVOList?.map(
              (boxProductVO) => {
                const boxProduct: BoxProduct = {
                  id: generateShortId(),
                  boxProductId: boxProductVO.productId,
                  boxProductName: boxProductVO.name,
                  boxProductWeight: boxProductVO.weight,
                  boxSpecId: boxProductVO.specId,
                  boxSpecName: boxProductVO.specName,
                  boxCostPrice: boxProductVO.costPrice,
                  boxSalePrice: boxProductVO.salePrice,
                  boxBrandId: boxBrand.brandId,
                  boxBrandName: boxBrand.name,
                  boxCount: 0,
                };

                return boxProduct;
              },
            );

            return {
              id: generateShortId(),
              boxBrandId: boxBrand.brandId,
              boxBrandName: boxBrand.name,
              boxBrandImage: boxBrand.image,
              boxBrandType: boxBrand.type,
              boxSpecList:
                boxSpecList
                  .map((boxSpec) => {
                    return {
                      id: generateShortId(),
                      boxSpecId: boxSpec.boxSpecId,
                      boxSpecName: boxSpec.boxSpecName,
                      boxProductList:
                        boxProductList?.filter(
                          (boxProduct) =>
                            boxProduct.boxSpecId === boxSpec.boxSpecId,
                        ) || [],
                    };
                  })
                  .filter(
                    (boxSpec) =>
                      boxSpec.boxProductList &&
                      boxSpec.boxProductList.length > 0,
                  ) || [],
            };
          }) || [];

      setBoxBrandList(boxBrandList as any);
      setLoading(false);
    };

    useEffect(() => {
      initBoxBrandList().then();
    }, []);

    return (
      <View className="flex flex-1 flex-col gap-2.5 p-2.5">
        {/* 替换原来的Tab导航为问答式选择 */}
        <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">
              {supplierVO.name}装车的纸箱使用情况
            </View>

            <PackageList
              boxType={"USED"}
              orderPackageList={orderPackageList}
              setOrderPackageList={setOrderPackageList}
              boxBrandList={boxBrandList}
            />
          </View>
        </View>
      </View>
    );
  },
);
