import hocAuth from "@/hocs/auth";
import { CommonComponent } from "@/types/typings";
import { View } from "@tarojs/components";
import { useEffect, useRef, useState } from "react";
import {
  Icon,
  MadeOptionRef,
  MarketOption,
  OrderVehicle,
  OrderVehicleRef,
  StallInfo,
  StallInfoRef,
  StallList,
  StallPackage,
  StallPackageRef,
  StallWeigh,
  StallWeighRef,
  SupplierPackageRef,
} from "@/components";
import { business } from "@/services";
import { buildUrl, generateShortId } from "@/utils";
import Taro from "@tarojs/taro";
import { Button } from "@nutui/nutui-react-taro";
import { WeightCalculationService } from "@/utils/classes/calculators";
import { purchase } from "@/constant";

const defaultSupplierList: Partial<BusinessAPI.OrderSupplier>[] = [
  {
    orderSupplierId: generateShortId(),
    supplierId: "",
    name: "档口1",
    type: "OTHER_STALL",
    payeeName: "",
    idCard: "",
    bankCard: "",
    phone: "",
    selected: true,
    wechatQr: "",
    isLast: undefined,

    // 空磅是否包含纸箱
    isPaper: false,
    // 默认按照毛重报价
    pricingMethod: "BY_GROSS_WEIGHT",
    // 空磅重量
    emptyWeight: undefined,
    // 总磅重量
    totalWeight: undefined,
    // 采购单价
    purchasePrice: undefined,
    // 空磅照片
    emptyWeightImg: "",
    // 总磅照片
    totalWeightImg: "",
    orderPackageList: [],
    packageUsage: [
      {
        boxType: "USED",
        isUsed: 0,
      },
    ],
  },
];

