const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_reservationTicketBookingHostParams = require("../../utils/reservationTicketBookingHostParams.js");
const require_bookingDetailHostActions = require("./bookingDetailHostActions.js");
const require_bookingDetailModalConstants = require("./bookingDetailModalConstants.js");
const require_bookingDetailFromRaw = require("./bookingDetailFromRaw.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
let antd = require("antd");
//#region src/plus/pisellReservation/components/bookingDetailModal/useBookingDetailActions.ts
/**
* 预约详情弹窗内单条 booking 的操作栏事件：编辑、结账、换资源、开始/完成、取消等。
*/
function useBookingDetailActions(options) {
	var _context$appHelper, _context$appHelper$is;
	const { raw, tableRow, reservationBiz, associatedMenuListIds, onActionSuccess, appHelperUtils } = options;
	const [isCancellingOrder, setIsCancellingOrder] = (0, react.useState)(false);
	const [isCompletingBooking, setIsCompletingBooking] = (0, react.useState)(false);
	const editBookingModalRef = (0, react.useRef)(null);
	const lastFormBookingRef = (0, react.useRef)(null);
	const context = require_useEngineContext.default();
	const isIOS = context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper$is = _context$appHelper.isIOS) === null || _context$appHelper$is === void 0 ? void 0 : _context$appHelper$is.call(_context$appHelper);
	const openActionConfirm = (0, react.useCallback)((key, onOk) => {
		antd.Modal.confirm({
			title: require_bookingDetailModalConstants.t(require_bookingDetailModalConstants.confirmTitleKey(key)),
			okText: require_bookingDetailModalConstants.t(require_bookingDetailModalConstants.confirmOkTextKey(key)),
			cancelText: require_bookingDetailModalConstants.t(require_bookingDetailModalConstants.confirmCancelTextKey(key)),
			centered: true,
			okButtonProps: key === "action-close" ? { danger: true } : { style: require_bookingDetailModalConstants.THEME_PRIMARY_BUTTON_STYLE },
			onOk
		});
	}, []);
	const handleCancelOrderConfirmed = (0, react.useCallback)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (bookingRaw) {
			if (isCancellingOrder) return;
			const { action, pisellos } = appHelperUtils || {};
			const orderId = require_bookingDetailHostActions.resolveOrderIdForHostActions(bookingRaw);
			if (orderId == null) {
				antd.message.error("Cancel order failed: missing order id");
				return;
			}
			try {
				setIsCancellingOrder(true);
				const salesModule = require_bookingDetailHostActions.getSalesHostModule(pisellos);
				const cancelOrder = salesModule === null || salesModule === void 0 ? void 0 : salesModule.cancelOrder;
				if (typeof cancelOrder !== "function") {
					antd.message.error("Cancel order failed: Sales module is unavailable");
					return;
				}
				yield cancelOrder.call(salesModule, [orderId]);
				antd.message.success("Cancel order successfully");
				require_bookingDetailHostActions.updateLocalOrder(action, orderId);
				yield onActionSuccess === null || onActionSuccess === void 0 ? void 0 : onActionSuccess();
			} catch (err) {
				console.error("[ReservationBookingDetailModal] cancel order failed", err);
				antd.message.error("Cancel order failed");
			} finally {
				setIsCancellingOrder(false);
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), [
		appHelperUtils,
		isCancellingOrder,
		onActionSuccess
	]);
	const handleStartBookingConfirmed = (0, react.useCallback)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (bookingRaw) {
			const { action, pisellos } = appHelperUtils || {};
			const orderId = require_bookingDetailHostActions.resolveOrderIdForHostActions(bookingRaw);
			const bookingId = require_bookingDetailHostActions.resolveBookingIdForHostActions(bookingRaw);
			if (bookingId == null) {
				antd.message.error("Complete booking failed: missing booking id");
				return;
			}
			try {
				setIsCompletingBooking(true);
				const salesModule = require_bookingDetailHostActions.getSalesHostModule(pisellos);
				const changeBookingStatus = salesModule === null || salesModule === void 0 ? void 0 : salesModule.changeBookingStatus;
				if (typeof changeBookingStatus !== "function") {
					antd.message.error("Complete booking failed: Sales module is unavailable");
					return;
				}
				yield changeBookingStatus.call(salesModule, {
					booking_id: bookingId,
					appointment_status: "started"
				});
				antd.message.success("Complete booking successfully");
				require_bookingDetailHostActions.updateLocalOrder(action, orderId);
				yield onActionSuccess === null || onActionSuccess === void 0 ? void 0 : onActionSuccess();
			} catch (err) {
				console.error("[ReservationBookingDetailModal] complete booking failed", err);
				antd.message.error("Complete booking failed");
			} finally {
				setIsCompletingBooking(false);
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}(), [appHelperUtils, onActionSuccess]);
	const handleCompleteBookingConfirmed = (0, react.useCallback)(function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (bookingRaw) {
			if (isCompletingBooking) return;
			const { action, pisellos } = appHelperUtils || {};
			const orderId = require_bookingDetailHostActions.resolveOrderIdForHostActions(bookingRaw);
			const bookingId = require_bookingDetailHostActions.resolveBookingIdForHostActions(bookingRaw);
			if (bookingId == null) {
				antd.message.error("Complete booking failed: missing booking id");
				return;
			}
			try {
				setIsCompletingBooking(true);
				const salesModule = require_bookingDetailHostActions.getSalesHostModule(pisellos);
				const changeBookingStatus = salesModule === null || salesModule === void 0 ? void 0 : salesModule.changeBookingStatus;
				if (typeof changeBookingStatus !== "function") {
					antd.message.error("Complete booking failed: Sales module is unavailable");
					return;
				}
				yield changeBookingStatus.call(salesModule, {
					booking_id: bookingId,
					appointment_status: "completed"
				});
				antd.message.success("Complete booking successfully");
				require_bookingDetailHostActions.updateLocalOrder(action, orderId);
				yield onActionSuccess === null || onActionSuccess === void 0 ? void 0 : onActionSuccess();
			} catch (err) {
				console.error("[ReservationBookingDetailModal] complete booking failed", err);
				antd.message.error("Complete booking failed");
			} finally {
				setIsCompletingBooking(false);
			}
		});
		return function(_x3) {
			return _ref3.apply(this, arguments);
		};
	}(), [
		appHelperUtils,
		isCompletingBooking,
		onActionSuccess
	]);
	return {
		editBookingModalRef,
		isCancellingOrder,
		isCompletingBooking,
		handleResourceChangeConfirmed: (0, react.useCallback)(() => {
			var _lastFormBookingRef$c;
			const { action } = appHelperUtils || {};
			const targetBooking = (_lastFormBookingRef$c = lastFormBookingRef.current) !== null && _lastFormBookingRef$c !== void 0 ? _lastFormBookingRef$c : raw;
			const orderId = targetBooking ? require_bookingDetailHostActions.resolveOrderIdForHostActions(targetBooking) : void 0;
			if (typeof action === "function") {
				action({
					type: "pisell1.closeSelectFloorMapResource",
					data: {},
					callback: () => {}
				});
				require_bookingDetailHostActions.updateLocalOrder(action, orderId);
			}
			lastFormBookingRef.current = null;
			onActionSuccess === null || onActionSuccess === void 0 || onActionSuccess();
		}, [
			appHelperUtils,
			onActionSuccess,
			raw
		]),
		handleActionCellClick: (0, react.useCallback)(function() {
			var _ref4 = require_asyncToGenerator._asyncToGenerator(function* (bookingRaw, key, e) {
				require_bookingDetailModalConstants.stopUiClick(e);
				if (!bookingRaw) return;
				const { action, NativePage } = appHelperUtils || {};
				const orderId = require_bookingDetailHostActions.resolveOrderIdForHostActions(bookingRaw);
				const fromResourceId = require_bookingDetailHostActions.resolveResourceIdFromRow(tableRow);
				const toStartDate = require_bookingDetailHostActions.resolveBookingDateTime(bookingRaw, "start_at", "start_date", "start_time");
				const toEndDate = require_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() : "";
							if (biz === "dine_in") {
								action({
									type: "pisell1.handleOpenCachedEditBooking",
									data: { order_id: orderId },
									callback: () => {}
								});
								break;
							}
							const createModeConfig = biz !== "" ? require_reservationTicketBookingHostParams.buildReservationTicketBookingCreateModeConfigBase({
								reservationBiz: biz,
								associated_menu_list_ids: associatedMenuListIds
							}) : void 0;
							action({
								type: "pisell1.handleOpenEditBooking",
								data: require_objectSpread2._objectSpread2({ order_id: orderId }, createModeConfig != null ? { createModeConfig } : {}),
								callback: () => {}
							});
						}
						break;
					case "action-cart":
						if (require_bookingDetailFromRaw.isBookingRawOrderPaid(bookingRaw)) {
							antd.message.info(require_bookingDetailModalConstants.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: bookingRaw,
								type: "0"
							},
							callback: () => {}
						});
						break;
					case "action-list":
						if (isIOS) {
							const nativePage = NativePage === null || NativePage === void 0 ? void 0 : NativePage();
							if ((nativePage === null || nativePage === void 0 ? 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") {
							antd.message.error("Change resource failed: action is unavailable");
							return;
						}
						if (!fromResourceId) {
							antd.message.error("Change resource failed: missing source resource");
							return;
						}
						if (!toStartDate || !toEndDate) {
							antd.message.error("Change resource failed: missing booking time");
							return;
						}
						{
							const startAt = (0, dayjs.default)(toStartDate);
							if (!startAt.isValid()) {
								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 _selected$resource, _editBookingModalRef$, _editBookingModalRef$2;
										const targetResourceId = selected === null || selected === void 0 || (_selected$resource = selected.resource) === null || _selected$resource === void 0 ? void 0 : _selected$resource.id;
										if (targetResourceId == null || String(targetResourceId).trim() === "") {
											antd.message.error("Change resource failed: missing target resource");
											return;
										}
										if (String(fromResourceId) === String(targetResourceId)) {
											antd.message.error(require_bookingDetailModalConstants.t("resource-already-bound"));
											return;
										}
										const targetResource = require_bookingDetailHostActions.buildEditBookingResourceSnapshot(selected);
										if (!require_bookingDetailHostActions.isSameResourceType(tableRow, targetResource)) {
											antd.message.error(require_bookingDetailModalConstants.t("resource-type-mismatch"));
											return;
										}
										lastFormBookingRef.current = bookingRaw;
										(_editBookingModalRef$ = editBookingModalRef.current) === null || _editBookingModalRef$ === void 0 || (_editBookingModalRef$2 = _editBookingModalRef$.open) === null || _editBookingModalRef$2 === void 0 || _editBookingModalRef$2.call(_editBookingModalRef$, {
											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;
				}
			});
			return function(_x4, _x5, _x6) {
				return _ref4.apply(this, arguments);
			};
		}(), [
			appHelperUtils,
			reservationBiz,
			associatedMenuListIds,
			tableRow,
			openActionConfirm,
			handleCancelOrderConfirmed,
			handleStartBookingConfirmed,
			handleCompleteBookingConfirmed
		])
	};
}
//#endregion
exports.useBookingDetailActions = useBookingDetailActions;
