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

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

export default function OrderWithdrawReview(props: IOrderWithdrawReviewProps) {
  const { auditVO, size = "normal", onFinish } = props;

  const onWithdraw = async () => {
    if (!auditVO) {
      Toast.show("toast", {
        icon: "warn",
        title: "提示",
        content: "撤回失败",
      });
      return;
    }

    let success = false;
    let errMessage = "";
    try {
      if (auditVO.subjectId) {
        const { data } = await business.order.withdrawReviewOrder({
          orderId: auditVO.subjectId,
          auditId: auditVO.auditId,
        });

        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={"danger"}
      size={size}
      onClick={async (e) => {
        Dialog.open("dialog", {
          title: "撤回提审提醒",
          content: "撤回后将回到草稿状态，是否确认撤回？",
          confirmText: "确认",
          cancelText: "取消",
          onConfirm: async () => {
            await onWithdraw();
            Dialog.close("dialog");
          },
          onCancel: () => {
            Dialog.close("dialog");
          },
        });
        e.stopPropagation();
      }}
    >
      撤回提审
    </Button>
  );
}
