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_index = require("../../../../pro/compensatedPisellContainer/index.js");
const require_withResponsive = require("../../../../responsive/withResponsive.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 _pisell_icon = require("@pisell/icon");
require("./index.less");
//#region src/plus/saleDetail/components/Voucher/index.tsx
const getCustomerId = (tempOrder) => {
	const customerId = Number(tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.customer_id);
	return Number.isFinite(customerId) ? customerId : void 0;
};
const mixedSort = (val) => {
	return [...val].sort((a, b) => Number(b === null || b === void 0 ? void 0 : b.isSelected) - Number(a === null || a === void 0 ? void 0 : a.isSelected));
};
const normalizeDiscount = (discount, disabled) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, discount), {}, { isDisabled: Boolean(disabled) || Boolean(discount.isDisabled) || Boolean(discount.isDisabledForProductUsed) });
function VoucherBase({ discountList, getDiscountList, scanPromotionCode, setDiscountSelected, customerId, isInModal = false, defaultExpanded, showTitle = true, disabled = false, className, variant }) {
	const [showDetail, setShowDetail] = (0, react.useState)(defaultExpanded !== null && defaultExpanded !== void 0 ? defaultExpanded : Boolean(isInModal));
	const [code, setCode] = (0, react.useState)("");
	const [innerDiscountList, setInnerDiscountList] = (0, react.useState)(discountList || []);
	const [applying, setApplying] = (0, react.useState)(false);
	const [selectingId, setSelectingId] = (0, react.useState)(null);
	const currentVariant = variant || "desktop";
	const inputSize = currentVariant === "phone" ? "middle" : "large";
	(0, react.useEffect)(() => {
		setInnerDiscountList(discountList || []);
	}, [discountList]);
	const refreshDiscountList = (0, react.useCallback)(() => {
		if (!getDiscountList) return;
		setInnerDiscountList(getDiscountList() || []);
	}, [getDiscountList]);
	const availableData = (0, react.useMemo)(() => (innerDiscountList || []).filter((item) => item === null || item === void 0 ? void 0 : item.isAvailable).map((item) => normalizeDiscount(item, disabled || selectingId === item.id)), [
		disabled,
		innerDiscountList,
		selectingId
	]);
	const handleDiscountChange = (0, react.useCallback)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (val) {
			if (!setDiscountSelected || disabled) return;
			const discountId = Number(val.id);
			if (!Number.isFinite(discountId)) return;
			try {
				setSelectingId(val.id);
				yield setDiscountSelected({
					discountId,
					isSelected: val.isSelected
				});
				refreshDiscountList();
			} catch (e) {
				console.error("[SaleDetail] setDiscountSelected failed", e);
			} finally {
				setSelectingId(null);
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), [
		disabled,
		refreshDiscountList,
		setDiscountSelected
	]);
	const handleApplyCode = (0, react.useCallback)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (codeParam) {
			const nextCode = (codeParam !== null && codeParam !== void 0 ? codeParam : code).trim();
			if (!nextCode || !scanPromotionCode || disabled) return;
			try {
				setApplying(true);
				const result = yield scanPromotionCode(nextCode, customerId);
				if (result === null || result === void 0 ? void 0 : result.isAvailable) {
					setCode("");
					refreshDiscountList();
					return;
				}
				const unavailableText = { time_limit: _pisell_utils.locales.getText("pisell2.text.goodpass.code-invalid-expired") };
				(0, _pisell_materials.PisellToast)({ content: (result === null || result === void 0 ? void 0 : result.type) === "server" ? _pisell_utils.locales.getText("pisell2.text.goodpass.code-invalid") : unavailableText[(result === null || result === void 0 ? void 0 : result.unavailableReason) || ""] || _pisell_utils.locales.getText("pisell2.text.goodpass.code-invalid-cart") });
			} catch (e) {
				console.error("[SaleDetail] scanPromotionCode failed", e);
				(0, _pisell_materials.PisellToast)({ content: _pisell_utils.locales.getText("pisell2.text.goodpass.code-invalid") });
			} finally {
				setApplying(false);
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}(), [
		code,
		customerId,
		disabled,
		refreshDiscountList,
		scanPromotionCode
	]);
	return /* @__PURE__ */ react.default.createElement("div", { className: (0, classnames.default)("pisell-sale-detail-voucher", `pisell-sale-detail-voucher--${currentVariant}`, className) }, showTitle && /* @__PURE__ */ react.default.createElement("div", { className: "pisell-sale-detail-voucher__title" }, /* @__PURE__ */ react.default.createElement("span", { className: "pisell-sale-detail-voucher__title-left" }, _pisell_utils.locales.getText("pisell2.text.goodpass")), !isInModal && /* @__PURE__ */ react.default.createElement("span", {
		className: "pisell-sale-detail-voucher__title-right",
		onClick: () => setShowDetail((prev) => !prev)
	}, _pisell_utils.locales.getText("pisell2.text.details"), " ", /* @__PURE__ */ react.default.createElement(_pisell_icon.ChevronDown, { className: (0, classnames.default)("pisell-sale-detail-voucher__title-icon", { "pisell-sale-detail-voucher__title-icon--show": showDetail }) }))), /* @__PURE__ */ react.default.createElement("div", { className: (0, classnames.default)("pisell-sale-detail-voucher__detail", { "pisell-sale-detail-voucher__detail--show": showDetail || isInModal }) }, availableData.length > 0 ? /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellGoodPassCard, {
		style: { width: "100%" },
		isInModal,
		dataSource: availableData,
		mixedSort,
		onChange: handleDiscountChange
	}) : isInModal ? /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellEmpty, { className: "pisell-sale-detail-voucher__empty" }) : null, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-sale-detail-voucher__code-wrapper" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-sale-detail-voucher__code-input" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-sale-detail-voucher__code-label" }, _pisell_utils.locales.getText("pisell2.text.goodpass.code"), ":"), /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellInput, {
		value: code,
		onChange: (e) => {
			var _e$target;
			setCode(((_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.value) || "");
		},
		size: inputSize,
		allowClear: true,
		disabled: disabled || applying,
		placeholder: _pisell_utils.locales.getText("pisell2.text.goodpass.enter-code")
	})), /* @__PURE__ */ react.default.createElement(antd.Button, {
		size: inputSize,
		loading: applying,
		onClick: () => handleApplyCode(),
		disabled: disabled || !code.trim()
	}, _pisell_utils.locales.getText("pisell2.text.apply")))));
}
function VoucherBaseWithSales({ dataSource, className, variant, isInModal, showTitle }) {
	const { sales, cart } = dataSource;
	return /* @__PURE__ */ react.default.createElement(VoucherBase, {
		className,
		variant,
		discountList: cart.discountList,
		scanPromotionCode: cart.scanCode,
		setDiscountSelected: cart.setDiscount,
		customerId: getCustomerId(sales.tempOrder),
		disabled: sales.status === "loading",
		isInModal,
		showTitle
	});
}
function VoucherComponent({ dataSource, renderType = "current", visible = false, onClose, className, variant }) {
	const currentVariant = variant || "desktop";
	const isPhoneVariant = currentVariant === "phone";
	const handleClose = onClose || (() => {});
	const title = _pisell_utils.locales.getText("pisell2.text.goodpass");
	if (renderType === "current") return /* @__PURE__ */ react.default.createElement(VoucherBaseWithSales, {
		dataSource,
		className,
		variant: currentVariant
	});
	return /* @__PURE__ */ react.default.createElement(require_index.default, {
		renderType: isPhoneVariant ? "drawer" : "modal",
		showHandlerBar: isPhoneVariant,
		onHandlerBarClick: handleClose,
		props: isPhoneVariant ? {
			title,
			open: visible,
			placement: "bottom",
			width: "100%",
			height: "auto",
			onClose: handleClose,
			footer: null,
			className: (0, classnames.default)("pisell-sale-detail-voucher-container", "pisell-sale-detail-voucher-container--drawer", !visible && "pisell-sale-detail-voucher-container--hidden"),
			bodyStyle: { padding: "12px 12px calc(12px + env(safe-area-inset-bottom))" },
			forceRender: true
		} : {
			title,
			open: visible,
			onCancel: handleClose,
			footer: null,
			width: 600,
			className: (0, classnames.default)("pisell-sale-detail-voucher-container", "pisell-sale-detail-voucher-container--modal", !visible && "pisell-sale-detail-voucher-container--hidden"),
			forceRender: true,
			bodyStyle: { padding: "24px" }
		}
	}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-sale-detail-voucher-container__content" }, /* @__PURE__ */ react.default.createElement(VoucherBaseWithSales, {
		dataSource,
		className,
		variant: currentVariant,
		isInModal: true,
		showTitle: false
	})));
}
VoucherComponent.displayName = "Voucher";
const Voucher = require_withResponsive.default(VoucherComponent);
//#endregion
exports.default = Voucher;
