var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saleDetail/hooks/saleDetailActions/orderActions.ts
var orderActions_exports = {};
__export(orderActions_exports, {
  useCancelActionItem: () => useCancelActionItem,
  useCheckoutActionItem: () => useCheckoutActionItem,
  useEditActionItem: () => useEditActionItem,
  useNoteActionItem: () => useNoteActionItem,
  useRefundActionItem: () => useRefundActionItem,
  useReturnActionItem: () => useReturnActionItem,
  useSaveActionItem: () => useSaveActionItem
});
module.exports = __toCommonJS(orderActions_exports);
var import_react = require("react");
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_selectors = require("../../../salesSdk/selectors");
var import_noteModal = __toESM(require("../../../noteModal"));
var import_utils2 = require("./utils");
var import_createHolderConfirmBridge = require("../../../salesSdk/holderConfirm/createHolderConfirmBridge");
var CHECKOUT_PAYMENT_STATUS = /* @__PURE__ */ new Set([
  "unfulfilled",
  "unpaid",
  "payment_processing"
]);
var PisellAmount = import_materials.PisellText.Amount;
function alertMissingAction(actionName) {
  const messageText = `[SaleDetail] Missing action: ${actionName}`;
  if (typeof window !== "undefined" && typeof window.alert === "function") {
    window.alert(messageText);
    return;
  }
  import_antd.message.error(messageText);
}
function normalizePaymentStatus(status) {
  return status === "partially_paid" ? "unpaid" : status || "";
}
function getNumericAmount(value) {
  const amount = Number(value ?? 0);
  return Number.isFinite(amount) ? amount : 0;
}
function resolveSaleDetailOrderIdFromResult(context, result) {
  var _a, _b, _c, _d, _e, _f;
  const fromResult = ((_a = result == null ? void 0 : result.data) == null ? void 0 : _a.order_id) ?? (result == null ? void 0 : result.order_id) ?? ((_c = (_b = result == null ? void 0 : result.response) == null ? void 0 : _b.data) == null ? void 0 : _c.order_id) ?? ((_f = (_e = (_d = result == null ? void 0 : result.data) == null ? void 0 : _d.response) == null ? void 0 : _e.data) == null ? void 0 : _f.order_id);
  if (fromResult !== void 0 && fromResult !== null && fromResult !== "") {
    return fromResult;
  }
  return (0, import_utils2.resolveSaleDetailOrderId)(context);
}
function isSalesOrderSubmitSuccess(result) {
  var _a, _b, _c;
  if (!result || typeof result !== "object") return false;
  const isErrorCode = result.code !== void 0 && result.code !== 200 && result.code !== "200";
  const isErrorStatus = result.status === false || typeof result.status === "number" && result.status >= 400;
  const isErrorSuccess = result.success === false;
  if (isErrorCode || isErrorStatus || isErrorSuccess) {
    return false;
  }
  if (result.status === true || result.status === 200) {
    return true;
  }
  if (result.code === 200 || result.code === "200") {
    return true;
  }
  const orderId = ((_a = result.data) == null ? void 0 : _a.order_id) ?? result.order_id ?? ((_c = (_b = result.response) == null ? void 0 : _b.data) == null ? void 0 : _c.order_id);
  return orderId !== void 0 && orderId !== null && orderId !== "";
}
function shouldCloseDialogAfterCheckout(result) {
  if (!result) return false;
  if (result.status === "cancelled" || result.type === "error") {
    return false;
  }
  if (typeof result.reset === "boolean") {
    return result.reset;
  }
  return true;
}
function deriveActionState(context) {
  var _a, _b;
  const tempOrder = context.sales.tempOrder;
  const bookings = context.cart.bookings || [];
  const items = context.cart.items || [];
  const summary = (_a = context.summary) == null ? void 0 : _a.summary;
  const rootBooking = (_b = tempOrder == null ? void 0 : tempOrder.bookings) == null ? void 0 : _b[0];
  const derivedEdit = (0, import_selectors.deriveDisabledEdit)(rootBooking, tempOrder);
  const paymentStatus = normalizePaymentStatus(tempOrder == null ? void 0 : tempOrder.payment_status);
  const hasOrderId = Boolean(tempOrder == null ? void 0 : tempOrder.order_id);
  const hasCartItems = Boolean(bookings.length || items.length);
  const totalAmount = getNumericAmount(summary == null ? void 0 : summary.total_amount);
  const expectAmount = getNumericAmount(summary == null ? void 0 : summary.expect_amount);
  const totalRefundAmount = getNumericAmount(summary == null ? void 0 : summary.total_refund_amount);
  const baseDisabled = (!hasCartItems || derivedEdit.disabledEdit) && Number(summary == null ? void 0 : summary.amount_gap) >= 0;
  const isCheckout = !hasOrderId || (rootBooking == null ? void 0 : rootBooking.appointment_status) !== "cancelled" && CHECKOUT_PAYMENT_STATUS.has(paymentStatus) && !derivedEdit.disabledEdit || totalAmount > 0;
  return {
    baseDisabled,
    checkoutDisabled: baseDisabled || !isCheckout || totalRefundAmount > 0 || totalAmount < 0 || expectAmount < 0 || Number(summary == null ? void 0 : summary.amount_gap) < 0,
    saveDisabled: baseDisabled
  };
}
function useEditBookingAction({
  context: saleDetailContext,
  onAfterEdit
}) {
  var _a, _b, _c, _d;
  const engineContext = (0, import_useEngineContext.default)();
  const action = (_b = (_a = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.action;
  const orderId = (0, import_utils2.resolveSaleDetailOrderId)(saleDetailContext);
  const { disabledEdit } = (0, import_selectors.deriveDisabledEdit)(
    (_c = saleDetailContext.sales.salesDetail) == null ? void 0 : _c.rootBooking,
    (_d = saleDetailContext.sales.salesDetail) == null ? void 0 : _d.header
  );
  const refreshSaleDetail = (0, import_react.useCallback)(async () => {
    await saleDetailContext.sales.refreshSalesDetail();
  }, [saleDetailContext.sales, orderId]);
  const handleEdit = (0, import_react.useCallback)(() => {
    var _a2, _b2, _c2;
    if (typeof action !== "function" || orderId == null) {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
      return;
    }
    const businessCode = ((_a2 = saleDetailContext.sales.tempOrder) == null ? void 0 : _a2.business_code) || ((_c2 = (_b2 = saleDetailContext.sales.salesDetail) == null ? void 0 : _b2.raw) == null ? void 0 : _c2.business_code);
    const isDineIn = String(businessCode ?? "") === "dine_in";
    action({
      type: isDineIn ? "pisell1.handleOpenCachedBigSale" : "pisell1.handleOpenCachedEditBooking",
      data: {
        order_id: orderId
      },
      callback: () => {
        void refreshSaleDetail();
        void (onAfterEdit == null ? void 0 : onAfterEdit());
      }
    });
  }, [action, onAfterEdit, orderId, refreshSaleDetail, saleDetailContext.sales]);
  return {
    disabled: disabledEdit || orderId == null,
    handleEdit
  };
}
function useEditActionItem({
  context,
  onAfterEdit
}) {
  const { disabled, handleEdit } = useEditBookingAction({
    context,
    onAfterEdit
  });
  return (0, import_react.useMemo)(
    () => ({
      id: "edit",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.edit"),
        className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--edit",
        disabled,
        icon: (0, import_react.createElement)(import_icons.EditOutlined),
        onClick: handleEdit
      }
    }),
    [disabled, handleEdit]
  );
}
function useReturnActionItem({
  context,
  onAfterEdit
}) {
  const { disabled, handleEdit } = useEditBookingAction({
    context,
    onAfterEdit
  });
  return (0, import_react.useMemo)(
    () => ({
      id: "return",
      buttonProps: {
        block: true,
        children: (0, import_react.createElement)(
          "span",
          { className: "pisell-sale-detail-button-actions__return-label" },
          import_utils.locales.getText("pisell2.sale-detail.action.return-item")
        ),
        className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--return",
        disabled,
        icon: (0, import_react.createElement)(import_icons.RollbackOutlined),
        onClick: handleEdit
      }
    }),
    [disabled, handleEdit]
  );
}
function useRefundActionItem({
  context
}) {
  var _a, _b;
  const engineContext = (0, import_useEngineContext.default)();
  const NativePage = (_b = (_a = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.NativePage;
  const orderId = (0, import_utils2.resolveSaleDetailOrderId)(context);
  const handleRefund = (0, import_react.useCallback)(() => {
    if (orderId == null) {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
      return;
    }
    const nativePage = typeof NativePage === "function" ? NativePage() : void 0;
    if (typeof (nativePage == null ? void 0 : nativePage.open) !== "function") {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
      return;
    }
    nativePage.open({
      page: "/native/order/refund",
      params: {
        order_id: orderId
      }
    });
  }, [NativePage, orderId]);
  return (0, import_react.useMemo)(
    () => ({
      id: "refund",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.refund"),
        className: "pisell-sale-detail-button-actions__button",
        disabled: orderId == null || typeof NativePage !== "function",
        icon: (0, import_react.createElement)(import_icons.UndoOutlined),
        onClick: handleRefund
      }
    }),
    [NativePage, handleRefund, orderId]
  );
}
function useCancelActionItem({
  context
}) {
  var _a, _b, _c, _d;
  const [loading, setLoading] = (0, import_react.useState)(false);
  const engineContext = (0, import_useEngineContext.default)();
  const action = (_b = (_a = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.action;
  const pisellos = (_d = (_c = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _c.utils) == null ? void 0 : _d.pisellos;
  const orderId = (0, import_utils2.resolveSaleDetailOrderId)(context);
  const refreshSaleDetail = (0, import_react.useCallback)(async () => {
    await context.sales.refreshSalesDetail();
  }, [context.sales, orderId]);
  const handleCancel = (0, import_react.useCallback)(() => {
    if (loading) return;
    import_antd.Modal.confirm({
      title: import_utils.locales.getText("pisell2.sale-detail.action.cancel-confirm-title"),
      okText: import_utils.locales.getText("pisell2.sale-detail.action.cancel-confirm-ok"),
      cancelText: import_utils.locales.getText(
        "pisell2.sale-detail.action.cancel-confirm-cancel"
      ),
      centered: true,
      okButtonProps: {
        danger: true
      },
      onOk: async () => {
        if (orderId == null) {
          import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
          return;
        }
        const salesModule = (0, import_utils2.getSalesHostModule)(pisellos);
        const cancelOrder = salesModule == null ? void 0 : salesModule.cancelOrder;
        if (typeof cancelOrder !== "function") {
          import_antd.message.error(
            import_utils.locales.getText("pisell2.sale-detail.cancel-order-unavailable")
          );
          return;
        }
        try {
          setLoading(true);
          await cancelOrder.call(salesModule, [orderId]);
          (0, import_utils2.updateLocalOrder)(action, orderId);
          await refreshSaleDetail();
        } catch (error) {
          import_antd.message.error(String((error == null ? void 0 : error.message) ?? error));
        } finally {
          setLoading(false);
        }
      }
    });
  }, [action, loading, orderId, pisellos, refreshSaleDetail]);
  return (0, import_react.useMemo)(
    () => ({
      id: "cancel",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.cancel"),
        className: "pisell-sale-detail-button-actions__button",
        danger: true,
        disabled: orderId == null,
        icon: (0, import_react.createElement)(import_icons.CloseCircleOutlined),
        loading,
        onClick: handleCancel
      }
    }),
    [handleCancel, loading, orderId]
  );
}
function useNoteActionItem({
  context
}) {
  var _a, _b, _c;
  const [noteModalOpen, setNoteModalOpen] = (0, import_react.useState)(false);
  const hasOrderNote = Boolean((_b = (_a = context.sales.tempOrder) == null ? void 0 : _a.note) == null ? void 0 : _b.trim());
  const handleNote = (0, import_react.useCallback)(() => {
    if (typeof context.sales.setOrderNote !== "function") {
      alertMissingAction("sales.setOrderNote");
      return;
    }
    setNoteModalOpen(true);
  }, [context.sales]);
  const handleNoteConfirm = (0, import_react.useCallback)(
    (noteValue) => {
      context.sales.setOrderNote(noteValue);
      setNoteModalOpen(false);
    },
    [context.sales]
  );
  const handleNoteDelete = (0, import_react.useCallback)(() => {
    context.sales.setOrderNote("");
    setNoteModalOpen(false);
  }, [context.sales]);
  const handleNoteCancel = (0, import_react.useCallback)(() => {
    setNoteModalOpen(false);
  }, []);
  return (0, import_react.useMemo)(
    () => {
      var _a2;
      return {
        id: "note",
        renderAfter: noteModalOpen ? (0, import_react.createElement)(import_noteModal.default, {
          open: noteModalOpen,
          title: import_utils.locales.getText("pisell2.text.add-order-notes"),
          value: ((_a2 = context.sales.tempOrder) == null ? void 0 : _a2.note) || "",
          onConfirm: handleNoteConfirm,
          onDelete: handleNoteDelete,
          onCancel: handleNoteCancel
        }) : null,
        buttonProps: {
          block: true,
          children: hasOrderNote ? (0, import_react.createElement)(
            "span",
            { className: "pisell-sale-detail-button-actions__note-content" },
            import_utils.locales.getText("pisell2.sale-detail.action.note"),
            (0, import_react.createElement)(
              "span",
              { className: "note-indicator" },
              (0, import_react.createElement)(import_materials.Iconfont, { type: "pisell2-info-circle2" })
            )
          ) : import_utils.locales.getText("pisell2.sale-detail.action.note"),
          className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--note",
          onClick: handleNote
        }
      };
    },
    [
      (_c = context.sales.tempOrder) == null ? void 0 : _c.note,
      handleNote,
      handleNoteCancel,
      handleNoteConfirm,
      handleNoteDelete,
      hasOrderNote,
      noteModalOpen
    ]
  );
}
function useSaveActionItem({
  context
}) {
  const [loading, setLoading] = (0, import_react.useState)(false);
  const { saveDisabled } = deriveActionState(context);
  const handleSave = (0, import_react.useCallback)(async () => {
    var _a;
    if (typeof context.cart.submit !== "function") {
      alertMissingAction("cart.submit");
      return;
    }
    setLoading(true);
    try {
      const res = await context.cart.submit();
      if (isSalesOrderSubmitSuccess(res)) {
        const orderId = resolveSaleDetailOrderIdFromResult(context, res);
        (_a = context.onOrderComplete) == null ? void 0 : _a.call(context, {
          type: "save",
          data: res,
          order_id: orderId,
          reset: true
        });
        context.sales.restore();
      } else {
        import_antd.message.error(String((res == null ? void 0 : res.message) ?? (res == null ? void 0 : res.msg) ?? res));
      }
    } catch (error) {
      if ((0, import_createHolderConfirmBridge.isHolderConfirmCancelled)(error)) return;
      import_antd.message.error(String((error == null ? void 0 : error.message) ?? error));
    } finally {
      setLoading(false);
    }
  }, [context.cart, context.onOrderComplete, context.sales]);
  return (0, import_react.useMemo)(
    () => ({
      id: "save",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.save"),
        className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--save",
        disabled: saveDisabled,
        icon: (0, import_react.createElement)(import_icons.SaveOutlined),
        loading,
        onClick: handleSave
      }
    }),
    [handleSave, loading, saveDisabled]
  );
}
function useCheckoutActionItem({
  context
}) {
  var _a;
  const [loading, setLoading] = (0, import_react.useState)(false);
  const orderId = (0, import_utils2.resolveSaleDetailOrderId)(context);
  const summary = (_a = context.summary) == null ? void 0 : _a.summary;
  const amountGap = getNumericAmount(summary == null ? void 0 : summary.amount_gap);
  const expectAmount = getNumericAmount(summary == null ? void 0 : summary.expect_amount);
  const orderPaidAmount = getNumericAmount(summary == null ? void 0 : summary.order_paid_amount);
  const amountDue = orderPaidAmount > 0 ? amountGap : expectAmount;
  const shouldShowCheckout = amountDue > 0;
  const { checkoutDisabled } = deriveActionState(context);
  const handleCheckout = (0, import_react.useCallback)(async () => {
    var _a2;
    if (typeof context.sales.openCheckout !== "function") {
      alertMissingAction("sales.openCheckout");
      return;
    }
    setLoading(true);
    try {
      const res = await context.sales.openCheckout();
      if (!shouldCloseDialogAfterCheckout(res)) {
        return;
      }
      const orderId2 = resolveSaleDetailOrderIdFromResult(context, res);
      (_a2 = context.onOrderComplete) == null ? void 0 : _a2.call(context, {
        type: "checkout",
        data: (res == null ? void 0 : res.data) ?? res,
        order_id: orderId2,
        reset: true
      });
    } catch (error) {
      if ((0, import_createHolderConfirmBridge.isHolderConfirmCancelled)(error)) return;
      import_antd.message.error(String((error == null ? void 0 : error.message) ?? error));
    } finally {
      setLoading(false);
    }
  }, [context]);
  return (0, import_react.useMemo)(
    () => ({
      id: "checkout",
      hidden: !shouldShowCheckout,
      buttonProps: {
        block: true,
        children: (0, import_react.createElement)(
          "span",
          { className: "pisell-sale-detail-button-actions__checkout-content" },
          (0, import_react.createElement)(
            "span",
            { className: "pisell-sale-detail-button-actions__checkout-title" },
            import_utils.locales.getText("pisell2.sale-detail.action.collect-money")
          ),
          (0, import_react.createElement)(
            "span",
            { className: "pisell-sale-detail-button-actions__checkout-amount" },
            import_utils.locales.getText("pisell2.sale-detail.amount-due"),
            (0, import_react.createElement)(PisellAmount, { value: amountDue })
          )
        ),
        className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--primary",
        type: "primary",
        disabled: orderId == null || checkoutDisabled || loading,
        loading,
        onClick: handleCheckout
      }
    }),
    [
      amountDue,
      checkoutDisabled,
      handleCheckout,
      loading,
      orderId,
      shouldShowCheckout
    ]
  );
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useCancelActionItem,
  useCheckoutActionItem,
  useEditActionItem,
  useNoteActionItem,
  useRefundActionItem,
  useReturnActionItem,
  useSaveActionItem
});
