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/components/DetailActions/index.tsx
var DetailActions_exports = {};
__export(DetailActions_exports, {
  DetailActions: () => DetailActions,
  TEMPLATE_A_ACTIONS: () => import_configs2.TEMPLATE_A_ACTIONS,
  TEMPLATE_B_PAY_ACTIONS: () => import_configs2.TEMPLATE_B_PAY_ACTIONS,
  TEMPLATE_B_SUMMARY_ACTIONS: () => import_configs2.TEMPLATE_B_SUMMARY_ACTIONS,
  useEditBookingAction: () => useEditBookingAction
});
module.exports = __toCommonJS(DetailActions_exports);
var import_react = __toESM(require("react"));
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
var import_classnames = __toESM(require("classnames"));
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_salesSdk = require("../../../salesSdk");
var import_SaveConfirmModal = require("../../../salesSdk/components/SaveConfirmModal");
var import_createHolderConfirmBridge = require("../../../salesSdk/holderConfirm/createHolderConfirmBridge");
var import_selectors = require("../../../salesSdk/selectors");
var import_useOrderNoteModal = require("../../hooks/useOrderNoteModal");
var import_serve = require("../../serve");
var import_configs = require("./configs");
var import_types = require("./types");
var import_utils2 = require("./utils");
var import_index = require("./index.less");
var import_configs2 = require("./configs");
var PisellAmount = import_materials.PisellText.Amount;
var ActionSpace = import_antd.Space;
var CHECKOUT_PAYMENT_STATUS = /* @__PURE__ */ new Set([
  "unfulfilled",
  "unpaid",
  "payment_processing"
]);
var WRISTBAND_PRINT_TAGS = [
  "ticket",
  "product_package_ticket",
  "appointment_ticket",
  "session_ticket"
];
var PRINT_MENU_ITEM_CLASS_NAME = "pisell-sale-detail-print-menu__item";
var PRINT_MENU_ICON_CLASS_NAME = "pisell-sale-detail-print-menu__icon";
var DetailActionRuntimeContext = (0, import_react.createContext)(null);
function useDetailActionRuntime() {
  const runtime = (0, import_react.useContext)(DetailActionRuntimeContext);
  if (!runtime) {
    throw new Error("[SaleDetail] DetailActions runtime is missing");
  }
  return runtime;
}
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 mergeActionConfig(actionConfig) {
  var _a;
  const defaultConfig = import_configs.DEFAULT_ACTION_CONFIG[actionConfig.key];
  return {
    ...defaultConfig,
    ...actionConfig,
    key: actionConfig.key,
    row: actionConfig.row ?? (defaultConfig == null ? void 0 : defaultConfig.row) ?? 1,
    order: actionConfig.order ?? (defaultConfig == null ? void 0 : defaultConfig.order) ?? 0,
    buttonProps: {
      ...defaultConfig == null ? void 0 : defaultConfig.buttonProps,
      ...actionConfig.buttonProps
    },
    children: (_a = actionConfig.children) == null ? void 0 : _a.map(mergeActionConfig)
  };
}
function collectActionKeys(actions = []) {
  return actions.reduce((keys, action) => {
    keys.add(action.key);
    collectActionKeys(action.children).forEach((key) => keys.add(key));
    return keys;
  }, /* @__PURE__ */ new Set());
}
function groupActionConfigs(actions = []) {
  const rows = actions.map(mergeActionConfig).filter((actionConfig) => !actionConfig.hidden).reduce((result, actionConfig) => {
    result[actionConfig.row] = result[actionConfig.row] || [];
    result[actionConfig.row].push(actionConfig);
    return result;
  }, {});
  return Object.keys(rows).map(Number).sort((prev, next) => prev - next).map((row) => rows[row].sort((prev, next) => prev.order - next.order)).filter((rowItems) => rowItems.length > 0);
}
function getActionModifierClassName(action) {
  if (/^[a-z0-9-]+$/.test(action.key)) {
    return `pisell-sale-detail-button-actions__button--${action.key}`;
  }
  return void 0;
}
function getSlotButtonProps(action, actionConfig) {
  const isPrimary = actionConfig.slot === "footer-primary";
  return {
    className: (0, import_classnames.default)(
      "pisell-sale-detail-button-actions__button",
      getActionModifierClassName(action),
      {
        "pisell-sale-detail-button-actions__button--primary": isPrimary,
        "pisell-sale-detail-button-actions__button--checkout-cart": action.key === "checkout-cart"
      }
    ),
    type: isPrimary ? "primary" : void 0
  };
}
function getCheckoutChildren(action) {
  var _a, _b;
  if (!((_a = action.meta) == null ? void 0 : _a.showAmountDue)) return action.label;
  return /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-sale-detail-button-actions__checkout-content" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-sale-detail-button-actions__checkout-title" }, action.label), /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-sale-detail-button-actions__checkout-amount" }, import_utils.locales.getText("pisell2.sale-detail.amount-due"), /* @__PURE__ */ import_react.default.createElement(PisellAmount, { value: Number(((_b = action.meta) == null ? void 0 : _b.amountDue) ?? 0) })));
}
function getNoteChildren(action) {
  return action.label;
}
function getReturnChildren(action) {
  return /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-sale-detail-button-actions__return-label" }, action.label);
}
function getActionChildren(action) {
  if (action.key === "checkout") return getCheckoutChildren(action);
  if (action.key === "note") return getNoteChildren(action);
  if (action.key === "return") return getReturnChildren(action);
  return action.label;
}
function toPrintMenuLabel(label) {
  if (typeof label !== "string") return label;
  return label.trim().replace(/[A-Za-z][A-Za-z'-]*/g, (word) => {
    const [firstLetter, ...restLetters] = word;
    return `${firstLetter.toUpperCase()}${restLetters.join("").toLowerCase()}`;
  });
}
function getPrintMenuIcon(iconType) {
  return /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { className: PRINT_MENU_ICON_CLASS_NAME, type: iconType });
}
function toButtonProps(action, actionConfig) {
  const shouldHideIconInChildren = action.key === "note";
  const baseButtonProps = {
    block: true,
    children: getActionChildren(action),
    danger: action.danger,
    disabled: action.disabled,
    icon: shouldHideIconInChildren ? void 0 : action.icon,
    loading: action.loading,
    onClick: action.onTrigger
  };
  return {
    ...baseButtonProps,
    ...getSlotButtonProps(action, actionConfig),
    ...actionConfig.buttonProps
  };
}
function isPrintSuccessful(result) {
  return (result == null ? void 0 : result.status) === "success" || (result == null ? void 0 : result.result) === true;
}
function deriveActionState(sales, cart, summaryState) {
  var _a;
  const tempOrder = sales.tempOrder;
  const bookings = cart.bookings || [];
  const items = cart.items || [];
  const summary = summaryState.summary;
  const rootBooking = (_a = tempOrder == null ? void 0 : tempOrder.bookings) == null ? void 0 : _a[0];
  const derivedEdit = (0, import_selectors.deriveDisabledEdit)(rootBooking, tempOrder);
  const paymentStatus = (0, import_utils2.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 = (0, import_utils2.getNumericAmount)(summary == null ? void 0 : summary.total_amount);
  const expectAmount = (0, import_utils2.getNumericAmount)(summary == null ? void 0 : summary.expect_amount);
  const totalRefundAmount = (0, import_utils2.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 {
    checkoutDisabled: baseDisabled || !isCheckout || totalRefundAmount > 0 || totalAmount < 0 || expectAmount < 0 || Number(summary == null ? void 0 : summary.amount_gap) < 0,
    saveDisabled: baseDisabled
  };
}
function useCheckoutActionState({
  validateHolder = false
} = {}) {
  const [loading, setLoading] = (0, import_react.useState)(false);
  const sales = (0, import_salesSdk.useSalesSdk)();
  const cart = (0, import_salesSdk.useSalesSdkCart)();
  const summaryState = (0, import_salesSdk.useSalesSdkSummary)();
  const runtime = useDetailActionRuntime();
  const orderId = (0, import_utils2.resolveSaleDetailOrderIdFromSales)(sales);
  const summary = summaryState.summary;
  const amountGap = (0, import_utils2.getNumericAmount)(summary == null ? void 0 : summary.amount_gap);
  const expectAmount = (0, import_utils2.getNumericAmount)(summary == null ? void 0 : summary.expect_amount);
  const orderPaidAmount = (0, import_utils2.getNumericAmount)(summary == null ? void 0 : summary.order_paid_amount);
  const amountDue = orderPaidAmount > 0 ? amountGap : expectAmount;
  const shouldHideCheckout = !!orderId && amountDue <= 0;
  const { checkoutDisabled } = deriveActionState(sales, cart, summaryState);
  const handleCheckout = (0, import_react.useCallback)(async () => {
    var _a;
    if (runtime.saveLoading) return void 0;
    if (typeof sales.openCheckout !== "function") {
      alertMissingAction("sales.openCheckout");
      return void 0;
    }
    setLoading(true);
    try {
      const res = await sales.openCheckout({ validateHolder });
      const shouldClose = (0, import_utils2.shouldCloseDialogAfterCheckout)(res);
      if (!shouldClose) {
        return res;
      }
      const resolvedOrderId = (0, import_utils2.resolveSaleDetailOrderIdFromSalesResult)(
        sales,
        res
      );
      (_a = runtime.onOrderComplete) == null ? void 0 : _a.call(runtime, {
        type: "checkout",
        data: (res == null ? void 0 : res.data) ?? res,
        order_id: resolvedOrderId,
        reset: true
      });
      return res;
    } catch (error) {
      if ((0, import_createHolderConfirmBridge.isHolderConfirmCancelled)(error)) return void 0;
      import_antd.message.error(String((error == null ? void 0 : error.message) ?? error));
      return void 0;
    } finally {
      setLoading(false);
    }
  }, [runtime, sales, validateHolder]);
  return {
    amountDue,
    checkoutDisabled,
    handleCheckout,
    loading,
    shouldHideCheckout
  };
}
var ActionButton = (0, import_react.memo)(function ActionButton2({
  action,
  actionConfig
}) {
  if (action.hidden) return null;
  return /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { ...toButtonProps(action, actionConfig) });
});
function useEditBookingAction({
  onAfterEdit
} = {}) {
  var _a, _b, _c, _d, _e, _f;
  const sales = (0, import_salesSdk.useSalesSdk)();
  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.resolveSaleDetailOrderIdFromSales)(sales);
  const { disabledEdit } = (0, import_selectors.deriveDisabledEdit)(
    (_c = sales.salesDetail) == null ? void 0 : _c.rootBooking,
    (_d = sales.salesDetail) == null ? void 0 : _d.header
  );
  const refreshSaleDetail = (0, import_react.useCallback)(async () => {
    await sales.refreshSalesDetail();
  }, [sales.refreshSalesDetail]);
  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 = sales.tempOrder) == null ? void 0 : _a2.business_code) || ((_c2 = (_b2 = sales.salesDetail) == null ? void 0 : _b2.raw) == null ? void 0 : _c2.business_code);
    action({
      type: "pisell1.handleOpenCachedBigSale",
      data: {
        business_code: businessCode,
        order_id: orderId
      },
      callback: (params) => {
        if ((params == null ? void 0 : params.type) === "close") {
          void refreshSaleDetail();
          void (onAfterEdit == null ? void 0 : onAfterEdit());
        }
      }
    });
  }, [
    action,
    onAfterEdit,
    orderId,
    refreshSaleDetail,
    (_e = sales.salesDetail) == null ? void 0 : _e.raw,
    (_f = sales.tempOrder) == null ? void 0 : _f.business_code
  ]);
  return {
    disabled: disabledEdit || orderId == null,
    handleEdit
  };
}
var EditAction = (0, import_react.memo)(function EditAction2({
  actionConfig
}) {
  const runtime = useDetailActionRuntime();
  const { disabled, handleEdit } = useEditBookingAction({
    onAfterEdit: runtime.refreshRemotePrintActions
  });
  return /* @__PURE__ */ import_react.default.createElement(
    ActionButton,
    {
      action: {
        key: "edit",
        label: import_utils.locales.getText("pisell2.sale-detail.action.edit"),
        disabled,
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.EditOutlined, null),
        onTrigger: handleEdit
      },
      actionConfig
    }
  );
});
var ReturnAction = (0, import_react.memo)(function ReturnAction2({
  actionConfig
}) {
  const runtime = useDetailActionRuntime();
  const { disabled, handleEdit } = useEditBookingAction({
    onAfterEdit: runtime.refreshRemotePrintActions
  });
  return /* @__PURE__ */ import_react.default.createElement(
    ActionButton,
    {
      action: {
        key: "return",
        label: import_utils.locales.getText("pisell2.sale-detail.action.return-item"),
        disabled,
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.RollbackOutlined, null),
        onTrigger: handleEdit
      },
      actionConfig
    }
  );
});
var RefundAction = (0, import_react.memo)(function RefundAction2({
  actionConfig
}) {
  var _a, _b;
  const sales = (0, import_salesSdk.useSalesSdk)();
  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.resolveSaleDetailOrderIdFromSales)(sales);
  const handleRefund = (0, import_react.useCallback)(async () => {
    var _a2;
    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;
    }
    await nativePage.open({
      page: "/native/order/refund",
      params: {
        order_id: orderId
      }
    });
    (_a2 = sales.refreshSalesDetail) == null ? void 0 : _a2.call(sales, { forceRemote: true });
  }, [NativePage, orderId, sales.refreshSalesDetail]);
  return /* @__PURE__ */ import_react.default.createElement(
    ActionButton,
    {
      action: {
        key: "refund",
        label: import_utils.locales.getText("pisell2.sale-detail.action.refund"),
        disabled: orderId == null || typeof NativePage !== "function",
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.UndoOutlined, null),
        onTrigger: handleRefund
      },
      actionConfig
    }
  );
});
var CancelAction = (0, import_react.memo)(function CancelAction2({
  actionConfig
}) {
  var _a, _b, _c, _d;
  const [loading, setLoading] = (0, import_react.useState)(false);
  const sales = (0, import_salesSdk.useSalesSdk)();
  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.resolveSaleDetailOrderIdFromSales)(sales);
  const refreshSaleDetail = (0, import_react.useCallback)(async ({ forceRemote } = {}) => {
    await sales.refreshSalesDetail({ forceRemote });
  }, [sales.refreshSalesDetail]);
  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({ forceRemote: true });
        } catch (error) {
          import_antd.message.error(String((error == null ? void 0 : error.message) ?? error));
        } finally {
          setLoading(false);
        }
      }
    });
  }, [action, loading, orderId, pisellos, refreshSaleDetail]);
  return /* @__PURE__ */ import_react.default.createElement(
    ActionButton,
    {
      action: {
        key: "cancel",
        label: import_utils.locales.getText("pisell2.sale-detail.action.cancel"),
        danger: true,
        disabled: orderId == null,
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.CloseCircleOutlined, null),
        loading,
        onTrigger: handleCancel
      },
      actionConfig
    }
  );
});
var NoteAction = (0, import_react.memo)(function NoteAction2({
  actionConfig
}) {
  const sales = (0, import_salesSdk.useSalesSdk)();
  const { openOrderNoteModal, orderNoteModal } = (0, import_useOrderNoteModal.useOrderNoteModal)({
    context: {
      sales
    }
  });
  const handleNote = (0, import_react.useCallback)(() => {
    openOrderNoteModal();
  }, [openOrderNoteModal]);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    ActionButton,
    {
      action: {
        key: "note",
        label: import_utils.locales.getText("pisell2.sale-detail.action.note"),
        onTrigger: handleNote
      },
      actionConfig
    }
  ), orderNoteModal);
});
var SelectFloorResourceAction = (0, import_react.memo)(function SelectFloorResourceAction2({
  actionConfig
}) {
  return /* @__PURE__ */ import_react.default.createElement(
    ActionButton,
    {
      action: {
        key: "select-floor-resource",
        label: import_utils.locales.getText("pisell2.sale-detail.action.select-resource")
      },
      actionConfig
    }
  );
});
var SaveAction = (0, import_react.memo)(function SaveAction2({
  actionConfig
}) {
  var _a, _b;
  const sales = (0, import_salesSdk.useSalesSdk)();
  const cart = (0, import_salesSdk.useSalesSdkCart)();
  const summaryState = (0, import_salesSdk.useSalesSdkSummary)();
  const runtime = useDetailActionRuntime();
  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 { saveDisabled } = deriveActionState(sales, cart, summaryState);
  const [saveConfirmOpen, setSaveConfirmOpen] = (0, import_react.useState)(false);
  const submitSave = (0, import_react.useCallback)(async () => {
    var _a2;
    if (typeof cart.submit !== "function") {
      alertMissingAction("cart.submit");
      return;
    }
    runtime.setSaveLoading(true);
    try {
      const isCreatingOrder = !(0, import_utils2.resolveSaleDetailOrderIdFromSales)(sales);
      const res = await cart.submit(void 0, {
        // holder 校验只由特定业务按钮显式开启，避免备注/切客户/加时保存误触发。
        validateHolder: actionConfig.validateHolder === true
      });
      if ((0, import_utils2.isSalesOrderSubmitSuccess)(res)) {
        const orderId = (0, import_utils2.resolveSaleDetailOrderIdFromSalesResult)(sales, res);
        (_a2 = runtime.onOrderComplete) == null ? void 0 : _a2.call(runtime, {
          type: "save",
          data: res,
          order_id: orderId,
          reset: true
        });
        import_antd.message.success(
          import_utils.locales.getText(
            isCreatingOrder ? "pisell2.sale-detail.order-saved-success" : "pisell2.sale-detail.order-updated-success"
          )
        );
        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 {
      runtime.setSaveLoading(false);
    }
  }, [cart, runtime, sales]);
  const handleSave = (0, import_react.useCallback)(() => {
    if (!(0, import_SaveConfirmModal.shouldOpenSaveConfirmModal)()) {
      void submitSave();
      return;
    }
    setSaveConfirmOpen(true);
  }, [submitSave]);
  const handleSaveConfirm = (0, import_react.useCallback)(() => {
    setSaveConfirmOpen(false);
    void submitSave();
  }, [submitSave]);
  const handleSaveConfirmCancel = (0, import_react.useCallback)(() => {
    setSaveConfirmOpen(false);
  }, []);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    ActionButton,
    {
      action: {
        key: "save",
        label: import_utils.locales.getText("pisell2.sale-detail.action.save"),
        disabled: saveDisabled,
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.SaveOutlined, null),
        loading: runtime.saveLoading,
        onTrigger: handleSave
      },
      actionConfig
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_SaveConfirmModal.SaveConfirmModal,
    {
      open: saveConfirmOpen,
      onCancel: handleSaveConfirmCancel,
      onConfirm: handleSaveConfirm
    }
  ));
});
var CheckoutAction = (0, import_react.memo)(function CheckoutAction2({
  actionConfig
}) {
  const {
    amountDue,
    checkoutDisabled,
    handleCheckout,
    loading,
    shouldHideCheckout
  } = useCheckoutActionState({
    validateHolder: actionConfig.validateHolder === true
  });
  return /* @__PURE__ */ import_react.default.createElement(
    ActionButton,
    {
      action: {
        key: "checkout",
        label: import_utils.locales.getText("pisell2.sale-detail.action.collect-money"),
        disabled: checkoutDisabled || loading,
        hidden: shouldHideCheckout,
        loading,
        onTrigger: handleCheckout,
        meta: {
          amountDue,
          showAmountDue: true
        }
      },
      actionConfig
    }
  );
});
var CheckoutCartAction = (0, import_react.memo)(function CheckoutCartAction2({
  actionConfig
}) {
  const sales = (0, import_salesSdk.useSalesSdk)();
  const { checkoutDisabled, handleCheckout, loading } = useCheckoutActionState({
    validateHolder: actionConfig.validateHolder === true
  });
  const restoreOrder = (0, import_react.useCallback)(() => {
    sales.restore();
  }, [sales.restore]);
  const handleCheckoutCart = (0, import_react.useCallback)(async () => {
    var _a, _b;
    const res = await handleCheckout();
    if (((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.status) === "cancelled" && ((_b = res == null ? void 0 : res.data) == null ? void 0 : _b.source) !== "back") {
      restoreOrder();
    }
  }, [handleCheckout, restoreOrder]);
  return /* @__PURE__ */ import_react.default.createElement(
    ActionButton,
    {
      action: {
        key: "checkout-cart",
        label: import_utils.locales.getText("pisell2.text.checkout"),
        disabled: checkoutDisabled || loading,
        loading,
        onTrigger: handleCheckoutCart
      },
      actionConfig
    }
  );
});
function toMenuItem(action, actionConfig) {
  const buttonProps = toButtonProps(action, actionConfig);
  return {
    key: action.key,
    label: toPrintMenuLabel(buttonProps.children),
    icon: buttonProps.icon,
    danger: buttonProps.danger,
    disabled: Boolean(buttonProps.disabled || buttonProps.loading),
    className: PRINT_MENU_ITEM_CLASS_NAME,
    onClick: action.onTrigger
  };
}
var PrintAction = (0, import_react.memo)(function PrintAction2({
  actionConfig
}) {
  var _a, _b, _c, _d;
  const [receiptLoading, setReceiptLoading] = (0, import_react.useState)(false);
  const [wristbandLoading, setWristbandLoading] = (0, import_react.useState)(false);
  const [loadingTag, setLoadingTag] = (0, import_react.useState)();
  const [machineCodePrintActions, setMachineCodePrintActions] = (0, import_react.useState)([]);
  const sales = (0, import_salesSdk.useSalesSdk)();
  const runtime = useDetailActionRuntime();
  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 getData = (_d = (_c = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _c.utils) == null ? void 0 : _d.getData;
  const orderId = (0, import_utils2.resolveSaleDetailOrderIdFromSales)(sales);
  const childConfigs = actionConfig.children || [];
  const enabledKeys = (0, import_react.useMemo)(() => collectActionKeys(childConfigs), [childConfigs]);
  const shouldShowWristbandPrint = (0, import_react.useMemo)(
    () => machineCodePrintActions.some(
      (printAction) => WRISTBAND_PRINT_TAGS.includes(String((printAction == null ? void 0 : printAction.tag) || ""))
    ),
    [machineCodePrintActions]
  );
  const refreshRemotePrintActions = (0, import_react.useCallback)(async () => {
    if (!enabledKeys.has("print-wallet") && !enabledKeys.has("print-wristband") || orderId == null || typeof getData !== "function") {
      setMachineCodePrintActions([]);
      return;
    }
    try {
      const response = await (0, import_serve.getRemotePrintActions)(
        { order_id: String(orderId) },
        { headers: { "Shop-Id": getData("shop_id") } }
      );
      setMachineCodePrintActions(response.machine_code_print_info_v2 || []);
    } catch (error) {
      console.error("[SaleDetail] Failed to load remote print actions", error);
    }
  }, [enabledKeys, getData, orderId]);
  (0, import_react.useEffect)(() => {
    void refreshRemotePrintActions();
  }, [refreshRemotePrintActions]);
  (0, import_react.useEffect)(
    () => runtime.registerRemotePrintRefresh(refreshRemotePrintActions),
    [refreshRemotePrintActions, runtime]
  );
  const handlePrintReceipts = (0, import_react.useCallback)(() => {
    if (receiptLoading) return;
    if (orderId == null) {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
      return;
    }
    if (typeof action !== "function" || typeof getData !== "function") {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
      return;
    }
    setReceiptLoading(true);
    try {
      action({
        type: "webpos.handlePrint",
        data: {
          type: import_types.EBizPrintType.INVOICE,
          data: {
            order_id: orderId
          }
        },
        callback: (result) => {
          setReceiptLoading(false);
          if (isPrintSuccessful(result)) return;
          import_antd.message.error(
            (result == null ? void 0 : result.msg) || (result == null ? void 0 : result.message) || import_utils.locales.getText("pisell2.sale-detail.print-failed")
          );
        }
      });
    } catch (error) {
      setReceiptLoading(false);
      import_antd.message.error(
        String(
          (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell2.sale-detail.print-failed")
        )
      );
    }
  }, [action, orderId, receiptLoading]);
  const handlePrintWristband = (0, import_react.useCallback)(async () => {
    if (wristbandLoading) return;
    if (orderId == null) {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
      return;
    }
    if (typeof action !== "function") {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
      return;
    }
    setWristbandLoading(true);
    try {
      const response = await (0, import_serve.getWristbandList)(
        { order_id: String(orderId) },
        { headers: { "Shop-Id": getData("shop_id") } }
      );
      const ticketList = Array.isArray(response == null ? void 0 : response.list) ? response.list : [];
      if (ticketList.length <= 0) {
        setWristbandLoading(false);
        import_antd.Modal.info({
          content: import_utils.locales.getText("pisell2.sale-detail.ticket-codes-pending"),
          okText: import_utils.locales.getText("pisell2.sale-detail.ticket-codes-pending-ok")
        });
        return;
      }
      const voucherIds = ticketList.map((item) => item.id);
      action({
        type: "webpos.handlePrint",
        data: {
          type: import_types.EBizPrintType.WRISTBAND,
          data: {
            order_id: orderId,
            voucher_ids: voucherIds
          }
        },
        callback: () => {
          setWristbandLoading(false);
        }
      });
    } catch (error) {
      setWristbandLoading(false);
      import_antd.message.error(
        String(
          (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell2.sale-detail.print-failed")
        )
      );
    }
  }, [action, getData, orderId, wristbandLoading]);
  const handlePrintMachineCode = (0, import_react.useCallback)(
    (printAction) => {
      const tag = String(printAction.tag || "").trim();
      if (!tag || loadingTag) return;
      if (orderId == null) {
        import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
        return;
      }
      if (typeof action !== "function") {
        import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
        return;
      }
      setLoadingTag(tag);
      try {
        action({
          type: "webpos.handlePrint",
          data: {
            type: import_types.EBizPrintType.WALLET,
            data: {
              order_id: orderId,
              machine_code_print_info_v2: [printAction]
            }
          },
          callback: () => {
            setLoadingTag(void 0);
          }
        });
      } catch (error) {
        setLoadingTag(void 0);
        import_antd.message.error(
          String(
            (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell2.sale-detail.print-failed")
          )
        );
      }
    },
    [action, loadingTag, orderId]
  );
  const menuItems = (0, import_react.useMemo)(() => {
    return childConfigs.filter((childConfig) => !childConfig.hidden).sort((prev, next) => prev.order - next.order).flatMap((childConfig) => {
      if (childConfig.key === "print-receipts") {
        return [
          toMenuItem(
            {
              key: "print-receipts",
              label: import_utils.locales.getText(
                "pisell2.sale-detail.action.print-receipt"
              ),
              disabled: orderId == null || typeof action !== "function" || receiptLoading,
              icon: getPrintMenuIcon("pisell2-receipt-check"),
              loading: receiptLoading,
              onTrigger: handlePrintReceipts
            },
            childConfig
          )
        ];
      }
      if (childConfig.key === "print-wristband") {
        if (!shouldShowWristbandPrint) return [];
        return [
          toMenuItem(
            {
              key: "print-wristband",
              label: import_utils.locales.getText(
                "pisell2.sale-detail.action.print-tickets"
              ),
              disabled: orderId == null || typeof action !== "function" || typeof getData !== "function" || wristbandLoading,
              icon: getPrintMenuIcon("pisell2-ticket-01"),
              loading: wristbandLoading,
              onTrigger: handlePrintWristband
            },
            childConfig
          )
        ];
      }
      if (childConfig.key === "print-wallet") {
        return machineCodePrintActions.map((printAction, index) => {
          const tag = String((printAction == null ? void 0 : printAction.tag) || "").trim();
          if (!tag || WRISTBAND_PRINT_TAGS.includes(tag)) {
            return void 0;
          }
          return toMenuItem(
            {
              key: `print-machine-code-${tag}-${index}`,
              label: printAction.name || import_utils.locales.getText(
                "pisell2.sale-detail.action.print-product-voucher"
              ),
              disabled: orderId == null || typeof action !== "function" || Boolean(loadingTag && loadingTag !== tag),
              icon: getPrintMenuIcon("pisell2-daijinquan"),
              loading: loadingTag === tag,
              onTrigger: () => {
                handlePrintMachineCode(printAction);
              }
            },
            childConfig
          );
        }).filter(Boolean);
      }
      return [];
    });
  }, [
    action,
    childConfigs,
    getData,
    handlePrintMachineCode,
    handlePrintReceipts,
    handlePrintWristband,
    loadingTag,
    machineCodePrintActions,
    orderId,
    receiptLoading,
    shouldShowWristbandPrint,
    wristbandLoading
  ]);
  if (!(menuItems == null ? void 0 : menuItems.length)) return null;
  const buttonProps = toButtonProps(
    {
      key: "print",
      label: import_utils.locales.getText("pisell2.sale-detail.action.print"),
      icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PrinterOutlined, null)
    },
    actionConfig
  );
  const { children, ...dropdownButtonProps } = buttonProps;
  return /* @__PURE__ */ import_react.default.createElement(
    import_antd.Dropdown,
    {
      menu: { items: menuItems },
      overlayClassName: "pisell-sale-detail-print-menu",
      trigger: ["click"],
      placement: "topCenter"
    },
    /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { ...dropdownButtonProps }, children)
  );
});
var ActionSlot = (0, import_react.memo)(function ActionSlot2({
  actionConfig
}) {
  if (actionConfig.hidden) return null;
  switch (actionConfig.key) {
    case "edit":
      return /* @__PURE__ */ import_react.default.createElement(EditAction, { actionConfig });
    case "return":
      return /* @__PURE__ */ import_react.default.createElement(ReturnAction, { actionConfig });
    case "refund":
      return /* @__PURE__ */ import_react.default.createElement(RefundAction, { actionConfig });
    case "cancel":
      return /* @__PURE__ */ import_react.default.createElement(CancelAction, { actionConfig });
    case "note":
      return /* @__PURE__ */ import_react.default.createElement(NoteAction, { actionConfig });
    case "select-floor-resource":
      return /* @__PURE__ */ import_react.default.createElement(SelectFloorResourceAction, { actionConfig });
    case "save":
      return /* @__PURE__ */ import_react.default.createElement(SaveAction, { actionConfig });
    case "checkout":
      return /* @__PURE__ */ import_react.default.createElement(CheckoutAction, { actionConfig });
    case "checkout-cart":
      return /* @__PURE__ */ import_react.default.createElement(CheckoutCartAction, { actionConfig });
    case "print":
      return /* @__PURE__ */ import_react.default.createElement(PrintAction, { actionConfig });
    default:
      return null;
  }
});
var DetailActions = (0, import_react.memo)(function DetailActions2({
  actions = [],
  onOrderComplete
}) {
  const [saveLoading, setSaveLoading] = (0, import_react.useState)(false);
  const remotePrintRefreshRef = (0, import_react.useRef)();
  const rows = (0, import_react.useMemo)(() => groupActionConfigs(actions), [actions]);
  const refreshRemotePrintActions = (0, import_react.useCallback)(() => {
    var _a;
    return (_a = remotePrintRefreshRef.current) == null ? void 0 : _a.call(remotePrintRefreshRef);
  }, []);
  const registerRemotePrintRefresh = (0, import_react.useCallback)(
    (refresh) => {
      remotePrintRefreshRef.current = refresh;
      return () => {
        if (remotePrintRefreshRef.current === refresh) {
          remotePrintRefreshRef.current = void 0;
        }
      };
    },
    []
  );
  const runtime = (0, import_react.useMemo)(
    () => ({
      onOrderComplete,
      refreshRemotePrintActions,
      registerRemotePrintRefresh,
      saveLoading,
      setSaveLoading
    }),
    [
      onOrderComplete,
      refreshRemotePrintActions,
      registerRemotePrintRefresh,
      saveLoading
    ]
  );
  if (!rows.length) return null;
  return /* @__PURE__ */ import_react.default.createElement(DetailActionRuntimeContext.Provider, { value: runtime }, /* @__PURE__ */ import_react.default.createElement(import_antd.Flex, { wrap: "wrap", vertical: true, style: { marginBottom: 10 } }, rows.map((row, rowIndex) => /* @__PURE__ */ import_react.default.createElement(ActionSpace, { key: rowIndex }, row.map((actionConfig) => /* @__PURE__ */ import_react.default.createElement(ActionSlot, { key: actionConfig.key, actionConfig }))))));
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  DetailActions,
  TEMPLATE_A_ACTIONS,
  TEMPLATE_B_PAY_ACTIONS,
  TEMPLATE_B_SUMMARY_ACTIONS,
  useEditBookingAction
});
