import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import { displayRoomTitleFromRow } from "../../floorRoomCard/floorRoomCardUtils.js";
import { buildDetailModalRoomCardData, resolveBookingIdForHeader } from "../../floorRoomCard/mapRowToFloorRoomCardData.js";
import { bookingDetailOrderStripFromRaw, isBookingRawOrderPaid } from "./bookingDetailFromRaw.js";
import { bookingProductLineToProductCardData } from "./bookingProductToProductCard.js";
import { FloorRoomCardFromData } from "../../floorRoomCard/FloorRoomCardFromData.js";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { message } from "antd";
import { locales } from "@pisell/utils";
import { PisellModal, ProductCard } from "@pisell/materials";
import { EditOutlined, PrinterOutlined, ShoppingCartOutlined, UnorderedListOutlined } from "@ant-design/icons";
import "./ReservationBookingDetailModal.less";
//#region src/plus/pisellReservation/components/bookingDetailModal/ReservationBookingDetailModal.tsx
/**
* 平面图只读点击：预约详情弹窗（RoomCard + 操作格 + 顶层 products → ProductCard）
*/
const PREFIX = "pisell-res-booking-detail-modal";
const I18N_BD = "pisell-reservation.booking-detail";
/** 与 `floorMap/reservationCards.tsx` 中 RoomCard 标题兜底一致 */
const I18N_ROOM_KIND_BOUND = "pisell-reservation.room-kind-bound";
/** 默认折叠时最多展示商品条数 */
const PRODUCT_PREVIEW_COUNT = 3;
const BD_MODAL_MASK = {
	onMouseDown: (e) => e.stopPropagation(),
	onClick: (e) => e.stopPropagation()
};
function t(key) {
	return 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();
}
/**
* 宿主 action / NativePage 用的订单主键：优先 `order.id`，否则顶层 `order_id`。
*/
function resolveOrderIdForHostActions(bookingRaw) {
	var _order$id;
	const order = bookingRaw.order;
	const 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 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;
}
const ACTION_KEYS = [
	"action-edit",
	"action-cart",
	"action-print",
	"action-list"
];
const ACTION_ICONS = [
	EditOutlined,
	ShoppingCartOutlined,
	PrinterOutlined,
	UnorderedListOutlined
];
function ReservationBookingDetailModal(props) {
	const { open, onClose, raw, tableRow, sceneElementName } = props;
	const [productsExpanded, setProductsExpanded] = useState(false);
	const engineContext = useEngineContext();
	const currencySymbol = orderCurrencySymbol(raw === null || raw === void 0 ? void 0 : raw.order);
	const productCardSources = useMemo(() => {
		if (!raw) return [];
		return parseBookingProducts(raw).map((line, i) => bookingProductLineToProductCardData(line, i));
	}, [raw]);
	useEffect(() => {
		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
	]);
	const roomCardData = useMemo(() => {
		if (!raw) return null;
		return buildDetailModalRoomCardData(raw, tableRow !== null && tableRow !== void 0 ? tableRow : null);
	}, [raw, tableRow]);
	const roomCardHeaderBookingId = useMemo(() => raw ? resolveBookingIdForHeader(raw) : "", [raw]);
	const visibleProductSources = useMemo(() => {
		if (productsExpanded) return productCardSources;
		return productCardSources.slice(0, PRODUCT_PREVIEW_COUNT);
	}, [productCardSources, productsExpanded]);
	const showSeeAll = productCardSources.length > PRODUCT_PREVIEW_COUNT && !productsExpanded;
	/** 商品区顶部：件数 + 订单总价（始终 summary.total_amount） */
	const productsSummaryLine = useMemo(() => {
		var _strip$itemsCount;
		if (!raw) return "";
		const strip = bookingDetailOrderStripFromRaw(raw);
		const count = (_strip$itemsCount = strip.itemsCount) !== null && _strip$itemsCount !== void 0 ? _strip$itemsCount : 0;
		return locales.getText(`${I18N_BD}.strip-items-total`).replace(/\{count\}/g, String(count)).replace(/\{total\}/g, strip.orderTotalWithSymbol);
	}, [raw]);
	/**
	* 与平面图绑定 RoomCard 顶栏同源：`displayRoomTitleFromRow` → `row.code` → 与图元占位同款兜底文案
	* （见 `floorMap/reservationCards.tsx` `renderReservationBoundRoomCardInner`）。
	*/
	const detailModalTitle = useMemo(() => {
		var _tableRow$code;
		if (tableRow == null) return locales.getText(`${I18N_BD}.modal-title`);
		const roomTitle = displayRoomTitleFromRow(tableRow, sceneElementName != null && String(sceneElementName).trim() !== "" ? String(sceneElementName).trim() : void 0).trim();
		const 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]);
	const canShow = Boolean(open && raw != null && roomCardData != null);
	const handleActionCellClick = useCallback((key, e) => {
		var _engineContext$appHel;
		stopUiClick(e);
		if (!raw) return;
		const { action, NativePage } = ((_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.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 (isBookingRawOrderPaid(raw)) {
					message.info(t("order-already-paid"));
					return;
				}
				if (typeof action === "function" && orderId != null) action({
					type: "pisell1.handleOpenPayment",
					data: { order: { id: orderId } },
					callback: (res) => {
						var _res$data;
						if (res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.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 || 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: `${PREFIX}-wrap`
	}, raw && roomCardData ? /* @__PURE__ */ React.createElement("div", { className: PREFIX }, /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__body` }, /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__booking-card` }, /* @__PURE__ */ React.createElement("div", {
		className: `${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: `${PREFIX}__action-grid`,
		role: "group",
		"aria-label": t("action-grid-aria")
	}, ACTION_KEYS.map((key, i) => {
		const Icon = ACTION_ICONS[i];
		return /* @__PURE__ */ React.createElement("button", {
			key,
			type: "button",
			className: `${PREFIX}__action-cell`,
			onClick: (ev) => handleActionCellClick(key, ev)
		}, /* @__PURE__ */ React.createElement(Icon, {
			className: `${PREFIX}__action-icon`,
			"aria-hidden": true
		}), /* @__PURE__ */ React.createElement("span", { className: `${PREFIX}__action-label` }, t(key)));
	})), /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__products-section` }, productsSummaryLine ? /* @__PURE__ */ React.createElement("div", {
		className: `${PREFIX}__products-summary`,
		role: "status"
	}, productsSummaryLine) : null, /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__products-list` }, visibleProductSources.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__products-empty` }, t("empty-items")) : visibleProductSources.map((ds) => /* @__PURE__ */ React.createElement("div", {
		key: String(ds._id),
		className: `${PREFIX}__product-card-slot`
	}, /* @__PURE__ */ React.createElement(ProductCard, {
		dataSource: _objectSpread2(_objectSpread2({}, ds), {}, { symbol: currencySymbol }),
		isShowImage: false,
		isShowHolder: false,
		isShowNote: false,
		isShowDelete: false,
		isShowPackageNote: false,
		isShowEditProduct: false
	})))), showSeeAll ? /* @__PURE__ */ React.createElement("button", {
		type: "button",
		className: `${PREFIX}__see-all`,
		onClick: (e) => {
			stopUiClick(e);
			setProductsExpanded(true);
		}
	}, t("see-all")) : null)))) : null);
}
//#endregion
export { ReservationBookingDetailModal };
