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 { showDiscountScanFailMessage } from "../../../booking/utils.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import { useAppointmentBooking, useAppointmentBookingAccount, useAppointmentBookingLogin, useShopDiscount } from "../../hooks.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
import { PisellGoodPassCard, PisellInput, PisellText, PisellToast } from "@pisell/materials";
import classNames from "classnames";
import { useDebounceFn } from "ahooks";
import ChevronDown from "@pisell/icon/es/ChevronDown";
import "../../../booking/components/voucher/index.less";
import UserCircle from "@pisell/icon/es/UserCircle";
import "./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 = useEngineContext();
	const appointmentBooking = useAppointmentBooking();
	const shopDiscount = useShopDiscount();
	const [showDetail, setShowDetail] = 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] = useState("");
	const [discountList, setDisCountList] = useState([]);
	useRef(products);
	const { openLoginModal } = useAppointmentBookingLogin();
	const { accountLists } = useAppointmentBookingAccount();
	const cart = appointmentBooking === null || appointmentBooking === void 0 || (_appointmentBooking$s = appointmentBooking.store) === null || _appointmentBooking$s === void 0 ? void 0 : _appointmentBooking$s.cart;
	const isUserLoggedIn = 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 = useMemo(() => {
		return discountList.filter((item) => !!item.isAvailable).map((discount) => {
			return _objectSpread2(_objectSpread2({}, discount), {}, {
				isDisabled: discount.isDisabled || discount.isDisabledForProductUsed,
				savedAmount: shopDiscount.calcDiscountApplicableProductTotalPrice(discount)
			});
		});
	}, [discountList]);
	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]);
	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 } = 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: _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);
	};
	useEffect(() => {
		onCartChange();
	}, [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])]);
	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 = _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 PisellToast({ content: showDiscountScanFailMessage(val, "goodpass", locales) });
		});
		return function onScanCode() {
			return _ref.apply(this, arguments);
		};
	}();
	const renderLoginCard = () => {
		if (isUserLoggedIn) return null;
		return /* @__PURE__ */ React.createElement("div", { className: "login-card" }, /* @__PURE__ */ React.createElement(UserCircle, { style: { fontSize: 28 } }), /* @__PURE__ */ React.createElement("div", { className: "text-wrapper" }, /* @__PURE__ */ React.createElement(PisellText, {
			className: "login-btn",
			onClick: () => {
				if (!action) return;
				openLoginModal({ callback: (status) => {} });
			}
		}, locales.getText("pisell2.text.goodpass.login")), /* @__PURE__ */ React.createElement("span", null, 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.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "voucher-title" }, /* @__PURE__ */ React.createElement("span", { className: "voucher-title-left" }, locales.getText("pisell2.text.goodpass")), /* @__PURE__ */ React.createElement("span", {
			className: "voucher-title-right",
			onClick: () => {
				console.log("showDetail: ", showDetail);
				setShowDetail(!showDetail);
			}
		}, locales.getText("pisell2.text.details"), " ", /* @__PURE__ */ React.createElement(ChevronDown, { className: classNames("voucher-right-icon", { show: showDetail }) }))), /* @__PURE__ */ React.createElement("div", { className: classNames("voucher-detail", { show: showDetail }) }, (availableData === null || availableData === void 0 ? void 0 : availableData.length) > 0 ? /* @__PURE__ */ React.createElement(PisellGoodPassCard, {
			style: { width: "100%" },
			dataSource: availableData,
			mixedSort,
			onChange: (val) => {
				batchUpdateCart(shopDiscount.setDiscountSelected({
					discountId: val.id,
					isSelected: val.isSelected
				}).productList);
			}
		}) : null, renderLoginCard(), /* @__PURE__ */ React.createElement("div", { className: "voucher-code-input-wrapper" }, /* @__PURE__ */ React.createElement("div", { className: "voucher-code-input" }, /* @__PURE__ */ React.createElement("div", { style: { whiteSpace: "nowrap" } }, locales.getText("pisell2.text.goodpass.code"), ":"), /* @__PURE__ */ React.createElement(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: locales.getText("pisell2.text.goodpass.enter-code")
		})), /* @__PURE__ */ React.createElement(Button, {
			size: "small",
			onClick: onScanCode,
			disabled: !code
		}, locales.getText("pisell2.text.apply")))));
	};
	return /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__appointment-booking-voucher-container" }, renderVoucherInfo());
};
//#endregion
export { VoucherCard as default };
