const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_index = require("../../../businessModel/SalesModel/Sales/index.js");
const require_serve = require("./serve.js");
const require_index$1 = require("../Customer/index.js");
const require_utils = require("../Checkout/utils.js");
const require_utils$1 = require("./utils.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let ahooks = require("ahooks");
//#region src/components/Sales/Cart/index.tsx
const defaultState = {
	cartItems: [],
	currentCartItem: null
};
const CartContext = (0, react.createContext)(void 0);
const CartProvider = ({ children }) => {
	const { appContext, appUtils, getUserInfo } = require_index$1.useCustomer();
	const { data, setData, hooks, getCurrentData } = require_index.useSales();
	const [openCart, setOpen] = (0, react.useState)(false);
	const checkRef = (0, react.useRef)(null);
	const cartData = (0, react.useMemo)(() => {
		return data.cartData || defaultState;
	}, [data]);
	const currentCartItem = (0, react.useMemo)(() => {
		return cartData.currentCartItem;
	}, [cartData]);
	/**
	* @title: 通过holder对购物车中商品进行分类展示
	* @Author: xiangfeng.xue
	*/
	const cartDataHolderList = (0, react.useMemo)(() => {
		var _cartData$cartItems, _getCurrentData$holde;
		if (!((_cartData$cartItems = cartData.cartItems) === null || _cartData$cartItems === void 0 ? void 0 : _cartData$cartItems.length)) return [];
		const selectedHolderItems = ((_getCurrentData$holde = getCurrentData().holderData) === null || _getCurrentData$holde === void 0 ? void 0 : _getCurrentData$holde.selectedHolderItems) || [];
		if (selectedHolderItems === null || selectedHolderItems === void 0 ? void 0 : selectedHolderItems.length) {
			const cartMap = getCurrentData().cartData.cartItems.reduce((map, cartItem) => {
				if (!map.has(cartItem.holder_id)) map.set(cartItem.holder_id, []);
				map.get(cartItem.holder_id).push(cartItem);
				return map;
			}, /* @__PURE__ */ new Map());
			const result = selectedHolderItems.map((holderItem) => {
				return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, holderItem), {}, { children: cartMap.get(holderItem.id) || [] });
			});
			if (cartMap.get(void 0)) result.push({ children: cartMap.get(void 0) });
			return result;
		} else return [{ children: cartData.cartItems }];
	}, [data]);
	const onOpenCart = () => {
		setOpen(true);
	};
	const onCloseCart = () => {
		setOpen(false);
	};
	const setCartData = (newCartData) => {
		setData({ cartData: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, getCurrentData().cartData || {}), newCartData) });
	};
	const createCartItemOriginData = () => {
		return {
			id: 0,
			number: 1,
			registration_type: "all",
			relation_products: [],
			product: null,
			holder: null,
			like_status: "common",
			relation_type: "form",
			schedule_id: 0,
			relation_id: null,
			start_date: null,
			start_time: null,
			select_date: null,
			end_time: null,
			end_date: null,
			sub_type: "days",
			duration: 0,
			is_all: false
		};
	};
	const createCartItem = () => {
		const cartItem = {
			_id: (0, _pisell_utils.getUniqueId)(),
			_originData: createCartItemOriginData()
		};
		setCurrentCartItem(cartItem);
		return cartItem;
	};
	/**
	* 从event列表直接创建购物车
	*/
	/**
	* @title:
	* @description: 从event列表直接创建购物车，没有holder时选择最后一次操作的holder信息
	* @param {any} eventItem
	* @return {void}
	* @Author: xiangfeng.xue
	* @Date: 2025-01-20 13:00
	*/
	const createCartItemFromEvent = (eventItem) => {
		console.log("eventItem>>>>>>", eventItem);
		const { resourceData, holderData } = getCurrentData();
		let cartItem = {
			_id: (0, _pisell_utils.getUniqueId)(),
			_originData: createCartItemOriginData(),
			resourceItem: resourceData === null || resourceData === void 0 ? void 0 : resourceData.currentResourceItem,
			eventItem: require_objectSpread2._objectSpread2({}, eventItem)
		};
		const currentHolderItem = getCurrentHolderItem();
		if (currentHolderItem) cartItem = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, cartItem), {}, { holderItem: currentHolderItem });
		setCurrentCartItem(cartItem);
		return cartItem;
	};
	/**
	* 使用holder直接创建购物车
	*/
	/**
	* @description: 使用holder直接创建购物车
	* @param {any} holderItem holder信息
	* @return {*}
	* @Author: xiangfeng.xue
	*/
	const createCartItemFromHolder = (holderItem) => {
		var _data$resourceData;
		const cartItem = {
			_id: (0, _pisell_utils.getUniqueId)(),
			_originData: createCartItemOriginData(),
			resourceItem: (_data$resourceData = data.resourceData) === null || _data$resourceData === void 0 ? void 0 : _data$resourceData.currentResourceItem,
			holderItem
		};
		setCurrentCartItem(cartItem);
		return cartItem;
	};
	const checkBeforeAddToCartResquest = (0, ahooks.useRequest)(require_serve.checkBeforeAddToCartApi, {
		manual: true,
		onSuccess: (res) => {
			var _res$data;
			if ((_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.length) {
				var _res$data2;
				const isUnavailable = checkCartItemIsUnavailable(res.data, checkRef.current.cartItem);
				checkRef.current.callback({
					result: isUnavailable ? false : true,
					num: isUnavailable ? (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.length : 0
				});
			} else checkRef.current.callback({ result: true });
		}
	});
	/**
	* @title: 商品加入购物车前进行校验
	* @description:
	* @Author: xiangfeng.xue
	*/
	const checkBeforeAddToCart = () => {
		return new Promise((resolve) => {
			var _appContext$appHelper;
			const _cartData = getCurrentData().cartData;
			const newCartItem = createCartItemData() || {};
			const params = require_utils.formatValues({
				state: { cartData: { cartItems: [..._cartData.cartItems || [], newCartItem] } },
				platform: appContext === null || appContext === void 0 || (_appContext$appHelper = appContext.appHelper) === null || _appContext$appHelper === void 0 || (_appContext$appHelper = _appContext$appHelper.constants) === null || _appContext$appHelper === void 0 ? void 0 : _appContext$appHelper.platform
			});
			checkRef.current = {
				callback: (res) => {
					resolve(res);
					checkRef.current = null;
				},
				cartItem: newCartItem
			};
			checkBeforeAddToCartResquest.runAsync(params);
		});
	};
	/**
	* @title: 构建当前商品的完整购物车数据
	* @description:
	* @return {*} Object | null
	* @Author: xiangfeng.xue
	*/
	const createCartItemData = () => {
		const _cartData = getCurrentData().cartData;
		if (_cartData.currentCartItem) {
			var _eventDetail$bookingO, _eventItem$eventDetai, _startDateInfo$times, _eventItem$eventDetai2, _endDateInfo$times, _eventItem$eventDetai3, _eventDetail$productD, _eventDetail$productD2, _eventDetail$productD3, _eventDetail$productD4;
			const { _id, eventItem = {}, holderItem = {} } = _cartData.currentCartItem || {};
			const eventDetail = eventItem === null || eventItem === void 0 ? void 0 : eventItem.eventDetail;
			const bookingOptionData = eventDetail === null || eventDetail === void 0 || (_eventDetail$bookingO = eventDetail.bookingOptionItem) === null || _eventDetail$bookingO === void 0 ? void 0 : _eventDetail$bookingO._originData;
			console.log("eventDetail>>>>>>", eventDetail);
			const startDateInfo = eventItem === null || eventItem === void 0 || (_eventItem$eventDetai = eventItem.eventDetail) === null || _eventItem$eventDetai === void 0 || (_eventItem$eventDetai = _eventItem$eventDetai.selectDate) === null || _eventItem$eventDetai === void 0 ? void 0 : _eventItem$eventDetai.startDateInfo;
			const startTime = startDateInfo === null || startDateInfo === void 0 || (_startDateInfo$times = startDateInfo.times) === null || _startDateInfo$times === void 0 || (_startDateInfo$times = _startDateInfo$times[0]) === null || _startDateInfo$times === void 0 ? void 0 : _startDateInfo$times.start_at;
			const endDateInfo = eventItem === null || eventItem === void 0 || (_eventItem$eventDetai2 = eventItem.eventDetail) === null || _eventItem$eventDetai2 === void 0 || (_eventItem$eventDetai2 = _eventItem$eventDetai2.selectDate) === null || _eventItem$eventDetai2 === void 0 ? void 0 : _eventItem$eventDetai2.endDateInfo;
			const endTime = endDateInfo === null || endDateInfo === void 0 || (_endDateInfo$times = endDateInfo.times) === null || _endDateInfo$times === void 0 || (_endDateInfo$times = _endDateInfo$times.slice(-1)) === null || _endDateInfo$times === void 0 || (_endDateInfo$times = _endDateInfo$times[0]) === null || _endDateInfo$times === void 0 ? void 0 : _endDateInfo$times.end_at;
			const num = 1;
			const { price, totalPrice, originTotal, is_charge_tax } = require_utils$1.handleProductInfo(eventDetail, num);
			const transformProduct = (_temp) => {
				var _temp$variant;
				if (!(_temp === null || _temp === void 0 || (_temp$variant = _temp.variant) === null || _temp$variant === void 0 ? void 0 : _temp$variant.length)) return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, _temp || {}), {}, { variant: [] });
				return _temp;
			};
			const newCartItem = {
				_id,
				id: eventItem.id,
				name: eventItem.title,
				price,
				origin_price: price,
				total: totalPrice,
				origin_total: isNaN(originTotal) || originTotal === 0 ? void 0 : originTotal,
				num,
				image: eventItem.image,
				isShowNote: true,
				note: "",
				holder_title: holderItem.name,
				holder_id: holderItem.id,
				symbol: appUtils === null || appUtils === void 0 ? void 0 : appUtils.getSymbolic(),
				start_date: (startDateInfo === null || startDateInfo === void 0 ? void 0 : startDateInfo.date) || "",
				start_time: startTime ? (0, dayjs.default)(startTime || "").format("HH:mm") : "",
				end_date: (endDateInfo === null || endDateInfo === void 0 ? void 0 : endDateInfo.date) || "",
				format: ["HH:mm DD/MM/YYYY", "YYYY-MM-DD HH:mm"],
				show_time: true,
				end_time: endTime ? (0, dayjs.default)(endTime || "").format("HH:mm") : "",
				custom_day_count: (eventItem === null || eventItem === void 0 || (_eventItem$eventDetai3 = eventItem.eventDetail) === null || _eventItem$eventDetai3 === void 0 || (_eventItem$eventDetai3 = _eventItem$eventDetai3.selectDate) === null || _eventItem$eventDetai3 === void 0 || (_eventItem$eventDetai3 = _eventItem$eventDetai3.dates) === null || _eventItem$eventDetai3 === void 0 ? void 0 : _eventItem$eventDetai3.length) || 0,
				is_charge_tax,
				selectedBundle: eventDetail === null || eventDetail === void 0 || (_eventDetail$productD = eventDetail.productDetail) === null || _eventDetail$productD === void 0 ? void 0 : _eventDetail$productD.bundle,
				selectedOptions: eventDetail === null || eventDetail === void 0 || (_eventDetail$productD2 = eventDetail.productDetail) === null || _eventDetail$productD2 === void 0 ? void 0 : _eventDetail$productD2.options,
				isNormalProduct: true,
				_originData: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, _cartData.currentCartItem._originData), {}, {
					product: {
						num: 1,
						product_id: bookingOptionData === null || bookingOptionData === void 0 ? void 0 : bookingOptionData.id,
						note: "",
						product_bundle: [],
						product_option_item: [],
						product_variant_id: 0
					},
					relation_id: eventItem.id,
					start_date: (startDateInfo === null || startDateInfo === void 0 ? void 0 : startDateInfo.date) || null,
					start_time: startTime ? (0, dayjs.default)(startTime || "").format("HH:mm") : null,
					select_date: (startDateInfo === null || startDateInfo === void 0 ? void 0 : startDateInfo.date) || null,
					metadata: {
						end_date_text: (endDateInfo === null || endDateInfo === void 0 ? void 0 : endDateInfo.date) || null,
						end_time_text: endTime ? (0, dayjs.default)(endTime || "").format("HH:mm") : null
					},
					event_unique_identifier: _id
				}),
				_eventDetail: eventDetail,
				_productDetail: eventDetail.productDetail,
				_productOrigin: transformProduct((eventDetail === null || eventDetail === void 0 || (_eventDetail$productD3 = eventDetail.productDetail) === null || _eventDetail$productD3 === void 0 ? void 0 : _eventDetail$productD3.origin) || bookingOptionData),
				_productInit: transformProduct((eventDetail === null || eventDetail === void 0 || (_eventDetail$productD4 = eventDetail.productDetail) === null || _eventDetail$productD4 === void 0 ? void 0 : _eventDetail$productD4.origin) || bookingOptionData)
			};
			newCartItem.deposit = require_utils$1.handleProductDeposit(newCartItem, eventDetail, num);
			newCartItem._originData = require_utils$1.handleCartItemOrigin(newCartItem, eventDetail);
			if (holderItem === null || holderItem === void 0 ? void 0 : holderItem._originData) {
				var _getUserInfo, _holderItem$_originDa, _holderItem$_originDa2, _holderItem$_originDa3;
				newCartItem._originData.holder = {
					customer_id: (_getUserInfo = getUserInfo()) === null || _getUserInfo === void 0 ? void 0 : _getUserInfo.id,
					form_id: holderItem === null || holderItem === void 0 || (_holderItem$_originDa = holderItem._originData) === null || _holderItem$_originDa === void 0 ? void 0 : _holderItem$_originDa.form_id,
					form_record: (holderItem === null || holderItem === void 0 || (_holderItem$_originDa2 = holderItem._originData) === null || _holderItem$_originDa2 === void 0 ? void 0 : _holderItem$_originDa2.form_record_id) ? [holderItem === null || holderItem === void 0 || (_holderItem$_originDa3 = holderItem._originData) === null || _holderItem$_originDa3 === void 0 ? void 0 : _holderItem$_originDa3.form_record_id] : null
				};
			}
			return newCartItem;
		}
		return null;
	};
	/**
	* 将商品加入购物车
	*/
	const addToCart = () => {
		const _cartData = getCurrentData().cartData;
		const newCartItem = createCartItemData();
		if (_cartData.currentCartItem && newCartItem) setCartData({
			cartItems: [..._cartData.cartItems || [], newCartItem],
			currentCartItem: null
		});
	};
	const updateCartItem = (cartItem, updateType) => {
		var _getCurrentData;
		setCartData({ cartItems: (_getCurrentData = getCurrentData()) === null || _getCurrentData === void 0 || (_getCurrentData = _getCurrentData.cartData) === null || _getCurrentData === void 0 || (_getCurrentData = _getCurrentData.cartItems) === null || _getCurrentData === void 0 ? void 0 : _getCurrentData.map((item) => {
			if (item._id === cartItem._id) {
				const _tempCartItem = require_objectSpread2._objectSpread2({}, cartItem || {});
				if (updateType === "deposit") {
					const eventDetail = _tempCartItem === null || _tempCartItem === void 0 ? void 0 : _tempCartItem._eventDetail;
					if (eventDetail) _tempCartItem.deposit = require_utils$1.handleProductDeposit(_tempCartItem, eventDetail, (_tempCartItem === null || _tempCartItem === void 0 ? void 0 : _tempCartItem.num) || 1);
				}
				return _tempCartItem;
			}
			return item;
		}) });
		return cartItem;
	};
	/**
	* 将holder添加到所有没有holder信息的商品中
	* @param holderItem any
	*/
	const addHolderToCartItem = (holderItem) => {
		setCartData({ cartItems: getCurrentData().cartData.cartItems.map((item) => {
			if (!item.holder_id) {
				var _getUserInfo2, _holderItem$_originDa4, _holderItem$_originDa5, _holderItem$_originDa6;
				item = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), {}, {
					holder_title: holderItem.name,
					holder_id: holderItem.id
				});
				item._originData.holder = {
					customer_id: (_getUserInfo2 = getUserInfo()) === null || _getUserInfo2 === void 0 ? void 0 : _getUserInfo2.id,
					form_id: holderItem === null || holderItem === void 0 || (_holderItem$_originDa4 = holderItem._originData) === null || _holderItem$_originDa4 === void 0 ? void 0 : _holderItem$_originDa4.form_id,
					form_record: (holderItem === null || holderItem === void 0 || (_holderItem$_originDa5 = holderItem._originData) === null || _holderItem$_originDa5 === void 0 ? void 0 : _holderItem$_originDa5.form_record_id) ? [holderItem === null || holderItem === void 0 || (_holderItem$_originDa6 = holderItem._originData) === null || _holderItem$_originDa6 === void 0 ? void 0 : _holderItem$_originDa6.form_record_id] : null
				};
			}
			return item;
		}) });
	};
	/**
	* @description: 给购物车中商品增加备注
	* @param {CartItem} cartItem
	* @Author: xiangfeng.xue
	*/
	const addNoteToCartItem = (cartItem) => {
		setCartData({ cartItems: getCurrentData().cartData.cartItems.map((item) => {
			if (item._id === cartItem._id) {
				item = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), {}, { note: cartItem.note });
				item._originData.product = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item._originData.product || {}), {}, { note: cartItem.note });
			}
			return item;
		}) });
	};
	const deleteCartItem = (cartItem) => {
		setCartData({ cartItems: getCurrentData().cartData.cartItems.filter((item) => item._id !== cartItem._id) });
	};
	const deleteCartItemByHolder = (holder_id) => {
		setCartData({ cartItems: getCurrentData().cartData.cartItems.filter((item) => item.holder_id !== holder_id) });
	};
	const clickCartItem = (cartItem) => {
		setCurrentCartItem(cartItem);
	};
	const setCurrentCartItem = (cartItem) => {
		setCartData({ currentCartItem: cartItem });
	};
	const updateCurrentCartItem = (cartItem) => {
		var _getCurrentData$cartD;
		const item = (_getCurrentData$cartD = getCurrentData().cartData) === null || _getCurrentData$cartD === void 0 ? void 0 : _getCurrentData$cartD.currentCartItem;
		if (item) setCurrentCartItem(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), cartItem));
	};
	const clearCurrentCartItem = () => {
		setCartData({ currentCartItem: null });
	};
	const checkHolder = () => {
		var _getCurrentData$cartD2;
		const currentCartItems = (_getCurrentData$cartD2 = getCurrentData().cartData) === null || _getCurrentData$cartD2 === void 0 ? void 0 : _getCurrentData$cartD2.cartItems;
		if (currentCartItems === null || currentCartItems === void 0 ? void 0 : currentCartItems.length) {
			if (currentCartItems.find((v) => !v.holder_id) === void 0) return true;
		}
		return false;
	};
	/**
	* @description: 获取当前操作中的holder信息
	* 如果currentHolderItem在selectedHolderItems中找不到，说明该holder已经被删除
	* 这时取selectedHolderItems中的最后一个，
	* @return {*}
	* @Author: xiangfeng.xue
	*/
	const getCurrentHolderItem = () => {
		const { selectedHolderItems, currentHolderItem } = getCurrentData().holderData || {};
		if (selectedHolderItems === null || selectedHolderItems === void 0 ? void 0 : selectedHolderItems.length) {
			let newCurrentHolderItem = currentHolderItem;
			if (selectedHolderItems.find((v) => v.id === (currentHolderItem === null || currentHolderItem === void 0 ? void 0 : currentHolderItem.id)) === void 0) newCurrentHolderItem = selectedHolderItems[selectedHolderItems.length - 1];
			return newCurrentHolderItem;
		}
		return null;
	};
	/**
	* @title: 检测购物车中商品是否是不可用状态
	* @description: 250210：本期只关注库存的检测结果
	* @param {any} list
	* @param {CartItem} item
	* @return {*} boolean
	* @Author: xiangfeng.xue
	*/
	const checkCartItemIsUnavailable = (list, item) => {
		var _item$_originData, _item$_originData2, _item$_originData3;
		const productId = (_item$_originData = item._originData) === null || _item$_originData === void 0 || (_item$_originData = _item$_originData.product) === null || _item$_originData === void 0 ? void 0 : _item$_originData.product_id;
		const relationId = (_item$_originData2 = item._originData) === null || _item$_originData2 === void 0 ? void 0 : _item$_originData2.relation_id;
		const eventUniqueIdentifier = (_item$_originData3 = item._originData) === null || _item$_originData3 === void 0 ? void 0 : _item$_originData3.event_unique_identifier;
		return list.find((res) => {
			var _res$details;
			const checkType = ["available_capacity"];
			if (((_res$details = res.details) === null || _res$details === void 0 ? void 0 : _res$details.find((v) => {
				var _checkType$includes;
				return (_checkType$includes = checkType.includes) === null || _checkType$includes === void 0 ? void 0 : _checkType$includes.call(checkType, v.type || "");
			})) !== void 0) return res.product_id === productId && res.relation_id === relationId && res.event_unique_identifier === eventUniqueIdentifier;
			return false;
		}) !== void 0;
	};
	/**
	* @title: 更新购物车中不可用的商品
	* @discription
	* @return {void}
	* @Author: xiangfeng.xue
	*/
	const updateDisabledCartItem = (list) => {
		const currentCartItems = getCurrentData().cartData.cartItems || [];
		if ((list === null || list === void 0 ? void 0 : list.length) && currentCartItems.length) setCartData({ cartItems: currentCartItems.map((item) => {
			if (checkCartItemIsUnavailable(list, item)) item.disabled = true;
			else item.disabled = false;
			return item;
		}) });
	};
	/**
	* @description: 获取没有商品信息的holder名称
	* @return {Array<string>}
	* @Author: xiangfeng.xue
	*/
	const getWithoutCartItemsHolderNames = () => {
		var _cartDataHolderList$f;
		const list = [];
		cartDataHolderList === null || cartDataHolderList === void 0 || (_cartDataHolderList$f = cartDataHolderList.forEach) === null || _cartDataHolderList$f === void 0 || _cartDataHolderList$f.call(cartDataHolderList, (v) => {
			var _v$children;
			if (!(v === null || v === void 0 || (_v$children = v.children) === null || _v$children === void 0 ? void 0 : _v$children.length)) list.push((v === null || v === void 0 ? void 0 : v.name) || "");
		});
		return list;
	};
	const contextValue = {
		createCartItem,
		createCartItemFromEvent,
		createCartItemFromHolder,
		addToCart,
		updateCartItem,
		deleteCartItem,
		clickCartItem,
		updateCurrentCartItem,
		clearCurrentCartItem,
		currentCartItem,
		cartData,
		checkHolder,
		openCart,
		onOpenCart,
		onCloseCart,
		deleteCartItemByHolder,
		addHolderToCartItem,
		cartDataHolderList,
		addNoteToCartItem,
		updateDisabledCartItem,
		getWithoutCartItemsHolderNames,
		checkBeforeAddToCartResquest,
		checkBeforeAddToCart
	};
	return /* @__PURE__ */ react.default.createElement(CartContext.Provider, { value: contextValue }, children);
};
/**
* 使用步骤管理的Hook
* @throws {Error} 如果在StepProvider外部使用会抛出错误
* @returns {StepContextType} 步骤管理上下文
*/
const useCart = () => {
	const context = react.default.useContext(CartContext);
	if (!context) throw new Error("useCart must be used within a CartProvider");
	return context;
};
var Cart_default = { defaultState };
//#endregion
exports.CartProvider = CartProvider;
exports.default = Cart_default;
exports.useCart = useCart;
