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 { _objectWithoutProperties } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import useEngineContext, { usePisellOS } from "../../../../hooks/useEngineContext.js";
import { useCustomer } from "../../../Sales/Customer/index.js";
import { useCart } from "../../../Sales/Cart/index.js";
import locales_default from "./components/locales.js";
import VoucherUI from "./components/Voucher.js";
import { useShopDiscount, useVoucherLogin } from "./hooks.js";
import React, { useEffect, useMemo, useState } from "react";
import { locales } from "@pisell/utils";
import { PisellToast } from "@pisell/materials";
//#region src/components/eventBooking/components/Voucher/index.tsx
const _excluded = ["discount_list"];
const ShopDiscountHooks = {
	onDiscountListChange: "shopDiscount:eventBooking:onDiscountListChange",
	onLoadPrepareCalcResult: "shopDiscount:eventBooking:onLoadPrepareCalcResult"
};
const VoucherCard = () => {
	var _context$appHelper, _utils$storage, _cartData$cartItems2;
	const utils = ((_context$appHelper = useEngineContext().appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const pisellos = usePisellOS();
	locales.init(locales_default, (utils === null || utils === void 0 || (_utils$storage = utils.storage) === null || _utils$storage === void 0 ? void 0 : _utils$storage.get("umi_locale")) || "en");
	const shopDiscount = useShopDiscount();
	const { cartData, updateCartItem } = useCart();
	const { isLogin, openLoginModal, getUserInfo } = useCustomer();
	const [showDetail, setShowDetail] = useState(false);
	const [code, setCode] = useState("");
	const [discountList, setDisCountList] = useState([]);
	const { getCartItemProductsWithQuotation } = useVoucherLogin();
	const currentUser = getUserInfo() || {};
	const cartUnique = useMemo(() => {
		var _cartData$cartItems;
		return cartData === null || cartData === void 0 || (_cartData$cartItems = cartData.cartItems) === null || _cartData$cartItems === void 0 || (_cartData$cartItems = _cartData$cartItems.map((item) => {
			const { _id, holder, product } = (item === null || item === void 0 ? void 0 : item._originData) || {};
			const _ref = product || {}, { discount_list } = _ref, rest = _objectWithoutProperties(_ref, _excluded);
			return JSON.stringify({
				_id,
				product: rest,
				holder
			});
		})) === null || _cartData$cartItems === void 0 ? void 0 : _cartData$cartItems.join("-");
	}, [cartData.cartItems]);
	useEffect(() => {
		if (isLogin() && (currentUser === null || currentUser === void 0 ? void 0 : currentUser.id)) {
			var _shopDiscount$setCust;
			shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setCust = shopDiscount.setCustomer) === null || _shopDiscount$setCust === void 0 || _shopDiscount$setCust.call(shopDiscount, currentUser);
		}
	}, [
		currentUser === null || currentUser === void 0 ? void 0 : currentUser.id,
		isLogin,
		shopDiscount
	]);
	useEffect(() => {
		var _shopDiscount$setProd;
		shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setProd = shopDiscount.setProductList) === null || _shopDiscount$setProd === void 0 || _shopDiscount$setProd.call(shopDiscount, (cartData === null || cartData === void 0 ? void 0 : cartData.cartItems) || []);
	}, [cartUnique, shopDiscount]);
	const batchUpdateCart = (productList) => {
		if (!(productList === null || productList === void 0 ? void 0 : productList.length)) return;
		productList.forEach((product) => {
			updateCartItem(product, "deposit");
		});
	};
	useEffect(() => {
		const onDiscountListChange = (discount) => {
			console.log("onDiscountListChange: ", discount);
			setDisCountList(discount);
		};
		const onLoadPrepareCalcResult = (result) => {
			var _result$productList;
			console.log("onLoadPrepareCalcResult: ", result);
			if (!(result === null || result === void 0 || (_result$productList = result.productList) === null || _result$productList === void 0 ? void 0 : _result$productList.length)) return;
			batchUpdateCart(result === null || result === void 0 ? void 0 : result.productList);
		};
		pisellos.effects.on(ShopDiscountHooks.onLoadPrepareCalcResult, onLoadPrepareCalcResult);
		pisellos.effects.on(ShopDiscountHooks.onDiscountListChange, onDiscountListChange);
		return () => {
			pisellos.effects.off(ShopDiscountHooks.onLoadPrepareCalcResult, onLoadPrepareCalcResult);
			pisellos.effects.off(ShopDiscountHooks.onDiscountListChange, onDiscountListChange);
		};
	}, []);
	useEffect(() => {
		var _shopDiscount$setBook;
		shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setBook = shopDiscount.setBookingSubject) === null || _shopDiscount$setBook === void 0 || _shopDiscount$setBook.call(shopDiscount, { type: "form" });
		const val = shopDiscount.calcDiscount((cartData === null || cartData === void 0 ? void 0 : cartData.cartItems) || []);
		if (val === null || val === void 0 ? void 0 : val.productList) batchUpdateCart(val.productList);
	}, [cartUnique]);
	const availableData = useMemo(() => {
		return discountList.filter((item) => !!item.isAvailable).map((discount) => {
			return _objectSpread2(_objectSpread2({}, discount), {}, {
				isDisabled: discount.isDisabled || discount.isDisabledForProductUsed,
				savedAmount: shopDiscount.calcDiscountApplicableProductTotalPrice(discount)
			});
		});
	}, [discountList, shopDiscount]);
	const onScanCode = function() {
		var _ref2 = _asyncToGenerator(function* () {
			if (!shopDiscount) {
				PisellToast({ content: locales.getText("pisell2.voucher.code-invalid") });
				return;
			}
			const val = yield shopDiscount.scanCode(code, currentUser.id);
			console.log("scanCodeValue: ", val);
			if (val === null || val === void 0 ? void 0 : val.isAvailable) {
				batchUpdateCart(val.productList);
				setCode("");
			} else PisellToast({ content: val.type === "server" ? locales.getText("pisell2.voucher.code-invalid") : locales.getText("pisell2.voucher.code-invalid-cart") });
		});
		return function onScanCode() {
			return _ref2.apply(this, arguments);
		};
	}();
	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 handleLoginClick = () => {
		openLoginModal({ callback: function() {
			var _ref3 = _asyncToGenerator(function* (status) {
				if (status === "success") yield getCartItemProductsWithQuotation();
			});
			return function callback(_x) {
				return _ref3.apply(this, arguments);
			};
		}() });
	};
	const handleDiscountChange = (val) => {
		if (!shopDiscount) return;
		const detail = shopDiscount.setDiscountSelected({
			discountId: val.id,
			isSelected: val.isSelected
		});
		console.log("Set discount selected:", detail);
		if (detail === null || detail === void 0 ? void 0 : detail.productList) batchUpdateCart(detail.productList);
	};
	const handleToggleDetail = () => {
		setShowDetail(!showDetail);
	};
	if (!((_cartData$cartItems2 = cartData.cartItems) === null || _cartData$cartItems2 === void 0 ? void 0 : _cartData$cartItems2.length)) return null;
	return /* @__PURE__ */ React.createElement(VoucherUI, {
		showDetail,
		onToggleDetail: handleToggleDetail,
		isLogin: isLogin(),
		onLoginClick: handleLoginClick,
		availableData,
		onDiscountChange: handleDiscountChange,
		mixedSort,
		code,
		onCodeChange: setCode,
		onApplyCode: onScanCode,
		codeDisabled: !code
	});
};
//#endregion
export { VoucherCard as default };
