import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import { buildReservationTicketBookingCreateModeConfigBase } from "../../utils/reservationTicketBookingHostParams.js";
import { buildEditBookingResourceSnapshot, getSalesHostModule, isSameResourceType, resolveBookingDateTime, resolveBookingIdForHostActions, resolveOrderIdForHostActions, resolveResourceIdFromRow, updateLocalOrder } from "./bookingDetailHostActions.js";
import { THEME_PRIMARY_BUTTON_STYLE, confirmCancelTextKey, confirmOkTextKey, confirmTitleKey, stopUiClick, t } from "./bookingDetailModalConstants.js";
import { isBookingRawOrderPaid } from "./bookingDetailFromRaw.js";
import dayjs from "dayjs";
import { useCallback, useRef, useState } from "react";
import { Modal, message } from "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] = useState(false);
	const [isCompletingBooking, setIsCompletingBooking] = useState(false);
	const editBookingModalRef = useRef(null);
	const lastFormBookingRef = useRef(null);
	const context = useEngineContext();
	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 = useCallback((key, onOk) => {
		Modal.confirm({
			title: t(confirmTitleKey(key)),
			okText: t(confirmOkTextKey(key)),
			cancelText: t(confirmCancelTextKey(key)),
			centered: true,
			okButtonProps: key === "action-close" ? { danger: true } : { style: THEME_PRIMARY_BUTTON_STYLE },
			onOk
		});
	}, []);
	const handleCancelOrderConfirmed = useCallback(function() {
		var _ref = _asyncToGenerator(function* (bookingRaw) {
			if (isCancellingOrder) return;
			const { action, pisellos } = appHelperUtils || {};
			const orderId = resolveOrderIdForHostActions(bookingRaw);
			if (orderId == null) {
				message.error("Cancel order failed: missing order id");
				return;
			}
			try {
				setIsCancellingOrder(true);
				const salesModule = getSalesHostModule(pisellos);
				const cancelOrder = salesModule === null || salesModule === void 0 ? void 0 : salesModule.cancelOrder;
				if (typeof cancelOrder !== "function") {
					message.error("Cancel order failed: Sales module is unavailable");
					return;
				}
				yield cancelOrder.call(salesModule, [orderId]);
				message.success("Cancel order successfully");
				updateLocalOrder(action, orderId);
				yield onActionSuccess === null || onActionSuccess === void 0 ? void 0 : onActionSuccess();
			} catch (err) {
				console.error("[ReservationBookingDetailModal] cancel order failed", err);
				message.error("Cancel order failed");
			} finally {
				setIsCancellingOrder(false);
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), [
		appHelperUtils,
		isCancellingOrder,
		onActionSuccess
	]);
	const handleStartBookingConfirmed = useCallback(function() {
		var _ref2 = _asyncToGenerator(function* (bookingRaw) {
			const { action, pisellos } = appHelperUtils || {};
			const orderId = resolveOrderIdForHostActions(bookingRaw);
			const bookingId = resolveBookingIdForHostActions(bookingRaw);
			if (bookingId == null) {
				message.error("Complete booking failed: missing booking id");
				return;
			}
			try {
				setIsCompletingBooking(true);
				const salesModule = getSalesHostModule(pisellos);
				const changeBookingStatus = salesModule === null || salesModule === void 0 ? void 0 : salesModule.changeBookingStatus;
				if (typeof changeBookingStatus !== "function") {
					message.error("Complete booking failed: Sales module is unavailable");
					return;
				}
				yield changeBookingStatus.call(salesModule, {
					booking_id: bookingId,
					appointment_status: "started"
				});
				message.success("Complete booking successfully");
				updateLocalOrder(action, orderId);
				yield onActionSuccess === null || onActionSuccess === void 0 ? void 0 : onActionSuccess();
			} catch (err) {
				console.error("[ReservationBookingDetailModal] complete booking failed", err);
				message.error("Complete booking failed");
			} finally {
				setIsCompletingBooking(false);
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}(), [appHelperUtils, onActionSuccess]);
	const handleCompleteBookingConfirmed = useCallback(function() {
		var _ref3 = _asyncToGenerator(function* (bookingRaw) {
			if (isCompletingBooking) return;
			const { action, pisellos } = appHelperUtils || {};
			const orderId = resolveOrderIdForHostActions(bookingRaw);
			const bookingId = resolveBookingIdForHostActions(bookingRaw);
			if (bookingId == null) {
				message.error("Complete booking failed: missing booking id");
				return;
			}
			try {
				setIsCompletingBooking(true);
				const salesModule = getSalesHostModule(pisellos);
				const changeBookingStatus = salesModule === null || salesModule === void 0 ? void 0 : salesModule.changeBookingStatus;
				if (typeof changeBookingStatus !== "function") {
					message.error("Complete booking failed: Sales module is unavailable");
					return;
				}
				yield changeBookingStatus.call(salesModule, {
					booking_id: bookingId,
					appointment_status: "completed"
				});
				message.success("Complete booking successfully");
				updateLocalOrder(action, orderId);
				yield onActionSuccess === null || onActionSuccess === void 0 ? void 0 : onActionSuccess();
			} catch (err) {
				console.error("[ReservationBookingDetailModal] complete booking failed", err);
				message.error("Complete booking failed");
			} finally {
				setIsCompletingBooking(false);
			}
		});
		return function(_x3) {
			return _ref3.apply(this, arguments);
		};
	}(), [
		appHelperUtils,
		isCompletingBooking,
		onActionSuccess
	]);
	return {
		editBookingModalRef,
		isCancellingOrder,
		isCompletingBooking,
		handleResourceChangeConfirmed: useCallback(() => {
			var _lastFormBookingRef$c;
			const { action } = appHelperUtils || {};
			const targetBooking = (_lastFormBookingRef$c = lastFormBookingRef.current) !== null && _lastFormBookingRef$c !== void 0 ? _lastFormBookingRef$c : raw;
			const orderId = targetBooking ? resolveOrderIdForHostActions(targetBooking) : void 0;
			if (typeof action === "function") {
				action({
					type: "pisell1.closeSelectFloorMapResource",
					data: {},
					callback: () => {}
				});
				updateLocalOrder(action, orderId);
			}
			lastFormBookingRef.current = null;
			onActionSuccess === null || onActionSuccess === void 0 || onActionSuccess();
		}, [
			appHelperUtils,
			onActionSuccess,
			raw
		]),
		handleActionCellClick: useCallback(function() {
			var _ref4 = _asyncToGenerator(function* (bookingRaw, key, e) {
				stopUiClick(e);
				if (!bookingRaw) return;
				const { action, NativePage } = appHelperUtils || {};
				const orderId = resolveOrderIdForHostActions(bookingRaw);
				const fromResourceId = resolveResourceIdFromRow(tableRow);
				const toStartDate = resolveBookingDateTime(bookingRaw, "start_at", "start_date", "start_time");
				const toEndDate = 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 !== "" ? buildReservationTicketBookingCreateModeConfigBase({
								reservationBiz: biz,
								associated_menu_list_ids: associatedMenuListIds
							}) : void 0;
							action({
								type: "pisell1.handleOpenEditBooking",
								data: _objectSpread2({ order_id: orderId }, createModeConfig != null ? { createModeConfig } : {}),
								callback: () => {}
							});
						}
						break;
					case "action-cart":
						if (isBookingRawOrderPaid(bookingRaw)) {
							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: 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") {
							message.error("Change resource failed: action is unavailable");
							return;
						}
						if (!fromResourceId) {
							message.error("Change resource failed: missing source resource");
							return;
						}
						if (!toStartDate || !toEndDate) {
							message.error("Change resource failed: missing booking time");
							return;
						}
						{
							const startAt = dayjs(toStartDate);
							if (!startAt.isValid()) {
								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() === "") {
											message.error("Change resource failed: missing target resource");
											return;
										}
										if (String(fromResourceId) === String(targetResourceId)) {
											message.error(t("resource-already-bound"));
											return;
										}
										const targetResource = buildEditBookingResourceSnapshot(selected);
										if (!isSameResourceType(tableRow, targetResource)) {
											message.error(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
export { useBookingDetailActions };
