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/ReservationBookingDetailModal.tsx
var ReservationBookingDetailModal_exports = {};
__export(ReservationBookingDetailModal_exports, {
  ReservationBookingDetailModal: () => ReservationBookingDetailModal
});
module.exports = __toCommonJS(ReservationBookingDetailModal_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_icons = require("@ant-design/icons");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_bookingDetailFromRaw = require("./bookingDetailFromRaw");
var import_bookingProductToProductCard = require("./bookingProductToProductCard");
var import_floorRoomCard = require("../../floorRoomCard");
var import_ReservationBookingDetailModal = require("./ReservationBookingDetailModal.less");
var PREFIX = "pisell-res-booking-detail-modal";
var I18N_BD = "pisell-reservation.booking-detail";
var I18N_ROOM_KIND_BOUND = "pisell-reservation.room-kind-bound";
var PRODUCT_PREVIEW_COUNT = 3;
var BD_MODAL_MASK = {
  onMouseDown: (e) => e.stopPropagation(),
  onClick: (e) => e.stopPropagation()
};
function t(key) {
  return import_utils.locales.getText(`${I18N_BD}.${key}`);
}
function parseBookingProducts(raw) {
  const p = raw.products;
  if (!Array.isArray(p)) return [];
  return p.filter((x) => x && typeof x === "object");
}
function orderCurrencySymbol(order) {
  if (!order) return "$";
  const s = order.currency_symbol;
  if (s != null && String(s).trim() !== "") return String(s).trim();
  return "$";
}
function stopUiClick(e) {
  e.preventDefault();
  e.stopPropagation();
}
function resolveOrderIdForHostActions(bookingRaw) {
  const order = bookingRaw.order;
  const id = (order == null ? void 0 : order.id) ?? bookingRaw.order_id;
  if (id == null || id === "") return void 0;
  if (typeof id === "number" && Number.isFinite(id)) return id;
  const s = String(id).trim();
  if (!s) return void 0;
  const n = Number(s);
  return Number.isFinite(n) && String(n) === s ? n : s;
}
var ACTION_KEYS = [
  "action-edit",
  "action-cart",
  "action-print",
  "action-list"
];
var ACTION_ICONS = [
  import_icons.EditOutlined,
  import_icons.ShoppingCartOutlined,
  import_icons.PrinterOutlined,
  import_icons.UnorderedListOutlined
];
function ReservationBookingDetailModal(props) {
  const { open, onClose, raw, tableRow, sceneElementName } = props;
  const [productsExpanded, setProductsExpanded] = (0, import_react.useState)(false);
  const engineContext = (0, import_useEngineContext.default)();
  const orderObj = raw == null ? void 0 : raw.order;
  const currencySymbol = orderCurrencySymbol(orderObj);
  const productCardSources = (0, import_react.useMemo)(() => {
    if (!raw) return [];
    return parseBookingProducts(raw).map(
      (line, i) => (0, import_bookingProductToProductCard.bookingProductLineToProductCardData)(line, i)
    );
  }, [raw]);
  (0, import_react.useEffect)(() => {
    setProductsExpanded(false);
  }, [raw == null ? void 0 : raw.id, raw == null ? void 0 : raw.booking_uid, raw == null ? void 0 : raw.booking_id]);
  const roomCardData = (0, import_react.useMemo)(() => {
    if (!raw) return null;
    return (0, import_floorRoomCard.buildDetailModalRoomCardData)(raw, tableRow ?? null);
  }, [raw, tableRow]);
  const roomCardHeaderBookingId = (0, import_react.useMemo)(
    () => raw ? (0, import_floorRoomCard.resolveBookingIdForHeader)(raw) : "",
    [raw]
  );
  const visibleProductSources = (0, import_react.useMemo)(() => {
    if (productsExpanded) return productCardSources;
    return productCardSources.slice(0, PRODUCT_PREVIEW_COUNT);
  }, [productCardSources, productsExpanded]);
  const showSeeAll = productCardSources.length > PRODUCT_PREVIEW_COUNT && !productsExpanded;
  const productsSummaryLine = (0, import_react.useMemo)(() => {
    if (!raw) return "";
    const strip = (0, import_bookingDetailFromRaw.bookingDetailOrderStripFromRaw)(raw);
    const count = strip.itemsCount ?? 0;
    return import_utils.locales.getText(`${I18N_BD}.strip-items-total`).replace(/\{count\}/g, String(count)).replace(/\{total\}/g, strip.orderTotalWithSymbol);
  }, [raw]);
  const detailModalTitle = (0, import_react.useMemo)(() => {
    var _a;
    if (tableRow == null) {
      return import_utils.locales.getText(`${I18N_BD}.modal-title`);
    }
    const scene = sceneElementName != null && String(sceneElementName).trim() !== "" ? String(sceneElementName).trim() : void 0;
    const roomTitle = (0, import_floorRoomCard.displayRoomTitleFromRow)(tableRow, scene).trim();
    const code = (_a = tableRow.code) == null ? void 0 : _a.trim();
    return roomTitle || code || import_utils.locales.getText(I18N_ROOM_KIND_BOUND);
  }, [tableRow, sceneElementName]);
  const canShow = Boolean(open && raw != null && roomCardData != null);
  const handleActionCellClick = (0, import_react.useCallback)(
    (key, e) => {
      var _a;
      stopUiClick(e);
      if (!raw) return;
      const { action, NativePage } = ((_a = engineContext.appHelper) == null ? void 0 : _a.utils) || {};
      const orderId = resolveOrderIdForHostActions(raw);
      switch (key) {
        case "action-edit":
          if (typeof action === "function" && orderId != null) {
            action({
              type: "pisell1.handleOpenEditBooking",
              data: { order_id: orderId },
              callback: () => {
              }
            });
          }
          break;
        case "action-cart":
          if ((0, import_bookingDetailFromRaw.isBookingRawOrderPaid)(raw)) {
            import_antd.message.info(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: raw,
                type: "2"
              },
              callback: () => {
              }
            });
          }
          break;
        case "action-list":
          if (typeof (NativePage == null ? void 0 : NativePage.open) === "function" && orderId != null) {
            NativePage.open({
              page: "/native/order/detail",
              params: { order_id: orderId }
            });
          }
          break;
        default:
          break;
      }
    },
    [raw, engineContext.appHelper]
  );
  return /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      platform: "pc",
      open: canShow,
      onCancel: onClose,
      maskProps: BD_MODAL_MASK,
      focusTriggerAfterClose: false,
      title: detailModalTitle,
      footer: null,
      destroyOnClose: true,
      width: 600,
      wrapClassName: `${PREFIX}-wrap`
    },
    raw && roomCardData ? /* @__PURE__ */ import_react.default.createElement("div", { className: PREFIX }, /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__body` }, /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__booking-card` }, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: `${PREFIX}__room-card-slot pisell-res-floor-room-card`,
        onMouseDown: stopUiClick,
        onClick: stopUiClick
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_floorRoomCard.FloorRoomCardFromData,
        {
          data: roomCardData,
          shellShape: "rect",
          hideHeaderCapacity: true,
          headerMainFieldOverride: roomCardHeaderBookingId
        }
      )
    ), /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: `${PREFIX}__action-grid`,
        role: "group",
        "aria-label": t("action-grid-aria")
      },
      ACTION_KEYS.map((key, i) => {
        const Icon = ACTION_ICONS[i];
        return /* @__PURE__ */ import_react.default.createElement(
          "button",
          {
            key,
            type: "button",
            className: `${PREFIX}__action-cell`,
            onClick: (ev) => handleActionCellClick(key, ev)
          },
          /* @__PURE__ */ import_react.default.createElement(Icon, { className: `${PREFIX}__action-icon`, "aria-hidden": true }),
          /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__action-label` }, t(key))
        );
      })
    ), /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__products-section` }, productsSummaryLine ? /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__products-summary`, role: "status" }, productsSummaryLine) : null, /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__products-list` }, visibleProductSources.length === 0 ? /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__products-empty` }, t("empty-items")) : visibleProductSources.map((ds) => /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        key: String(ds._id),
        className: `${PREFIX}__product-card-slot`
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.ProductCard,
        {
          dataSource: { ...ds, symbol: currencySymbol },
          isShowImage: false,
          isShowHolder: false,
          isShowNote: false,
          isShowDelete: false,
          isShowPackageNote: false,
          isShowEditProduct: false
        }
      )
    ))), showSeeAll ? /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        type: "button",
        className: `${PREFIX}__see-all`,
        onClick: (e) => {
          stopUiClick(e);
          setProductsExpanded(true);
        }
      },
      t("see-all")
    ) : null)))) : null
  );
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ReservationBookingDetailModal
});
