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 { createCacheItem, genValues, isBundle, isOption, setHandleAddService, setHandleSetService } from "./utils.js";
import { getMultiDay, getProductExtend, isMultiDayProduct } from "../../../booking/info2/service/addService/utils.js";
import { getEffectiveMenuListIds } from "../../utils/menuListIds.js";
import { addService, addServiceScroll, genHolderKey, genServiceKey, getIsShowNumber, isSameProduct } from "../../utils/index.js";
import { concatBookings, createBookingItemsByGroup } from "../../../booking/info/service2/Group/utils.js";
import { holderId, isNormalProductByDurationSchedule } from "../../../booking/info/service2/utils.js";
import { getIsEject, getIsOnlySession, getMainPrice, getProductTotalPrice, isSessionProduct, isWalkIn, request } from "../../../booking/utils.js";
import { isBooking4Shop } from "../../../booking/info/utils.js";
import useEngineContext, { usePisellOS, usePlatform } from "../../../../hooks/useEngineContext.js";
import withResponsive from "../../../../responsive/withResponsive.js";
import { SelectHolderModal, selectHolderModal } from "../../../booking/utils/selectHolderModal.js";
import { getOpenNormalServiceHandler } from "../../../booking/info2/service/openNormalService.js";
import { useIsActive } from "../../context/IsActiveContext.js";
import useCartChangeEffect from "../../hooks/pisellos/useCartChangeEffect.js";
import { useProducts } from "../../hooks/pisellos/useProducts.js";
import { useService } from "../../../booking/info/service/serviceManager/index.js";
import ProductDisplayAdapter_default from "../ProductDisplayAdapter/ProductDisplayAdapter.js";
import { resolveProductDisplayConfig } from "../ProductDisplayAdapter/types.js";
import notAvailable_default from "../notAvailable/index.js";
import MultiDayTimeSelectModal from "./MultiDayTimeSelectModal.js";
import { getStockValidationResult, setHiddenStockAlertForToday } from "../../../../pro/skuDetailModal/utils.js";
import dayjs from "dayjs";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { getUniqueId, locales, sendWarningLog } from "@pisell/utils";
import { Button, Checkbox, PisellModal, useToast } from "@pisell/materials";
import { useMemoizedFn } from "ahooks";
import "./index.less";
//#region src/components/ticketBooking/components/addServiceVariant/addService.tsx
const productListResponsiveConfigMap = {
	phone: {
		productSelect: {
			layout: {
				grid: false,
				config: "12"
			},
			productListSetting: {
				imgWidth: "80px",
				imgHeight: "80px",
				coverTextFontSize: 24,
				skuCardPaddingX: 8,
				skuCardPaddingY: 8,
				gap: 10,
				rightStyle: {
					alignItems: "initial",
					minHeight: "80px",
					justifyContent: "space-between"
				}
			}
		},
		skuList: {
			listConfig: {
				columns: 1,
				columnGap: 8,
				rowGap: 8,
				skeletonConfig: {
					imageWidth: 80,
					imageHeight: 80,
					direction: "row",
					gap: 10,
					padding: 8,
					rows: 2
				}
			},
			skuCardAllConfig: {
				skuCardConfig: {
					layoutDirection: "row",
					paddingX: 8,
					paddingY: 8
				},
				skuImageConfig: {
					width: "80px",
					height: "80px",
					textFontSize: 24
				},
				skuTextConfig: {
					skuNameConfig: {
						fontWeight: 600,
						ellipsisCount: 2
					},
					skuSubtitleConfig: { ellipsisCount: 1 },
					skuPriceConfig: { priceFontWeight: 600 }
				},
				style: {
					gap: 10,
					alignItems: "center"
				},
				rightStyle: {
					alignItems: "initial",
					minHeight: "80px",
					justifyContent: "space-between"
				}
			}
		}
	},
	smallTablet: {
		productSelect: {
			layout: {
				grid: true,
				config: "12:12"
			},
			productListSetting: {
				imgWidth: "88px",
				imgHeight: "88px",
				coverTextFontSize: 24,
				skuCardPaddingX: 10,
				skuCardPaddingY: 10,
				gap: 12,
				rightStyle: {
					alignItems: "initial",
					minHeight: "88px",
					justifyContent: "space-between"
				}
			}
		},
		skuList: {
			listConfig: {
				columns: 2,
				columnGap: 10,
				rowGap: 10,
				skeletonConfig: {
					imageWidth: 88,
					imageHeight: 88,
					direction: "row",
					gap: 12,
					padding: 10,
					rows: 2
				}
			},
			skuCardAllConfig: {
				skuCardConfig: {
					layoutDirection: "row",
					paddingX: 10,
					paddingY: 10
				},
				skuImageConfig: {
					width: "88px",
					height: "88px",
					textFontSize: 24
				},
				skuTextConfig: {
					skuNameConfig: {
						fontWeight: 600,
						ellipsisCount: 2
					},
					skuSubtitleConfig: { ellipsisCount: 1 },
					skuPriceConfig: { priceFontWeight: 600 }
				},
				style: {
					gap: 12,
					alignItems: "center"
				},
				rightStyle: {
					alignItems: "initial",
					minHeight: "88px",
					justifyContent: "space-between"
				}
			}
		}
	},
	tablet: {
		productSelect: {
			layout: {
				grid: true,
				config: "12:12"
			},
			productListSetting: {
				imgWidth: "96px",
				imgHeight: "88px",
				coverTextFontSize: 28,
				skuCardPaddingX: 10,
				skuCardPaddingY: 10,
				gap: 12,
				rightStyle: {
					alignItems: "initial",
					minHeight: "88px",
					justifyContent: "space-between"
				}
			}
		},
		skuList: {
			listConfig: {
				columns: 3,
				columnGap: 12,
				rowGap: 12,
				skeletonConfig: {
					imageWidth: "100%",
					imageHeight: 104,
					direction: "column",
					gap: 10,
					padding: 10,
					rows: 2
				}
			},
			skuCardAllConfig: {
				skuCardConfig: {
					layoutDirection: "column",
					paddingX: 10,
					paddingY: 10
				},
				skuImageConfig: {
					width: "100%",
					height: "104px",
					textFontSize: 30
				},
				skuTextConfig: {
					skuNameConfig: {
						fontWeight: 600,
						ellipsisCount: 2
					},
					skuSubtitleConfig: { ellipsisCount: 1 },
					skuPriceConfig: { priceFontWeight: 600 }
				}
			}
		}
	},
	pos: { productSelect: { layout: {
		grid: true,
		config: "12:12"
	} } },
	desktop: {
		productSelect: {
			layout: {
				grid: true,
				config: "8:8:8"
			},
			productListSetting: {
				imgWidth: "120px",
				imgHeight: "96px",
				coverTextFontSize: 36,
				skuCardPaddingX: 12,
				skuCardPaddingY: 12,
				gap: 12,
				rightStyle: {
					alignItems: "initial",
					minHeight: "96px",
					justifyContent: "space-between"
				}
			}
		},
		skuList: {
			listConfig: {
				columns: 5,
				columnGap: 12,
				rowGap: 12,
				skeletonConfig: {
					imageWidth: "100%",
					imageHeight: 112,
					direction: "column",
					gap: 12,
					padding: 12,
					rows: 2
				}
			},
			skuCardAllConfig: {
				skuCardConfig: {
					layoutDirection: "column",
					paddingX: 12,
					paddingY: 12
				},
				skuImageConfig: {
					width: "100%",
					height: "112px",
					textFontSize: 32
				},
				skuTextConfig: {
					skuNameConfig: {
						fontWeight: 600,
						ellipsisCount: 2
					},
					skuSubtitleConfig: { ellipsisCount: 1 },
					skuPriceConfig: { priceFontWeight: 600 }
				}
			}
		}
	}
};
const getProductListResponsiveConfig = (variant) => {
	if (!variant) return void 0;
	return productListResponsiveConfigMap[variant];
};
const getProductDisplayResponsiveMode = (config) => {
	if (config === "sku-list-a2") return "skuListA2";
	if (config === "sku-list-a5") return "skuListA5";
};
const getColumnsFromProductSelectLayout = (layout) => {
	const layoutConfig = layout === null || layout === void 0 ? void 0 : layout.config;
	if (!layoutConfig) return void 0;
	return layoutConfig.split(":").filter(Boolean).length || void 0;
};
const omitUndefined = (obj) => {
	return Object.entries(obj).reduce((acc, [key, value]) => {
		if (value !== void 0) acc[key] = value;
		return acc;
	}, {});
};
const getSkuListA2ResponsiveConfig = (config) => {
	if (!config) return void 0;
	const setting = config.productListSetting || {};
	const columns = getColumnsFromProductSelectLayout(config.layout);
	const imageWidth = setting.imgWidth;
	const imageHeight = setting.imgHeight;
	const paddingX = setting.skuCardPaddingX;
	const paddingY = setting.skuCardPaddingY;
	const gap = setting.gap;
	return {
		listConfig: omitUndefined({
			columns,
			columnGap: gap,
			rowGap: gap,
			skeletonConfig: imageWidth && imageHeight ? omitUndefined({
				imageWidth,
				imageHeight,
				direction: "row",
				gap,
				padding: paddingY !== null && paddingY !== void 0 ? paddingY : paddingX,
				rows: 2
			}) : void 0
		}),
		skuCardAllConfig: {
			skuCardConfig: omitUndefined({
				layoutDirection: "row",
				paddingX,
				paddingY
			}),
			skuImageConfig: omitUndefined({
				width: imageWidth,
				height: imageHeight,
				textFontSize: setting.coverTextFontSize
			}),
			style: omitUndefined({
				gap,
				alignItems: "center"
			}),
			rightStyle: setting.rightStyle
		}
	};
};
const mergeSkuTextConfig = (base = {}, override = {}) => _objectSpread2(_objectSpread2(_objectSpread2({}, base), override), {}, {
	infoConfig: _objectSpread2(_objectSpread2({}, base.infoConfig), override.infoConfig),
	skuNameConfig: _objectSpread2(_objectSpread2({}, base.skuNameConfig), override.skuNameConfig),
	skuSubtitleConfig: _objectSpread2(_objectSpread2({}, base.skuSubtitleConfig), override.skuSubtitleConfig),
	skuPriceConfig: _objectSpread2(_objectSpread2({}, base.skuPriceConfig), override.skuPriceConfig),
	skuStockConfig: _objectSpread2(_objectSpread2({}, base.skuStockConfig), override.skuStockConfig)
});
const mergeSkuCardAllConfig = (base = {}, override = {}) => _objectSpread2(_objectSpread2(_objectSpread2({}, base), override), {}, {
	skuCardConfig: _objectSpread2(_objectSpread2({}, base.skuCardConfig), override.skuCardConfig),
	skuImageConfig: _objectSpread2(_objectSpread2({}, base.skuImageConfig), override.skuImageConfig),
	skuTextConfig: mergeSkuTextConfig(base.skuTextConfig, override.skuTextConfig),
	skuActionConfig: _objectSpread2(_objectSpread2({}, base.skuActionConfig), override.skuActionConfig),
	skuExtraConfig: _objectSpread2(_objectSpread2({}, base.skuExtraConfig), override.skuExtraConfig),
	style: _objectSpread2(_objectSpread2({}, base.style), override.style),
	rightStyle: _objectSpread2(_objectSpread2({}, base.rightStyle), override.rightStyle)
});
const AddSerivce = (props) => {
	var _context$appHelper, _context$appHelper2, _context$appHelper2$g, _context$appHelper$ut, _context$appHelper$ut2, _context$appHelper$ut3, _state$service, _state$bookingConfig, _state$client2, _state$bookingConfig11;
	const { onEdit, state, dispatch, renderMode = "current", onPrerenderComplete, onGetProductsReady, productDisplayConfig, variant } = props;
	console.log("AddSerivce props", props);
	const context = useEngineContext();
	const platform = usePlatform();
	const { getData } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const notAvailableRef = useRef(null);
	request.setRequest(context.appHelper.utils.request);
	const isActive = useIsActive();
	usePisellOS();
	const { onCartChange } = useCartChangeEffect();
	const Toast = useToast();
	const { createBookingData, createBooking } = useService({
		renderMode,
		onEdit,
		state,
		dispatch
	});
	const isBooking4 = isBooking4Shop(((_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 || (_context$appHelper2$g = _context$appHelper2.getData) === null || _context$appHelper2$g === void 0 ? void 0 : _context$appHelper2$g.call(_context$appHelper2, "shop_id")) || ((_context$appHelper$ut = context.appHelper.utils.store) === null || _context$appHelper$ut === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut.getState) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.call(_context$appHelper$ut)) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.global) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.globalConfig) === null || _context$appHelper$ut2 === void 0 ? void 0 : _context$appHelper$ut2.id), state === null || state === void 0 ? void 0 : state.renderType, (_context$appHelper$ut3 = context.appHelper.utils) === null || _context$appHelper$ut3 === void 0 ? void 0 : _context$appHelper$ut3.businessUtils);
	const [currentProduct, setCurrentProduct] = useState(null);
	const [firstLoading, setFirstLoading] = useState(true);
	const [multiDayModalOpen, setMultiDayModalOpen] = useState(false);
	const [multiDayModalLoading, setMultiDayModalLoading] = useState(false);
	const [pendingMultiDayData, setPendingMultiDayData] = useState(null);
	const [directStockAlertOpen, setDirectStockAlertOpen] = useState(false);
	const [directStockAlertDontShowAgainChecked, setDirectStockAlertDontShowAgainChecked] = useState(false);
	const directStockPendingRef = useRef(null);
	const directStockProductIdRef = useRef(0);
	const stateRef = useRef(state);
	stateRef.current = state;
	const prerenderCompletedRef = useRef(false);
	useRef((state === null || state === void 0 || (_state$service = state.service) === null || _state$service === void 0 ? void 0 : _state$service.value) || []);
	const lastOperationTimeRef = useRef(0);
	const productDisplayAdapterRef = useRef(null);
	const { getProducts, products, loading, getScheduleTimePoints } = useProducts(notAvailableRef);
	useEffect(() => {
		if (onGetProductsReady && getProducts) onGetProductsReady(getProducts);
	}, []);
	useEffect(() => {
		const timer = setTimeout(() => {
			setFirstLoading(false);
		}, 300);
		return () => {
			clearTimeout(timer);
		};
	}, []);
	useEffect(() => {
		return () => {
			Object.values(debounceTimersRef.current).forEach((timer) => {
				if (timer) clearTimeout(timer);
			});
			debounceTimersRef.current = {};
		};
	}, []);
	useEffect(() => {
		if (!loading && !prerenderCompletedRef.current) {
			onPrerenderComplete === null || onPrerenderComplete === void 0 || onPrerenderComplete();
			prerenderCompletedRef.current = true;
		}
	}, [loading]);
	useEffect(() => {
		const handler = (event) => {
			var _event$detail, _productDisplayAdapte, _productDisplayAdapte2;
			const cacheItem = event === null || event === void 0 || (_event$detail = event.detail) === null || _event$detail === void 0 ? void 0 : _event$detail.cacheItem;
			console.log("Modal closed with result:", event.detail.cacheItem);
			if (!(cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.id)) return;
			addServiceScroll(String(cacheItem.id), cacheItem);
			(_productDisplayAdapte = productDisplayAdapterRef.current) === null || _productDisplayAdapte === void 0 || (_productDisplayAdapte = _productDisplayAdapte.getTabbarRef()) === null || _productDisplayAdapte === void 0 || (_productDisplayAdapte2 = _productDisplayAdapte.closeSearchMode) === null || _productDisplayAdapte2 === void 0 || _productDisplayAdapte2.call(_productDisplayAdapte);
		};
		window.addEventListener("onAddNewService", handler);
		return () => {
			window.removeEventListener("onAddNewService", handler);
		};
	}, []);
	const pendingCacheValuesRef = useRef({});
	const clickCountRef = useRef({});
	const debounceTimersRef = useRef({});
	const menuList = useMemo(() => getEffectiveMenuListIds(state), [state === null || state === void 0 ? void 0 : state.associated_menu_list_ids, state === null || state === void 0 || (_state$bookingConfig = state.bookingConfig) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.config]);
	const customerId = useMemo(() => {
		var _state$client;
		return ((_state$client = state.client) === null || _state$client === void 0 || (_state$client = _state$client.value) === null || _state$client === void 0 ? void 0 : _state$client.id) || void 0;
	}, [(_state$client2 = state.client) === null || _state$client2 === void 0 || (_state$client2 = _state$client2.value) === null || _state$client2 === void 0 ? void 0 : _state$client2.id]);
	const scanAddService = useMemoizedFn((list, code) => {
		let newService = [...stateRef.current.service.value || []];
		list.forEach((item) => {
			if (isBundle(item) || isOption(item)) {
				handleSelectProduct(item);
				return;
			}
			if (((item === null || item === void 0 ? void 0 : item.variant) || []).filter((variantItem) => (variantItem === null || variantItem === void 0 ? void 0 : variantItem.code) === code || (variantItem === null || variantItem === void 0 ? void 0 : variantItem.barcode) === code).length >= 2) {
				handleSelectProduct(item);
				return;
			}
			let cacheItem = createCacheItem(item, genValues(item, code), stateRef.current);
			cacheItem._serviceKey = genServiceKey(cacheItem);
			cacheItem._holderKey = genHolderKey(cacheItem);
			cacheItem.autoClose = false;
			let { list: _list, quantity } = addService([...newService], cacheItem, stateRef.current);
			handleAddToast(cacheItem.title, quantity);
			newService = _list;
		});
		stateRef.current = _objectSpread2(_objectSpread2({}, stateRef.current), {}, { service: _objectSpread2(_objectSpread2({}, stateRef.current.service), {}, { value: newService }) });
		dispatch({
			type: "setService",
			payload: {
				value: newService,
				edit: true
			}
		});
	});
	useMemo(() => {
		if (isActive) {
			setHandleSetService(scanAddService);
			setHandleAddService((productData, callbackPromotion) => {
				openProductModal(productData, "select", callbackPromotion);
			});
		}
	}, [isActive]);
	const handleAddToast = (title, quantity) => {
		var _Toast$success;
		Toast === null || Toast === void 0 || (_Toast$success = Toast.success) === null || _Toast$success === void 0 || _Toast$success.call(Toast, /* @__PURE__ */ React.createElement("div", { className: "add-toast-wrap" }, /* @__PURE__ */ React.createElement("div", { className: "add-toast-title" }, title), /* @__PURE__ */ React.createElement("div", { className: "add-toast-quantity" }, locales.getText("pisell2.ticket-booking.in-cart")(quantity || 1))));
	};
	const executeCacheValues = useMemoizedFn((productId, originalCacheValues, item, originalCallback) => {
		const clickCount = clickCountRef.current[productId] || 1;
		const finalCacheValues = _objectSpread2(_objectSpread2({}, originalCacheValues), {}, { quantity: clickCount });
		delete pendingCacheValuesRef.current[productId];
		delete clickCountRef.current[productId];
		delete debounceTimersRef.current[productId];
		originalCallback(finalCacheValues, "", item, true);
		lastOperationTimeRef.current = Date.now();
	});
	useMemoizedFn((productId, cacheValues, item, callback) => {
		if (debounceTimersRef.current[productId]) clearTimeout(debounceTimersRef.current[productId]);
		const debounceTime = Number(localStorage.getItem("pisell_service_add_debounce_time")) || 0;
		debounceTimersRef.current[productId] = setTimeout(() => {
			executeCacheValues(productId, cacheValues, item, callback);
		}, debounceTime);
	});
	const checkResourceAvailability = useMemoizedFn((item) => {
		if (!isNormalProductByDurationSchedule(item)) {
			var _state$service3;
			if (!Array.isArray((_state$service3 = state.service) === null || _state$service3 === void 0 ? void 0 : _state$service3.resourcesOrigin) || !state.service.resourcesOrigin.length) {
				dispatch({
					type: "setService",
					payload: _objectSpread2(_objectSpread2({}, stateRef.current.service), {}, { reloadResourceModal: true })
				});
				return false;
			}
		}
		return true;
	});
	const createCacheItemFromParams = useMemoizedFn((item, params, detail, options) => {
		var _state$bookingConfig2, _detail$_extend, _detail$_extend2, _detail$_extend3, _detail$_extend4, _detail$_extend5, _detail$_extend6, _detail$_extend$price, _detail$_extend7, _cacheItem$_extend, _cacheItem$_extend2;
		const _detail = detail || item;
		const other = JSON.parse(JSON.stringify(params));
		other.session = params.session;
		let cacheItem = _objectSpread2(_objectSpread2({}, _detail), {}, {
			product_id: item.id,
			_id: getUniqueId(),
			is_price_include_tax: getData("is_price_include_tax"),
			_key: params.key,
			_extend: {
				start_date: (options === null || options === void 0 ? void 0 : options.startDate) || state.date.value,
				quantity: (params === null || params === void 0 ? void 0 : params.quantity) || 1,
				product_name: item.title,
				other,
				end_date: options === null || options === void 0 ? void 0 : options.endDate,
				isFormSubject: (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 || (_state$bookingConfig2 = _state$bookingConfig2.appointment_subject) === null || _state$bookingConfig2 === void 0 ? void 0 : _state$bookingConfig2.type) === "form",
				isNormalProduct: isNormalProductByDurationSchedule(item),
				note: _detail === null || _detail === void 0 || (_detail$_extend = _detail._extend) === null || _detail$_extend === void 0 ? void 0 : _detail$_extend.note,
				priceOverride: _detail === null || _detail === void 0 || (_detail$_extend2 = _detail._extend) === null || _detail$_extend2 === void 0 ? void 0 : _detail$_extend2.priceOverride,
				origin_total: _detail === null || _detail === void 0 || (_detail$_extend3 = _detail._extend) === null || _detail$_extend3 === void 0 ? void 0 : _detail$_extend3.origin_total,
				_skuValue: _detail === null || _detail === void 0 || (_detail$_extend4 = _detail._extend) === null || _detail$_extend4 === void 0 ? void 0 : _detail$_extend4.skuValue,
				price: _detail === null || _detail === void 0 || (_detail$_extend5 = _detail._extend) === null || _detail$_extend5 === void 0 ? void 0 : _detail$_extend5.price,
				weighing: _detail === null || _detail === void 0 || (_detail$_extend6 = _detail._extend) === null || _detail$_extend6 === void 0 ? void 0 : _detail$_extend6.weighing
			},
			new: 1
		});
		cacheItem._extend.price = getMainPrice(cacheItem, (_detail$_extend$price = _detail === null || _detail === void 0 || (_detail$_extend7 = _detail._extend) === null || _detail$_extend7 === void 0 ? void 0 : _detail$_extend7.price) !== null && _detail$_extend$price !== void 0 ? _detail$_extend$price : _detail.price);
		let _total = getProductTotalPrice(cacheItem);
		cacheItem._extend.total = _total;
		if (!((_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.origin_total) && ((_cacheItem$_extend2 = cacheItem._extend) === null || _cacheItem$_extend2 === void 0 ? void 0 : _cacheItem$_extend2.origin_total) !== 0) cacheItem._extend.origin_total = _total;
		if (!!state.service.cacheItem) {
			var _state$service$cacheI;
			cacheItem._id = (_state$service$cacheI = state.service.cacheItem) === null || _state$service$cacheI === void 0 ? void 0 : _state$service$cacheI._id;
			cacheItem.new = 0;
		}
		if (renderMode === "current") cacheItem.currentDefaultTime = state.date.value.format("HH:mm");
		cacheItem = isNormalProductByDurationSchedule(item) ? _objectSpread2(_objectSpread2({}, cacheItem), {}, { autoClose: true }) : getProductExtend({
			cacheItem,
			state,
			isDisabledTime: true
		});
		if (state.renderType === "eventBooking") cacheItem.autoClose = false;
		return cacheItem;
	});
	const getProductKey = useMemoizedFn((item, cacheItem) => {
		return cacheItem._serviceKey || `${item.id}_${cacheItem._key}`;
	});
	const getServiceQuantity = useMemoizedFn((cacheItem) => {
		var _stateRef$current$ser, _existingService$_ext;
		const existingService = (_stateRef$current$ser = stateRef.current.service.value) === null || _stateRef$current$ser === void 0 ? void 0 : _stateRef$current$ser.find((val) => isSameProduct(val, cacheItem));
		return (existingService === null || existingService === void 0 || (_existingService$_ext = existingService._extend) === null || _existingService$_ext === void 0 ? void 0 : _existingService$_ext.quantity) || 0;
	});
	const getMultiDayCacheItem = function() {
		var _ref = _asyncToGenerator(function* (cacheItem, isConcatBookings) {
			cacheItem = yield getMultiDay({
				start_date: cacheItem._extend.start_date,
				end_date: cacheItem._extend.end_date,
				state: stateRef.current,
				cacheItem
			});
			cacheItem = createBookingItemsByGroup(cacheItem);
			if (isConcatBookings) cacheItem = concatBookings(cacheItem);
			return cacheItem;
		});
		return function getMultiDayCacheItem(_x, _x2) {
			return _ref.apply(this, arguments);
		};
	}();
	const processAutoCloseService = useMemoizedFn(function() {
		var _ref2 = _asyncToGenerator(function* (cacheItem, item, detail, notShowToast, callbackPromotion) {
			var _cacheItem$_extend3;
			console.time("processAutoCloseService2");
			cacheItem.autoClose = false;
			cacheItem._serviceKey = genServiceKey(cacheItem);
			const isMultiDay = isMultiDayProduct(cacheItem);
			if (isMultiDay) cacheItem = yield getMultiDayCacheItem(cacheItem);
			if (callbackPromotion) {
				callbackPromotion(cacheItem);
				return;
			}
			const productKey = getProductKey(item, cacheItem);
			const addCount = (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend3 = cacheItem._extend) === null || _cacheItem$_extend3 === void 0 ? void 0 : _cacheItem$_extend3.quantity) || 1;
			if (pendingCacheValuesRef.current[productKey]) clickCountRef.current[productKey] = (clickCountRef.current[productKey] || 1) + addCount;
			else {
				pendingCacheValuesRef.current[productKey] = {
					cacheItem,
					item,
					detail,
					notShowToast
				};
				clickCountRef.current[productKey] = addCount;
			}
			if (!notShowToast) {
				const totalQuantity = getServiceQuantity(cacheItem) + (clickCountRef.current[productKey] || 1);
				handleAddToast(cacheItem.title, totalQuantity);
			}
			if (debounceTimersRef.current[productKey]) clearTimeout(debounceTimersRef.current[productKey]);
			const debounceTime = Number(localStorage.getItem("pisell_service_add_debounce_time")) || 0;
			debounceTimersRef.current[productKey] = setTimeout(() => {
				executeServiceDispatch(productKey, isMultiDay);
			}, debounceTime);
			console.timeEnd("processAutoCloseService2");
		});
		return function(_x3, _x4, _x5, _x6, _x7) {
			return _ref2.apply(this, arguments);
		};
	}());
	const executeServiceDispatch = useMemoizedFn((productKey, isMultiDay) => {
		var _cacheItem$_extend4;
		console.time("executeServiceDispatch");
		console.time("executeServiceDispatch1");
		const pendingData = pendingCacheValuesRef.current[productKey];
		if (!pendingData) return;
		const { cacheItem, item, detail } = pendingData;
		const clickCount = clickCountRef.current[productKey] || (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend4 = cacheItem._extend) === null || _cacheItem$_extend4 === void 0 ? void 0 : _cacheItem$_extend4.quantity) || 1;
		const finalCacheItem = isMultiDay ? cacheItem : _objectSpread2(_objectSpread2({}, cacheItem), {}, { _extend: _objectSpread2(_objectSpread2({}, cacheItem._extend), {}, { quantity: clickCount }) });
		console.timeEnd("executeServiceDispatch1");
		console.time("executeServiceDispatch addService");
		let { list: _list, quantity } = addService([...stateRef.current.service.value || []], finalCacheItem, stateRef.current, isMultiDay);
		console.timeEnd("executeServiceDispatch addService");
		console.time("executeServiceDispatch2");
		window.dispatchEvent(new CustomEvent("onAddNewService", { detail: { cacheItem: finalCacheItem } }));
		console.timeEnd("executeServiceDispatch2");
		console.time("executeServiceDispatch3");
		logServiceForSpecificShop(item, detail, _list);
		stateRef.current = _objectSpread2(_objectSpread2({}, stateRef.current), {}, { service: _objectSpread2(_objectSpread2({}, stateRef.current.service), {}, { value: _list }) });
		onCartChange("add", _list);
		dispatch({
			type: "setService",
			payload: {
				addModal: false,
				value: _list,
				edit: true,
				changeService: false
			}
		});
		console.timeEnd("executeServiceDispatch3");
		console.timeEnd("executeServiceDispatch");
		delete pendingCacheValuesRef.current[productKey];
		delete clickCountRef.current[productKey];
		delete debounceTimersRef.current[productKey];
	});
	const processManualEditService = useMemoizedFn(function() {
		var _ref3 = _asyncToGenerator(function* (cacheItem, callbackPromotion) {
			var _window$openBookingEd, _window;
			(_window$openBookingEd = (_window = window).openBookingEditModal) === null || _window$openBookingEd === void 0 || _window$openBookingEd.call(_window);
			if (isMultiDayProduct(cacheItem)) cacheItem = yield getMultiDayCacheItem(cacheItem, true);
			dispatch({
				type: "setService",
				payload: {
					editModal: true,
					cacheItem,
					addModal: !cacheItem.autoClose,
					changeService: false,
					callbackPromotion
				}
			});
			onEdit === null || onEdit === void 0 || onEdit(cacheItem);
		});
		return function(_x8, _x9) {
			return _ref3.apply(this, arguments);
		};
	}());
	const logServiceForSpecificShop = useMemoizedFn((item, detail, _list) => {
		try {
			var _context$appHelper$ut4, _context$appHelper$ut5;
			if (((_context$appHelper$ut4 = context.appHelper.utils.store) === null || _context$appHelper$ut4 === void 0 || (_context$appHelper$ut5 = _context$appHelper$ut4.getState) === null || _context$appHelper$ut5 === void 0 || (_context$appHelper$ut5 = _context$appHelper$ut5.call(_context$appHelper$ut4)) === null || _context$appHelper$ut5 === void 0 || (_context$appHelper$ut5 = _context$appHelper$ut5.global) === null || _context$appHelper$ut5 === void 0 || (_context$appHelper$ut5 = _context$appHelper$ut5.globalConfig) === null || _context$appHelper$ut5 === void 0 ? void 0 : _context$appHelper$ut5.id) === 2155) {
				const val = _list === null || _list === void 0 ? void 0 : _list.map((s) => {
					return {
						product_id: s === null || s === void 0 ? void 0 : s.product_id,
						detailId: s === null || s === void 0 ? void 0 : s.id,
						detailProductId: s === null || s === void 0 ? void 0 : s.product_id,
						product_name: s === null || s === void 0 ? void 0 : s.title,
						price: s === null || s === void 0 ? void 0 : s.price,
						_id: s === null || s === void 0 ? void 0 : s._id,
						_key: s === null || s === void 0 ? void 0 : s._key,
						_serviceKey: s === null || s === void 0 ? void 0 : s._serviceKey
					};
				});
				const sendData = {
					product_id: item === null || item === void 0 ? void 0 : item.id,
					detailId: detail === null || detail === void 0 ? void 0 : detail.id,
					detailProductId: detail === null || detail === void 0 ? void 0 : detail.product_id,
					product_name: item === null || item === void 0 ? void 0 : item.title,
					price: detail === null || detail === void 0 ? void 0 : detail.price,
					serviceVal: val
				};
				sendWarningLog({
					title: "addService",
					content: [{
						key: "添加数据",
						value: JSON.stringify(sendData)
					}, {
						key: "日期",
						value: dayjs().format("YYYY-MM-DD HH:mm:ss")
					}]
				});
			}
		} catch (error) {}
	});
	const handleBookingCreation = useMemoizedFn(function() {
		var _ref4 = _asyncToGenerator(function* (item, params, detail) {
			createBooking({ booking: yield createBookingData({ product: _objectSpread2(_objectSpread2({}, detail || item), {}, { _params: params }) }) });
		});
		return function(_x10, _x11, _x12) {
			return _ref4.apply(this, arguments);
		};
	}());
	const handleMultiDayConfirm = useMemoizedFn(function() {
		var _ref5 = _asyncToGenerator(function* (startDate, endDate, duration) {
			if (!pendingMultiDayData) return;
			setMultiDayModalLoading(true);
			try {
				const { item, detail, e, notShowToast } = pendingMultiDayData;
				yield handleBooking4Service(item, e, detail, notShowToast, {
					startDate,
					endDate
				});
				setPendingMultiDayData(null);
				setMultiDayModalOpen(false);
			} catch (error) {
				console.error("添加跨日商品失败:", error);
			} finally {
				setMultiDayModalLoading(false);
			}
		});
		return function(_x13, _x14, _x15) {
			return _ref5.apply(this, arguments);
		};
	}());
	const handleMultiDayCancel = useMemoizedFn(() => {
		setMultiDayModalOpen(false);
		setPendingMultiDayData(null);
	});
	const handleAddHolder = useMemoizedFn(function() {
		var _ref6 = _asyncToGenerator(function* (cacheItem) {
			var _stateRef$current2, _cacheItem$_extend5;
			const holderConfig = ((_stateRef$current2 = stateRef.current) === null || _stateRef$current2 === void 0 || (_stateRef$current2 = _stateRef$current2.bookingConfig) === null || _stateRef$current2 === void 0 ? void 0 : _stateRef$current2.holder) || {};
			const currentMaxSelectedCount = (holderConfig === null || holderConfig === void 0 ? void 0 : holderConfig.maxSelectedCount) || (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend5 = cacheItem._extend) === null || _cacheItem$_extend5 === void 0 ? void 0 : _cacheItem$_extend5.quantity) || 1;
			return yield selectHolderModal({
				state: stateRef.current,
				dispatch,
				maxSelectedCount: currentMaxSelectedCount
			});
		});
		return function(_x16) {
			return _ref6.apply(this, arguments);
		};
	}());
	const handleBooking4Service = useMemoizedFn(function() {
		var _ref7 = _asyncToGenerator(function* (item, params, detail, notShowToast, options) {
			var _state$client3, _state$bookingConfig3, _state$bookingConfig4;
			let cacheItem = createCacheItemFromParams(item, params, detail, options);
			const callbackPromotion = options === null || options === void 0 ? void 0 : options.callbackPromotion;
			if (!isNormalProductByDurationSchedule(cacheItem) && (!cacheItem._extend.holder_id || !cacheItem._extend.holder_id.length) && !isWalkIn((_state$client3 = state.client) === null || _state$client3 === void 0 || (_state$client3 = _state$client3.value) === null || _state$client3 === void 0 ? void 0 : _state$client3.id) && (state === null || state === void 0 || (_state$bookingConfig3 = state.bookingConfig) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.config) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.basic) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.appointment_subject) === null || _state$bookingConfig3 === void 0 ? void 0 : _state$bookingConfig3.type) === "form" && (state === null || state === void 0 || (_state$bookingConfig4 = state.bookingConfig) === null || _state$bookingConfig4 === void 0 || (_state$bookingConfig4 = _state$bookingConfig4.config) === null || _state$bookingConfig4 === void 0 || (_state$bookingConfig4 = _state$bookingConfig4.basic) === null || _state$bookingConfig4 === void 0 || (_state$bookingConfig4 = _state$bookingConfig4.appointment_subject) === null || _state$bookingConfig4 === void 0 ? void 0 : _state$bookingConfig4.show_hold_on_add_cart) !== 0 && !callbackPromotion) {
				const res = yield handleAddHolder(cacheItem);
				if (res && res.length > 0) cacheItem._extend.holder_id = res;
				else {
					var _state$bookingConfig5;
					if ((state === null || state === void 0 || (_state$bookingConfig5 = state.bookingConfig) === null || _state$bookingConfig5 === void 0 || (_state$bookingConfig5 = _state$bookingConfig5.config) === null || _state$bookingConfig5 === void 0 || (_state$bookingConfig5 = _state$bookingConfig5.basic) === null || _state$bookingConfig5 === void 0 ? void 0 : _state$bookingConfig5.subject_require) === "require") return;
				}
			}
			if (cacheItem.autoClose) yield processAutoCloseService(cacheItem, item, detail, notShowToast, callbackPromotion);
			else yield processManualEditService(cacheItem, callbackPromotion);
		});
		return function(_x17, _x18, _x19, _x20, _x21) {
			return _ref7.apply(this, arguments);
		};
	}());
	const proceedDirectAddService = useMemoizedFn(function() {
		var _ref8 = _asyncToGenerator(function* (params) {
			var _state$client4, _state$bookingConfig6, _state$bookingConfig7;
			const { cacheItem, item, detail } = params;
			if (!isNormalProductByDurationSchedule(cacheItem) && (!cacheItem._extend.holder_id || !cacheItem._extend.holder_id.length) && !isWalkIn((_state$client4 = state.client) === null || _state$client4 === void 0 || (_state$client4 = _state$client4.value) === null || _state$client4 === void 0 ? void 0 : _state$client4.id) && (state === null || state === void 0 || (_state$bookingConfig6 = state.bookingConfig) === null || _state$bookingConfig6 === void 0 || (_state$bookingConfig6 = _state$bookingConfig6.config) === null || _state$bookingConfig6 === void 0 || (_state$bookingConfig6 = _state$bookingConfig6.basic) === null || _state$bookingConfig6 === void 0 || (_state$bookingConfig6 = _state$bookingConfig6.appointment_subject) === null || _state$bookingConfig6 === void 0 ? void 0 : _state$bookingConfig6.type) === "form" && (state === null || state === void 0 || (_state$bookingConfig7 = state.bookingConfig) === null || _state$bookingConfig7 === void 0 || (_state$bookingConfig7 = _state$bookingConfig7.config) === null || _state$bookingConfig7 === void 0 || (_state$bookingConfig7 = _state$bookingConfig7.basic) === null || _state$bookingConfig7 === void 0 || (_state$bookingConfig7 = _state$bookingConfig7.appointment_subject) === null || _state$bookingConfig7 === void 0 ? void 0 : _state$bookingConfig7.show_hold_on_add_cart) !== 0) {
				const res = yield handleAddHolder(cacheItem);
				if (res && res.length > 0) cacheItem._extend.holder_id = res;
				else {
					var _state$bookingConfig8;
					if ((state === null || state === void 0 || (_state$bookingConfig8 = state.bookingConfig) === null || _state$bookingConfig8 === void 0 || (_state$bookingConfig8 = _state$bookingConfig8.config) === null || _state$bookingConfig8 === void 0 || (_state$bookingConfig8 = _state$bookingConfig8.basic) === null || _state$bookingConfig8 === void 0 ? void 0 : _state$bookingConfig8.subject_require) === "require") return;
				}
			}
			if (cacheItem.autoClose) yield processAutoCloseService(cacheItem, item, detail || item, false);
			else yield processManualEditService(cacheItem);
		});
		return function(_x22) {
			return _ref8.apply(this, arguments);
		};
	}());
	const handleDirectStockAlertCancel = useMemoizedFn(() => {
		directStockPendingRef.current = null;
		directStockProductIdRef.current = 0;
		setDirectStockAlertOpen(false);
		setDirectStockAlertDontShowAgainChecked(false);
	});
	const handleDirectStockAlertContinue = useMemoizedFn(_asyncToGenerator(function* () {
		var _stateRef$current$boo, _stateRef$current3;
		const pendingData = directStockPendingRef.current;
		if (!pendingData) {
			setDirectStockAlertOpen(false);
			return;
		}
		if (Number((_stateRef$current$boo = (_stateRef$current3 = stateRef.current) === null || _stateRef$current3 === void 0 || (_stateRef$current3 = _stateRef$current3.bookingConfig) === null || _stateRef$current3 === void 0 || (_stateRef$current3 = _stateRef$current3.config) === null || _stateRef$current3 === void 0 || (_stateRef$current3 = _stateRef$current3.stock_setting) === null || _stateRef$current3 === void 0 ? void 0 : _stateRef$current3.do_not_show_again_today) !== null && _stateRef$current$boo !== void 0 ? _stateRef$current$boo : 0) === 1 && directStockAlertDontShowAgainChecked) setHiddenStockAlertForToday({ productId: directStockProductIdRef.current });
		yield proceedDirectAddService(pendingData);
		directStockPendingRef.current = null;
		directStockProductIdRef.current = 0;
		setDirectStockAlertOpen(false);
		setDirectStockAlertDontShowAgainChecked(false);
	}));
	const handleDirectAddService = useMemoizedFn(function() {
		var _ref9 = _asyncToGenerator(function* (item) {
			var _state$bookingConfig9;
			if (!isBooking4) {
				yield handleBookingCreation(item, item.cartDetailValue);
				return;
			}
			const cacheItem = createCacheItemFromParams(item, item.cartDetailValue);
			const stockResult = getStockValidationResult({
				value: item === null || item === void 0 ? void 0 : item.cartDetailValue,
				data: item,
				bookingConfig: state === null || state === void 0 || (_state$bookingConfig9 = state.bookingConfig) === null || _state$bookingConfig9 === void 0 ? void 0 : _state$bookingConfig9.config
			});
			if (stockResult.shouldBlock) {
				Toast === null || Toast === void 0 || Toast.fail(locales.getText("pisell2.skuOptionsSelection.variantItemCard.soldOut"));
				return;
			}
			if (stockResult.shouldShowAlert) {
				directStockPendingRef.current = {
					cacheItem,
					item,
					detail: item
				};
				directStockProductIdRef.current = stockResult.productId;
				setDirectStockAlertDontShowAgainChecked(false);
				setDirectStockAlertOpen(true);
				return;
			}
			yield proceedDirectAddService({
				cacheItem,
				item,
				detail: item
			});
		});
		return function(_x23) {
			return _ref9.apply(this, arguments);
		};
	}());
	const createProductModalCallback = useMemoizedFn((item, callbackPromotion) => {
		return function() {
			var _ref10 = _asyncToGenerator(function* (e, extension_type, detail, notShowToast) {
				setCurrentProduct(null);
				if (!isBooking4) {
					yield handleBookingCreation(item, e, detail);
					return;
				}
				if (isMultiDayProduct(detail || item)) {
					setPendingMultiDayData({
						item,
						detail,
						e,
						notShowToast
					});
					setMultiDayModalOpen(true);
					return;
				}
				yield handleBooking4Service(item, e, detail, notShowToast, {
					startDate: state.date.value,
					callbackPromotion
				});
			});
			return function(_x24, _x25, _x26, _x27) {
				return _ref10.apply(this, arguments);
			};
		}();
	});
	const openProductModal = useMemoizedFn((item, type = "select", callbackPromotion) => {
		const isSession = isSessionProduct(item);
		const isOnlySession = getIsOnlySession(item);
		const isEject = getIsEject(item, type);
		if (isNormalProductByDurationSchedule(item)) {
			const openNormalService = getOpenNormalServiceHandler();
			if (openNormalService) openNormalService({
				mode: "create",
				productId: item.id,
				productData: item,
				date: state.date.value.format("YYYY-MM-DD"),
				isEject: isEject ? 1 : 0,
				skuDetailConfig: item.skuDetailConfig || {},
				onClose: () => {
					setCurrentProduct(null);
				},
				callback: createProductModalCallback(item, callbackPromotion)
			});
		} else state.action({
			type: "pisell1.handleOpenProductModal",
			data: {
				id: item.id,
				date: state.date.value.format("YYYY-MM-DD"),
				productDetail: item,
				showConfig: {
					option: true,
					session: isSession,
					variant: true,
					package: true,
					number: getIsShowNumber(item, state)
				},
				value: item === null || item === void 0 ? void 0 : item.initValue,
				isOnlySession,
				is_eject: isEject ? 1 : 0,
				customer_id: customerId,
				isOS: isSession
			},
			onCancel: () => {
				setCurrentProduct(null);
			},
			callback: createProductModalCallback(item, callbackPromotion)
		});
	});
	const handleSelectProduct = useMemoizedFn(function() {
		var _ref11 = _asyncToGenerator(function* (item, type = "select") {
			console.time("handleSelectProduct2");
			console.log(item, "handleSelectProduct");
			console.time("checkResourceAvailability");
			if (!checkResourceAvailability(item)) return;
			console.timeEnd("checkResourceAvailability");
			if (item.open_sold_weight) {
				openProductModal(item, type);
				return;
			}
			if (!item.isOpenDetailModal && item.cartDetailValue) {
				yield handleDirectAddService(item);
				return;
			}
			openProductModal(item, type);
		});
		return function(_x28) {
			return _ref11.apply(this, arguments);
		};
	}());
	/**
	const handleSelectProduct = useMemoizedFn(
	(item: any, type: 'select' | 'detail' = 'select') => {
	console.log(item, 'handleSelectProduct');
	if (!isNormalProductByDurationSchedule(item)) {
	if (
	!Array.isArray(state.service?.resourcesOrigin) ||
	!state.service.resourcesOrigin.length
	) {
	dispatch({
	type: 'setService',
	payload: {
	...stateRef.current.service,
	reloadResourceModal: true,
	},
	});
	return;
	}
	}
	const isSession = isSessionProduct(item);
	// 是否有单规格 组合规格 套餐, 或者session商品 如果没有不需要打开弹窗
	const isEject = getIsEject(item, type);
	const isOnlySession = getIsOnlySession(item);
	let lock = false;
	// 对于不需要打开弹窗的商品, 直接模拟数据, 不走弹窗
	let cacheValues = null;
	if (isEject) {
	setCurrentProduct(item);
	} else {
	setCurrentProduct(null);
	if (item?.extension_type === 'normal') {
	cacheValues = {
	bundle: [],
	key: item.id,
	option: [],
	product_id: item.id,
	product_variant_id: 0,
	quantity: 1,
	rowKey: item.id,
	session: null,
	unique: '08974625397',
	_originalItem: item, // 保存原始商品信息
	};
	}
	}
	
	const callback = async (
	e: any,
	extension_type: any,
	detail: any,
	notShowToast: boolean
	) => {
	setCurrentProduct(null);
	// 防止选择商品弹窗多次触发callback
	// if (lock) {
	//   return;
	// }
	
	lock = true;
	
	// 2秒后解除
	setTimeout(() => {
	lock = false;
	}, 2000);
	if (!isBooking4) {
	// info1 addService 逻辑
	//  预生成预约数据
	const data = await createBookingData({
	product: { ...(detail || item), _params: e },
	});
	// 创建预约
	createBooking({ booking: data });
	return;
	}
	const _currentItem = detail || item;
	// info2 addService 逻辑
	const _detail = _currentItem;
	const other = JSON.parse(JSON.stringify(e));
	
	other.session = e.session;
	
	let cacheItem: any = {
	..._detail,
	product_id: _currentItem.id,
	_id: getUniqueId(),
	_key: e.key,
	_extend: {
	start_date: state.date.value,
	quantity: e?.quantity || 1,
	price: _detail.price,
	product_name: _currentItem.title,
	other,
	isNormalProduct: isNormalProductByDurationSchedule(item),
	},
	new: 1,
	};
	cacheItem._extend.price = getMainPrice(cacheItem,_detail.price);
	let _total = getProductTotalPrice(cacheItem);
	// 用于折扣 可修改
	cacheItem._extend.total = _total;
	// 用于储存原价
	cacheItem._extend.origin_total = _total;
	const _isEdit = !!state.service.cacheItem;
	if (_isEdit) {
	cacheItem._id = state.service.cacheItem?._id;
	cacheItem.new = 0;
	}
	// 渲染到当前位置模式时，默认无资源 时间默认取顶部设置的时间
	if (renderMode === 'current') {
	// cacheItem._extend.resource = 0;
	cacheItem.currentDefaultTime = state.date.value.format('HH:mm');
	}
	
	cacheItem = getProductExtend({
	cacheItem,
	state,
	isDisabledTime: true,
	});
	
	if (state.renderType === 'eventBooking') {
	cacheItem.autoClose = false;
	}
	if (cacheItem.autoClose) {
	cacheItem.autoClose = false;
	
	cacheItem._serviceKey = genServiceKey(cacheItem);
	
	const val = getCurrentServiceValue();
	let { list: _list, quantity } = addService(
	[...stateRef.current.service.value],
	cacheItem,
	stateRef.current
	);
	
	// 更新ref以确保后续快速操作时使用最新值
	latestServiceValueRef.current = _list;
	
	lastOperationTimeRef.current = Date.now();
	
	if (!notShowToast) {
	handleAddToast(cacheItem.title, quantity || 1);
	}
	
	window.dispatchEvent(
	new CustomEvent('onAddNewService', {
	detail: {
	cacheItem,
	},
	})
	);
	
	try {
	if (
	context.appHelper.utils.store?.getState?.()?.global?.globalConfig
	?.id === 2155
	) {
	const val = _list?.map((s) => {
	return {
	product_id: s?.product_id,
	detailId: s?.id,
	detailProductId: s?.product_id,
	product_name: s?.title,
	price: s?.price,
	_id: s?._id,
	_key: s?._key,
	_serviceKey: s?._serviceKey,
	};
	});
	const sendData = {
	product_id: _currentItem?.id,
	detailId: _detail?.id,
	detailProductId: _detail?.product_id,
	product_name: _currentItem?.title,
	price: _detail?.price,
	serviceVal: val,
	};
	sendWarningLog({
	title: 'addService',
	content: [
	{ key: '添加数据', value: JSON.stringify(sendData) },
	{
	key: '日期',
	value: dayjs().format('YYYY-MM-DD HH:mm:ss'),
	},
	],
	});
	}
	} catch (error) {}
	
	dispatch({
	type: 'setService',
	payload: {
	addModal: false,
	value: _list,
	edit: true,
	changeService: false,
	},
	});
	} else {
	window.openBookingEditModal?.();
	dispatch({
	type: 'setService',
	payload: {
	editModal: true,
	cacheItem: cacheItem,
	addModal: !cacheItem.autoClose,
	changeService: false,
	},
	});
	
	onEdit?.(cacheItem);
	}
	};
	
	// 如果不需要打开弹窗, 直接添加数据
	if (cacheValues) {
	const productId = item.id.toString();
	
	// 如果已经有pending的同商品，增加点击次数
	if (pendingCacheValuesRef.current[productId]) {
	clickCountRef.current[productId] =
	(clickCountRef.current[productId] || 1) + 1;
	} else {
	// 第一次点击，初始化数据
	pendingCacheValuesRef.current[productId] = cacheValues;
	clickCountRef.current[productId] = 1;
	}
	const cacheItem = createSimpleCacheItem(item, cacheValues, stateRef.current);
	
	const detail = stateRef.current.service.value?.find((val: any) =>
	isSameProduct(val, cacheItem)
	);
	
	const originalQuantity = detail?._extend?.quantity || 0;
	
	Toast?.success?.(
	<div className="add-toast-wrap">
	<div className="add-toast-title">{item.title}</div>
	<div className="add-toast-quantity">
	{locales.getText('pisell2.ticket-booking.in-cart')(
	(clickCountRef.current[productId] || 1) + originalQuantity
	)}
	</div>
	</div>
	);
	
	debouncedExecuteCacheValues(productId, cacheValues, item, callback);
	
	return;
	}
	// 如果是完全的普通商品
	// 或者非 sessions 商品但有 sku 规格商品
	if (isNormalProductByDurationSchedule(item)) {
	const openNormalService = getOpenNormalServiceHandler();
	if (openNormalService) {
	openNormalService({
	mode: 'create',
	productId: item.id,
	date: state.date.value.format('YYYY-MM-DD'),
	isEject: isEject ? 1 : 0,
	onClose: () => {
	setCurrentProduct(null);
	},
	callback,
	});
	}
	} else {
	state.action({
	type: 'pisell1.handleOpenProductModal',
	data: {
	id: item.id,
	date: state.date.value.format('YYYY-MM-DD'),
	showConfig: {
	option: true,
	session: isSession,
	variant: true,
	package: true,
	number: getIsShowNumber(item, state),
	},
	isOnlySession,
	is_eject: isEject ? 1 : 0,
	customer_id: customerId,
	isOS: isSession,
	},
	onCancel: () => {
	setCurrentProduct(null);
	},
	callback,
	});
	}
	}
	);
	*/
	const renderList = useMemo(() => {
		return products || [];
	}, [products, state === null || state === void 0 ? void 0 : state.activeCartId]);
	const currentDate = useMemo(() => {
		return state.date.value.format("YYYY-MM-DD");
	}, [state.date.value]);
	const currentDatetime = useMemo(() => {
		return state.date.value.format("YYYY-MM-DD HH:mm:ss");
	}, [state.date.value]);
	useEffect(() => {
		if (renderMode === "current" && state.bookingConfig && platform !== "shop") {
			getProducts({
				schedule_date: currentDate,
				customer_id: customerId,
				menu_list_ids: menuList,
				schedule_datetime: currentDatetime
			});
			getScheduleTimePoints({ menu_list_ids: menuList });
		}
	}, [
		renderMode,
		customerId,
		menuList
	]);
	useEffect(() => {
		if (renderMode === "current" && state.bookingConfig && platform === "shop") getProducts({
			schedule_date: currentDate,
			customer_id: customerId,
			menu_list_ids: menuList,
			schedule_datetime: currentDatetime
		});
	}, [
		renderMode,
		currentDate,
		customerId,
		menuList,
		currentDatetime
	]);
	const finalDisplayConfig = useMemo(() => {
		const resolvedConfig = resolveProductDisplayConfig(productDisplayConfig);
		const responsiveConfig = getProductListResponsiveConfig(variant);
		const responsiveMode = getProductDisplayResponsiveMode(productDisplayConfig);
		if (responsiveMode === "skuListA2") {
			const skuListConfig = resolvedConfig.skuListConfig || {};
			const skuListA2ResponsiveConfig = getSkuListA2ResponsiveConfig(responsiveConfig === null || responsiveConfig === void 0 ? void 0 : responsiveConfig.productSelect);
			if (!skuListA2ResponsiveConfig) return resolvedConfig;
			return _objectSpread2(_objectSpread2({}, resolvedConfig), {}, { skuListConfig: _objectSpread2(_objectSpread2({}, skuListConfig), {}, {
				listConfig: _objectSpread2(_objectSpread2({}, skuListConfig.listConfig), skuListA2ResponsiveConfig.listConfig),
				skuCardAllConfig: mergeSkuCardAllConfig(skuListConfig.skuCardAllConfig, skuListA2ResponsiveConfig.skuCardAllConfig)
			}) });
		}
		if (responsiveMode === "skuListA5" && (responsiveConfig === null || responsiveConfig === void 0 ? void 0 : responsiveConfig.skuList)) {
			const skuListConfig = resolvedConfig.skuListConfig || {};
			const skuListResponsiveConfig = responsiveConfig.skuList;
			return _objectSpread2(_objectSpread2({}, resolvedConfig), {}, { skuListConfig: _objectSpread2(_objectSpread2({}, skuListConfig), {}, {
				listConfig: _objectSpread2(_objectSpread2({}, skuListConfig.listConfig), skuListResponsiveConfig.listConfig),
				skuCardAllConfig: mergeSkuCardAllConfig(skuListConfig.skuCardAllConfig, skuListResponsiveConfig.skuCardAllConfig)
			}) });
		}
		return resolvedConfig;
	}, [productDisplayConfig, variant]);
	return useMemo(() => {
		if (renderMode === "current") {
			var _pendingMultiDayData$, _state$bookingConfig$, _state$bookingConfig10;
			return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ProductDisplayAdapter_default, {
				ref: productDisplayAdapterRef,
				config: finalDisplayConfig,
				dataSource: renderList,
				loading: !renderList.length && loading || firstLoading,
				currentProductId: currentProduct === null || currentProduct === void 0 ? void 0 : currentProduct.id,
				onSelectProduct: handleSelectProduct
			}), /* @__PURE__ */ React.createElement(notAvailable_default, { ref: notAvailableRef }), /* @__PURE__ */ React.createElement(MultiDayTimeSelectModal, {
				open: multiDayModalOpen,
				productName: pendingMultiDayData === null || pendingMultiDayData === void 0 || (_pendingMultiDayData$ = pendingMultiDayData.item) === null || _pendingMultiDayData$ === void 0 ? void 0 : _pendingMultiDayData$.title,
				locale: state === null || state === void 0 ? void 0 : state.locale,
				defaultStartDate: state.date.value,
				loading: multiDayModalLoading,
				onConfirm: handleMultiDayConfirm,
				onCancel: handleMultiDayCancel
			}), /* @__PURE__ */ React.createElement(SelectHolderModal, null), /* @__PURE__ */ React.createElement(PisellModal, {
				platform: "pc",
				open: directStockAlertOpen,
				title: locales.getText("pisell2.text.sku.detail.modal.stock.alert.title"),
				headerDivider: false,
				footer: /* @__PURE__ */ React.createElement("div", { style: {
					width: "100%",
					display: "flex",
					justifyContent: "flex-end",
					gap: 12
				} }, /* @__PURE__ */ React.createElement(Button, {
					size: "large",
					onClick: handleDirectStockAlertCancel
				}, locales.getText("pisell2.text.sku.detail.modal.stock.alert.btn.cancel")), /* @__PURE__ */ React.createElement(Button, {
					type: "primary",
					size: "large",
					onClick: handleDirectStockAlertContinue
				}, locales.getText("pisell2.text.sku.detail.modal.stock.alert.btn.continue"))),
				width: 520,
				centered: true,
				destroyOnClose: true,
				maskClosable: false,
				zIndex: 2e3,
				onCancel: handleDirectStockAlertCancel
			}, /* @__PURE__ */ React.createElement("div", { style: { padding: "40px 0 0 0" } }, /* @__PURE__ */ React.createElement("div", { style: {
				color: "#344054",
				fontSize: 14,
				lineHeight: "22px"
			} }, locales.getText("pisell2.text.sku.detail.modal.stock.alert.desc")), Number((_state$bookingConfig$ = state === null || state === void 0 || (_state$bookingConfig10 = state.bookingConfig) === null || _state$bookingConfig10 === void 0 || (_state$bookingConfig10 = _state$bookingConfig10.config) === null || _state$bookingConfig10 === void 0 || (_state$bookingConfig10 = _state$bookingConfig10.stock_setting) === null || _state$bookingConfig10 === void 0 ? void 0 : _state$bookingConfig10.do_not_show_again_today) !== null && _state$bookingConfig$ !== void 0 ? _state$bookingConfig$ : 0) === 1 && /* @__PURE__ */ React.createElement("div", { style: { marginTop: 16 } }, /* @__PURE__ */ React.createElement(Checkbox, {
				checked: directStockAlertDontShowAgainChecked,
				onChange: (e) => {
					var _e$target;
					setDirectStockAlertDontShowAgainChecked(!!(e === null || e === void 0 || (_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.checked));
				}
			}, locales.getText("pisell2.text.sku.detail.modal.stock.alert.checkbox"))))));
		}
		return null;
	}, [
		firstLoading,
		state.service.addModal,
		locales,
		renderList,
		state.amountSymbol,
		state.renderType,
		state === null || state === void 0 ? void 0 : state.activeCartId,
		holderId(state),
		loading,
		currentProduct,
		isBooking4,
		finalDisplayConfig,
		multiDayModalOpen,
		pendingMultiDayData,
		multiDayModalLoading,
		directStockAlertOpen,
		directStockAlertDontShowAgainChecked,
		state === null || state === void 0 || (_state$bookingConfig11 = state.bookingConfig) === null || _state$bookingConfig11 === void 0 || (_state$bookingConfig11 = _state$bookingConfig11.config) === null || _state$bookingConfig11 === void 0 || (_state$bookingConfig11 = _state$bookingConfig11.stock_setting) === null || _state$bookingConfig11 === void 0 ? void 0 : _state$bookingConfig11.do_not_show_again_today
	]);
};
AddSerivce.displayName = "AddSerivce";
var addService_default = withResponsive(AddSerivce);
//#endregion
export { addService_default as default };
