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/pisellReservation/components/bookingDetailModal/useBookingDetailActions.ts
var useBookingDetailActions_exports = {};
__export(useBookingDetailActions_exports, {
  useBookingDetailActions: () => useBookingDetailActions
});
module.exports = __toCommonJS(useBookingDetailActions_exports);
var import_react = require("react");
var import_antd = require("antd");
var import_dayjs = __toESM(require("dayjs"));
var import_bookingDetailFromRaw = require("./bookingDetailFromRaw");
var import_bookingDetailHostActions = require("./bookingDetailHostActions");
var import_bookingDetailModalConstants = require("./bookingDetailModalConstants");
var import_reservationTicketBookingHostParams = require("../../utils/reservationTicketBookingHostParams");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
function useBookingDetailActions(options) {
  var _a, _b, _c;
  const {
    raw,
    tableRow,
    reservationBiz,
    associatedMenuListIds,
    onActionSuccess,
    appHelperUtils
  } = options;
  const [isCancellingOrder, setIsCancellingOrder] = (0, import_react.useState)(false);
  const [isCompletingBooking, setIsCompletingBooking] = (0, import_react.useState)(false);
  const editBookingModalRef = (0, import_react.useRef)(null);
  const lastFormBookingRef = (0, import_react.useRef)(null);
  const context = (0, import_useEngineContext.default)();
  const isIOS = (_c = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.isIOS) == null ? void 0 : _c.call(_b);
  const openActionConfirm = (0, import_react.useCallback)(
    (key, onOk) => {
      import_antd.Modal.confirm({
        title: (0, import_bookingDetailModalConstants.t)((0, import_bookingDetailModalConstants.confirmTitleKey)(key)),
        okText: (0, import_bookingDetailModalConstants.t)((0, import_bookingDetailModalConstants.confirmOkTextKey)(key)),
        cancelText: (0, import_bookingDetailModalConstants.t)((0, import_bookingDetailModalConstants.confirmCancelTextKey)(key)),
        centered: true,
        okButtonProps: key === "action-close" ? { danger: true } : { style: import_bookingDetailModalConstants.THEME_PRIMARY_BUTTON_STYLE },
        onOk
      });
    },
    []
  );
  const handleCancelOrderConfirmed = (0, import_react.useCallback)(
    async (bookingRaw) => {
      if (isCancellingOrder) return;
      const { action, pisellos } = appHelperUtils || {};
      const orderId = (0, import_bookingDetailHostActions.resolveOrderIdForHostActions)(bookingRaw);
      if (orderId == null) {
        import_antd.message.error("Cancel order failed: missing order id");
        return;
      }
      try {
        setIsCancellingOrder(true);
        const salesModule = (0, import_bookingDetailHostActions.getSalesHostModule)(pisellos);
        const cancelOrder = salesModule == null ? void 0 : salesModule.cancelOrder;
        if (typeof cancelOrder !== "function") {
          import_antd.message.error("Cancel order failed: Sales module is unavailable");
          return;
        }
        await cancelOrder.call(
          salesModule,
          [orderId]
        );
        import_antd.message.success("Cancel order successfully");
        (0, import_bookingDetailHostActions.updateLocalOrder)(action, orderId);
        await (onActionSuccess == null ? void 0 : onActionSuccess());
      } catch (err) {
        console.error("[ReservationBookingDetailModal] cancel order failed", err);
        import_antd.message.error("Cancel order failed");
      } finally {
        setIsCancellingOrder(false);
      }
    },
    [appHelperUtils, isCancellingOrder, onActionSuccess]
  );
  const handleStartBookingConfirmed = (0, import_react.useCallback)(
    async (bookingRaw) => {
      const { action, pisellos } = appHelperUtils || {};
      const orderId = (0, import_bookingDetailHostActions.resolveOrderIdForHostActions)(bookingRaw);
      const bookingId = (0, import_bookingDetailHostActions.resolveBookingIdForHostActions)(bookingRaw);
      if (bookingId == null) {
        import_antd.message.error("Complete booking failed: missing booking id");
        return;
      }
      try {
        setIsCompletingBooking(true);
        const salesModule = (0, import_bookingDetailHostActions.getSalesHostModule)(pisellos);
        const changeBookingStatus = salesModule == null ? void 0 : salesModule.changeBookingStatus;
        if (typeof changeBookingStatus !== "function") {
          import_antd.message.error("Complete booking failed: Sales module is unavailable");
          return;
        }
        await changeBookingStatus.call(salesModule, {
          booking_id: bookingId,
          appointment_status: "started"
        });
        import_antd.message.success("Complete booking successfully");
        (0, import_bookingDetailHostActions.updateLocalOrder)(action, orderId);
        await (onActionSuccess == null ? void 0 : onActionSuccess());
      } catch (err) {
        console.error("[ReservationBookingDetailModal] complete booking failed", err);
        import_antd.message.error("Complete booking failed");
      } finally {
        setIsCompletingBooking(false);
      }
    },
    [appHelperUtils, onActionSuccess]
  );
  const handleCompleteBookingConfirmed = (0, import_react.useCallback)(
    async (bookingRaw) => {
      if (isCompletingBooking) return;
      const { action, pisellos } = appHelperUtils || {};
      const orderId = (0, import_bookingDetailHostActions.resolveOrderIdForHostActions)(bookingRaw);
      const bookingId = (0, import_bookingDetailHostActions.resolveBookingIdForHostActions)(bookingRaw);
      if (bookingId == null) {
        import_antd.message.error("Complete booking failed: missing booking id");
        return;
      }
      try {
        setIsCompletingBooking(true);
        const salesModule = (0, import_bookingDetailHostActions.getSalesHostModule)(pisellos);
        const changeBookingStatus = salesModule == null ? void 0 : salesModule.changeBookingStatus;
        if (typeof changeBookingStatus !== "function") {
          import_antd.message.error("Complete booking failed: Sales module is unavailable");
          return;
        }
        await changeBookingStatus.call(salesModule, {
          booking_id: bookingId,
          appointment_status: "completed"
        });
        import_antd.message.success("Complete booking successfully");
        (0, import_bookingDetailHostActions.updateLocalOrder)(action, orderId);
        await (onActionSuccess == null ? void 0 : onActionSuccess());
      } catch (err) {
        console.error("[ReservationBookingDetailModal] complete booking failed", err);
        import_antd.message.error("Complete booking failed");
      } finally {
        setIsCompletingBooking(false);
      }
    },
    [appHelperUtils, isCompletingBooking, onActionSuccess]
  );
  const handleResourceChangeConfirmed = (0, import_react.useCallback)(() => {
    const { action } = appHelperUtils || {};
    const targetBooking = lastFormBookingRef.current ?? raw;
    const orderId = targetBooking ? (0, import_bookingDetailHostActions.resolveOrderIdForHostActions)(targetBooking) : void 0;
    if (typeof action === "function") {
      action({
        type: "pisell1.closeSelectFloorMapResource",
        data: {},
        callback: () => {
        }
      });
      (0, import_bookingDetailHostActions.updateLocalOrder)(action, orderId);
    }
    lastFormBookingRef.current = null;
    void (onActionSuccess == null ? void 0 : onActionSuccess());
  }, [appHelperUtils, onActionSuccess, raw]);
  const handleActionCellClick = (0, import_react.useCallback)(
    async (bookingRaw, key, e) => {
      (0, import_bookingDetailModalConstants.stopUiClick)(e);
      if (!bookingRaw) return;
      const { action, NativePage } = appHelperUtils || {};
      const orderId = (0, import_bookingDetailHostActions.resolveOrderIdForHostActions)(bookingRaw);
      const fromResourceId = (0, import_bookingDetailHostActions.resolveResourceIdFromRow)(tableRow);
      const toStartDate = (0, import_bookingDetailHostActions.resolveBookingDateTime)(
        bookingRaw,
        "start_at",
        "start_date",
        "start_time"
      );
      const toEndDate = (0, import_bookingDetailHostActions.resolveBookingDateTime)(
        bookingRaw,
        "end_at",
        "end_date",
        "end_time"
      );
      switch (key) {
        case "action-edit":
          if (typeof action === "function" && orderId != null) {
            const biz = reservationBiz != null && String(reservationBiz).trim() !== "" ? String(reservationBiz).trim() : "";
            const isDineIn = biz === "dine_in";
            if (isDineIn) {
              action({
                type: "pisell1.handleOpenCachedEditBooking",
                data: { order_id: orderId },
                callback: () => {
                }
              });
              break;
            }
            const createModeConfig = biz !== "" ? (0, import_reservationTicketBookingHostParams.buildReservationTicketBookingCreateModeConfigBase)({
              reservationBiz: biz,
              associated_menu_list_ids: associatedMenuListIds
            }) : void 0;
            action({
              type: "pisell1.handleOpenEditBooking",
              data: {
                order_id: orderId,
                ...createModeConfig != null ? { createModeConfig } : {}
              },
              callback: () => {
              }
            });
          }
          break;
        case "action-cart":
          if ((0, import_bookingDetailFromRaw.isBookingRawOrderPaid)(bookingRaw)) {
            import_antd.message.info((0, import_bookingDetailModalConstants.t)("order-already-paid"));
            return;
          }
          if (typeof action === "function" && orderId != null) {
            action({
              type: "pisell1.handleOpenPayment",
              data: { order: { id: orderId } },
              callback: (res) => {
                var _a2;
                if ((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.isCallbackFromToast) return;
              }
            });
          }
          break;
        case "action-print":
          if (typeof action === "function") {
            action({
              type: "webpos.handlePrint",
              data: {
                data: bookingRaw,
                type: "0"
              },
              callback: () => {
              }
            });
          }
          break;
        case "action-list": {
          if (isIOS) {
            const nativePage = NativePage == null ? void 0 : NativePage();
            if ((nativePage == null ? void 0 : nativePage.open) && orderId != null) {
              nativePage.open({
                page: "/native/order/detail",
                params: { order_id: orderId }
              });
            }
          } else {
            if (typeof action === "function") {
              action({
                type: "pisell1.handleOpenSaleDetail",
                data: { osProps: { orderId } },
                callback: () => {
                }
              });
            }
          }
          break;
        }
        case "action-form":
          if (typeof action !== "function") {
            import_antd.message.error("Change resource failed: action is unavailable");
            return;
          }
          if (!fromResourceId) {
            import_antd.message.error("Change resource failed: missing source resource");
            return;
          }
          if (!toStartDate || !toEndDate) {
            import_antd.message.error("Change resource failed: missing booking time");
            return;
          }
          {
            const startAt = (0, import_dayjs.default)(toStartDate);
            if (!startAt.isValid()) {
              import_antd.message.error("Change resource failed: invalid booking time");
              return;
            }
            action({
              type: "pisell1.handleSelectFloorMapResource",
              data: {
                reservationBiz,
                associatedMenuListIds,
                scheduleValue: {
                  date: startAt.startOf("day"),
                  at: startAt
                },
                onClick: (selected) => {
                  var _a2, _b2, _c2;
                  const targetResourceId = (_a2 = selected == null ? void 0 : selected.resource) == null ? void 0 : _a2.id;
                  if (targetResourceId == null || String(targetResourceId).trim() === "") {
                    import_antd.message.error(
                      "Change resource failed: missing target resource"
                    );
                    return;
                  }
                  if (String(fromResourceId) === String(targetResourceId)) {
                    import_antd.message.error((0, import_bookingDetailModalConstants.t)("resource-already-bound"));
                    return;
                  }
                  const targetResource = (0, import_bookingDetailHostActions.buildEditBookingResourceSnapshot)(selected);
                  if (!(0, import_bookingDetailHostActions.isSameResourceType)(tableRow, targetResource)) {
                    import_antd.message.error((0, import_bookingDetailModalConstants.t)("resource-type-mismatch"));
                    return;
                  }
                  lastFormBookingRef.current = bookingRaw;
                  (_c2 = (_b2 = editBookingModalRef.current) == null ? void 0 : _b2.open) == null ? void 0 : _c2.call(_b2, {
                    event: bookingRaw,
                    fromResourceId,
                    toResourceId: String(targetResourceId),
                    toResource: targetResource,
                    toStartDate,
                    toEndDate,
                    mode: "resource-only"
                  });
                }
              },
              callback: () => {
              }
            });
          }
          break;
        case "action-close":
          openActionConfirm(
            "action-close",
            () => handleCancelOrderConfirmed(bookingRaw)
          );
          break;
        case "action-start":
          openActionConfirm(
            "action-start",
            () => handleStartBookingConfirmed(bookingRaw)
          );
          break;
        case "action-complete":
          openActionConfirm(
            "action-complete",
            () => handleCompleteBookingConfirmed(bookingRaw)
          );
          break;
        default:
          break;
      }
    },
    [
      appHelperUtils,
      reservationBiz,
      associatedMenuListIds,
      tableRow,
      openActionConfirm,
      handleCancelOrderConfirmed,
      handleStartBookingConfirmed,
      handleCompleteBookingConfirmed
    ]
  );
  return {
    editBookingModalRef,
    isCancellingOrder,
    isCompletingBooking,
    handleResourceChangeConfirmed,
    handleActionCellClick
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useBookingDetailActions
});