export default hocAuth(function Page(props: CommonComponent) {
  const { router, userRoleVO, setLoading } = props;

  const orderId = router.params.orderId as string;
  const defaultStep = router.params.step as number;
  const defaultActive = router.params.active as number;
  const defaultSupplierId = router.params.supplierId as string;
  const defaultOrderSupplierId = router.params.orderSupplierId as string;
  const auditId = router.params.auditId as BusinessAPI.AuditVO["auditId"];

  const orderOptionRef = useRef<MadeOptionRef>(null);
  const vehicleRef = useRef<OrderVehicleRef>(null);
  // 创建MelonStall组件的ref数组
  const stallInfoRefs = useRef<StallInfoRef[]>([]);
  // 创建Weigh组件的ref数组
  const stallWeighRefs = useRef<StallWeighRef[]>([]);
  // 创建OrderPackage组件的ref
  const stallPackageRefs = useRef<StallPackageRef[]>([]);

  const [orderVO, setOrderVO] = useState<BusinessAPI.OrderVO>();
  const [auditVO, setAuditVO] = useState<BusinessAPI.AuditVO>();

  useEffect(() => {
    if (auditId) {
      business.audit
        .showAudit({
          auditShowQry: {
            auditId,
          },
        })
        .then(({ data: { data: auditVO, success: auditSuccess } }) => {
          if (auditSuccess && auditVO) {
            setAuditVO(auditVO);
          }
        });
    }
  }, [auditId]);

  const [step, setStep] = useState<any>();

  useEffect(() => {
    if (orderId) {
      setLoading(true);
      business.order
        .showOrder({
          orderShowQry: {
            orderId: orderId,
            type: "MARKET_PURCHASE",
          },
        })
        .then(({ data: { data: orderVO, success } }) => {
          if (success && orderVO) {
            // 如果订单状态不是草稿，则跳转到预览页面
            if (orderVO.state !== "DRAFT") {
              if (userRoleVO.slug === "market-buyer") {
                Taro.redirectTo({
                  url: buildUrl("/pages/purchase/market/preview", {
                    orderId: orderVO.orderId,
                  }),
                });
                return;
              }
              if (userRoleVO.slug === "reviewer") {
                Taro.redirectTo({
                  url: buildUrl("/pages/audit/audit", {
                    orderId: orderVO.orderId,
                  }),
                });
                return;
              }
              if (userRoleVO.slug === "boss") {
                Taro.redirectTo({
                  url: buildUrl("/pages/approval/audit", {
                    orderId: orderVO.orderId,
                  }),
                });
                return;
              }
            }

            if (
              !(
                orderVO.orderSupplierList &&
                orderVO.orderSupplierList.length > 0
              )
            ) {
              orderVO.orderSupplierList = defaultSupplierList as any;
            }
            setOrderVO(orderVO);
            const orderSupplierList1 =
              orderVO.orderSupplierList || ([defaultSupplierList] as any);
            if (defaultOrderSupplierId) {
              const index = orderSupplierList1.findIndex(
                (item: any) => item.orderSupplierId === defaultOrderSupplierId,
              );
              orderSupplierList1[index].selected = true;
            } else {
              orderSupplierList1[0].selected = true;
            }

            console.log("defaultStep", defaultStep);
            let active: number;
            if (defaultActive) {
              active = defaultActive;
            } else if (defaultStep) {
              active = defaultStep;
            } else {
              active = orderVO.active || 1;
              if (active < 1 || active > purchase.marketSteps.length - 1) {
                active = 1;
              }
            }

            setOrderVO({
              ...orderVO,
              active:
                active > purchase.marketSteps.length - 1
                  ? purchase.marketSteps.length - 1
                  : active,
              orderSupplierList: orderSupplierList1,
              orderCostList: orderVO.orderCostList?.map((item) => {
                return {
                  ...item,
                  selected: true,
                };
              }),
              orderCostItemList: orderVO.orderCostItemList?.map((item) => {
                return {
                  ...item,
                  selected: true,
                };
              }),
            });
          }
        })
        .catch((err) => {
          console.error("获取调货订单失败:", err);
        })
        .finally(() => {
          setLoading(false);
        });
    } else {
      setOrderVO({
        ...orderVO!,
        active: 1,
        orderSupplierList: defaultSupplierList as any,
        type: "MARKET_PURCHASE",
      });
    }
  }, [orderId]);

  useEffect(() => {
    setStep(purchase.marketSteps[orderVO?.active! - 1]);
  }, [orderVO?.active]);

  const setOrderSupplierList = (
    orderSupplierList: BusinessAPI.OrderSupplier[],
  ) => {
    setOrderVO((prev) => ({
      ...prev!,
      orderSupplierList,
    }));
  };

  useEffect(() => {
    if (defaultSupplierId) {
      setLoading(true);
      business.supplier
        .showSupplier({
          supplierShowQry: {
            supplierId: defaultSupplierId,
          },
        })
        .then(({ data: { data: supplierVO } }) => {
          if (supplierVO) {
            setOrderSupplierList([
              {
                orderSupplierId: generateShortId(),
                ...supplierVO,
                selected: true,
              } as any,
            ]);
          }
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [defaultSupplierId]);

  if (step === undefined) {
    return;
  }

  return (
    <>
      <View className={"sticky top-0 z-11"}>
        {auditVO?.state === "AUDIT_REJECTED" && (
          <View className="flex flex-col gap-2 bg-red-50 p-3">
            <View className="flex items-center gap-2">
              <Icon name="exclamation" color="red" size={16} />
              <View className="text-base font-bold text-red-700">驳回原因</View>
            </View>
            <View className="pl-6 text-sm text-red-600">
              {auditVO?.auditReason || "暂无驳回原因"}
            </View>
          </View>
        )}
        {step.value < purchase.marketSteps.length && (
          <View className="h-12 bg-white p-2.5 shadow-sm">
            <View className="step-indicator flex h-2 rounded-full bg-gray-200">
              <View
                className="bg-primary rounded-full"
                style={`width: ${(100 / purchase.marketSteps.length) * step.value}%`}
              ></View>
            </View>
            <View className="mt-1 text-sm font-bold text-[#000000]">
              {step.title.replace("{}", purchase.marketSteps.length - 1)}
            </View>
          </View>
        )}

        {step.value >= 2 && step.value <= 4 && (
          <StallList
            value={orderVO as any}
            onChange={(orderVO: BusinessAPI.OrderVO) => {
              setOrderVO(orderVO);
            }}
            melonStallRefs={stallInfoRefs}
            weighRefs={stallWeighRefs}
            orderPackageRefs={stallPackageRefs}
          />
        )}
      </View>

      <View className={"flex flex-1 flex-col bg-[#D1D5DB]"}>
        {/* 车辆信息 */}
        {step.value === 1 && (
          <OrderVehicle
            value={orderVO as any}
            onChange={(orderVO: BusinessAPI.OrderVO) => {
              setOrderVO((prev) => {
                return {
                  ...prev!,
                  ...orderVO,
                };
              });
            }}
            ref={vehicleRef}
          />
        )}

        {/* 瓜农信息 */}
        {orderVO?.orderSupplierList?.map(
          (item: BusinessAPI.OrderSupplier, index) => {
            if (!item.selected) {
              return;
            }

            if (step.value === 2) {
              // 确保ref数组足够长
              while (stallInfoRefs.current.length <= index) {
                stallInfoRefs.current.push({
                  validate: () => true, // 默认验证方法
                } as StallInfoRef);
              }

              return (
                <StallInfo
                  index={index}
                  key={item.orderSupplierId}
                  value={orderVO as any}
                  onChange={(orderVO: BusinessAPI.OrderVO) => {
                    setOrderVO((prev) => {
                      return {
                        ...prev!,
                        ...orderVO,
                        orderSupplierList:
                          WeightCalculationService.calculateWeights(
                            orderVO?.orderSupplierList,
                          ),
                      };
                    });
                  }}
                  ref={(ref) => {
                    if (ref) {
                      stallInfoRefs.current[index] = ref;
                    }
                  }}
                />
              );
            }

            // 称重信息
            if (step.value === 3) {
              // 确保ref数组足够长
              while (stallWeighRefs.current.length <= index) {
                stallWeighRefs.current.push({
                  validate: () => true, // 默认验证方法
                } as StallWeighRef);
              }

              return (
                <StallWeigh
                  index={index}
                  key={item.orderSupplierId}
                  value={orderVO as any}
                  onChange={(orderVO: BusinessAPI.OrderVO) => {
                    setOrderVO((prev) => {
                      return {
                        ...prev!,
                        ...orderVO,
                        orderSupplierList:
                          WeightCalculationService.calculateWeights(
                            orderVO?.orderSupplierList,
                          ),
                      };
                    });
                  }}
                  ref={(ref) => {
                    if (ref) {
                      stallWeighRefs.current[index] = ref;
                    }
                  }}
                />
              );
            }

            // 包装信息
            if (step.value === 4) {
              // 确保ref数组足够长
              while (stallPackageRefs.current.length <= index) {
                stallPackageRefs.current.push({
                  validate: () => true, // 默认验证方法
                } as SupplierPackageRef);
              }

              return (
                <StallPackage
                  index={index}
                  key={item.orderSupplierId}
                  value={orderVO as any}
                  onChange={(orderVO: BusinessAPI.OrderVO) => {
                    setOrderVO((prev) => {
                      return {
                        ...prev!,
                        ...orderVO,
                        orderSupplierList:
                          WeightCalculationService.calculateWeights(
                            orderVO.orderSupplierList,
                          ),
                      };
                    });
                  }}
                  ref={(ref) => {
                    if (ref) {
                      stallPackageRefs.current[index] = ref;
                    }
                  }}
                />
              );
            }
          },
        )}

        {step.value === 4 &&
          !orderVO?.orderSupplierList[orderVO?.orderSupplierList.length - 1]
            ?.isLast && (
            <View className="flex flex-col gap-2.5 bg-[#D1D5DB] p-2.5">
              <View className={"flex flex-1 flex-col gap-2.5"}>
                <View className="text-sm font-bold">快捷操作</View>
                <Button
                  icon={<Icon name={"plus"} size={20} />}
                  type={"primary"}
                  size={"large"}
                  fill={"outline"}
                  block
                  className="border-primary text-primary flex w-full items-center justify-center !border-4 !bg-white"
                  onClick={() => {
                    orderOptionRef.current?.onAdd();
                  }}
                >
                  <View>添加另一个档口</View>
                </Button>
              </View>
            </View>
          )}

        {/* 按钮操作 */}
        <MarketOption
          ref={orderOptionRef}
          value={orderVO as any}
          onChange={(orderVO: BusinessAPI.OrderVO) =>
            setOrderVO((prev) => {
              return {
                ...prev!,
                ...orderVO,
              };
            })
          }
          vehicleRef={vehicleRef}
          stallInfoRefs={stallInfoRefs}
          stallWeighRefs={stallWeighRefs}
          stallPackageRefs={stallPackageRefs}
        />
      </View>
    </>
  );
});
