function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
/**
 * 平面图只读点击：预约详情弹窗（RoomCard + 操作格 + 顶层 products → ProductCard）
 */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { message } from 'antd';
import useEngineContext from "../../../../hooks/useEngineContext";
import { EditOutlined, PrinterOutlined, ShoppingCartOutlined, UnorderedListOutlined } from '@ant-design/icons';
import { ProductCard, PisellModal } from '@pisell/materials';
import { locales } from '@pisell/utils';
import { bookingDetailOrderStripFromRaw, isBookingRawOrderPaid } from "./bookingDetailFromRaw";
import { bookingProductLineToProductCardData } from "./bookingProductToProductCard";
import { buildDetailModalRoomCardData, displayRoomTitleFromRow, FloorRoomCardFromData, resolveBookingIdForHeader } from "../../floorRoomCard";
import "./ReservationBookingDetailModal.less";
var PREFIX = 'pisell-res-booking-detail-modal';
var I18N_BD = 'pisell-reservation.booking-detail';
/** 与 `floorMap/reservationCards.tsx` 中 RoomCard 标题兜底一致 */
var I18N_ROOM_KIND_BOUND = 'pisell-reservation.room-kind-bound';
/** 默认折叠时最多展示商品条数 */
var PRODUCT_PREVIEW_COUNT = 3;
var BD_MODAL_MASK = {
  onMouseDown: function onMouseDown(e) {
    return e.stopPropagation();
  },
  onClick: function onClick(e) {
    return e.stopPropagation();
  }
};
function t(key) {
  return locales.getText("".concat(I18N_BD, ".").concat(key));
}
function parseBookingProducts(raw) {
  var p = raw.products;
  if (!Array.isArray(p)) return [];
  return p.filter(function (x) {
    return x && _typeof(x) === 'object';
  });
}
function orderCurrencySymbol(order) {
  if (!order) return '$';
  var s = order.currency_symbol;
  if (s != null && String(s).trim() !== '') return String(s).trim();
  return '$';
}
function stopUiClick(e) {
  e.preventDefault();
  e.stopPropagation();
}

/**
 * 宿主 action / NativePage 用的订单主键：优先 `order.id`，否则顶层 `order_id`。
 */
