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

export interface IOrderPackageProps {
  orderPackageList: BusinessAPI.OrderPackage[];
  onChange: (orderPackageList: BusinessAPI.OrderPackage[]) => void;
}

export default function OrderPackage(props: IOrderPackageProps) {
  const { orderPackageList, onChange } = props;

  const [hasEmptyBox, setHasEmptyBox] = useState(false);
  const [boxBrandList, setBoxBrandList] = useState<BoxBrand[]>();

  // 初始化空箱品牌数据
  const initBoxBrandList = async () => {
    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);
  };

  // 当传入的value发生变化时，重新初始化列表
  useEffect(() => {
    initBoxBrandList().then();

    if (orderPackageList?.length > 0) {
      setHasEmptyBox(true);
    }
  }, []);

  console.log("orderPackageList", orderPackageList);

  return (
    <View className={"flex flex-1 flex-col gap-2.5"}>
      <View className="bg-primary/10 flex flex-col gap-2.5 rounded-lg p-2.5 text-sm text-gray-600">
        <View className="flex flex-col gap-2.5">
          <View className="flex items-center justify-between">
            <View className="block text-sm font-normal text-[#000000]">
              带空箱了吗？
            </View>
            <View className="flex flex-row items-center">
              <Checkbox
                className={"flex flex-row items-center"}
                checked={hasEmptyBox}
                onChange={(checked) => {
                  setHasEmptyBox(checked);
                  if (!checked) {
                    onChange([]);
                  }
                }}
              >
                <View className={"text-sm font-normal text-[#000000]"}>
                  带了
                </View>
              </Checkbox>
            </View>
          </View>

          {/* 空箱信息展示 */}
          {hasEmptyBox && (
            <PackageList
              boxType={"EMPTY"}
              orderPackageList={orderPackageList}
              setOrderPackageList={onChange}
              boxBrandList={boxBrandList}
            />
          )}
        </View>
      </View>
    </View>
  );
}
