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 { deriveDisabledEdit } from "../../salesSdk/selectors.js";
import { getWristbandList } from "../serve.js";
import { createElement, useCallback, useMemo, useState } from "react";
import { Modal, message } from "antd";
import { locales } from "@pisell/utils";
import { PisellText } from "@pisell/materials";
import { CloseCircleOutlined, EditOutlined, PrinterOutlined, RollbackOutlined, UndoOutlined } from "@ant-design/icons";
//#region src/plus/saleDetail/hooks/useSaleDetailActions.ts
const PisellAmount = PisellText.Amount;
const WRISTBAND_TAGS = [
	"ticket",
	"product_package_ticket",
	"appointment_ticket",
	"session_ticket"
];
const DEFAULT_SALE_DETAIL_ACTIONS = ["checkout"];
const DEFAULT_ACTION_CONFIG = {
	checkout: {
		row: 2,
		order: 20,
		buttonProps: { size: "large" }
	},
	refund: {
		row: 1,
		order: 10,
		buttonProps: { size: "large" }
	},
	return: {
		row: 1,
		order: 20,
		buttonProps: { size: "large" }
	},
	edit: {
		row: 1,
		order: 30,
		buttonProps: { size: "large" }
	},
	print: {
		row: 1,
		order: 20,
		buttonProps: { size: "large" }
	},
	"print-product-voucher": {
		row: 3,
		order: 10,
		buttonProps: { size: "large" }
	},
	"print-receipts": {
		row: 3,
		order: 30,
		buttonProps: { size: "large" }
	},
	"print-wristband": {
		row: 3,
		order: 20,
		buttonProps: { size: "large" }
	},
	"print-all": {
		row: 3,
		order: 40,
		buttonProps: { size: "large" }
	},
	cancel: {
		row: 3,
		order: 30,
		buttonProps: { size: "large" }
	},
	more: {
		row: 2,
		order: 10,
		buttonProps: { size: "large" }
	}
};
var EBizPrintType = /* @__PURE__ */ function(EBizPrintType) {
	/** 小票打印 */
	EBizPrintType["INVOICE"] = "INVOICE";
	/** 商品券打印 */
	EBizPrintType["WALLET"] = "WALLET";
	/** 手环打印 */
	EBizPrintType["WRISTBAND"] = "WRISTBAND";
	/** 全部打印 */
	EBizPrintType["PRINT_ALL"] = "PRINT_ALL";
	return EBizPrintType;
}(EBizPrintType || {});
const WRISTBAND_PRINT_TAGS = [
	"ticket",
	"product_package_ticket",
	"appointment_ticket",
	"session_ticket"
];
function hasWristbandVoucher(dataSource) {
	var _dataSource$sales$tem;
	const vouchers = (_dataSource$sales$tem = dataSource.sales.tempOrder) === null || _dataSource$sales$tem === void 0 ? void 0 : _dataSource$sales$tem.vouchers;
	return Array.isArray(vouchers) ? vouchers.some((voucher) => WRISTBAND_PRINT_TAGS.includes(String((voucher === null || voucher === void 0 ? void 0 : voucher.tag) || ""))) : false;
}
function toButtonGroupList(items) {
	const actionRows = items.filter((item) => !item.hidden).sort((prev, next) => {
		var _prev$order, _next$order;
		return ((_prev$order = prev.order) !== null && _prev$order !== void 0 ? _prev$order : 0) - ((_next$order = next.order) !== null && _next$order !== void 0 ? _next$order : 0);
	}).reduce((rows, item) => {
		var _item$row;
		const row = (_item$row = item.row) !== null && _item$row !== void 0 ? _item$row : 1;
		rows[row] = rows[row] || [];
		rows[row].push(item);
		return rows;
	}, {});
	return Object.keys(actionRows).map(Number).sort((prev, next) => prev - next).map((row) => actionRows[row]).filter((rowItems) => rowItems.length > 0);
}
function getActionKey(action) {
	return typeof action === "string" ? action : action.name;
}
function getActionConfig(action) {
	return typeof action === "string" ? {} : action;
}
function mergeActionItem(item, config) {
	return _objectSpread2(_objectSpread2(_objectSpread2({}, item), config), {}, { buttonProps: _objectSpread2(_objectSpread2({}, item.buttonProps), config.buttonProps) });
}
function toDropdownMenuItem(item) {
	const { buttonProps } = item;
	return {
		key: item.id,
		label: buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.children,
		icon: buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.icon,
		danger: buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.danger,
		disabled: Boolean((buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.disabled) || (buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.loading)),
		onClick: buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.onClick,
		children: item.isMore ? item.menuData : void 0
	};
}
function getSortedVisibleActionItems(items) {
	return items.filter((item) => !item.hidden).sort((prev, next) => {
		var _prev$order2, _next$order2;
		return ((_prev$order2 = prev.order) !== null && _prev$order2 !== void 0 ? _prev$order2 : 0) - ((_next$order2 = next.order) !== null && _next$order2 !== void 0 ? _next$order2 : 0);
	});
}
function resolveSaleDetailOrderId(dataSource) {
	var _dataSource$sales$tem2, _dataSource$sales$tem3, _dataSource$sales$sal;
	const id = (_dataSource$sales$tem2 = (_dataSource$sales$tem3 = dataSource.sales.tempOrder) === null || _dataSource$sales$tem3 === void 0 ? void 0 : _dataSource$sales$tem3.order_id) !== null && _dataSource$sales$tem2 !== void 0 ? _dataSource$sales$tem2 : (_dataSource$sales$sal = dataSource.sales.salesDetail) === null || _dataSource$sales$sal === void 0 || (_dataSource$sales$sal = _dataSource$sales$sal.header) === null || _dataSource$sales$sal === void 0 ? void 0 : _dataSource$sales$sal.order_id;
	if (id == null || id === "") return void 0;
	if (typeof id === "number" && Number.isFinite(id)) return id;
	const value = String(id).trim();
	if (!value) return void 0;
	const numericId = Number(value);
	return Number.isFinite(numericId) && String(numericId) === value ? numericId : value;
}
function getSalesHostModule(pisellos) {
	var _getModule;
	return pisellos === null || pisellos === void 0 || (_getModule = pisellos.getModule) === null || _getModule === void 0 ? void 0 : _getModule.call(pisellos, "sales");
}
function updateLocalOrder(action, orderId) {
	if (orderId == null || typeof action !== "function") return;
	action({
		type: "webpos.updateLocalOrderApi",
		data: { order_id: orderId }
	});
}
function hasOwnValue(record, key) {
	return record[key] !== void 0 && record[key] !== null;
}
function getSaleDetailPrintSource(dataSource) {
	var _ref, _dataSource$sales$sal2, _dataSource$sales$sal3;
	return (_ref = (_dataSource$sales$sal2 = (_dataSource$sales$sal3 = dataSource.sales.salesDetail) === null || _dataSource$sales$sal3 === void 0 ? void 0 : _dataSource$sales$sal3.raw) !== null && _dataSource$sales$sal2 !== void 0 ? _dataSource$sales$sal2 : dataSource.sales.tempOrder) !== null && _ref !== void 0 ? _ref : {};
}
function getArrayValue(record, key) {
	const value = record[key];
	return Array.isArray(value) ? value : void 0;
}
function buildSaleDetailPrintData(dataSource, orderId) {
	const source = getSaleDetailPrintSource(dataSource);
	const paymentInfo = source.payment_info;
	const printData = { order_id: orderId };
	if (hasOwnValue(source, "machine_code_print_info")) printData.machine_code_print_info = source.machine_code_print_info;
	if (hasOwnValue(source, "machine_code_print_info_v2")) printData.machine_code_print_info_v2 = source.machine_code_print_info_v2;
	if (hasOwnValue(source, "small_ticket_data")) printData.small_ticket_data = source.small_ticket_data;
	else if (paymentInfo && hasOwnValue(paymentInfo, "small_ticket_data")) printData.small_ticket_data = paymentInfo.small_ticket_data;
	if (hasOwnValue(source, "voucher_ids")) printData.voucher_ids = source.voucher_ids;
	return printData;
}
function buildSaleDetailWristbandPrintData(dataSource, orderId) {
	const source = getSaleDetailPrintSource(dataSource);
	const machineCodePrintInfoV2 = getArrayValue(source, "machine_code_print_info_v2");
	const voucherIds = getArrayValue(source, "voucher_ids");
	const printData = { order_id: orderId };
	if (voucherIds === null || voucherIds === void 0 ? void 0 : voucherIds.length) {
		printData.voucher_ids = voucherIds;
		return printData;
	}
	const wristbandPrintInfo = machineCodePrintInfoV2 === null || machineCodePrintInfoV2 === void 0 ? void 0 : machineCodePrintInfoV2.filter((item) => WRISTBAND_PRINT_TAGS.includes(String((item === null || item === void 0 ? void 0 : item.tag) || "")));
	if (wristbandPrintInfo === null || wristbandPrintInfo === void 0 ? void 0 : wristbandPrintInfo.length) printData.machine_code_print_info_v2 = wristbandPrintInfo;
	return printData;
}
function isPrintSuccessful(result) {
	return (result === null || result === void 0 ? void 0 : result.status) === "success" || (result === null || result === void 0 ? void 0 : result.result) === true;
}
function useEditBookingAction({ dataSource, getRemotePrintActionsData }) {
	var _context$appHelper, _dataSource$sales$sal4, _dataSource$sales$sal5;
	const context = useEngineContext();
	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 = resolveSaleDetailOrderId(dataSource);
	const { disabledEdit } = deriveDisabledEdit((_dataSource$sales$sal4 = dataSource.sales.salesDetail) === null || _dataSource$sales$sal4 === void 0 ? void 0 : _dataSource$sales$sal4.rootBooking, (_dataSource$sales$sal5 = dataSource.sales.salesDetail) === null || _dataSource$sales$sal5 === void 0 ? void 0 : _dataSource$sales$sal5.header);
	const refreshSaleDetail = useCallback(_asyncToGenerator(function* () {
		yield dataSource.sales.refreshSalesDetail();
	}), [dataSource.sales, orderId]);
	const handleEdit = useCallback(() => {
		if (typeof action !== "function" || orderId == null) {
			message.error(locales.getText("pisell2.sale-detail.action-unavailable"));
			return;
		}
		action({
			type: "pisell1.handleOpenCachedEditBooking",
			data: { order_id: orderId },
			callback: () => {
				refreshSaleDetail();
				getRemotePrintActionsData === null || getRemotePrintActionsData === void 0 || getRemotePrintActionsData();
			}
		});
	}, [
		action,
		getRemotePrintActionsData,
		orderId,
		refreshSaleDetail
	]);
	return {
		disabled: disabledEdit || orderId == null,
		handleEdit
	};
}
function useEditActionItem({ dataSource, getRemotePrintActionsData }) {
	const { disabled, handleEdit } = useEditBookingAction({
		dataSource,
		getRemotePrintActionsData
	});
	return useMemo(() => ({
		id: "edit",
		buttonProps: {
			block: true,
			children: locales.getText("pisell2.sale-detail.action.edit"),
			className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--edit",
			disabled,
			icon: createElement(EditOutlined),
			onClick: handleEdit
		}
	}), [disabled, handleEdit]);
}
function useReturnActionItem({ dataSource, getRemotePrintActionsData }) {
	const { disabled, handleEdit } = useEditBookingAction({
		dataSource,
		getRemotePrintActionsData
	});
	return useMemo(() => ({
		id: "return",
		buttonProps: {
			block: true,
			children: createElement("span", { className: "pisell-sale-detail-button-actions__return-label" }, locales.getText("pisell2.sale-detail.action.return-item")),
			className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--return",
			disabled,
			icon: createElement(RollbackOutlined),
			onClick: handleEdit
		}
	}), [disabled, handleEdit]);
}
function useRefundActionItem({ dataSource }) {
	var _context$appHelper2;
	const context = useEngineContext();
	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 = resolveSaleDetailOrderId(dataSource);
	const handleRefund = useCallback(() => {
		if (orderId == null) {
			message.error(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") {
			message.error(locales.getText("pisell2.sale-detail.action-unavailable"));
			return;
		}
		nativePage.open({
			page: "/native/order/refund",
			params: { order_id: orderId }
		});
	}, [NativePage, orderId]);
	return useMemo(() => ({
		id: "refund",
		buttonProps: {
			block: true,
			children: locales.getText("pisell2.sale-detail.action.refund"),
			className: "pisell-sale-detail-button-actions__button",
			disabled: orderId == null || typeof NativePage !== "function",
			icon: createElement(UndoOutlined),
			onClick: handleRefund
		}
	}), [
		NativePage,
		handleRefund,
		orderId
	]);
}
function useSaleDetailPrintAction(dataSource, printType, buildPrintData = buildSaleDetailPrintData) {
	var _context$appHelper3;
	const [loading, setLoading] = useState(false);
	const context = useEngineContext();
	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 orderId = resolveSaleDetailOrderId(dataSource);
	const handlePrint = useCallback(() => {
		if (loading) return;
		if (orderId == null) {
			message.error(locales.getText("pisell2.sale-detail.missing-order-id"));
			return;
		}
		if (typeof action !== "function") {
			message.error(locales.getText("pisell2.sale-detail.action-unavailable"));
			return;
		}
		setLoading(true);
		try {
			action({
				type: "webpos.handlePrint",
				data: {
					type: printType,
					data: buildPrintData(dataSource, orderId)
				},
				callback: (result) => {
					setLoading(false);
					if (isPrintSuccessful(result)) return;
				}
			});
		} catch (_unused) {
			setLoading(false);
		}
	}, [
		action,
		buildPrintData,
		dataSource,
		loading,
		orderId,
		printType
	]);
	return {
		disabled: orderId == null || typeof action !== "function" || loading,
		handlePrint,
		loading
	};
}
function usePrintReceiptsActionItem({ dataSource }) {
	const { disabled, handlePrint, loading } = useSaleDetailPrintAction(dataSource, EBizPrintType.INVOICE);
	return useMemo(() => ({
		id: "print-receipts",
		buttonProps: {
			block: true,
			children: locales.getText("pisell2.sale-detail.action.print-receipts"),
			className: "pisell-sale-detail-button-actions__button",
			disabled,
			icon: createElement(PrinterOutlined),
			loading,
			onClick: handlePrint
		}
	}), [
		disabled,
		handlePrint,
		loading
	]);
}
function usePrintActionItem() {
	return useMemo(() => ({
		id: "print",
		isMore: true,
		buttonProps: {
			block: true,
			children: locales.getText("pisell2.sale-detail.action.print"),
			className: "pisell-sale-detail-button-actions__button",
			icon: createElement(PrinterOutlined)
		}
	}), []);
}
function usePrintProductVoucherActionItem({ dataSource }) {
	const { disabled, handlePrint, loading } = useSaleDetailPrintAction(dataSource, EBizPrintType.WALLET);
	return useMemo(() => ({
		id: "print-product-voucher",
		buttonProps: {
			block: true,
			children: locales.getText("pisell2.sale-detail.action.print-product-voucher"),
			className: "pisell-sale-detail-button-actions__button",
			disabled,
			icon: createElement(PrinterOutlined),
			loading,
			onClick: handlePrint
		}
	}), [
		disabled,
		handlePrint,
		loading
	]);
}
function useMachineCodePrintActionItems({ dataSource, machineCodePrintActions = [] }) {
	var _context$appHelper4, _context$appHelper5;
	const [loadingTag, setLoadingTag] = useState();
	const context = useEngineContext();
	const action = 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.action;
	const getData = context === null || context === void 0 || (_context$appHelper5 = context.appHelper) === null || _context$appHelper5 === void 0 || (_context$appHelper5 = _context$appHelper5.utils) === null || _context$appHelper5 === void 0 ? void 0 : _context$appHelper5.getData;
	const orderId = resolveSaleDetailOrderId(dataSource);
	const handlePrintMachineCode = useCallback(function() {
		var _ref2 = _asyncToGenerator(function* (printAction) {
			const tag = String(printAction.tag || "").trim();
			console.log(printAction, "printAction xxxxx");
			if (!tag || loadingTag) return;
			if (orderId == null) return;
			if (typeof action !== "function" || typeof getData !== "function") return;
			setLoadingTag(tag);
			try {
				action({
					type: "webpos.handlePrint",
					data: {
						type: EBizPrintType.WALLET,
						data: {
							order_id: orderId,
							machine_code_print_info_v2: [printAction]
						}
					},
					callback: () => {
						setLoadingTag(void 0);
					}
				});
			} catch (error) {
				var _error$message;
				setLoadingTag(void 0);
				message.error(String((_error$message = error === null || error === void 0 ? void 0 : error.message) !== null && _error$message !== void 0 ? _error$message : error));
			}
		});
		return function(_x) {
			return _ref2.apply(this, arguments);
		};
	}(), [
		action,
		getData,
		loadingTag,
		orderId
	]);
	return useMemo(() => machineCodePrintActions.map((printAction, index) => {
		const tag = String((printAction === null || printAction === void 0 ? void 0 : printAction.tag) || "").trim();
		if (!tag || WRISTBAND_TAGS.includes(tag)) return void 0;
		return {
			id: `print-machine-code-${tag}-${index}`,
			order: 10 + index,
			buttonProps: {
				block: true,
				children: printAction.name || locales.getText("pisell2.sale-detail.action.print-product-voucher"),
				className: "pisell-sale-detail-button-actions__button",
				disabled: orderId == null || typeof action !== "function" || typeof getData !== "function" || Boolean(loadingTag && loadingTag !== tag),
				icon: createElement(PrinterOutlined),
				loading: loadingTag === tag,
				onClick: () => {
					handlePrintMachineCode(printAction);
				}
			}
		};
	}).filter(Boolean), [
		action,
		getData,
		handlePrintMachineCode,
		loadingTag,
		machineCodePrintActions,
		orderId
	]);
}
function usePrintWristbandActionItem({ dataSource }) {
	var _context$appHelper6;
	const context = useEngineContext();
	const action = context === null || context === void 0 || (_context$appHelper6 = context.appHelper) === null || _context$appHelper6 === void 0 || (_context$appHelper6 = _context$appHelper6.utils) === null || _context$appHelper6 === void 0 ? void 0 : _context$appHelper6.action;
	const getData = context.appHelper.utils.getData;
	const { disabled, loading } = useSaleDetailPrintAction(dataSource, EBizPrintType.WRISTBAND, buildSaleDetailWristbandPrintData);
	const orderId = resolveSaleDetailOrderId(dataSource);
	const shouldShowWristbandPrint = hasWristbandVoucher(dataSource);
	const handlePrintWristband = useCallback(_asyncToGenerator(function* () {
		const res = yield getWristbandList({ order_id: orderId }, { headers: { "Shop-Id": getData("shop_id") } });
		const voucherIds = Array.isArray(res.list) ? res.list.map((item) => item.id) : [];
		action({
			type: "webpos.handlePrint",
			data: {
				type: EBizPrintType.WRISTBAND,
				data: {
					order_id: orderId,
					voucher_ids: voucherIds
				}
			}
		});
	}), [
		action,
		getData,
		orderId
	]);
	return useMemo(() => ({
		id: "print-wristband",
		hidden: !shouldShowWristbandPrint,
		buttonProps: {
			block: true,
			children: locales.getText("pisell2.sale-detail.action.print-wristband"),
			className: "pisell-sale-detail-button-actions__button",
			disabled,
			icon: createElement(PrinterOutlined),
			loading,
			onClick: handlePrintWristband
		}
	}), [
		disabled,
		handlePrintWristband,
		loading,
		shouldShowWristbandPrint
	]);
}
function usePrintAllActionItem({ dataSource }) {
	const { disabled, handlePrint, loading } = useSaleDetailPrintAction(dataSource, EBizPrintType.PRINT_ALL);
	return useMemo(() => ({
		id: "print-all",
		buttonProps: {
			block: true,
			children: locales.getText("pisell2.sale-detail.action.print-all"),
			className: "pisell-sale-detail-button-actions__button",
			disabled,
			icon: createElement(PrinterOutlined),
			loading,
			onClick: handlePrint
		}
	}), [
		disabled,
		handlePrint,
		loading
	]);
}
function useMoreActionItem({ printReceiptsAction, printWristbandAction, cancelAction }) {
	return useMemo(() => ({
		id: "more",
		isMore: true,
		buttonProps: {
			block: true,
			className: "pisell-sale-detail-button-actions__button"
		},
		menuData: [
			toDropdownMenuItem(printReceiptsAction),
			toDropdownMenuItem(printWristbandAction),
			toDropdownMenuItem(cancelAction)
		]
	}), [
		cancelAction,
		printReceiptsAction,
		printWristbandAction
	]);
}
function useCancelActionItem({ dataSource }) {
	var _context$appHelper7, _context$appHelper8;
	const [loading, setLoading] = useState(false);
	const context = useEngineContext();
	const action = context === null || context === void 0 || (_context$appHelper7 = context.appHelper) === null || _context$appHelper7 === void 0 || (_context$appHelper7 = _context$appHelper7.utils) === null || _context$appHelper7 === void 0 ? void 0 : _context$appHelper7.action;
	const pisellos = context === null || context === void 0 || (_context$appHelper8 = context.appHelper) === null || _context$appHelper8 === void 0 || (_context$appHelper8 = _context$appHelper8.utils) === null || _context$appHelper8 === void 0 ? void 0 : _context$appHelper8.pisellos;
	const orderId = resolveSaleDetailOrderId(dataSource);
	const refreshSaleDetail = useCallback(_asyncToGenerator(function* () {
		yield dataSource.sales.refreshSalesDetail();
	}), [dataSource.sales, orderId]);
	const handleCancel = useCallback(() => {
		if (loading) return;
		Modal.confirm({
			title: locales.getText("pisell2.sale-detail.action.cancel-confirm-title"),
			okText: locales.getText("pisell2.sale-detail.action.cancel-confirm-ok"),
			cancelText: locales.getText("pisell2.sale-detail.action.cancel-confirm-cancel"),
			centered: true,
			okButtonProps: { danger: true },
			onOk: function() {
				var _ref3 = _asyncToGenerator(function* () {
					if (orderId == null) {
						message.error(locales.getText("pisell2.sale-detail.missing-order-id"));
						return;
					}
					const salesModule = getSalesHostModule(pisellos);
					const cancelOrder = salesModule === null || salesModule === void 0 ? void 0 : salesModule.cancelOrder;
					if (typeof cancelOrder !== "function") {
						message.error(locales.getText("pisell2.sale-detail.cancel-order-unavailable"));
						return;
					}
					try {
						setLoading(true);
						yield cancelOrder.call(salesModule, [orderId]);
						updateLocalOrder(action, orderId);
						yield refreshSaleDetail();
						message.success(locales.getText("pisell2.sale-detail.cancel-order-success"));
					} catch (error) {
						var _error$message2;
						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);
					}
				});
				return function onOk() {
					return _ref3.apply(this, arguments);
				};
			}()
		});
	}, [
		action,
		loading,
		orderId,
		pisellos,
		refreshSaleDetail
	]);
	return useMemo(() => ({
		id: "cancel",
		buttonProps: {
			block: true,
			children: locales.getText("pisell2.sale-detail.action.cancel"),
			className: "pisell-sale-detail-button-actions__button",
			danger: true,
			disabled: orderId == null,
			icon: createElement(CloseCircleOutlined),
			loading,
			onClick: handleCancel
		}
	}), [
		handleCancel,
		loading,
		orderId
	]);
}
function useCheckoutActionItem({ dataSource }) {
	var _dataSource$summary, _summary$amount_gap, _summary$expect_amoun, _summary$order_paid_a;
	const [loading, setLoading] = useState(false);
	const tempOrder = dataSource.sales.tempOrder;
	const orderId = resolveSaleDetailOrderId(dataSource);
	const summary = (_dataSource$summary = dataSource.summary) === null || _dataSource$summary === void 0 ? void 0 : _dataSource$summary.summary;
	const amountGap = (_summary$amount_gap = summary === null || summary === void 0 ? void 0 : summary.amount_gap) !== null && _summary$amount_gap !== void 0 ? _summary$amount_gap : 0;
	const expectAmount = (_summary$expect_amoun = summary === null || summary === void 0 ? void 0 : summary.expect_amount) !== null && _summary$expect_amoun !== void 0 ? _summary$expect_amoun : 0;
	const amountDue = Number((_summary$order_paid_a = summary === null || summary === void 0 ? void 0 : summary.order_paid_amount) !== null && _summary$order_paid_a !== void 0 ? _summary$order_paid_a : 0) > 0 ? amountGap : expectAmount;
	const shouldShowCheckout = Number(amountDue) > 0;
	const isPaid = (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payment_status) === "paid";
	const orderStatus = tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.status;
	const checkoutDisabledByAmount = summary ? Number(summary.total_refund_amount) > 0 || Number(summary.total_amount) <= 0 || Number(summary.expect_amount) <= 0 : false;
	const refreshSaleDetail = useCallback(_asyncToGenerator(function* () {
		yield dataSource.sales.refreshSalesDetail();
	}), [dataSource.sales, orderId]);
	const handleCheckout = useCallback(_asyncToGenerator(function* () {
		setLoading(true);
		try {
			yield dataSource.sales.openCheckout();
			yield refreshSaleDetail();
		} finally {
			setLoading(false);
		}
	}), [dataSource.sales, refreshSaleDetail]);
	return useMemo(() => ({
		id: "checkout",
		hidden: !shouldShowCheckout,
		buttonProps: {
			block: true,
			children: createElement("span", { className: "pisell-sale-detail-button-actions__checkout-content" }, createElement("span", { className: "pisell-sale-detail-button-actions__checkout-title" }, locales.getText("pisell2.sale-detail.action.collect-money")), createElement("span", { className: "pisell-sale-detail-button-actions__checkout-amount" }, locales.getText("pisell2.sale-detail.action.amount-due"), " ", createElement(PisellAmount, { value: amountDue }))),
			className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--primary",
			type: "primary",
			loading,
			disabled: orderId == null || loading || checkoutDisabledByAmount || isPaid || orderStatus === "cancelled",
			onClick: handleCheckout
		}
	}), [
		amountDue,
		checkoutDisabledByAmount,
		handleCheckout,
		isPaid,
		loading,
		orderId,
		orderStatus,
		shouldShowCheckout
	]);
}
function useSaleDetailActions({ dataSource, actions = DEFAULT_SALE_DETAIL_ACTIONS, machineCodePrintActions = [], getRemotePrintActionsData }) {
	var _dataSource$sales$tem4;
	const editAction = useEditActionItem({
		dataSource,
		getRemotePrintActionsData
	});
	const refundAction = useRefundActionItem({ dataSource });
	const returnAction = useReturnActionItem({
		dataSource,
		getRemotePrintActionsData
	});
	const printAction = usePrintActionItem();
	const printProductVoucherAction = usePrintProductVoucherActionItem({ dataSource });
	const machineCodePrintActionItems = useMachineCodePrintActionItems({
		dataSource,
		machineCodePrintActions
	});
	const printReceiptsAction = usePrintReceiptsActionItem({ dataSource });
	const printWristbandAction = usePrintWristbandActionItem({ dataSource });
	const printAllAction = usePrintAllActionItem({ dataSource });
	const cancelAction = useCancelActionItem({ dataSource });
	const checkoutAction = useCheckoutActionItem({ dataSource });
	const moreAction = useMoreActionItem({
		printReceiptsAction,
		printWristbandAction,
		cancelAction
	});
	const isCancelled = ((_dataSource$sales$tem4 = dataSource.sales.tempOrder) === null || _dataSource$sales$tem4 === void 0 ? void 0 : _dataSource$sales$tem4.status) === "cancelled";
	return useMemo(() => {
		if (isCancelled) return [];
		const actionItemMap = {
			edit: editAction,
			refund: refundAction,
			return: returnAction,
			print: printAction,
			"print-product-voucher": printProductVoucherAction,
			"print-receipts": printReceiptsAction,
			"print-wristband": printWristbandAction,
			"print-all": printAllAction,
			cancel: cancelAction,
			checkout: checkoutAction,
			more: moreAction
		};
		const resolveActionItem = (action) => {
			var _config$items;
			const actionKey = getActionKey(action);
			const actionConfig = getActionConfig(action);
			const config = _objectSpread2(_objectSpread2(_objectSpread2({}, DEFAULT_ACTION_CONFIG[actionKey]), actionConfig), {}, { buttonProps: _objectSpread2(_objectSpread2({}, DEFAULT_ACTION_CONFIG[actionKey].buttonProps), actionConfig.buttonProps) });
			const actionItem = mergeActionItem(actionItemMap[actionKey], config);
			if (!((_config$items = config.items) === null || _config$items === void 0 ? void 0 : _config$items.length)) return actionItem;
			const nestedActionItems = getSortedVisibleActionItems([...actionKey === "print" ? machineCodePrintActionItems : [], ...config.items.map(resolveActionItem)]);
			if (nestedActionItems.length === 1) return _objectSpread2(_objectSpread2({}, nestedActionItems[0]), {}, {
				row: actionItem.row,
				order: actionItem.order
			});
			const menuData = nestedActionItems.map(toDropdownMenuItem);
			return _objectSpread2(_objectSpread2({}, actionItem), {}, {
				isMore: true,
				menuData
			});
		};
		return toButtonGroupList(actions.map(resolveActionItem));
	}, [
		actions,
		cancelAction,
		checkoutAction,
		editAction,
		isCancelled,
		machineCodePrintActionItems,
		machineCodePrintActions,
		moreAction,
		printAction,
		printAllAction,
		printProductVoucherAction,
		printReceiptsAction,
		printWristbandAction,
		refundAction,
		returnAction
	]);
}
//#endregion
export { useSaleDetailActions };
