const require_runtime = require("../../../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../../../../hooks/useEngineContext.js");
const require_index = require("../../../../../../businessModel/SalesModel/Sales/index.js");
const require_index$1 = require("../../../../../Sales/Step/index.js");
const require_index$2 = require("../../../../../Sales/Customer/index.js");
const require_utils = require("../../../../../Sales/Checkout/utils.js");
const require_index$3 = require("../../../../../Sales/Cart/index.js");
const require_utils$1 = require("../../../../../appointmentBooking/utils.js");
const require_index$4 = require("../../../../../Sales/Checkout/index.js");
const require_index$5 = require("../../../../../Sales/Holder/index.js");
const require_serve = require("../../../../../Sales/Event/serve.js");
const require_index$6 = require("../../../../../Sales/Summary/index.js");
const require_index$7 = require("../../OrderProductModal/index.js");
const require_index$8 = require("../../EmptyHolderModal/index.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let ahooks = require("ahooks");
require("./index.less");
//#region src/components/eventBooking/components/Provider/Cart/ContinueButton/index.tsx
const ContinueButton = () => {
	var _context$appHelper, _context$appHelper2, _context$appHelper3, _cartData$cartItems;
	const hasSubscribedRef = (0, react.useRef)(false);
	const { data } = require_index.useSales();
	const { onHolderOpen } = require_index$5.useHolder();
	const { checkHolder, onCloseCart, cartData, getWithoutCartItemsHolderNames } = require_index$3.useCart();
	const { currentStepData, nextStep, isLastStep } = require_index$1.useStep();
	const { onCheckout, createBooking, onCheckBeforeBooking, checkBeforeBooking, freePay } = require_index$4.useCheckout();
	const { openLoginModal, isLogin } = require_index$2.useCustomer();
	const { deposit, isAgreeDepositPolicy } = require_index$6.useSummary();
	const [openCheckout, setOpenCheckout] = (0, react.useState)(false);
	const [checkedNumber, setCheckedNumber] = (0, react.useState)(0);
	const [openEmptyHolder, setOpenEmptyHolder] = (0, react.useState)(false);
	const { setData, removeSessionStorage } = require_index.useSales();
	const context = require_useEngineContext.default();
	!(context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.constants) === null || _context$appHelper === void 0) && _context$appHelper.config;
	const utils = (context === null || context === void 0 || (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.utils) || {};
	const { pubsub } = context.appHelper.utils;
	const { getStore, action } = ((_context$appHelper3 = context.appHelper) === null || _context$appHelper3 === void 0 ? void 0 : _context$appHelper3.utils) || {};
	/**
	* @title: 下单
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-02-10 17:54
	*/
	const handleCheckout = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* () {
			const params = require_utils.getFormParams(data);
			action === null || action === void 0 || action({
				type: "pisell1.goProductForm",
				data: params,
				callback: function() {
					var _ref = require_asyncToGenerator._asyncToGenerator(function* (e) {
						var _context$appHelper4;
						if ((e === null || e === void 0 ? void 0 : e.type) === "close") return;
						const result = yield onCheckout(require_utils.formatValues({
							state: data,
							platform: context === null || context === void 0 || (_context$appHelper4 = context.appHelper) === null || _context$appHelper4 === void 0 || (_context$appHelper4 = _context$appHelper4.constants) === null || _context$appHelper4 === void 0 ? void 0 : _context$appHelper4.platform,
							excludeDisabled: false,
							extra: { relation_forms: e }
						}));
						if (result === null || result === void 0 ? void 0 : result.success) removeSessionStorage();
						else {
							var _result$err;
							(0, _pisell_materials.PisellToast)({ content: (result === null || result === void 0 || (_result$err = result.err) === null || _result$err === void 0 ? void 0 : _result$err.message) || "" });
						}
					});
					return function callback(_x) {
						return _ref.apply(this, arguments);
					};
				}()
			});
		});
		return function handleCheckout() {
			return _ref2.apply(this, arguments);
		};
	}();
	/**
	* 登录后根据返回商品价格更新cartItem price
	*/
	const _getProductPrice = (0, ahooks.useRequest)(require_serve.getProductPrice, {
		manual: true,
		onSuccess: (res) => {
			const productById = (res.data || []).reduce((pre, cur) => {
				pre[cur.id] = cur;
				return pre;
			}, {});
			console.log("start update price");
			const newCartItems = cartData.cartItems.map((item) => {
				const { product } = item._originData || {};
				let newProduct = productById[product.product_id];
				let _totalPrice = Number(newProduct.price);
				if (!(item === null || item === void 0 ? void 0 : item._productDetail)) {
					item.price = _totalPrice;
					item.total = _totalPrice;
					return item;
				}
				const { bundle = [], options } = item._productDetail;
				if (Array.isArray(product === null || product === void 0 ? void 0 : product.product_bundle) && product.product_bundle.length > 0) {
					const { bundle_group = [] } = newProduct;
					for (let i = 0; i < product.product_bundle.length; i++) {
						var _targetBundleGroup$bu;
						const { bundle_group_id, bundle_id, option } = product.product_bundle[i];
						const _originBundleItemInfo = bundle.find((bi) => bi.id === bundle_id);
						const _targetBundleGroup = bundle_group.find((bg) => bg.id === bundle_group_id);
						if (_targetBundleGroup === null || _targetBundleGroup === void 0 || (_targetBundleGroup$bu = _targetBundleGroup.bundle_item) === null || _targetBundleGroup$bu === void 0 ? void 0 : _targetBundleGroup$bu.length) {
							let _newBundleItemInfo = _targetBundleGroup.bundle_item.find((bi) => bi.id === bundle_id);
							if ((_originBundleItemInfo === null || _originBundleItemInfo === void 0 ? void 0 : _originBundleItemInfo._bundle_product_id) === (_newBundleItemInfo === null || _newBundleItemInfo === void 0 ? void 0 : _newBundleItemInfo.bundle_product_id)) {
								const { price_type, num = 1, option: _originBundleItemOptions } = _originBundleItemInfo;
								const _bundleItemPrice = Number(_newBundleItemInfo.price);
								if (price_type === "markup") _totalPrice += _bundleItemPrice * num;
								else if (price_type === "markdown") _totalPrice -= _bundleItemPrice * num;
								else _totalPrice += _bundleItemPrice * num;
								if (Array.isArray(option) && (option === null || option === void 0 ? void 0 : option.length) > 0) for (let j = 0; j < option.length; j++) {
									const { option_group_item_id } = option[j];
									const _originOptionItem = _originBundleItemOptions.find((op) => op.product_option_item_id === option_group_item_id);
									if (_originOptionItem) {
										const { price, num: _optionNum = 1 } = _originOptionItem;
										_totalPrice += Number(price) * _optionNum;
									}
								}
							}
						}
					}
				} else {
					if (product === null || product === void 0 ? void 0 : product.product_variant_id) {
						const { variant = [] } = newProduct;
						const _variant = variant.find((v) => v.id === product.product_variant_id);
						if (_variant) _totalPrice = Number(_variant.price);
					}
					if (Array.isArray(product === null || product === void 0 ? void 0 : product.product_option_item) && product.product_option_item.length > 0) for (let i = 0; i < product.product_option_item.length; i++) {
						const { option_group_item_id } = product.product_option_item[i];
						const _originOptionItem = options.find((op) => op.product_option_item_id === option_group_item_id);
						if (_originOptionItem) {
							const { price, num = 1 } = _originOptionItem;
							_totalPrice += Number(price) * num;
						}
					}
				}
				item.price = _totalPrice;
				item.total = _totalPrice;
				return item;
			});
			console.log("new cart data", newCartItems);
			setData({ cartData: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, cartData), {}, { cartItems: newCartItems }) });
		}
	});
	/**
	* 登录后重新获取应用报价单后的价格
	* 过滤掉组规格商品
	*/
	const getCartItemProductsWithQuotation = function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* () {
			var _store$getState;
			const ids = cartData.cartItems.map((item) => {
				const { product = {} } = item._originData || {};
				const { product_id } = product;
				return product_id;
			}).filter((id) => !!id);
			const store = getStore();
			const customer = store === null || store === void 0 || (_store$getState = store.getState()) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 ? void 0 : _store$getState.userInfo;
			if (!(ids === null || ids === void 0 ? void 0 : ids.length)) return;
			_getProductPrice.run({
				ids,
				customer_id: customer === null || customer === void 0 ? void 0 : customer.id
			});
		});
		return function getCartItemProductsWithQuotation() {
			return _ref3.apply(this, arguments);
		};
	}();
	/**
	* @title: 下一步
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-02-08 18:57
	*/
	const handleNextStep = function() {
		var _ref4 = require_asyncToGenerator._asyncToGenerator(function* () {
			onCloseCart();
			setOpenEmptyHolder(false);
			if (isLastStep) return handleCheckout();
			nextStep();
		});
		return function handleNextStep() {
			return _ref4.apply(this, arguments);
		};
	}();
	/**
	* @title: 判断是打开holder弹窗还是进行下一步
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-02-08 14:00
	*/
	const handleHolder = () => {
		if (!checkHolder()) {
			onHolderOpen();
			return;
		}
		const emptyHolders = getWithoutCartItemsHolderNames();
		if ((emptyHolders === null || emptyHolders === void 0 ? void 0 : emptyHolders.length) > 0) return setOpenEmptyHolder(true);
		handleNextStep();
	};
	/**
	* @title: 点击继续
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-01-16 16:30
	*/
	const handleContinue = function() {
		var _ref6 = require_asyncToGenerator._asyncToGenerator(function* () {
			if (isLastStep) {
				var _context$appHelper5, _deposit$protocols;
				const value = require_utils.formatValues({
					state: data,
					platform: context === null || context === void 0 || (_context$appHelper5 = context.appHelper) === null || _context$appHelper5 === void 0 || (_context$appHelper5 = _context$appHelper5.constants) === null || _context$appHelper5 === void 0 ? void 0 : _context$appHelper5.platform
				});
				if ((deposit === null || deposit === void 0 ? void 0 : deposit.hasDeposit) && (deposit === null || deposit === void 0 || (_deposit$protocols = deposit.protocols) === null || _deposit$protocols === void 0 ? void 0 : _deposit$protocols.length) > 0 && !isAgreeDepositPolicy) {
					require_utils$1.Toast(_pisell_utils.locales.getText("pisell2.appointment.deposit.agree.policy"));
					return;
				}
				const checkRes = yield onCheckBeforeBooking(value);
				if ((checkRes === null || checkRes === void 0 ? void 0 : checkRes.result) === false) {
					setCheckedNumber(checkRes === null || checkRes === void 0 ? void 0 : checkRes.num);
					setOpenCheckout(true);
					return;
				}
				const emptyHolders = getWithoutCartItemsHolderNames();
				if ((emptyHolders === null || emptyHolders === void 0 ? void 0 : emptyHolders.length) > 0) return setOpenEmptyHolder(true);
				onCloseCart();
				return handleCheckout();
			}
			if (!isLogin()) {
				onCloseCart();
				return openLoginModal({ callback: function() {
					var _ref5 = require_asyncToGenerator._asyncToGenerator(function* (status) {
						if (status === "success") {
							yield getCartItemProductsWithQuotation();
							handleHolder();
						}
					});
					return function callback(_x2) {
						return _ref5.apply(this, arguments);
					};
				}() });
			}
			handleHolder();
		});
		return function handleContinue() {
			return _ref6.apply(this, arguments);
		};
	}();
	const handleSubmit = () => {
		var _utils$businessUtils, _utils$businessUtils$;
		if (utils === null || utils === void 0 || (_utils$businessUtils = utils.businessUtils) === null || _utils$businessUtils === void 0 || (_utils$businessUtils$ = _utils$businessUtils.isGuestUser) === null || _utils$businessUtils$ === void 0 ? void 0 : _utils$businessUtils$.call(_utils$businessUtils)) {
			var _utils$businessUtils2, _utils$businessUtils3;
			if (!hasSubscribedRef.current) {
				pubsub.subscribe("bind.guest.user", handleContinue);
				hasSubscribedRef.current = true;
			}
			utils === null || utils === void 0 || (_utils$businessUtils2 = utils.businessUtils) === null || _utils$businessUtils2 === void 0 || (_utils$businessUtils3 = _utils$businessUtils2.openRegisterModal) === null || _utils$businessUtils3 === void 0 || _utils$businessUtils3.call(_utils$businessUtils2, true);
			return;
		}
		handleContinue();
	};
	(0, react.useEffect)(() => {
		return () => {
			pubsub.unsubscribe("bind.guest.user", handleContinue);
			hasSubscribedRef.current = false;
		};
	}, []);
	/**
	* @title: 确认按钮文案
	* @description:
	* @param {*} useMemo
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-01-17 16:10
	*/
	const continueText = (0, react.useMemo)(() => {
		if (isLastStep) return _pisell_utils.locales.getText("pisell2.event.checkout");
		else return _pisell_utils.locales.getText("pisell2.event.close.continue");
	}, [currentStepData === null || currentStepData === void 0 ? void 0 : currentStepData.key]);
	/**
	* @title: 确认按钮loading
	* @description:
	* @param {*} useMemo
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-01-21 23:03
	*/
	const confirmLoading = (0, react.useMemo)(() => {
		if (!isLastStep) return false;
		return (createBooking === null || createBooking === void 0 ? void 0 : createBooking.loading) || (checkBeforeBooking === null || checkBeforeBooking === void 0 ? void 0 : checkBeforeBooking.loading) || (freePay === null || freePay === void 0 ? void 0 : freePay.loading);
	}, [
		isLastStep,
		createBooking === null || createBooking === void 0 ? void 0 : createBooking.loading,
		checkBeforeBooking === null || checkBeforeBooking === void 0 ? void 0 : checkBeforeBooking.loading,
		freePay === null || freePay === void 0 ? void 0 : freePay.loading
	]);
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
		disabled: !(cartData === null || cartData === void 0 || (_cartData$cartItems = cartData.cartItems) === null || _cartData$cartItems === void 0 ? void 0 : _cartData$cartItems.length),
		size: "large",
		type: "primary",
		onClick: () => isLastStep ? handleSubmit() : handleContinue(),
		loading: confirmLoading
	}, continueText), /* @__PURE__ */ react.default.createElement(require_index$7.default, {
		open: openCheckout,
		type: "checkout",
		onCancel: () => setOpenCheckout(false)
	}), /* @__PURE__ */ react.default.createElement(require_index$8.default, {
		open: openEmptyHolder,
		lists: getWithoutCartItemsHolderNames(),
		onCancel: () => setOpenEmptyHolder(false),
		onOk: () => handleNextStep()
	}));
};
//#endregion
exports.default = ContinueButton;