function resolveOrderIdForHostActions(bookingRaw) {
  var _order$id;
  var order = bookingRaw.order;
  var id = (_order$id = order === null || order === void 0 ? void 0 : order.id) !== null && _order$id !== void 0 ? _order$id : bookingRaw.order_id;
  if (id == null || id === '') return undefined;
  if (typeof id === 'number' && Number.isFinite(id)) return id;
  var s = String(id).trim();
  if (!s) return undefined;
  var 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 = [EditOutlined, ShoppingCartOutlined, PrinterOutlined, UnorderedListOutlined];
export function ReservationBookingDetailModal(props) {
  var open = props.open,
    onClose = props.onClose,
    raw = props.raw,
    tableRow = props.tableRow,
    sceneElementName = props.sceneElementName;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    productsExpanded = _useState2[0],
    setProductsExpanded = _useState2[1];
  var engineContext = useEngineContext();
  var orderObj = raw === null || raw === void 0 ? void 0 : raw.order;
  var currencySymbol = orderCurrencySymbol(orderObj);
  var productCardSources = useMemo(function () {
    if (!raw) return [];
    return parseBookingProducts(raw).map(function (line, i) {
      return bookingProductLineToProductCardData(line, i);
    });
  }, [raw]);
  useEffect(function () {
    setProductsExpanded(false);
  }, [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 roomCardData = useMemo(function () {
    if (!raw) return null;
    return buildDetailModalRoomCardData(raw, tableRow !== null && tableRow !== void 0 ? tableRow : null);
  }, [raw, tableRow]);
  var roomCardHeaderBookingId = useMemo(function () {
    return raw ? resolveBookingIdForHeader(raw) : '';
  }, [raw]);
  var visibleProductSources = useMemo(function () {
    if (productsExpanded) return productCardSources;
    return productCardSources.slice(0, PRODUCT_PREVIEW_COUNT);
  }, [productCardSources, productsExpanded]);
  var showSeeAll = productCardSources.length > PRODUCT_PREVIEW_COUNT && !productsExpanded;

  /** 商品区顶部：件数 + 订单总价（始终 summary.total_amount） */
  var productsSummaryLine = useMemo(function () {
    var _strip$itemsCount;
    if (!raw) return '';
    var strip = bookingDetailOrderStripFromRaw(raw);
    var count = (_strip$itemsCount = strip.itemsCount) !== null && _strip$itemsCount !== void 0 ? _strip$itemsCount : 0;
    return locales.getText("".concat(I18N_BD, ".strip-items-total")).replace(/\{count\}/g, String(count)).replace(/\{total\}/g, strip.orderTotalWithSymbol);
  }, [raw]);

  /**
   * 与平面图绑定 RoomCard 顶栏同源：`displayRoomTitleFromRow` → `row.code` → 与图元占位同款兜底文案
   * （见 `floorMap/reservationCards.tsx` `renderReservationBoundRoomCardInner`）。
   */
  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();
    return roomTitle || code || locales.getText(I18N_ROOM_KIND_BOUND);
  }, [tableRow, sceneElementName]);
  var canShow = Boolean(open && raw != null && roomCardData != null);
  var handleActionCellClick = useCallback(function (key, e) {
    var _engineContext$appHel;
    stopUiClick(e);
    if (!raw) return;
    var _ref = ((_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.utils) || {},
      action = _ref.action,
      NativePage = _ref.NativePage;
    var orderId = resolveOrderIdForHostActions(raw);
    switch (key) {
      case 'action-edit':
        if (typeof action === 'function' && orderId != null) {
          action({
            type: 'pisell1.handleOpenEditBooking',
            data: {
              order_id: orderId
            },
            callback: function callback() {}
          });
        }
        break;
      case 'action-cart':
        if (isBookingRawOrderPaid(raw)) {
          message.info(t('order-already-paid'));
          return;
        }
        if (typeof action === 'function' && orderId != null) {
          action({
            type: 'pisell1.handleOpenPayment',
            data: {
              order: {
                id: orderId
              }
            },
            callback: function callback(res) {
              var _res$data;
              if (res !== null && res !== void 0 && (_res$data = res.data) !== null && _res$data !== void 0 && _res$data.isCallbackFromToast) return;
            }
          });
        }
        break;
      case 'action-print':
        if (typeof action === 'function') {
          action({
            type: 'webpos.handlePrint',
            data: {
              data: raw,
              type: '2'
            },
            callback: function callback() {}
          });
        }
        break;
      case 'action-list':
        if (typeof (NativePage === null || NativePage === void 0 ? 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__*/React.createElement(PisellModal, {
    platform: "pc",
    open: canShow,
    onCancel: onClose,
    maskProps: BD_MODAL_MASK,
    focusTriggerAfterClose: false,
    title: detailModalTitle,
    footer: null,
    destroyOnClose: true,
    width: 600,
    wrapClassName: "".concat(PREFIX, "-wrap")
  }, raw && roomCardData ? /*#__PURE__*/React.createElement("div", {
    className: PREFIX
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__body")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__booking-card")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__room-card-slot pisell-res-floor-room-card"),
    onMouseDown: stopUiClick,
    onClick: stopUiClick
  }, /*#__PURE__*/React.createElement(FloorRoomCardFromData, {
    data: roomCardData,
    shellShape: "rect",
    hideHeaderCapacity: true,
    headerMainFieldOverride: roomCardHeaderBookingId
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__action-grid"),
    role: "group",
    "aria-label": t('action-grid-aria')
  }, ACTION_KEYS.map(function (key, i) {
    var Icon = ACTION_ICONS[i];
    return /*#__PURE__*/React.createElement("button", {
      key: key,
      type: "button",
      className: "".concat(PREFIX, "__action-cell"),
      onClick: function onClick(ev) {
        return handleActionCellClick(key, ev);
      }
    }, /*#__PURE__*/React.createElement(Icon, {
      className: "".concat(PREFIX, "__action-icon"),
      "aria-hidden": true
    }), /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__action-label")
    }, t(key)));
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__products-section")
  }, productsSummaryLine ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__products-summary"),
    role: "status"
  }, productsSummaryLine) : null, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__products-list")
  }, visibleProductSources.length === 0 ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__products-empty")
  }, t('empty-items')) : visibleProductSources.map(function (ds) {
    return /*#__PURE__*/React.createElement("div", {
      key: String(ds._id),
      className: "".concat(PREFIX, "__product-card-slot")
    }, /*#__PURE__*/React.createElement(ProductCard, {
      dataSource: _objectSpread(_objectSpread({}, ds), {}, {
        symbol: currencySymbol
      }),
      isShowImage: false,
      isShowHolder: false,
      isShowNote: false,
      isShowDelete: false,
      isShowPackageNote: false,
      isShowEditProduct: false
    }));
  })), showSeeAll ? /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: "".concat(PREFIX, "__see-all"),
    onClick: function onClick(e) {
      stopUiClick(e);
      setProductsExpanded(true);
    }
  }, t('see-all')) : null)))) : null);
}