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

interface IOrderSubmitReviewProps {
  orderVO: BusinessAPI.OrderVO;
  size?: ButtonSize;
  onFinish?: (auditVO: BusinessAPI.AuditVO) => void;
}

export default function OrderSubmitReview(props: IOrderSubmitReviewProps) {
  const { orderVO, size = "normal", onFinish } = props;

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

    try {
      // 更新成功后再提交审核
      const {
        data: { data: auditVO, success, errMessage },
      } = await business.order.submitReviewOrder({
        orderId: orderVO.orderId,
      });

      if (success) {
        Toast.show("toast", {
          icon: "success",
          title: "提示",
          content: "提交成功",
        });
        // 可以在这里添加跳转逻辑，例如返回列表页
        onFinish?.(auditVO!);
      } 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 = orderVO.orderSupplierList?.some(
          (supplier) => supplier.isLast,
        );

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

        // 产地采购单需要判断瓜农是否上传合同
        // if (orderVO.type === "PRODUCTION_PURCHASE") {
        //   // 检查是否存在合同未上传的瓜农
        //   const hasNoUpdateContractSupplier = orderVO.orderSupplierList?.find(
        //     (supplier) => !supplier.contractUpload,
        //   );
        //
        //   if (hasNoUpdateContractSupplier) {
        //     Dialog.open("dialog", {
        //       title: "提交审核提醒",
        //       content: `检测到瓜农“${hasNoUpdateContractSupplier.name}”未上传合同。请返回票证上传步骤上传合同？`,
        //       confirmText: "去票证上传",
        //       cancelText: "取消",
        //       onConfirm: async () => {
        //         Taro.redirectTo({
        //           url: buildUrl(purchase.path[orderVO.type].create, {
        //             orderId: orderVO.orderId,
        //             supplierId: hasNoUpdateContractSupplier.supplierId,
        //             step: "5",
        //           }),
        //         });
        //         Dialog.close("dialog");
        //       },
        //       onCancel: () => {
        //         Dialog.close("dialog");
        //       },
        //     });
        //     e.stopPropagation();
        //     return;
        //   }
        // }

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