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 CompensatedPisellContainer from "../../../../pro/compensatedPisellContainer/index.js";
import withResponsive from "../../../../responsive/withResponsive.js";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
import { PisellEmpty, PisellGoodPassCard, PisellInput, PisellToast } from "@pisell/materials";
import classNames from "classnames";
import { ChevronDown } from "@pisell/icon";
import "./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) => _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] = useState(defaultExpanded !== null && defaultExpanded !== void 0 ? defaultExpanded : Boolean(isInModal));
	const [code, setCode] = useState("");
	const [innerDiscountList, setInnerDiscountList] = useState(discountList || []);
	const [applying, setApplying] = useState(false);
	const [selectingId, setSelectingId] = useState(null);
	const currentVariant = variant || "desktop";
	const inputSize = currentVariant === "phone" ? "middle" : "large";
	useEffect(() => {
		setInnerDiscountList(discountList || []);
	}, [discountList]);
	const refreshDiscountList = useCallback(() => {
		if (!getDiscountList) return;
		setInnerDiscountList(getDiscountList() || []);
	}, [getDiscountList]);
	const availableData = 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 = useCallback(function() {
		var _ref = _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 = useCallback(function() {
		var _ref2 = _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: locales.getText("pisell2.text.goodpass.code-invalid-expired") };
				PisellToast({ content: (result === null || result === void 0 ? void 0 : result.type) === "server" ? locales.getText("pisell2.text.goodpass.code-invalid") : unavailableText[(result === null || result === void 0 ? void 0 : result.unavailableReason) || ""] || locales.getText("pisell2.text.goodpass.code-invalid-cart") });
			} catch (e) {
				console.error("[SaleDetail] scanPromotionCode failed", e);
				PisellToast({ content: 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.createElement("div", { className: classNames("pisell-sale-detail-voucher", `pisell-sale-detail-voucher--${currentVariant}`, className) }, showTitle && /* @__PURE__ */ React.createElement("div", { className: "pisell-sale-detail-voucher__title" }, /* @__PURE__ */ React.createElement("span", { className: "pisell-sale-detail-voucher__title-left" }, locales.getText("pisell2.text.goodpass")), !isInModal && /* @__PURE__ */ React.createElement("span", {
		className: "pisell-sale-detail-voucher__title-right",
		onClick: () => setShowDetail((prev) => !prev)
	}, locales.getText("pisell2.text.details"), " ", /* @__PURE__ */ React.createElement(ChevronDown, { className: classNames("pisell-sale-detail-voucher__title-icon", { "pisell-sale-detail-voucher__title-icon--show": showDetail }) }))), /* @__PURE__ */ React.createElement("div", { className: classNames("pisell-sale-detail-voucher__detail", { "pisell-sale-detail-voucher__detail--show": showDetail || isInModal }) }, availableData.length > 0 ? /* @__PURE__ */ React.createElement(PisellGoodPassCard, {
		style: { width: "100%" },
		isInModal,
		dataSource: availableData,
		mixedSort,
		onChange: handleDiscountChange
	}) : isInModal ? /* @__PURE__ */ React.createElement(PisellEmpty, { className: "pisell-sale-detail-voucher__empty" }) : null, /* @__PURE__ */ React.createElement("div", { className: "pisell-sale-detail-voucher__code-wrapper" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-sale-detail-voucher__code-input" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-sale-detail-voucher__code-label" }, locales.getText("pisell2.text.goodpass.code"), ":"), /* @__PURE__ */ React.createElement(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: locales.getText("pisell2.text.goodpass.enter-code")
	})), /* @__PURE__ */ React.createElement(Button, {
		size: inputSize,
		loading: applying,
		onClick: () => handleApplyCode(),
		disabled: disabled || !code.trim()
	}, locales.getText("pisell2.text.apply")))));
}
function VoucherBaseWithSales({ dataSource, className, variant, isInModal, showTitle }) {
	const { sales, cart } = dataSource;
	return /* @__PURE__ */ React.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 = locales.getText("pisell2.text.goodpass");
	if (renderType === "current") return /* @__PURE__ */ React.createElement(VoucherBaseWithSales, {
		dataSource,
		className,
		variant: currentVariant
	});
	return /* @__PURE__ */ React.createElement(CompensatedPisellContainer, {
		renderType: isPhoneVariant ? "drawer" : "modal",
		showHandlerBar: isPhoneVariant,
		onHandlerBarClick: handleClose,
		props: isPhoneVariant ? {
			title,
			open: visible,
			placement: "bottom",
			width: "100%",
			height: "auto",
			onClose: handleClose,
			footer: null,
			className: classNames("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: classNames("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.createElement("div", { className: "pisell-sale-detail-voucher-container__content" }, /* @__PURE__ */ React.createElement(VoucherBaseWithSales, {
		dataSource,
		className,
		variant: currentVariant,
		isInModal: true,
		showTitle: false
	})));
}
VoucherComponent.displayName = "Voucher";
const Voucher = withResponsive(VoucherComponent);
//#endregion
export { Voucher as default };
