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_hooks = require("../../hooks.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
let ahooks = require("ahooks");
let _pisell_icon_es_ChevronDown = require("@pisell/icon/es/ChevronDown");
_pisell_icon_es_ChevronDown = require_runtime.__toESM(_pisell_icon_es_ChevronDown);
require("../../../booking/components/voucher/index.less");
let _pisell_icon_es_UserCircle = require("@pisell/icon/es/UserCircle");
_pisell_icon_es_UserCircle = require_runtime.__toESM(_pisell_icon_es_UserCircle);
require("./index.less");
//#region src/components/appointmentBooking/components/Voucher/index.tsx
const ShopDiscountHooks = {
	onInited: "shopDiscount:onInited",
	onDestroy: "shopDiscount:onDestroy",
	onLoadDiscountList: "shopDiscount:onLoadDiscountList",
	onCustomerChange: "shopDiscount:onCustomerChange",
	onDiscountListChange: "shopDiscount:onDiscountListChange",
	onRulesListChange: "shopDiscount:onRulesListChange",
	onLoadPrepareCalcResult: "shopDiscount:onLoadPrepareCalcResult"
};
const VoucherCard = (props) => {
	var _context$appHelper, _appointmentBooking$s;
	const { products, currentUser } = props;
	const context = require_useEngineContext.default();
	const appointmentBooking = require_hooks.useAppointmentBooking();
	const shopDiscount = require_hooks.useShopDiscount();
	const [showDetail, setShowDetail] = (0, react.useState)(false);
	const { pisellos, action, token, store } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const { utils } = context.appHelper || {};
	const [code, setCode] = (0, react.useState)("");
	const [discountList, setDisCountList] = (0, react.useState)([]);
	(0, react.useRef)(products);
	const { openLoginModal } = require_hooks.useAppointmentBookingLogin();
	const { accountLists } = require_hooks.useAppointmentBookingAccount();
	const cart = appointmentBooking === null || appointmentBooking === void 0 || (_appointmentBooking$s = appointmentBooking.store) === null || _appointmentBooking$s === void 0 ? void 0 : _appointmentBooking$s.cart;
	const isUserLoggedIn = (0, react.useMemo)(() => {
		var _utils$token, _utils$token$get;
		return !!(utils === null || utils === void 0 || (_utils$token = utils.token) === null || _utils$token === void 0 || (_utils$token$get = _utils$token.get) === null || _utils$token$get === void 0 ? void 0 : _utils$token$get.call(_utils$token)) || false;
	}, [store]);
	const availableData = (0, react.useMemo)(() => {
		return discountList.filter((item) => !!item.isAvailable).map((discount) => {
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, discount), {}, {
				isDisabled: discount.isDisabled || discount.isDisabledForProductUsed,
				savedAmount: shopDiscount.calcDiscountApplicableProductTotalPrice(discount)
			});
		});
	}, [discountList]);
	(0, react.useEffect)(() => {
		if (isUserLoggedIn) {
			var _shopDiscount$setCust;
			const shopDiscount = pisellos.getModule("shopDiscount");
			shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setCust = shopDiscount.setCustomer) === null || _shopDiscount$setCust === void 0 || _shopDiscount$setCust.call(shopDiscount, currentUser);
		}
	}, [currentUser.id, isUserLoggedIn]);
	(0, react.useEffect)(() => {
		var _shopDiscount$setProd;
		shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setProd = shopDiscount.setProductList) === null || _shopDiscount$setProd === void 0 || _shopDiscount$setProd.call(shopDiscount, products);
	}, [products]);
	const { run: onCartChange } = (0, ahooks.useDebounceFn)(() => {
		onCartChangeFn();
	}, { wait: 300 });
	const batchUpdateCart = (productList) => {
		var _appointmentBooking$b;
		const items = productList.map((item) => {
			var _item$_origin;
			return {
				_id: item._id,
				quantity: item.num,
				bundle: item.bundle,
				options: item._optionsOrigin,
				product: require_objectSpread2._objectSpread2({}, item._productOrigin),
				discounts: ((_item$_origin = item._origin) === null || _item$_origin === void 0 || (_item$_origin = _item$_origin.product) === null || _item$_origin === void 0 ? void 0 : _item$_origin.discount_list) || []
			};
		});
		appointmentBooking === null || appointmentBooking === void 0 || (_appointmentBooking$b = appointmentBooking.batchUpdateCart) === null || _appointmentBooking$b === void 0 || _appointmentBooking$b.call(appointmentBooking, items);
	};
	const onCartChangeFn = () => {
		var _shopDiscount$setBook, _appointmentBooking$o, _shopDiscount$getDisc;
		const products = cart === null || cart === void 0 ? void 0 : cart.getItems();
		shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setBook = shopDiscount.setBookingSubject) === null || _shopDiscount$setBook === void 0 || _shopDiscount$setBook.call(shopDiscount, appointmentBooking === null || appointmentBooking === void 0 || (_appointmentBooking$o = appointmentBooking.otherParams) === null || _appointmentBooking$o === void 0 || (_appointmentBooking$o = _appointmentBooking$o.bookingSetting) === null || _appointmentBooking$o === void 0 ? void 0 : _appointmentBooking$o.bookingSubject);
		if (Array.isArray(shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$getDisc = shopDiscount.getDiscountList) === null || _shopDiscount$getDisc === void 0 ? void 0 : _shopDiscount$getDisc.call(shopDiscount)) && !(shopDiscount === null || shopDiscount === void 0 ? void 0 : shopDiscount.getDiscountList().length)) return;
		batchUpdateCart(shopDiscount.calcDiscount(products).productList);
	};
	(0, react.useEffect)(() => {
		onCartChange();
	}, [(0, react.useMemo)(() => {
		let _ret;
		try {
			_ret = JSON.stringify(products.map((item) => (item === null || item === void 0 ? void 0 : item.holder_id) || ""));
		} catch (error) {
			_ret = "";
		}
		return _ret;
	}, [products])]);
	(0, react.useEffect)(() => {
		setDisCountList(shopDiscount.getDiscountList());
		pisellos.effects.on(ShopDiscountHooks.onLoadPrepareCalcResult, (result) => {
			batchUpdateCart(result.productList);
		});
		pisellos.effects.on("appointmentBooking_cart:onAddItem", onCartChange);
		pisellos.effects.on("appointmentBooking_cart:onUpdateQuotationPrice", onCartChange);
		pisellos.effects.on("appointmentBooking_cart:onUpdateBookingDate", onCartChange);
		pisellos.effects.on("appointmentBooking_cart:onUpdateCartItemNums", onCartChange);
		pisellos.effects.on("appointmentBooking_cart:onRemoveItem", onCartChange);
		pisellos.effects.on(ShopDiscountHooks.onDiscountListChange, (discount) => {
			console.log(discount, "discountChange");
			setDisCountList(discount);
		});
	}, []);
	const onScanCode = function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* () {
			const customerId = currentUser.id;
			const val = yield shopDiscount.scanCode(code, customerId);
			if (val === null || val === void 0 ? void 0 : val.isAvailable) {
				batchUpdateCart(val.productList);
				setCode("");
			} else {
				const content = { time_limit: _pisell_utils.locales.getText("pisell2.text.goodpass.code-invalid-expired") };
				(0, _pisell_materials.PisellToast)({ content: val.type === "server" ? _pisell_utils.locales.getText("pisell2.text.goodpass.code-invalid") : content[val === null || val === void 0 ? void 0 : val.unavailableReason] || _pisell_utils.locales.getText("pisell2.text.goodpass.code-invalid-cart") });
			}
		});
		return function onScanCode() {
			return _ref.apply(this, arguments);
		};
	}();
	const renderLoginCard = () => {
		if (isUserLoggedIn) return null;
		return /* @__PURE__ */ react.default.createElement("div", { className: "login-card" }, /* @__PURE__ */ react.default.createElement(_pisell_icon_es_UserCircle.default, { style: { fontSize: 28 } }), /* @__PURE__ */ react.default.createElement("div", { className: "text-wrapper" }, /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellText, {
			className: "login-btn",
			onClick: () => {
				if (!action) return;
				openLoginModal({ callback: (status) => {} });
			}
		}, _pisell_utils.locales.getText("pisell2.text.goodpass.login")), /* @__PURE__ */ react.default.createElement("span", null, _pisell_utils.locales.getText("pisell2.text.goodpass.login-tip"))));
	};
	const mixedSort = (val) => {
		return [...val].sort((a, b) => {
			return Number(b === null || b === void 0 ? void 0 : b.isSelected) - Number(a === null || a === void 0 ? void 0 : a.isSelected);
		});
	};
	const renderVoucherInfo = () => {
		return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("div", { className: "voucher-title" }, /* @__PURE__ */ react.default.createElement("span", { className: "voucher-title-left" }, _pisell_utils.locales.getText("pisell2.text.goodpass")), /* @__PURE__ */ react.default.createElement("span", {
			className: "voucher-title-right",
			onClick: () => {
				console.log("showDetail: ", showDetail);
				setShowDetail(!showDetail);
			}
		}, _pisell_utils.locales.getText("pisell2.text.details"), " ", /* @__PURE__ */ react.default.createElement(_pisell_icon_es_ChevronDown.default, { className: (0, classnames.default)("voucher-right-icon", { show: showDetail }) }))), /* @__PURE__ */ react.default.createElement("div", { className: (0, classnames.default)("voucher-detail", { show: showDetail }) }, (availableData === null || availableData === void 0 ? void 0 : availableData.length) > 0 ? /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellGoodPassCard, {
			style: { width: "100%" },
			dataSource: availableData,
			mixedSort,
			onChange: (val) => {
				batchUpdateCart(shopDiscount.setDiscountSelected({
					discountId: val.id,
					isSelected: val.isSelected
				}).productList);
			}
		}) : null, renderLoginCard(), /* @__PURE__ */ react.default.createElement("div", { className: "voucher-code-input-wrapper" }, /* @__PURE__ */ react.default.createElement("div", { className: "voucher-code-input" }, /* @__PURE__ */ react.default.createElement("div", { style: { whiteSpace: "nowrap" } }, _pisell_utils.locales.getText("pisell2.text.goodpass.code"), ":"), /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellInput, {
			value: code,
			allowClear: true,
			onChange: (e) => {
				var _e$target;
				setCode((_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.value);
			},
			size: "small",
			placeholder: _pisell_utils.locales.getText("pisell2.text.goodpass.enter-code")
		})), /* @__PURE__ */ react.default.createElement(antd.Button, {
			size: "small",
			onClick: onScanCode,
			disabled: !code
		}, _pisell_utils.locales.getText("pisell2.text.apply")))));
	};
	return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__appointment-booking-voucher-container" }, renderVoucherInfo());
};
//#endregion
exports.default = VoucherCard;
