require("../../../../_virtual/_rolldown/runtime.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_index = require("../../../noteModal/index.js");
const require_selectors = require("../../../salesSdk/selectors.js");
const require_utils = require("./utils.js");
let react = require("react");
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let _ant_design_icons = require("@ant-design/icons");
//#region src/plus/saleDetail/hooks/saleDetailActions/orderActions.ts
const CHECKOUT_PAYMENT_STATUS = new Set([
	"unfulfilled",
	"unpaid",
	"payment_processing"
]);
function alertMissingAction(actionName) {
	const messageText = `[SaleDetail] Missing action: ${actionName}`;
	if (typeof window !== "undefined" && typeof window.alert === "function") {
		window.alert(messageText);
		return;
	}
	antd.message.error(messageText);
}
function normalizePaymentStatus(status) {
	return status === "partially_paid" ? "unpaid" : status || "";
}
function getNumericAmount(value) {
	const amount = Number(value !== null && value !== void 0 ? value : 0);
	return Number.isFinite(amount) ? amount : 0;
}
function deriveActionState(dataSource) {
	var _dataSource$summary, _tempOrder$bookings;
	const tempOrder = dataSource.sales.tempOrder;
	const bookings = dataSource.cart.bookings || [];
	const items = dataSource.cart.items || [];
	const summary = (_dataSource$summary = dataSource.summary) === null || _dataSource$summary === void 0 ? void 0 : _dataSource$summary.summary;
	const rootBooking = tempOrder === null || tempOrder === void 0 || (_tempOrder$bookings = tempOrder.bookings) === null || _tempOrder$bookings === void 0 ? void 0 : _tempOrder$bookings[0];
	const derivedEdit = require_selectors.deriveDisabledEdit(rootBooking, tempOrder);
	const paymentStatus = normalizePaymentStatus(tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payment_status);
	const hasOrderId = Boolean(tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id);
	const hasCartItems = Boolean(bookings.length || items.length);
	const totalAmount = getNumericAmount(summary === null || summary === void 0 ? void 0 : summary.total_amount);
	const expectAmount = getNumericAmount(summary === null || summary === void 0 ? void 0 : summary.expect_amount);
	const totalRefundAmount = getNumericAmount(summary === null || summary === void 0 ? void 0 : summary.total_refund_amount);
	const baseDisabled = !hasCartItems || derivedEdit.disabledEdit;
	const isCheckout = !hasOrderId || (rootBooking === null || rootBooking === void 0 ? void 0 : rootBooking.appointment_status) !== "cancelled" && CHECKOUT_PAYMENT_STATUS.has(paymentStatus) && !derivedEdit.disabledEdit || totalAmount > 0;
	return {
		baseDisabled,
		checkoutDisabled: baseDisabled || !isCheckout || totalRefundAmount > 0 || totalAmount < 0 || expectAmount < 0,
		saveDisabled: baseDisabled
	};
}
function useEditBookingAction({ dataSource }) {
	var _context$appHelper, _dataSource$sales$sal, _dataSource$sales$sal2;
	const context = require_useEngineContext.default();
	const action = context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.action;
	const orderId = require_utils.resolveSaleDetailOrderId(dataSource);
	const { disabledEdit } = require_selectors.deriveDisabledEdit((_dataSource$sales$sal = dataSource.sales.salesDetail) === null || _dataSource$sales$sal === void 0 ? void 0 : _dataSource$sales$sal.rootBooking, (_dataSource$sales$sal2 = dataSource.sales.salesDetail) === null || _dataSource$sales$sal2 === void 0 ? void 0 : _dataSource$sales$sal2.header);
	const refreshSaleDetail = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		yield dataSource.sales.refreshSalesDetail();
	}), [dataSource.sales, orderId]);
	const handleEdit = (0, react.useCallback)(() => {
		if (typeof action !== "function" || orderId == null) {
			antd.message.error(_pisell_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
			return;
		}
		action({
			type: "pisell1.handleOpenCachedEditBooking",
			data: { order_id: orderId },
			callback: () => {
				refreshSaleDetail();
			}
		});
	}, [
		action,
		orderId,
		refreshSaleDetail
	]);
	return {
		disabled: disabledEdit || orderId == null,
		handleEdit
	};
}
function useEditActionItem({ dataSource }) {
	const { disabled, handleEdit } = useEditBookingAction({ dataSource });
	return (0, react.useMemo)(() => ({
		id: "edit",
		buttonProps: {
			block: true,
			children: _pisell_utils.locales.getText("pisell2.sale-detail.action.edit"),
			className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--edit",
			disabled,
			icon: (0, react.createElement)(_ant_design_icons.EditOutlined),
			onClick: handleEdit
		}
	}), [disabled, handleEdit]);
}
function useReturnActionItem({ dataSource }) {
	const { disabled, handleEdit } = useEditBookingAction({ dataSource });
	return (0, react.useMemo)(() => ({
		id: "return",
		buttonProps: {
			block: true,
			children: _pisell_utils.locales.getText("pisell2.sale-detail.action.return"),
			className: "pisell-sale-detail-button-actions__button",
			disabled,
			icon: (0, react.createElement)(_ant_design_icons.RollbackOutlined),
			onClick: handleEdit
		}
	}), [disabled, handleEdit]);
}
function useRefundActionItem({ dataSource }) {
	var _context$appHelper2;
	const context = require_useEngineContext.default();
	const NativePage = context === null || context === void 0 || (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.NativePage;
	const orderId = require_utils.resolveSaleDetailOrderId(dataSource);
	const handleRefund = (0, react.useCallback)(() => {
		if (orderId == null) {
			antd.message.error(_pisell_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
			return;
		}
		const nativePage = typeof NativePage === "function" ? NativePage() : void 0;
		if (typeof (nativePage === null || nativePage === void 0 ? void 0 : nativePage.open) !== "function") {
			antd.message.error(_pisell_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
			return;
		}
		nativePage.open({
			page: "/native/order/refund",
			params: { order_id: orderId }
		});
	}, [NativePage, orderId]);
	return (0, react.useMemo)(() => ({
		id: "refund",
		buttonProps: {
			block: true,
			children: _pisell_utils.locales.getText("pisell2.sale-detail.action.refund"),
			className: "pisell-sale-detail-button-actions__button",
			disabled: orderId == null || typeof NativePage !== "function",
			icon: (0, react.createElement)(_ant_design_icons.UndoOutlined),
			onClick: handleRefund
		}
	}), [
		NativePage,
		handleRefund,
		orderId
	]);
}
function useCancelActionItem({ dataSource }) {
	var _context$appHelper3, _context$appHelper4;
	const [loading, setLoading] = (0, react.useState)(false);
	const context = require_useEngineContext.default();
	const action = context === null || context === void 0 || (_context$appHelper3 = context.appHelper) === null || _context$appHelper3 === void 0 || (_context$appHelper3 = _context$appHelper3.utils) === null || _context$appHelper3 === void 0 ? void 0 : _context$appHelper3.action;
	const pisellos = context === null || context === void 0 || (_context$appHelper4 = context.appHelper) === null || _context$appHelper4 === void 0 || (_context$appHelper4 = _context$appHelper4.utils) === null || _context$appHelper4 === void 0 ? void 0 : _context$appHelper4.pisellos;
	const orderId = require_utils.resolveSaleDetailOrderId(dataSource);
	const refreshSaleDetail = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		yield dataSource.sales.refreshSalesDetail();
	}), [dataSource.sales, orderId]);
	const handleCancel = (0, react.useCallback)(() => {
		if (loading) return;
		antd.Modal.confirm({
			title: _pisell_utils.locales.getText("pisell2.sale-detail.action.cancel-confirm-title"),
			okText: _pisell_utils.locales.getText("pisell2.sale-detail.action.cancel-confirm-ok"),
			cancelText: _pisell_utils.locales.getText("pisell2.sale-detail.action.cancel-confirm-cancel"),
			centered: true,
			okButtonProps: { danger: true },
			onOk: function() {
				var _ref = require_asyncToGenerator._asyncToGenerator(function* () {
					if (orderId == null) {
						antd.message.error(_pisell_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
						return;
					}
					const salesModule = require_utils.getSalesHostModule(pisellos);
					const cancelOrder = salesModule === null || salesModule === void 0 ? void 0 : salesModule.cancelOrder;
					if (typeof cancelOrder !== "function") {
						antd.message.error(_pisell_utils.locales.getText("pisell2.sale-detail.cancel-order-unavailable"));
						return;
					}
					try {
						setLoading(true);
						yield cancelOrder.call(salesModule, [orderId]);
						require_utils.updateLocalOrder(action, orderId);
						yield refreshSaleDetail();
					} catch (error) {
						var _error$message;
						antd.message.error(String((_error$message = error === null || error === void 0 ? void 0 : error.message) !== null && _error$message !== void 0 ? _error$message : error));
					} finally {
						setLoading(false);
					}
				});
				return function onOk() {
					return _ref.apply(this, arguments);
				};
			}()
		});
	}, [
		action,
		loading,
		orderId,
		pisellos,
		refreshSaleDetail
	]);
	return (0, react.useMemo)(() => ({
		id: "cancel",
		buttonProps: {
			block: true,
			children: _pisell_utils.locales.getText("pisell2.sale-detail.action.cancel"),
			className: "pisell-sale-detail-button-actions__button",
			danger: true,
			disabled: orderId == null,
			icon: (0, react.createElement)(_ant_design_icons.CloseCircleOutlined),
			loading,
			onClick: handleCancel
		}
	}), [
		handleCancel,
		loading,
		orderId
	]);
}
function useNoteActionItem({ dataSource }) {
	var _dataSource$sales$tem, _dataSource$sales$tem3;
	const [noteModalOpen, setNoteModalOpen] = (0, react.useState)(false);
	const hasOrderNote = Boolean((_dataSource$sales$tem = dataSource.sales.tempOrder) === null || _dataSource$sales$tem === void 0 || (_dataSource$sales$tem = _dataSource$sales$tem.note) === null || _dataSource$sales$tem === void 0 ? void 0 : _dataSource$sales$tem.trim());
	const handleNote = (0, react.useCallback)(() => {
		if (typeof dataSource.sales.setOrderNote !== "function") {
			alertMissingAction("sales.setOrderNote");
			return;
		}
		setNoteModalOpen(true);
	}, [dataSource.sales]);
	const handleNoteConfirm = (0, react.useCallback)((noteValue) => {
		dataSource.sales.setOrderNote(noteValue);
		setNoteModalOpen(false);
	}, [dataSource.sales]);
	const handleNoteDelete = (0, react.useCallback)(() => {
		dataSource.sales.setOrderNote("");
		setNoteModalOpen(false);
	}, [dataSource.sales]);
	const handleNoteCancel = (0, react.useCallback)(() => {
		setNoteModalOpen(false);
	}, []);
	return (0, react.useMemo)(() => {
		var _dataSource$sales$tem2;
		return {
			id: "note",
			renderAfter: noteModalOpen ? (0, react.createElement)(require_index.default, {
				open: noteModalOpen,
				title: _pisell_utils.locales.getText("pisell2.text.add-order-notes"),
				value: ((_dataSource$sales$tem2 = dataSource.sales.tempOrder) === null || _dataSource$sales$tem2 === void 0 ? void 0 : _dataSource$sales$tem2.note) || "",
				onConfirm: handleNoteConfirm,
				onDelete: handleNoteDelete,
				onCancel: handleNoteCancel
			}) : null,
			buttonProps: {
				block: true,
				children: hasOrderNote ? (0, react.createElement)("span", { className: "pisell-sale-detail-button-actions__note-content" }, _pisell_utils.locales.getText("pisell2.sale-detail.action.note"), (0, react.createElement)("span", { className: "note-indicator" }, (0, react.createElement)(_pisell_materials.Iconfont, { type: "pisell2-info-circle2" }))) : _pisell_utils.locales.getText("pisell2.sale-detail.action.note"),
				className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--note",
				onClick: handleNote
			}
		};
	}, [
		(_dataSource$sales$tem3 = dataSource.sales.tempOrder) === null || _dataSource$sales$tem3 === void 0 ? void 0 : _dataSource$sales$tem3.note,
		handleNote,
		handleNoteCancel,
		handleNoteConfirm,
		handleNoteDelete,
		hasOrderNote,
		noteModalOpen
	]);
}
function useSaveActionItem({ dataSource }) {
	const [loading, setLoading] = (0, react.useState)(false);
	const { saveDisabled } = deriveActionState(dataSource);
	const handleSave = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (typeof dataSource.cart.submit !== "function") {
			alertMissingAction("cart.submit");
			return;
		}
		setLoading(true);
		try {
			const res = yield dataSource.cart.submit();
			if (res === null || res === void 0 ? void 0 : res.status) dataSource.sales.restore();
			else {
				var _res$message;
				antd.message.error(String((_res$message = res === null || res === void 0 ? void 0 : res.message) !== null && _res$message !== void 0 ? _res$message : res));
			}
		} catch (error) {
			var _error$message2;
			antd.message.error(String((_error$message2 = error === null || error === void 0 ? void 0 : error.message) !== null && _error$message2 !== void 0 ? _error$message2 : error));
		} finally {
			setLoading(false);
		}
	}), [dataSource.cart]);
	return (0, react.useMemo)(() => ({
		id: "save",
		buttonProps: {
			block: true,
			children: _pisell_utils.locales.getText("pisell2.sale-detail.action.save"),
			className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--save",
			disabled: saveDisabled,
			icon: (0, react.createElement)(_ant_design_icons.SaveOutlined),
			loading,
			onClick: handleSave
		}
	}), [
		handleSave,
		loading,
		saveDisabled
	]);
}
function useCheckoutActionItem({ dataSource }) {
	const [loading, setLoading] = (0, react.useState)(false);
	dataSource.sales.tempOrder;
	const orderId = require_utils.resolveSaleDetailOrderId(dataSource);
	const { checkoutDisabled } = deriveActionState(dataSource);
	const refreshSaleDetail = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		yield dataSource.sales.refreshSalesDetail();
	}), [dataSource.sales, orderId]);
	const handleCheckout = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (typeof dataSource.sales.openCheckout !== "function") {
			alertMissingAction("sales.openCheckout");
			return;
		}
		setLoading(true);
		try {
			yield dataSource.sales.openCheckout();
		} catch (error) {
			var _error$message3;
			antd.message.error(String((_error$message3 = error === null || error === void 0 ? void 0 : error.message) !== null && _error$message3 !== void 0 ? _error$message3 : error));
		} finally {
			setLoading(false);
		}
	}), [dataSource.sales, refreshSaleDetail]);
	return (0, react.useMemo)(() => ({
		id: "checkout",
		buttonProps: {
			block: true,
			children: _pisell_utils.locales.getText("pisell2.text.checkout"),
			className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--primary",
			type: "primary",
			disabled: checkoutDisabled,
			loading,
			icon: (0, react.createElement)(_pisell_materials.Iconfont, { type: "pisell2-coins-hand" }),
			onClick: handleCheckout
		}
	}), [
		checkoutDisabled,
		handleCheckout,
		loading,
		orderId
	]);
}
//#endregion
exports.useCancelActionItem = useCancelActionItem;
exports.useCheckoutActionItem = useCheckoutActionItem;
exports.useEditActionItem = useEditActionItem;
exports.useNoteActionItem = useNoteActionItem;
exports.useRefundActionItem = useRefundActionItem;
exports.useReturnActionItem = useReturnActionItem;
exports.useSaveActionItem = useSaveActionItem;
