function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
 * 平面图只读点击：预约详情弹窗。
 * 内容由宿主 sales.getResourceBookingItem 返回的三段子列表驱动；
 * 每条 booking 渲染为「RoomCard + 操作栏 + 商品」一个完整单元。
 */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { locales } from '@pisell/utils';
import { PisellModal } from '@pisell/materials';
import useEngineContext from "../../../../hooks/useEngineContext";
import EditBookingModal from "../../../../components/booking/editBookingModal";
import { appendBookingCountSuffix, displayRoomTitleFromRow } from "../../floorRoomCard";
import { openNewReservationBookingFromHost } from "../../utils/reservationTicketBookingHostParams";
import { BookingDetailUnit } from "./BookingDetailUnit";
import { BD_MODAL_MASK, DETAIL_TAB_ITEMS, I18N_BD, I18N_ROOM_KIND_BOUND, PREFIX, stopUiClick, t } from "./bookingDetailModalConstants";
import { useResourceBookingItem } from "./bookingDetailResourceBookingItem";
import { useBookingDetailActions } from "./useBookingDetailActions";
import "./ReservationBookingDetailModal.less";
export function ReservationBookingDetailModal(props) {
  var _engineContext$appHel;
  var open = props.open,
    onClose = props.onClose,
    onActionSuccess = props.onActionSuccess,
    raw = props.raw,
    tableRow = props.tableRow,
    sceneElementName = props.sceneElementName,
    reservationBiz = props.reservationBiz,
    associatedMenuListIds = props.associatedMenuListIds,
    reservationRuleProduct = props.reservationRuleProduct,
    floorDayBookingList = props.floorDayBookingList,
    currentTime = props.currentTime,
    followWallClock = props.followWallClock;
  var _useState = useState('current-occupied'),
    _useState2 = _slicedToArray(_useState, 2),
    activeTab = _useState2[0],
    setActiveTab = _useState2[1];
  var engineContext = useEngineContext();
  var appHelperUtils = engineContext === null || engineContext === void 0 || (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.utils;
  var _useResourceBookingIt = useResourceBookingItem(activeTab, {
      open: open,
      raw: raw,
      tableRow: tableRow,
      floorDayBookingList: floorDayBookingList,
      currentTime: currentTime,
      followWallClock: followWallClock,
      pisellos: appHelperUtils === null || appHelperUtils === void 0 ? void 0 : appHelperUtils.pisellos
    }),
    resourceBookingItem = _useResourceBookingIt.resourceBookingItem,
    resourceBookingItemLoading = _useResourceBookingIt.resourceBookingItemLoading,
    activeTabBookings = _useResourceBookingIt.activeTabBookings;

  /**
   * 各 Tab 当前数量：与 `useResourceBookingItem.activeTabBookings` 同源选段，
   * 用于在 Tab 名后追加 `(N)`。`resourceBookingItem == null`（首次加载未回）
   * 时不计算计数，避免在 Tab 标签上闪过 `(0)`。
   */
  var tabCounts = useMemo(function () {
    if (resourceBookingItem == null) return null;
    return {
      'current-occupied': resourceBookingItem.bookings.length,
      ended: resourceBookingItem.completedBookings.length,
      unpaid: resourceBookingItem.unpaidBookings.length
    };
  }, [resourceBookingItem]);
  var _useBookingDetailActi = useBookingDetailActions({
      raw: raw,
      tableRow: tableRow,
      reservationBiz: reservationBiz,
      associatedMenuListIds: associatedMenuListIds,
      onActionSuccess: onActionSuccess,
      appHelperUtils: appHelperUtils
    }),
    editBookingModalRef = _useBookingDetailActi.editBookingModalRef,
    isCancellingOrder = _useBookingDetailActi.isCancellingOrder,
    isCompletingBooking = _useBookingDetailActi.isCompletingBooking,
    handleResourceChangeConfirmed = _useBookingDetailActi.handleResourceChangeConfirmed,
    handleActionCellClick = _useBookingDetailActi.handleActionCellClick;
  useEffect(function () {
    setActiveTab('current-occupied');
  }, [raw === null || raw === void 0 ? void 0 : raw.id, raw === null || raw === void 0 ? void 0 : raw.booking_uid, raw === null || raw === void 0 ? void 0 : raw.booking_id]);
  var detailModalTitle = useMemo(function () {
    var _tableRow$code;
    if (tableRow == null) {
      return locales.getText("".concat(I18N_BD, ".modal-title"));
    }
    var scene = sceneElementName != null && String(sceneElementName).trim() !== '' ? String(sceneElementName).trim() : undefined;
    var roomTitle = displayRoomTitleFromRow(tableRow, scene).trim();
    var code = (_tableRow$code = tableRow.code) === null || _tableRow$code === void 0 ? void 0 : _tableRow$code.trim();
    var baseTitle = roomTitle || code || locales.getText(I18N_ROOM_KIND_BOUND);
    /**
     * 标题尾部按 `(N/M)` 拼当前资源订单计数，与平面图大卡 header / 小卡 tooltip
     * 同源；helper 接口为通用 `BookingCountSource`，`PisellReservationTableRow`
     * 的 `bookingCount` / `completeBookingCount` 字段结构化命中即可。
     * `bookingCount` 缺失或为 0 时不渲染计数，标题与之前完全一致。
     */
    return appendBookingCountSuffix(baseTitle, tableRow);
  }, [tableRow, sceneElementName]);
  var canShow = Boolean(open && raw != null);
  var handleHeaderCloseClick = useCallback(function (e) {
    stopUiClick(e);
    onClose(e);
  }, [onClose]);
  var handleHeaderNewOrderClick = useCallback(function (e) {
    stopUiClick(e);
    openNewReservationBookingFromHost({
      appHelperUtils: appHelperUtils,
      reservationBiz: reservationBiz,
      associatedMenuListIds: associatedMenuListIds,
      reservationRuleProduct: reservationRuleProduct,
      row: tableRow !== null && tableRow !== void 0 ? tableRow : null
    });
  }, [appHelperUtils, reservationBiz, associatedMenuListIds, reservationRuleProduct, tableRow]);
  var detailModalHeader = useMemo(function () {
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__header")
    }, /*#__PURE__*/React.createElement("button", {
      type: "button",
      className: "".concat(PREFIX, "__header-action ").concat(PREFIX, "__header-action--left"),
      onClick: handleHeaderCloseClick
    }, t('header-close')), /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__header-title")
    }, detailModalTitle), /*#__PURE__*/React.createElement("button", {
      type: "button",
      className: "".concat(PREFIX, "__header-action ").concat(PREFIX, "__header-action--right"),
      onClick: handleHeaderNewOrderClick
    }, t('header-new-order')));
  }, [detailModalTitle, handleHeaderCloseClick, handleHeaderNewOrderClick]);
  var getApp = appHelperUtils === null || appHelperUtils === void 0 ? void 0 : appHelperUtils.getApp;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(PisellModal, {
    platform: "pc",
    open: canShow,
    onCancel: onClose,
    maskProps: BD_MODAL_MASK,
    focusTriggerAfterClose: false,
    title: detailModalHeader,
    closable: false,
    footer: null,
    destroyOnClose: true,
    width: 560,
    wrapClassName: "".concat(PREFIX, "-wrap"),
    zIndex: 900
  }, raw ? /*#__PURE__*/React.createElement("div", {
    className: PREFIX
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__body")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__tabs"),
    role: "tablist",
    "aria-label": t('tabs-aria')
  }, DETAIL_TAB_ITEMS.map(function (_ref) {
    var key = _ref.key,
      labelKey = _ref.labelKey;
    var active = activeTab === key;
    var count = tabCounts === null || tabCounts === void 0 ? void 0 : tabCounts[key];
    return /*#__PURE__*/React.createElement("button", {
      key: key,
      type: "button",
      role: "tab",
      "aria-selected": active,
      className: "".concat(PREFIX, "__tab").concat(active ? " ".concat(PREFIX, "__tab--active") : ''),
      onClick: function onClick(e) {
        stopUiClick(e);
        setActiveTab(key);
      }
    }, t(labelKey), count != null ? /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__tab-count")
    }, ' ', "(", count, ")") : null);
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__bookings-list"),
    role: "tabpanel",
    "aria-label": t("tab-".concat(activeTab))
  }, activeTabBookings.length === 0 ? !resourceBookingItemLoading ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__bookings-empty")
  }, t('empty-tab-bookings')) : null : activeTabBookings.map(function (bookingRaw, idx) {
    var _ref2, _ref3, _bookingRaw$id;
    var unitKey = String((_ref2 = (_ref3 = (_bookingRaw$id = bookingRaw.id) !== null && _bookingRaw$id !== void 0 ? _bookingRaw$id : bookingRaw.booking_uid) !== null && _ref3 !== void 0 ? _ref3 : bookingRaw.booking_id) !== null && _ref2 !== void 0 ? _ref2 : idx);
    return /*#__PURE__*/React.createElement(BookingDetailUnit, {
      key: unitKey,
      bookingRaw: bookingRaw,
      tableRow: tableRow,
      isCancellingOrder: isCancellingOrder,
      isCompletingBooking: isCompletingBooking,
      getApp: getApp,
      onActionCellClick: handleActionCellClick
    });
  })))) : null), /*#__PURE__*/React.createElement(EditBookingModal, {
    ref: editBookingModalRef,
    open: false,
    onCancel: function onCancel() {},
    onOk: handleResourceChangeConfirmed
  }));
}