import { Button, ButtonSize, Dialog, Toast } from "@nutui/nutui-react-taro";
import { business } from "@/services";
import Taro from "@tarojs/taro";
import { buildUrl } from "@/utils";

interface ITransferOrderSubmitReviewProps {
  purchaseOrderVO: BusinessAPI.PurchaseOrderVO;
  size?: ButtonSize;
  onFinish?: () => void;
}

export default function TransferOrderSubmitReview(
  props: ITransferOrderSubmitReviewProps,
) {
  const { purchaseOrderVO, size = "normal", onFinish } = props;

  const onSubmit = async () => {
    if (!purchaseOrderVO || !purchaseOrderVO.orderId) {
      Toast.show("toast", {
        icon: "warn",
        title: "提示",
        content: "提交失败",
      });
      return;
    }

    let success = false;
    let errMessage = "";
    try {
      // 更新成功后再提交审核
      const { data } = await business.purchaseOrder.submitReviewPurchaseOrder({
        orderId: purchaseOrderVO.orderId,
      });

      if (data.success) {
        success = data.success;
      } else {
        errMessage = data?.errMessage || "";
      }

      if (success) {
        Toast.show("toast", {
          icon: "success",
          title: "提示",
          content: "提交成功",
        });
        // 可以在这里添加跳转逻辑，例如返回列表页
        onFinish?.();
      } else {
        Toast.show("toast", {
          icon: "warn",
          title: "提示",
          content: "提交失败",
        });
        console.error("提交调货订单失败:", errMessage);
      }
    } catch (error) {
      Toast.show("toast", {
        icon: "fail",
        title: "提示",
        content: "提交失败",
      });
      console.error("提交调货订单失败:", error);
    }
  };

  return (
    <Button
      block
      type={"primary"}
      size={size}
      className="btn-large bg-primary ml-2 flex-1 text-white"
      onClick={async (e) => {
        // 检查是否已标记最后一个供应商
        const hasLastSupplier = purchaseOrderVO.orderSupplierList?.some(
          (supplier) => supplier.isLast,
        );

        if (!hasLastSupplier) {
          const lastSupplier =
            purchaseOrderVO.orderSupplierList[
              purchaseOrderVO.orderSupplierList.length - 1
            ];
          Dialog.open("dialog", {
            title: "提交审核提醒",
            content: `这车货目前还在拼车状态。一旦确认车辆已满载，就需要在档口信息那里，把“${lastSupplier.name}”的这车货标记为“不需要拼车”。`,
            confirmText: "不需要拼车",
            cancelText: "去继续拼车",
            onConfirm: async () => {
              Taro.redirectTo({
                url: buildUrl("/pages/transfer/create", {
                  orderId: purchaseOrderVO.orderId,
                  orderSupplierId: lastSupplier.orderSupplierId,
                  step: "2",
                }),
              });
              Dialog.close("dialog");
            },
            onCancel: () => {
              Taro.redirectTo({
                url: buildUrl("/pages/transfer/create", {
                  orderId: purchaseOrderVO.orderId,
                  step: "6",
                }),
              });
              Dialog.close("dialog");
            },
          });
          e.stopPropagation();
          return;
        }

        Dialog.open("dialog", {
          title: "提交审核提醒",
          content: `提交后报价审核员将看到此审核采购单，请确保所有档口信息都录入进来了，确认提交调货订单？`,
          confirmText: "确认",
          cancelText: "取消",
          onConfirm: async () => {
            await onSubmit();
            Dialog.close("dialog");
          },
          onCancel: () => {
            Dialog.close("dialog");
          },
        });
        e.stopPropagation();
      }}
    >
      提交审核
    </Button>
  );
}
