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 { useScanOrderLogin } from "../../hooks.js";
import { useScanOrderContext } from "../../context.js";
import React, { useCallback, useMemo, useState } from "react";
import { Button, message } from "antd";
import { locales } from "@pisell/utils";
import { PisellGoodPassCard, PisellInput, PisellText } from "@pisell/materials";
import classNames from "classnames";
import ChevronDown from "@pisell/icon/es/ChevronDown";
import "../../../booking/components/voucher/index.less";
import UserCircle from "@pisell/icon/es/UserCircle";
import "../../../appointmentBooking/components/Voucher/index.less";
//#region src/components/scanOrder/components/Voucher/index.tsx
/**
* scanOrder 优惠券/Promotion 组件
* 参照 venueBooking/Voucher 实现，适配 scanOrder 模块的 scanCode / getDiscountList / setDiscountSelected
* 包含：标题行折叠、PisellGoodPassCard 券列表、未登录登录卡片、Code 输入 + Apply
*/
/**
* VoucherCard -- 优惠券/Promotion 区块
* 嵌入购物车底部，提供券列表展示、勾选、扫码兑码、未登录引导等能力
*/
function VoucherCard() {
	const { discountList, runModuleAction, refreshViewModel, scanOrderModule } = useScanOrderContext();
	const { isLogin, openLoginModal } = useScanOrderLogin();
	const [showDetail, setShowDetail] = useState(true);
	const [code, setCode] = useState("");
	const availableData = useMemo(() => {
		return (discountList || []).filter((item) => !!item.isAvailable).map((discount) => _objectSpread2(_objectSpread2({}, discount), {}, { isDisabled: discount.isDisabled || discount.isDisabledForProductUsed }));
	}, [discountList]);
	/** 从 OS 模块同步最新折扣列表并刷新购物车视图 */
	const syncAfterDiscountChange = useCallback(_asyncToGenerator(function* () {
		yield refreshViewModel();
	}), [refreshViewModel]);
	/** 扫码/兑码 Apply */
	const onScanCode = useCallback(_asyncToGenerator(function* () {
		if (!code.trim()) return;
		try {
			var _scanOrderModule$getT;
			const tempOrder = scanOrderModule === null || scanOrderModule === void 0 || (_scanOrderModule$getT = scanOrderModule.getTempOrder) === null || _scanOrderModule$getT === void 0 ? void 0 : _scanOrderModule$getT.call(scanOrderModule);
			const result = yield runModuleAction("scanCode", code, (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.customer_id) || void 0);
			if (result === null || result === void 0 ? void 0 : result.isAvailable) {
				setCode("");
				yield syncAfterDiscountChange();
			} else {
				const content = { time_limit: locales.getText("pisell2.text.goodpass.code-invalid-expired") };
				message.error({ content: String((result === null || result === void 0 ? void 0 : result.type) === "server" ? locales.getText("pisell2.text.goodpass.code-invalid") : content[result === null || result === void 0 ? void 0 : result.unavailableReason] || locales.getText("pisell2.text.goodpass.code-invalid-cart")) });
			}
		} catch (error) {
			console.warn("[scanOrder] scanCode failed", error);
			message.error({ content: String(locales.getText("pisell2.text.goodpass.code-invalid") || "兑换码无效") });
		}
	}), [
		code,
		scanOrderModule,
		runModuleAction,
		syncAfterDiscountChange
	]);
	/** 勾选/取消勾选某张券 */
	const onDiscountChange = useCallback(function() {
		var _ref = _asyncToGenerator(function* (val) {
			try {
				yield runModuleAction("setDiscountSelected", {
					discountId: val.id,
					isSelected: val.isSelected
				});
				yield syncAfterDiscountChange();
			} catch (error) {
				console.warn("[scanOrder] setDiscountSelected failed", error);
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), [runModuleAction, syncAfterDiscountChange]);
	/** 排序：选中的券排前面 */
	const mixedSort = useCallback((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 renderLoginCard = () => {
		if (isLogin) return null;
		return /* @__PURE__ */ React.createElement("div", { className: "login-card" }, /* @__PURE__ */ React.createElement(UserCircle, { style: { fontSize: 28 } }), /* @__PURE__ */ React.createElement("div", {
			className: "text-wrapper",
			style: { maxWidth: "none" }
		}, /* @__PURE__ */ React.createElement(PisellText, {
			className: "login-btn",
			onClick: () => {
				openLoginModal({ callback: () => {} });
			}
		}, locales.getText("pisell2.text.goodpass.login")), " ", /* @__PURE__ */ React.createElement("span", null, locales.getText("pisell2.text.goodpass.login-tip"))));
	};
	return /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__appointment-booking-voucher-container",
		style: { marginTop: "10px" }
	}, /* @__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: () => 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.length > 0 ? /* @__PURE__ */ React.createElement(PisellGoodPassCard, {
		style: { width: "100%" },
		dataSource: availableData,
		mixedSort,
		onChange: onDiscountChange
	}) : 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;
			return 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.trim()
	}, locales.getText("pisell2.text.apply")))));
}
//#endregion
export { VoucherCard as default };
