import { View } from "@tarojs/components";
import { Button, Dialog, SafeArea, Toast } from "@nutui/nutui-react-taro";
import React, { forwardRef, useImperativeHandle } from "react";
import { globalStore } from "@/store/global-store";
import Taro from "@tarojs/taro";
import { buildUrl, generateShortId } from "@/utils";
import { business } from "@/services";
import purchase from "@/constant/purchase";

// 定义ref暴露的方法接口
export interface MarketOptionRef {
  onAdd: () => void;
  scrollToTop: () => void;
}

interface IMarketOptionProps {
  value: BusinessAPI.OrderVO;
  onChange: (orderVO: BusinessAPI.OrderVO) => void;

  vehicleRef: React.MutableRefObject<any>;
  stallInfoRefs: React.MutableRefObject<any[]>;
  stallWeighRefs: React.MutableRefObject<any[]>;
  stallPackageRefs: React.MutableRefObject<any[]>;
}

export default forwardRef<MarketOptionRef, IMarketOptionProps>(
  function MarketOption(props: IMarketOptionProps, ref) {
    const {
      value,
      onChange,

      vehicleRef,
      stallInfoRefs,
      stallWeighRefs,
      stallPackageRefs,
    } = props;

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

    const active = Number(value.active);

    // 滚动到页面顶部
    const scrollToTop = () => {
      Taro.pageScrollTo({
        scrollTop: 0,
        duration: 100,
      });
    };
    const setActive = (active: number) => {
      scrollToTop();
      onChange({
        ...value,
        active,
      });
    };

    // 车辆信息和经销商信息的保存
    const saveVehicleAndDealerInfo = async () => {
      if (!value) {
        Toast.show("toast", {
          icon: "warn",
          title: "提示",
          content: "保存失败",
        });
        return false;
      }

      try {
        let tempOrderId = value.orderId;
        if (tempOrderId) {
          const { data } = await business.order.saveOrderStep1({
            orderId: tempOrderId,
            active: active,
            type: "MARKET_PURCHASE",
            orderVehicle: value.orderVehicle,
            orderDealer: value.orderDealer,
          });

          if (data.success) {
            return true;
          } else {
            Toast.show("toast", {
              icon: "warn",
              title: "提示",
              content: data?.errMessage || "保存失败",
            });
            return false;
          }
        } else {
          const { data } = await business.order.saveOrderStep1({
            active: active,
            type: "MARKET_PURCHASE",
            orderVehicle: value.orderVehicle,
            orderDealer: value.orderDealer,
          });

          if (data.success) {
            onChange({
              ...value,
              orderId: data.data?.orderId!,
            });
            return true;
          } else {
            Toast.show("toast", {
              icon: "warn",
              title: "提示",
              content: data?.errMessage || "保存失败",
            });
            return false;
          }
        }
      } catch (error) {
        Toast.show("toast", {
          icon: "fail",
          title: "提示",
          content: "保存失败",
        });
        console.error("保存车辆和经销商信息失败:", error);
        return false;
      }
    };

    // 供应商信息的保存（基础信息，称重信息，包材信息）
    const saveSupplierInfo = async () => {
      if (!value || !value.orderId) {
        Toast.show("toast", {
          icon: "warn",
          title: "提示",
          content: "保存失败",
        });
        return false;
      }

      try {
        const { data } = await business.order.saveOrderStep2({
          orderId: value.orderId,
          active: active,
          type: "MARKET_PURCHASE",
          orderSupplierList: value.orderSupplierList,
        });

        if (data.success) {
          return true;
        } else {
          Toast.show("toast", {
            icon: "warn",
            title: "提示",
            content: data?.errMessage || "保存失败",
          });
          return false;
        }
      } catch (error) {
        Toast.show("toast", {
          icon: "fail",
          title: "提示",
          content: "保存失败",
        });
        console.error("保存供应商信息失败:", error);
        return false;
      }
    };

    const onFinish = async () => {
      // 只保存供应商信息
      const costSuccess = await saveSupplierInfo();
      if (!costSuccess) {
        Dialog.close("dialog");
        return;
      }

      // 跳转到预览页面
      Taro.redirectTo({
        url: buildUrl("/pages/purchase/market/preview", {
          orderId: value.orderId,
        }),
      });
    };

    const onAdd = () => {
      saveSupplierInfo();
      const orderSupplierList = value?.orderSupplierList;
      // 获取当前选中的供应商
      const selectedIndex = orderSupplierList?.findIndex(
        (supplier) => supplier.selected,
      );
      if (active === 2 && !stallInfoRefs.current[selectedIndex]?.validate()) {
        return;
      }
      // 在第三步（称重信息）时进行校验
      else if (
        active === 3 &&
        !stallWeighRefs.current[selectedIndex]?.validate()
      ) {
        return;
      } // 在第四步（包装信息）时进行校验
      else if (
        active === 4 &&
        !stallPackageRefs.current[selectedIndex]?.validate()
      ) {
        return;
      }

      scrollToTop();
      onChange({
        ...value,
        active: 2,
        orderSupplierList: [
          ...orderSupplierList.map((supplierVO: BusinessAPI.OrderSupplier) => {
            supplierVO.selected = false;
            return supplierVO;
          }),
          {
            orderSupplierId: generateShortId(),
            supplierId: "",
            name: "档口" + (orderSupplierList.length + 1),
            type: "OTHER_STALL",
            payeeName: "",
            idCard: "",
            bankName: "",
            bankCard: "",
            phone: "",
            selected: true,
            loadingMode: orderSupplierList[selectedIndex].loadingMode,
            pricingMethod: orderSupplierList[selectedIndex].pricingMethod,
            orderPackageList: [],
            productId: orderSupplierList[selectedIndex]?.productId,
            productName: orderSupplierList[selectedIndex]?.productName,
            costTemplate: orderSupplierList[selectedIndex]?.costTemplate,
          } as any,
        ],
      });
    };

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

    async function saveDraft() {
      Dialog.open("dialog", {
        title: "暂存确认",
        content: "确定要暂存当前采购订单吗？",
        confirmText: "确认暂存",
        cancelText: "取消",
        onConfirm: async () => {
          // 按步骤调用保存接口进行暂存
          let success = true;

          // 保存第一步车辆和经销商信息
          if (active == 1) {
            success = await saveVehicleAndDealerInfo();
          }

          // 保存第二到第五步的供应商信息
          if (success && active >= 2 && active <= 5) {
            success = await saveSupplierInfo();
          }

          Dialog.close("dialog");

          if (success) {
            Toast.show("toast", {
              icon: "success",
              title: "提示",
              content: "当前采购订单已暂存成功",
            });
            Taro.redirectTo({
              url: purchase.path["MARKET_PURCHASE"].drafts,
            });
          }
        },
        onCancel: () => {
          Dialog.close("dialog");
        },
      });
    }

    if (!active) {
      return;
    }

    return (
      <View className={"sticky bottom-0 z-10 bg-white"}>
        <View className="flex justify-between gap-2 border-t border-gray-200 p-2.5">
          {active > 1 && active <= purchase.marketSteps.length - 1 && (
            <View className={"flex-1"}>
              <Button
                block
                type={"default"}
                size={"large"}
                onClick={() => {
                  if (active > 1) {
                    if (active === 5) {
                      // 获取当前选中的供应商
                      const selectedIndex = orderSupplierList.findIndex(
                        (supplier) => supplier.selected,
                      );
                      if (
                        orderSupplierList[selectedIndex].loadingMode ===
                        "FRAME_WITH_NET"
                      ) {
                        setActive(active - 2);
                      } else {
                        setActive(active - 1);
                      }
                    } else {
                      setActive(active - 1);
                    }
                  }
                }}
              >
                上一步
              </Button>
            </View>
          )}

          {active >= 1 && active <= purchase.marketSteps.length - 1 && (
            <View className={"flex-1"}>
              <Button
                block
                type={"default"}
                size={"large"}
                onClick={async () => {
                  await saveDraft();
                }}
              >
                暂存
              </Button>
            </View>
          )}

          {active < purchase.marketSteps.length - 1 && (
            <View className={"flex-1"}>
              <Button
                block
                type={"primary"}
                size={"large"}
                className="bg-primary flex-1 text-white"
                onClick={async () => {
                  setLoading(true);
                  // 在第一步（车辆信息）时进行校验
                  if (active === 1) {
                    if (vehicleRef.current?.validate()) {
                      const success = await saveVehicleAndDealerInfo();
                      if (success) {
                        setActive(active + 1);
                      }
                    }
                  }
                  // 在第二步（档口信息）时进行校验
                  else if (active === 2) {
                    // 获取当前选中的供应商
                    const selectedIndex = orderSupplierList.findIndex(
                      (supplier) => supplier.selected,
                    );
                    if (
                      selectedIndex !== -1 &&
                      stallInfoRefs.current[selectedIndex]?.validate()
                    ) {
                      const success = await saveSupplierInfo();
                      if (success) {
                        setActive(active + 1);
                      }
                    }
                  }
                  // 在第三步（称重信息）时进行校验
                  else if (active === 3) {
                    // 获取当前选中的供应商
                    const selectedIndex = orderSupplierList.findIndex(
                      (supplier) => supplier.selected,
                    );
                    if (
                      selectedIndex !== -1 &&
                      stallWeighRefs.current[selectedIndex]?.validate()
                    ) {
                      const success = await saveSupplierInfo();
                      if (success) {
                        // 判断装箱方式
                        if (
                          orderSupplierList[selectedIndex].loadingMode ===
                          "FRAME_WITH_NET"
                        ) {
                          setActive(active + 2);
                        } else {
                          setActive(active + 1);
                        }
                      }
                    }
                  } // 在第四步（包装信息）时进行校验
                  else if (active === 4) {
                    // 获取当前选中的供应商
                    const selectedIndex = orderSupplierList.findIndex(
                      (supplier) => supplier.selected,
                    );
                    if (
                      selectedIndex !== -1 &&
                      stallPackageRefs.current[selectedIndex]?.validate()
                    ) {
                      const success = await saveSupplierInfo();
                      if (success) {
                        setActive(active + 1);
                      }
                    }
                  } // 在第五步（票证上传）时进行校验
                  else if (active === 5) {
                    const success = await saveSupplierInfo();
                    if (success) {
                      setActive(active + 1);
                    }
                  } else {
                    setActive(active + 1);
                  }
                  setLoading(false);
                }}
              >
                下一步
              </Button>
            </View>
          )}
          {active == purchase.marketSteps.length - 1 && (
            <>
              <View className={"flex-1"}>
                <Button
                  block
                  type={"primary"}
                  size={"large"}
                  className="btn-large bg-primary ml-2 flex-1 text-white"
                  onClick={async () => {
                    setLoading(true);
                    // 第六步（人工辅料费用）时进行校验
                    await onFinish();
                    setLoading(false);
                  }}
                >
                  预览
                </Button>
              </View>
            </>
          )}
        </View>
        <SafeArea position={"bottom"} />
      </View>
    );
  },
);
