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 { genHolderKey } from "../../ticketBooking/utils/index.js";
import { isNormalProductByDurationSchedule } from "../info/service2/utils.js";
import { SelectHolderModal, selectHolderModal } from "./selectHolderModal.js";
import Lists from "../info/service/Lists.js";
import React, { useEffect, useState } from "react";
import { Button, Modal } from "antd";
import { getUniqueId, locales } from "@pisell/utils";
import { PisellContainer } from "@pisell/materials";
import { useDebounceFn } from "ahooks";
import "./confirmHolderModal.less";
//#region src/components/booking/utils/confirmHolderModal.tsx
let modalState = null;
let setModalState = null;
/**
* 计算未分配的 holder 数量
*/
function calculateUnassignedHolderCount(state) {
	var _state$service;
	const unassignedProducts = ((state === null || state === void 0 || (_state$service = state.service) === null || _state$service === void 0 ? void 0 : _state$service.value) || []).filter((item) => {
		var _item$_extend, _item$_extend2;
		return (!((_item$_extend = item._extend) === null || _item$_extend === void 0 ? void 0 : _item$_extend.holder_id) || ((_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 || (_item$_extend2 = _item$_extend2.holder_id) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.length) === 0) && !isNormalProductByDurationSchedule(item);
	});
	const arr = [];
	unassignedProducts.forEach((item) => {
		var _item$_extend3;
		if (item === null || item === void 0 || (_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3.groupId) {
			if (!arr.some((sub) => {
				var _sub$_extend, _item$_extend4;
				return (sub === null || sub === void 0 || (_sub$_extend = sub._extend) === null || _sub$_extend === void 0 ? void 0 : _sub$_extend.groupId) === (item === null || item === void 0 || (_item$_extend4 = item._extend) === null || _item$_extend4 === void 0 ? void 0 : _item$_extend4.groupId);
			})) arr.push(item);
		} else arr.push(item);
	});
	return arr.reduce((sum, item) => {
		var _item$_extend5;
		return sum + (((_item$_extend5 = item._extend) === null || _item$_extend5 === void 0 ? void 0 : _item$_extend5.quantity) || 1);
	}, 0);
}
/**
* 确认 Holder 弹窗组件（直接返回 PisellContainer，不使用 createPortal）
*/
const ConfirmHolderModal = () => {
	var _state$bookingConfig2;
	const [localState, setLocalState] = useState(modalState);
	useEffect(() => {
		setModalState = (newState) => {
			setLocalState(newState);
			modalState = newState;
		};
		return () => {
			setModalState = null;
		};
	}, []);
	const { state, dispatch, resolve } = localState || {};
	const handleClose = () => {
		if (!localState || !localState.open) return;
		Modal.confirm({
			title: locales.getText("pisell2.text.deposit-delete-message-title"),
			content: locales.getText("pisell2.text.close-confirm-message"),
			okText: locales.getText("pisell2.text.confirm"),
			cancelText: locales.getText("pisell2.text.cancel"),
			centered: true,
			onOk: () => {
				if (setModalState) setModalState(_objectSpread2(_objectSpread2({}, localState), {}, { open: false }));
				if (resolve) resolve();
			},
			onCancel: () => {}
		});
	};
	const { run: debouncedHandleClose } = useDebounceFn(handleClose, {
		wait: 500,
		leading: true,
		trailing: false
	});
	if (!localState || !localState.open) return /* @__PURE__ */ React.createElement(SelectHolderModal, null);
	const unassignedCount = calculateUnassignedHolderCount(state);
	const handleSkip = () => {
		if (setModalState) setModalState(_objectSpread2(_objectSpread2({}, localState), {}, { open: false }));
		if (resolve) resolve();
	};
	const handleConfirm = () => {
		if (setModalState) setModalState(_objectSpread2(_objectSpread2({}, localState), {}, { open: false }));
		if (resolve) resolve();
	};
	const handleChange = function() {
		var _ref = _asyncToGenerator(function* (currentItem, type, other) {
			var _state$bookingConfig, _currentItem$cacheIte, _currentItem$_extend;
			const holderConfig = (state === null || state === void 0 || (_state$bookingConfig = state.bookingConfig) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.holder) || {};
			const currentMaxSelectedCount = (holderConfig === null || holderConfig === void 0 ? void 0 : holderConfig.maxSelectedCount) || (currentItem === null || currentItem === void 0 || (_currentItem$cacheIte = currentItem.cacheItem) === null || _currentItem$cacheIte === void 0 || (_currentItem$cacheIte = _currentItem$cacheIte._extend) === null || _currentItem$cacheIte === void 0 ? void 0 : _currentItem$cacheIte.quantity) || 1;
			const currentHolderId = currentItem === null || currentItem === void 0 || (_currentItem$_extend = currentItem._extend) === null || _currentItem$_extend === void 0 ? void 0 : _currentItem$_extend.holder_id;
			const result = yield selectHolderModal({
				state,
				dispatch,
				initialValue: currentHolderId ? Array.isArray(currentHolderId) ? currentHolderId : [currentHolderId] : void 0,
				maxSelectedCount: currentMaxSelectedCount
			});
			if (result && result.length > 0) {
				var _cacheItem$_extend, _cacheItem$_extend3, _cacheItem$_extend4, _cacheItem$_extend5;
				console.log(currentItem, result);
				const _list = state.service.value;
				const cacheItem = currentItem.cacheItem;
				if (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.groupId) {
					var _cacheItem$_extend2;
					const groupId = cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend2 = cacheItem._extend) === null || _cacheItem$_extend2 === void 0 ? void 0 : _cacheItem$_extend2.groupId;
					_list.filter((item) => {
						var _item$_extend6;
						return (item === null || item === void 0 || (_item$_extend6 = item._extend) === null || _item$_extend6 === void 0 ? void 0 : _item$_extend6.groupId) === groupId;
					}).forEach((item) => {
						item._extend.holder_id = result;
					});
				} else {
					cacheItem._extend.holder_id = result;
					const index = _list.findIndex((item) => item._id === cacheItem._id);
					if (index !== -1) _list[index] = cacheItem;
				}
				if (((_cacheItem$_extend3 = cacheItem._extend) === null || _cacheItem$_extend3 === void 0 || (_cacheItem$_extend3 = _cacheItem$_extend3.holder_id) === null || _cacheItem$_extend3 === void 0 ? void 0 : _cacheItem$_extend3.length) > 1 || ((_cacheItem$_extend4 = cacheItem._extend) === null || _cacheItem$_extend4 === void 0 ? void 0 : _cacheItem$_extend4.quantity) > 1 && ((_cacheItem$_extend5 = cacheItem._extend) === null || _cacheItem$_extend5 === void 0 || (_cacheItem$_extend5 = _cacheItem$_extend5.holder_id) === null || _cacheItem$_extend5 === void 0 ? void 0 : _cacheItem$_extend5.length) >= 1) {
					let holder_ids = cacheItem._extend.holder_id;
					cacheItem._extend.holder_id = holder_ids[0];
					holder_ids = holder_ids.slice(1);
					cacheItem._holderKey = genHolderKey(cacheItem);
					holder_ids.forEach((holder_id) => {
						const newItem = _objectSpread2(_objectSpread2({}, cacheItem), {}, {
							_id: getUniqueId(),
							_extend: _objectSpread2(_objectSpread2({}, cacheItem._extend), {}, {
								holder_id: [holder_id],
								quantity: 1
							})
						});
						newItem._holderKey = genHolderKey(newItem);
						_list.unshift(newItem);
						cacheItem._extend.quantity -= 1;
					});
					if (cacheItem._extend.quantity > 1) {
						const newItem = _objectSpread2(_objectSpread2({}, cacheItem), {}, {
							_id: getUniqueId(),
							_extend: _objectSpread2(_objectSpread2({}, cacheItem._extend), {}, {
								holder_id: void 0,
								quantity: cacheItem._extend.quantity - 1
							})
						});
						newItem._holderKey = genHolderKey(newItem);
						_list.unshift(newItem);
						cacheItem._extend.quantity = 1;
					}
				}
				_list.sort((a, b) => {
					var _a$_extend, _b$_extend;
					const aHasHolderId = ((_a$_extend = a._extend) === null || _a$_extend === void 0 ? void 0 : _a$_extend.holder_id) && (Array.isArray(a._extend.holder_id) ? a._extend.holder_id.length > 0 : true);
					const bHasHolderId = ((_b$_extend = b._extend) === null || _b$_extend === void 0 ? void 0 : _b$_extend.holder_id) && (Array.isArray(b._extend.holder_id) ? b._extend.holder_id.length > 0 : true);
					if (!aHasHolderId && bHasHolderId) return -1;
					if (aHasHolderId && !bHasHolderId) return 1;
					return 0;
				});
				dispatch({
					type: "setService",
					payload: {
						value: _list,
						edit: true
					}
				});
			}
		});
		return function handleChange(_x, _x2, _x3) {
			return _ref.apply(this, arguments);
		};
	}();
	const title = locales.getText("pisell2.text.holder-unassigned")(unassignedCount);
	const hintText = locales.getText("pisell2.text.press-card-assign-holder");
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PisellContainer, {
		renderType: "modal",
		props: {
			open: localState.open,
			onCancel: () => {
				debouncedHandleClose();
			},
			title,
			footer: null,
			width: 800,
			destroyOnClose: true,
			maskClosable: false,
			closable: true
		}
	}, /* @__PURE__ */ React.createElement("div", { className: "confirm-holder-modal-content" }, /* @__PURE__ */ React.createElement("div", { className: "confirm-holder-modal-hint" }, hintText), /* @__PURE__ */ React.createElement("div", { className: "confirm-holder-modal-service" }, /* @__PURE__ */ React.createElement(Lists, {
		isParallelResource: true,
		isShowDelete: false,
		isShowAmountFooter: false,
		onChange: handleChange
	})), /* @__PURE__ */ React.createElement("div", { className: "confirm-holder-modal-footer" }, (state === null || state === void 0 || (_state$bookingConfig2 = state.bookingConfig) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.config) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.basic) === null || _state$bookingConfig2 === void 0 ? void 0 : _state$bookingConfig2.subject_require) !== "require" ? /* @__PURE__ */ React.createElement(Button, {
		onClick: handleSkip,
		className: "skip-button",
		size: "large"
	}, locales.getText("pisell2.text.skip-for-now")) : null, /* @__PURE__ */ React.createElement(Button, {
		type: "primary",
		onClick: handleConfirm,
		className: "confirm-button"
	}, locales.getText("pisell2.text.confirm"))))), /* @__PURE__ */ React.createElement(SelectHolderModal, null));
};
/**
* 通过 await 调用的确认 Holder 弹窗
* @param state 状态对象
* @param dispatch dispatch 函数
* @returns Promise，resolve 时返回 void（无论点击哪个按钮都会继续执行）
*/
function showConfirmHolderModal(state, dispatch) {
	return new Promise((resolve) => {
		modalState = {
			open: true,
			state,
			dispatch,
			resolve
		};
		if (setModalState) setModalState(modalState);
		else console.warn("ConfirmHolderModal component is not mounted. Please render <ConfirmHolderModal /> in your component tree.");
	});
}
//#endregion
export { ConfirmHolderModal, showConfirmHolderModal };
