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 { getProductDetail } from "../../components/booking/info/service/serve.js";
import { Context } from "../../components/booking/info/model.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import NoteModal from "../../plus/noteModal/index.js";
import DiscountKeyboard from "../priceKeyboard/components/discountKeyboard/index.js";
import useToast$1 from "../../hooks/useToast.js";
import useLogger from "../../hooks/useLogger.js";
import NumericStepper from "../NumericStepper/index.js";
import locales_default from "./locales.js";
import SKUOptionsSelection from "../../plus/skuOptionsSelection/index.js";
import { checkSkuStockCanSell } from "./utils.js";
import React, { forwardRef, useContext, useImperativeHandle, useMemo, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import Decimal from "decimal.js";
import { cloneDeep } from "lodash";
import { Button, Checkbox, Iconfont, PisellModal, PisellProcedure } from "@pisell/materials";
import Delete_wght300_24px from "@pisell/icon/es/Delete_wght300_24px";
import "./index.less";
//#region src/pro/skuDetailModal/index.tsx
const SkuDetailModal = ({ onConfirm, onRemove, onClose }, ref) => {
	var _context$appHelper, _store$getState, _context$engine, _productData$_extend2, _bookingState$booking10, _bookingState$booking11;
	const [open, setOpen] = useState(false);
	const [productData, setProductData] = useState(null);
	const [note, setNote] = useState("");
	const [quantity, setQuantity] = useState(1);
	/**
	* @description 手动改价（单价维度）
	* - null 表示未设置过手动改价
	* - 只要设置过，右侧总价展示始终以该单价为准
	*/
	const [priceOverride, setPriceOverride] = useState(null);
	const [showPriceAdjustModal, setShowPriceAdjustModal] = useState(false);
	const [discounts, setDiscounts] = useState([]);
	const [noteModalOpen, setNoteModalOpen] = useState(false);
	const [skuValue, setSkuValue] = useState({
		price: 0,
		product_id: 0,
		product_variant_id: 0,
		bundle: [],
		option: []
	});
	const [skuDefaultValue, setSkuDefaultValue] = useState({
		product_id: 0,
		price: 0,
		product_variant_id: 0,
		bundle: [],
		option: []
	});
	const openParamsRef = useRef(null);
	const Toast = useToast$1();
	const logger = useLogger();
	/**
	* @description SKUOptionsSelection ref，用于触发内部校验与读取最终值
	*/
	const skuOptionsSelectionRef = useRef(null);
	/**
	* @description 库存提醒弹窗（允许缺货加入购物车时触发）
	*/
	const [stockAlertOpen, setStockAlertOpen] = useState(false);
	const [stockAlertDontShowAgainChecked, setStockAlertDontShowAgainChecked] = useState(false);
	const pendingConfirmDataRef = useRef(null);
	const [currentStep, setCurrentStep] = useState(0);
	const procedureRef = useRef(null);
	const context = useEngineContext();
	const { store, getData, isWebPos } = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	/**
	* @description
	* booking state 需要从 Booking 的 Context 读取（与 editService 保持一致），不要用 store.getState()
	*/
	const { state: bookingState } = useContext(Context) || {};
	const symbol = (store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || (_store$getState = _store$getState.call(store)) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 ? void 0 : _store$getState.symbol) || "$";
	locales.init(locales_default, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || "en");
	const getDetailData = function() {
		var _ref = _asyncToGenerator(function* (data, open_deposit) {
			if (isWebPos && data.productData) return { data: data.productData };
			else return yield getProductDetail(String(data.id), {
				schedule_date: data.date,
				is_eject: data.is_eject,
				open_deposit
			});
		});
		return function getDetailData(_x, _x2) {
			return _ref.apply(this, arguments);
		};
	}();
	/**
	* @description 当前商品是否存在 SKU 选择数据（套餐/单规格/组合规格）
	* - 当 bundle_group、option_group、variant_group 都不存在或为空数组时：
	*   - 不显示整个 SKUOptionsSelection
	*   - 步骤条不显示“选择套餐”这一步
	*
	* @note `ProductData` 类型里未显式声明这几个 group 字段，这里按运行时字段做兼容判断
	*/
	const hasSkuOptions = useMemo(() => {
		const data = productData;
		const hasVariantGroup = Array.isArray(data === null || data === void 0 ? void 0 : data.variant_group) && data.variant_group.length > 0;
		const hasOptionGroup = Array.isArray(data === null || data === void 0 ? void 0 : data.option_group) && data.option_group.length > 0;
		const hasBundleGroup = Array.isArray(data === null || data === void 0 ? void 0 : data.bundle_group) && data.bundle_group.length > 0;
		return hasVariantGroup || hasOptionGroup || hasBundleGroup;
	}, [productData]);
	/**
	* @description Procedure steps：根据是否存在 SKU 选择数据动态生成
	*/
	const procedureSteps = useMemo(() => {
		const items = [{
			title: locales.getText("pisell2.text.sku.detail.modal.step.details"),
			description: ""
		}];
		if (hasSkuOptions) items.push({
			title: locales.getText("pisell2.text.sku.detail.modal.step.select.bundle"),
			description: ""
		});
		return items;
	}, [hasSkuOptions]);
	const maxStepIndex = useMemo(() => Math.max(0, procedureSteps.length - 1), [procedureSteps]);
	useImperativeHandle(ref, () => ({ open: function() {
		var _ref3 = _asyncToGenerator(function* (data) {
			var _data$_extend, _data$_extend2, _data$_extend3, _data$_extend4, _data$_extend5, _data$_extend6, _data$_extend7, _data$_extend8, _data$_extend9, _data$_extend10, _data$_extend11, _data$_extend12, _data$_extend13;
			setCurrentStep(0);
			setNoteModalOpen(false);
			logger === null || logger === void 0 || logger.addLog({
				type: "info",
				title: "sku_detail_modal_open",
				metadata: { data }
			});
			if ("date" in data && !("_extend" in data)) {
				var _ref2, _is_eject, _hydratedData$_extend;
				logger === null || logger === void 0 || logger.addLog({
					type: "info",
					title: "sku_detail_modal_open_create",
					metadata: {}
				});
				openParamsRef.current = data;
				const productDetail = yield getDetailData(data, (getData === null || getData === void 0 ? void 0 : getData("bookingv2_deposit")) || 0);
				const apiData = (productDetail === null || productDetail === void 0 ? void 0 : productDetail.data) || {};
				const basePrice = Number((apiData === null || apiData === void 0 ? void 0 : apiData.price) || 0);
				const hydratedData = _objectSpread2(_objectSpread2({}, apiData), {}, {
					id: (apiData === null || apiData === void 0 ? void 0 : apiData.id) || data.id,
					product_id: (apiData === null || apiData === void 0 ? void 0 : apiData.product_id) || data.id,
					_extend: _objectSpread2(_objectSpread2({}, (apiData === null || apiData === void 0 ? void 0 : apiData._extend) || {}), {}, {
						product_name: (apiData === null || apiData === void 0 ? void 0 : apiData.title) || (apiData === null || apiData === void 0 ? void 0 : apiData.product_name) || "",
						quantity: 1,
						price: basePrice,
						total: basePrice,
						origin_total: basePrice,
						note: "",
						skuValue: {
							product_id: (apiData === null || apiData === void 0 ? void 0 : apiData.id) || data.id,
							product_variant_id: 0,
							bundle: [],
							option: []
						}
					})
				});
				if (!(Number((_ref2 = (_is_eject = apiData === null || apiData === void 0 ? void 0 : apiData.is_eject) !== null && _is_eject !== void 0 ? _is_eject : data.is_eject) !== null && _ref2 !== void 0 ? _ref2 : 0) === 1)) {
					onConfirm === null || onConfirm === void 0 || onConfirm(hydratedData);
					modalCloseAction();
					return;
				}
				setProductData(hydratedData);
				setNote("");
				setQuantity((apiData === null || apiData === void 0 ? void 0 : apiData.min_num_unit) || 1);
				setDiscounts([]);
				setSkuValue({
					product_id: hydratedData.id,
					product_variant_id: 0,
					bundle: [],
					option: []
				});
				setSkuDefaultValue({
					product_id: hydratedData.id,
					product_variant_id: 0,
					bundle: [],
					option: [],
					price: (hydratedData === null || hydratedData === void 0 || (_hydratedData$_extend = hydratedData._extend) === null || _hydratedData$_extend === void 0 ? void 0 : _hydratedData$_extend.price) || 0
				});
				setPriceOverride(null);
				setShowPriceAdjustModal(false);
				const hydratedAny = hydratedData;
				setCurrentStep(Array.isArray(hydratedAny === null || hydratedAny === void 0 ? void 0 : hydratedAny.variant_group) && hydratedAny.variant_group.length > 0 || Array.isArray(hydratedAny === null || hydratedAny === void 0 ? void 0 : hydratedAny.option_group) && hydratedAny.option_group.length > 0 || Array.isArray(hydratedAny === null || hydratedAny === void 0 ? void 0 : hydratedAny.bundle_group) && hydratedAny.bundle_group.length > 0 ? 1 : 0);
				setOpen(true);
				return;
			}
			logger === null || logger === void 0 || logger.addLog({
				type: "info",
				title: "sku_detail_modal_open_edit",
				metadata: {}
			});
			openParamsRef.current = null;
			const _data = cloneDeep(data);
			setProductData(_data);
			console.log(_data, "_data");
			setNote((_data === null || _data === void 0 || (_data$_extend = _data._extend) === null || _data$_extend === void 0 ? void 0 : _data$_extend.note) || "");
			setQuantity((_data === null || _data === void 0 || (_data$_extend2 = _data._extend) === null || _data$_extend2 === void 0 ? void 0 : _data$_extend2.quantity) || 1);
			setDiscounts((_data === null || _data === void 0 ? void 0 : _data.discount_list) || []);
			console.log({
				product_id: _data === null || _data === void 0 ? void 0 : _data.product_id,
				product_variant_id: (_data === null || _data === void 0 || (_data$_extend3 = _data._extend) === null || _data$_extend3 === void 0 || (_data$_extend3 = _data$_extend3.other) === null || _data$_extend3 === void 0 ? void 0 : _data$_extend3.product_variant_id) || 0,
				bundle: (_data === null || _data === void 0 || (_data$_extend4 = _data._extend) === null || _data$_extend4 === void 0 || (_data$_extend4 = _data$_extend4.other) === null || _data$_extend4 === void 0 ? void 0 : _data$_extend4.bundle) || [],
				option: (_data === null || _data === void 0 || (_data$_extend5 = _data._extend) === null || _data$_extend5 === void 0 || (_data$_extend5 = _data$_extend5.other) === null || _data$_extend5 === void 0 ? void 0 : _data$_extend5.option) || []
			}, "skuValue");
			setSkuValue({
				product_id: _data === null || _data === void 0 ? void 0 : _data.product_id,
				product_variant_id: (_data === null || _data === void 0 || (_data$_extend6 = _data._extend) === null || _data$_extend6 === void 0 || (_data$_extend6 = _data$_extend6.other) === null || _data$_extend6 === void 0 ? void 0 : _data$_extend6.product_variant_id) || 0,
				bundle: (_data === null || _data === void 0 || (_data$_extend7 = _data._extend) === null || _data$_extend7 === void 0 || (_data$_extend7 = _data$_extend7.other) === null || _data$_extend7 === void 0 ? void 0 : _data$_extend7.bundle) || [],
				option: (_data === null || _data === void 0 || (_data$_extend8 = _data._extend) === null || _data$_extend8 === void 0 || (_data$_extend8 = _data$_extend8.other) === null || _data$_extend8 === void 0 ? void 0 : _data$_extend8.option) || []
			});
			setSkuDefaultValue({
				product_id: _data === null || _data === void 0 ? void 0 : _data.product_id,
				product_variant_id: (_data === null || _data === void 0 || (_data$_extend9 = _data._extend) === null || _data$_extend9 === void 0 || (_data$_extend9 = _data$_extend9.other) === null || _data$_extend9 === void 0 ? void 0 : _data$_extend9.product_variant_id) || 0,
				price: (_data === null || _data === void 0 || (_data$_extend10 = _data._extend) === null || _data$_extend10 === void 0 ? void 0 : _data$_extend10.price) || 0,
				bundle: (_data === null || _data === void 0 || (_data$_extend11 = _data._extend) === null || _data$_extend11 === void 0 || (_data$_extend11 = _data$_extend11.other) === null || _data$_extend11 === void 0 ? void 0 : _data$_extend11.bundle) || [],
				option: (_data === null || _data === void 0 || (_data$_extend12 = _data._extend) === null || _data$_extend12 === void 0 || (_data$_extend12 = _data$_extend12.other) === null || _data$_extend12 === void 0 ? void 0 : _data$_extend12.option) || []
			});
			setPriceOverride((_data === null || _data === void 0 || (_data$_extend13 = _data._extend) === null || _data$_extend13 === void 0 ? void 0 : _data$_extend13.priceOverride) || void 0);
			setShowPriceAdjustModal(false);
			const dataAny = _data;
			setCurrentStep(Array.isArray(dataAny === null || dataAny === void 0 ? void 0 : dataAny.variant_group) && dataAny.variant_group.length > 0 || Array.isArray(dataAny === null || dataAny === void 0 ? void 0 : dataAny.option_group) && dataAny.option_group.length > 0 || Array.isArray(dataAny === null || dataAny === void 0 ? void 0 : dataAny.bundle_group) && dataAny.bundle_group.length > 0 ? 1 : 0);
			setTimeout(() => {
				logger === null || logger === void 0 || logger.addLog({
					type: "info",
					title: "sku_detail_modal_open_edit_show",
					metadata: {}
				});
				setOpen(true);
			}, 0);
		});
		return function open(_x3) {
			return _ref3.apply(this, arguments);
		};
	}() }));
	useMemo(() => {
		var _productData$_extend;
		const price = (productData === null || productData === void 0 || (_productData$_extend = productData._extend) === null || _productData$_extend === void 0 ? void 0 : _productData$_extend.price) || 0;
		return `${Number(price) < 0 ? "-" : ""}${symbol}${Math.abs(Number(price))}`;
	}, [productData === null || productData === void 0 || (_productData$_extend2 = productData._extend) === null || _productData$_extend2 === void 0 ? void 0 : _productData$_extend2.price, symbol]);
	/**
	* @title 商品单价（含套餐/单规格/组合规格）
	* @description
	* - 套餐：主商品价格 + 选择的套餐子商品（含其单规格）的总价
	* - 单规格：主商品价格 + 单规格加价
	* - 组合规格：使用选中变体价格作为主商品价格，再叠加 bundle/option
	*
	* @note 计算规则对齐 booking/utils.ts 的 getProductTotalPrice
	*/
	const unitPrice = useMemo(() => {
		return getSelectedUnitPrice({
			productData,
			skuValue: (skuValue === null || skuValue === void 0 ? void 0 : skuValue.product_id) ? skuValue : skuDefaultValue
		});
	}, [
		productData,
		skuValue,
		skuDefaultValue
	]);
	/**
	* @description 最终用于展示总价的单价
	* - 若设置过手动改价，则始终使用手动改价单价
	* - 否则使用 sku 计算出来的单价
	*/
	const displayUnitPrice = useMemo(() => {
		if (priceOverride === null || typeof priceOverride === "undefined") return unitPrice;
		return priceOverride;
	}, [priceOverride, unitPrice]);
	/**
	* @title 售价小计
	* @description
	* 小计展示的是「商品单价」（即主商品 + 套餐子商品 + 单规格/组合规格加价的合计）
	*/
	const subtotal = useMemo(() => {
		return new Decimal(unitPrice || 0);
	}, [unitPrice]);
	const subtotalText = useMemo(() => {
		return `${subtotal.toNumber() < 0 ? "-" : ""}${symbol}${subtotal.abs().toNumber().toFixed(2)}`;
	}, [subtotal, symbol]);
	const discountsCount = useMemo(() => {
		return (discounts === null || discounts === void 0 ? void 0 : discounts.length) || 0;
	}, [discounts]);
	/**
	* @title 折扣信息
	*/
	const totalDiscounts = useMemo(() => {
		if ((discounts === null || discounts === void 0 ? void 0 : discounts.length) > 0) return discounts.reduce((sum, discount) => {
			const _quantity = ["discount_card", "product_discount_card"].includes((discount === null || discount === void 0 ? void 0 : discount.type) || "") ? quantity : 1;
			return sum.plus(new Decimal((discount === null || discount === void 0 ? void 0 : discount.amount) || 0).mul(_quantity));
		}, new Decimal(0)).toNumber().toFixed(2);
		return "0.00";
	}, [discounts, quantity]);
	/**
	* @title 最终价格
	* @description 商品总价 = 商品单价 * 商品数量
	*/
	const finalTotal = useMemo(() => {
		const deTotal = new Decimal(displayUnitPrice || "0");
		const deQuantity = new Decimal(quantity || "1");
		return deTotal.mul(deQuantity);
	}, [displayUnitPrice, quantity]);
	const totalText = useMemo(() => {
		return `${finalTotal.toNumber() < 0 ? "-" : ""}${symbol}${finalTotal.abs().toNumber().toFixed(2)}`;
	}, [finalTotal, symbol]);
	/**
	* @description 价格变动展示（仅当设置过手动改价时展示）
	* - 展示手动改价的单价
	* - 展示相对 sku 单价的变动额： (priceOverride - unitPrice) * quantity
	*/
	const priceOverrideText = useMemo(() => {
		if (priceOverride === null || typeof priceOverride === "undefined") return "";
		const prefix = `(${locales.getText("pisell2.text.sku.detail.modal.price.override")} `;
		const overrideNumber = new Decimal(priceOverride || 0);
		return `${prefix}${overrideNumber.toNumber() < 0 ? "-" : ""}${symbol}${overrideNumber.abs().toNumber().toFixed(2)})`;
	}, [priceOverride, symbol]);
	const priceChangeText = useMemo(() => {
		if (priceOverride === null || typeof priceOverride === "undefined") return "";
		const diff = new Decimal(priceOverride || 0).minus(new Decimal(unitPrice || 0)).mul(new Decimal(quantity || 1));
		const diffNumber = diff.toNumber();
		return `${diffNumber > 0 ? "+" : diffNumber < 0 ? "-" : ""}${symbol}${diff.abs().toNumber().toFixed(2)}`;
	}, [
		priceOverride,
		unitPrice,
		quantity,
		symbol
	]);
	const modalCloseAction = () => {
		setOpen(false);
		setProductData(null);
		setNote("");
		setQuantity(1);
		setNoteModalOpen(false);
		setPriceOverride(null);
		setShowPriceAdjustModal(false);
		setDiscounts([]);
		openParamsRef.current = null;
		setCurrentStep(0);
	};
	const handleCancel = () => {
		modalCloseAction();
		onClose === null || onClose === void 0 || onClose();
	};
	/**
	* @description 检查当前选择下的库存是否充足
	*/
	const handleCheckStock = (params) => {
		var _value$bundle;
		const value = (params === null || params === void 0 ? void 0 : params.value) || skuValue;
		const data = (params === null || params === void 0 ? void 0 : params.data) || productData;
		if (!data) return true;
		if ((value === null || value === void 0 ? void 0 : value.product_variant_id) && data) {
			var _variant;
			if (!checkSkuStockCanSell(data === null || data === void 0 || (_variant = data.variant) === null || _variant === void 0 ? void 0 : _variant.find((item) => item.id === value.product_variant_id)).hasStock) return false;
		}
		if ((value === null || value === void 0 || (_value$bundle = value.bundle) === null || _value$bundle === void 0 ? void 0 : _value$bundle.length) > 0 && data) {
			if (!(value === null || value === void 0 ? void 0 : value.bundle.every((item) => {
				return checkSkuStockCanSell(item).hasStock;
			}))) return false;
		}
		if (value === null || value === void 0 ? void 0 : value.product_variant_id) return true;
		if (!checkSkuStockCanSell(data).hasStock) return false;
		return true;
	};
	const handleConfirm = function() {
		var _ref4 = _asyncToGenerator(function* () {
			var _bookingState$booking;
			if (currentStep === 0 && hasSkuOptions) {
				var _procedureRef$current, _procedureRef$current2;
				(_procedureRef$current = procedureRef.current) === null || _procedureRef$current === void 0 || (_procedureRef$current2 = _procedureRef$current.goToStep) === null || _procedureRef$current2 === void 0 || _procedureRef$current2.call(_procedureRef$current, 1);
				setCurrentStep(1);
				return;
			}
			/**
			* @description Confirm 前是否需要触发 SKU 选择校验
			* - required_option_validation 不为 0：需要校验（失败阻断）
			* - required_option_validation 为 0：不校验（无论成功/失败都允许提交）
			*
			* @note 配置缺失时默认走“需要校验”，保持更安全的默认行为
			*/
			const requiredOptionValidation = bookingState === null || bookingState === void 0 || (_bookingState$booking = bookingState.bookingConfig) === null || _bookingState$booking === void 0 || (_bookingState$booking = _bookingState$booking.config) === null || _bookingState$booking === void 0 || (_bookingState$booking = _bookingState$booking.product_setting_tab) === null || _bookingState$booking === void 0 ? void 0 : _bookingState$booking.required_option_validation;
			if (Number(requiredOptionValidation !== null && requiredOptionValidation !== void 0 ? requiredOptionValidation : 1) !== 0 && hasSkuOptions) try {
				var _skuOptionsSelectionR, _skuOptionsSelectionR2;
				if (!(yield (_skuOptionsSelectionR = skuOptionsSelectionRef.current) === null || _skuOptionsSelectionR === void 0 || (_skuOptionsSelectionR2 = _skuOptionsSelectionR.validate) === null || _skuOptionsSelectionR2 === void 0 ? void 0 : _skuOptionsSelectionR2.call(_skuOptionsSelectionR))) return;
			} catch (error) {
				console.log("sku_detail_modal_validate_error>>>>>", error);
				return;
			}
			if (productData && onConfirm) {
				var _skuOptionsSelectionR3, _skuOptionsSelectionR4, _bookingState$booking2, _bookingState$booking3, _bookingState$booking4, _bookingState$booking5, _bookingState$booking6, _bookingState$booking7;
				/**
				* @description 优先从 SKUOptionsSelection ref 读取最新转换后的值
				*/
				const latestSkuValue = ((_skuOptionsSelectionR3 = skuOptionsSelectionRef.current) === null || _skuOptionsSelectionR3 === void 0 || (_skuOptionsSelectionR4 = _skuOptionsSelectionR3.getTransformValues) === null || _skuOptionsSelectionR4 === void 0 ? void 0 : _skuOptionsSelectionR4.call(_skuOptionsSelectionR3)) || skuValue || skuDefaultValue;
				const originTotal = new Decimal(unitPrice || 0).toNumber();
				const updatedData = _objectSpread2(_objectSpread2({}, productData), {}, {
					discount_list: discounts || [],
					_extend: _objectSpread2(_objectSpread2({}, (productData === null || productData === void 0 ? void 0 : productData._extend) || {}), {}, {
						quantity,
						note,
						other: getOtherFromSkuValue({
							productData,
							skuValue: latestSkuValue
						}),
						skuValue: getOtherFromSkuValue({
							productData,
							skuValue: latestSkuValue
						}),
						origin_total: originTotal
					}, priceOverride !== null && typeof priceOverride !== "undefined" ? { priceOverride } : {})
				});
				/**
				* @description 库存校验（受全局配置控制）
				* - stock_validation === 1：启用库存校验
				* - allow_add_to_cart_when_out_stock === 1：缺货允许加入购物车（弹窗提示）
				*/
				const stockValidation = Number((_bookingState$booking2 = bookingState === null || bookingState === void 0 || (_bookingState$booking3 = bookingState.bookingConfig) === null || _bookingState$booking3 === void 0 || (_bookingState$booking3 = _bookingState$booking3.config) === null || _bookingState$booking3 === void 0 || (_bookingState$booking3 = _bookingState$booking3.stock_setting) === null || _bookingState$booking3 === void 0 ? void 0 : _bookingState$booking3.stock_validation) !== null && _bookingState$booking2 !== void 0 ? _bookingState$booking2 : 0);
				const allowAddToCartWhenOutStock = Number((_bookingState$booking4 = bookingState === null || bookingState === void 0 || (_bookingState$booking5 = bookingState.bookingConfig) === null || _bookingState$booking5 === void 0 || (_bookingState$booking5 = _bookingState$booking5.config) === null || _bookingState$booking5 === void 0 || (_bookingState$booking5 = _bookingState$booking5.stock_setting) === null || _bookingState$booking5 === void 0 ? void 0 : _bookingState$booking5.allow_add_to_cart_when_out_stock) !== null && _bookingState$booking4 !== void 0 ? _bookingState$booking4 : 0);
				const enableDontShowAgainToday = Number((_bookingState$booking6 = bookingState === null || bookingState === void 0 || (_bookingState$booking7 = bookingState.bookingConfig) === null || _bookingState$booking7 === void 0 || (_bookingState$booking7 = _bookingState$booking7.config) === null || _bookingState$booking7 === void 0 || (_bookingState$booking7 = _bookingState$booking7.stock_setting) === null || _bookingState$booking7 === void 0 ? void 0 : _bookingState$booking7.do_not_show_again_today) !== null && _bookingState$booking6 !== void 0 ? _bookingState$booking6 : 0);
				if (stockValidation === 1) {
					if (!handleCheckStock({
						value: latestSkuValue,
						data: productData
					})) {
						if (allowAddToCartWhenOutStock !== 1) {
							Toast === null || Toast === void 0 || Toast.fail(locales.getText("pisell2.skuOptionsSelection.variantItemCard.soldOut"));
							return;
						}
						const productId = Number((productData === null || productData === void 0 ? void 0 : productData.product_id) || 0);
						if (!(enableDontShowAgainToday === 1 && hasHiddenStockAlertForToday({ productId }))) {
							pendingConfirmDataRef.current = updatedData;
							setStockAlertDontShowAgainChecked(false);
							setStockAlertOpen(true);
							return;
						}
					}
				}
				onConfirm(updatedData);
				modalCloseAction();
			}
		});
		return function handleConfirm() {
			return _ref4.apply(this, arguments);
		};
	}();
	const handleStockAlertCancel = () => {
		pendingConfirmDataRef.current = null;
		setStockAlertOpen(false);
		setStockAlertDontShowAgainChecked(false);
	};
	const handleStockAlertContinue = () => {
		var _bookingState$booking8, _bookingState$booking9;
		const pendingData = pendingConfirmDataRef.current;
		if (!pendingData) {
			setStockAlertOpen(false);
			return;
		}
		if (Number((_bookingState$booking8 = bookingState === null || bookingState === void 0 || (_bookingState$booking9 = bookingState.bookingConfig) === null || _bookingState$booking9 === void 0 || (_bookingState$booking9 = _bookingState$booking9.config) === null || _bookingState$booking9 === void 0 || (_bookingState$booking9 = _bookingState$booking9.stock_setting) === null || _bookingState$booking9 === void 0 ? void 0 : _bookingState$booking9.do_not_show_again_today) !== null && _bookingState$booking8 !== void 0 ? _bookingState$booking8 : 0) === 1 && stockAlertDontShowAgainChecked) setHiddenStockAlertForToday({ productId: Number((productData === null || productData === void 0 ? void 0 : productData.product_id) || 0) });
		onConfirm === null || onConfirm === void 0 || onConfirm(pendingData);
		pendingConfirmDataRef.current = null;
		setStockAlertOpen(false);
		modalCloseAction();
	};
	const handleRemove = () => {
		if (productData && onRemove) {
			onRemove(productData);
			modalCloseAction();
		}
	};
	const handleQuantityChange = (value) => {
		if (value && value > 0) setQuantity(value);
	};
	const onNoteConfirm = (note) => {
		setNote(note);
		setNoteModalOpen(false);
	};
	const onNoteDelete = () => {
		setNote("");
		setNoteModalOpen(false);
	};
	const onNoteCancel = () => {
		setNoteModalOpen(false);
	};
	const handleManualPriceChange = () => {
		if (!productData) return;
		setShowPriceAdjustModal(true);
	};
	const handlePriceAdjustConfirm = (value) => {
		setPriceOverride(value);
		setDiscounts([]);
		setShowPriceAdjustModal(false);
	};
	const coverText = useMemo(() => {
		var _productData$title;
		const title = (productData === null || productData === void 0 || (_productData$title = productData.title) === null || _productData$title === void 0 ? void 0 : _productData$title.trim()) || "";
		if (!title) return "";
		return Array.from(title).slice(0, 2).join("");
	}, [productData === null || productData === void 0 ? void 0 : productData.title]);
	const isCreateMode = !!openParamsRef.current;
	const leftContent = () => {
		return /* @__PURE__ */ React.createElement("div", { className: "sku-detail-left" }, /* @__PURE__ */ React.createElement("div", { className: "sku-detail-left-content" }, /* @__PURE__ */ React.createElement("div", { className: "product-image" }, (productData === null || productData === void 0 ? void 0 : productData.cover) ? /* @__PURE__ */ React.createElement("img", { src: (productData === null || productData === void 0 ? void 0 : productData.cover) || "" }) : /* @__PURE__ */ React.createElement("div", { className: "product-cover-text" }, coverText)), /* @__PURE__ */ React.createElement("div", { className: "product-info" }, /* @__PURE__ */ React.createElement("div", { className: "product-info-left" }, /* @__PURE__ */ React.createElement("div", { className: "product-name" }, (productData === null || productData === void 0 ? void 0 : productData.title) || ""), /* @__PURE__ */ React.createElement("div", { className: "product-spec" }))), /* @__PURE__ */ React.createElement("div", { className: "product-actions" }, /* @__PURE__ */ React.createElement(Button, {
			size: "large",
			className: "add-note-btn",
			onClick: () => setNoteModalOpen(true)
		}, locales.getText("pisell2.text.sku.detail.modal.btn.add.note"))), note && /* @__PURE__ */ React.createElement("div", { className: "note-section" }, /* @__PURE__ */ React.createElement("div", null, locales.getText("pisell2.text.sku.detail.modal.note")), /* @__PURE__ */ React.createElement("div", {
			className: "note-text",
			onClick: () => setNoteModalOpen(true)
		}, note))), /* @__PURE__ */ React.createElement("div", { className: "price-summary-section" }, /* @__PURE__ */ React.createElement("div", { className: "price-item" }, /* @__PURE__ */ React.createElement("div", null, locales.getText("pisell2.text.sku.detail.modal.subtotal")), /* @__PURE__ */ React.createElement("div", null, subtotalText)), /* @__PURE__ */ React.createElement("div", { className: "price-item" }, /* @__PURE__ */ React.createElement("div", null, locales.getText("pisell2.text.sku.detail.modal.discount"), discountsCount > 0 && /* @__PURE__ */ React.createElement("span", { className: "price-item-danger" }, "\xA0(", discountsCount, ")")), /* @__PURE__ */ React.createElement("div", { className: "price-item-danger" }, discountsCount > 0 ? "-" : "", symbol, totalDiscounts)), priceOverride !== null && typeof priceOverride !== "undefined" && /* @__PURE__ */ React.createElement("div", { className: "price-item" }, /* @__PURE__ */ React.createElement("div", { onClick: handleManualPriceChange }, locales.getText("pisell2.text.sku.detail.modal.manual.price.change"), /* @__PURE__ */ React.createElement("span", { className: "price-item-override" }, priceOverrideText)), /* @__PURE__ */ React.createElement("div", { className: "price-item-danger" }, priceChangeText)), /* @__PURE__ */ React.createElement("div", { className: "price-item-total" }, /* @__PURE__ */ React.createElement("div", null, locales.getText("pisell2.text.sku.detail.modal.total"), /* @__PURE__ */ React.createElement("span", { className: "price-item-total-gst" }, "（", (productData === null || productData === void 0 ? void 0 : productData.is_charge_tax) ? locales.getText("pisell2.text.sku.detail.modal.gst.incl") : locales.getText("pisell2.text.sku.detail.modal.gst.excl"), "）")), /* @__PURE__ */ React.createElement("div", null, totalText))));
	};
	if (!productData) return null;
	const rightContent = () => {
		return /* @__PURE__ */ React.createElement("div", { className: "sku-detail-right-content" }, currentStep === 0 && /* @__PURE__ */ React.createElement("div", { className: "sku-detail-right-content-detail" }, /* @__PURE__ */ React.createElement("div", { className: "sku-detail-right-content-detail-description" }, (productData === null || productData === void 0 ? void 0 : productData.subtitle) ? /* @__PURE__ */ React.createElement("div", { className: "sku-detail-right-content-detail-subtitle" }, productData.subtitle) : null, (productData === null || productData === void 0 ? void 0 : productData.description) ? /* @__PURE__ */ React.createElement("div", {
			className: "sku-detail-right-content-detail-description-html",
			dangerouslySetInnerHTML: { __html: productData.description }
		}) : null, (productData === null || productData === void 0 ? void 0 : productData.description) === "" && !hasSkuOptions && /* @__PURE__ */ React.createElement("div", { className: "sku-detail-right-content-detail-placeholder" }, /* @__PURE__ */ React.createElement("img", {
			width: 300,
			height: 300,
			src: "https://static.pisellcdn.com/sku_empty.png",
			alt: "placeholder"
		}), /* @__PURE__ */ React.createElement("p", null, "No additional options for this item")))), currentStep === 1 && hasSkuOptions && /* @__PURE__ */ React.createElement(SKUOptionsSelection, {
			ref: skuOptionsSelectionRef,
			dataSource: productData,
			value: skuDefaultValue,
			skuCardConfig: {
				title: { lineClamp: 1 },
				subTitle: { lineClamp: 1 }
			},
			customConfig: {
				modalWidth: "680px",
				selectorLayout: {
					type: "antdGrid",
					columns: 2,
					gutter: [16, 16]
				}
			},
			onChange: (v) => {
				console.log("SKUOptionsSelectionOnChange", v);
				setSkuValue(v);
			},
			customScrollParent: ".pisell-sku-detail-modal .sku-detail-right-content"
		}));
	};
	const leftHeaderClose = () => {
		return /* @__PURE__ */ React.createElement("div", {
			className: "sku-detail-left-close",
			onClick: handleCancel
		}, /* @__PURE__ */ React.createElement(Iconfont, { type: "pisell2-x-close" }), locales.getText("pisell2.text.sku.detail.modal.btn.close"));
	};
	/**
	* @description Procedure Header：返回按钮（仅在非第一步展示）
	* - 第一页不展示，但必须渲染一个空 div 占位，避免 header 布局抖动
	*/
	const leftHeaderBack = () => {
		if (currentStep === 0) return /* @__PURE__ */ React.createElement("div", { className: "sku-detail-left-back-placeholder" });
		return /* @__PURE__ */ React.createElement("div", {
			className: "sku-detail-left-back",
			onClick: () => {
				var _procedureRef$current3, _procedureRef$current4;
				(_procedureRef$current3 = procedureRef.current) === null || _procedureRef$current3 === void 0 || (_procedureRef$current4 = _procedureRef$current3.goToStep) === null || _procedureRef$current4 === void 0 || _procedureRef$current4.call(_procedureRef$current3, 0);
				setCurrentStep(0);
			}
		}, /* @__PURE__ */ React.createElement(Iconfont, { type: "pisell2-arrow-left" }), locales.getText("pisell2.text.sku.detail.modal.btn.back"));
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PisellModal, {
		platform: "pc",
		open,
		header: null,
		headerDivider: false,
		footer: null,
		onCancel: handleCancel,
		closable: false,
		destroyOnClose: true,
		width: "80%",
		className: "pisell-sku-detail-modal"
	}, /* @__PURE__ */ React.createElement(PisellProcedure, {
		ref: procedureRef,
		className: "pisell-sku-procedure",
		mode: "modal",
		defaultCurrent: currentStep,
		layoutMode: "ratio",
		onStepsChange: (result) => {
			setCurrentStep(Math.min(Number(result.currentStep || 0), maxStepIndex));
		},
		headerProps: {
			showBackOnFirstStep: true,
			showSteps: procedureSteps.length > 1,
			left: leftHeaderBack(),
			right: leftHeaderClose(),
			stepsProps: { items: procedureSteps }
		},
		onFirstStepBack: () => {
			handleCancel();
		},
		showSideBar: true,
		showFooter: true,
		bodyProps: {
			direction: "horizontal",
			contentOrder: "sidebar-first",
			contentSlot: rightContent(),
			sidebarSlot: leftContent(),
			sidebarContainerSelector: ".pisell-sku-detail-modal"
		},
		footerProps: {
			position: "fixed-bottom",
			style: { height: "72px !important" },
			leftSlot: /* @__PURE__ */ React.createElement("div", { className: "quantity-section" }, /* @__PURE__ */ React.createElement("div", { className: "quantity-section-title" }, locales.getText("pisell2.text.sku.detail.modal.quantity")), /* @__PURE__ */ React.createElement(NumericStepper, {
				variant: "capsule",
				value: quantity,
				onChange: handleQuantityChange,
				min: 1,
				max: 99999
			})),
			actions: /* @__PURE__ */ React.createElement("div", { className: "sku-detail-content-footer" }, /* @__PURE__ */ React.createElement("div", { className: "modal-actions" }, isCreateMode ? /* @__PURE__ */ React.createElement(Button, {
				type: "default",
				size: "large",
				className: "sku-detail-content-footer-remove-btn",
				onClick: handleCancel
			}, locales.getText("pisell2.text.cancel") || "Cancel") : /* @__PURE__ */ React.createElement(Button, {
				type: "primary",
				danger: true,
				size: "large",
				icon: /* @__PURE__ */ React.createElement(Delete_wght300_24px, { style: { fontSize: 20 } }),
				className: "sku-detail-content-footer-remove-btn",
				onClick: handleRemove
			}, locales.getText("pisell2.text.sku.detail.modal.btn.remove")), /* @__PURE__ */ React.createElement(Button, {
				type: "default",
				size: "large",
				onClick: handleManualPriceChange,
				className: "sku-detail-content-footer-price-btn"
			}, /* @__PURE__ */ React.createElement("span", { className: "sku-detail-content-footer-price-btn-text" }, locales.getText("pisell2.text.sku.detail.modal.btn.manual.price.change"))), /* @__PURE__ */ React.createElement(Button, {
				type: "primary",
				size: "large",
				onClick: handleConfirm,
				className: "sku-detail-content-footer-confirm-btn"
			}, currentStep === 0 && hasSkuOptions ? /* @__PURE__ */ React.createElement("span", { className: "sku-detail-content-footer-confirm-btn-text" }, locales.getText("pisell2.text.sku.detail.modal.btn.next")) : /* @__PURE__ */ React.createElement("span", { className: "sku-detail-content-footer-confirm-btn-text" }, locales.getText("pisell2.text.sku.detail.modal.btn.confirm")))))
		}
	}), noteModalOpen && /* @__PURE__ */ React.createElement(NoteModal, {
		open: noteModalOpen,
		value: note,
		onCancel: onNoteCancel,
		onConfirm: onNoteConfirm,
		onDelete: onNoteDelete
	}), /* @__PURE__ */ React.createElement(DiscountKeyboard, {
		containerProps: {
			renderType: "modal",
			open: showPriceAdjustModal,
			onCancel: () => setShowPriceAdjustModal(false)
		},
		enableExceedMaxAmount: true,
		originalValue: displayUnitPrice || 0,
		defaultValue: displayUnitPrice || 0,
		onEnter: (discountAmount) => {
			handlePriceAdjustConfirm(new Decimal(displayUnitPrice || 0).minus(discountAmount).toNumber());
		},
		selectType: "dark"
	})), /* @__PURE__ */ React.createElement(PisellModal, {
		platform: "pc",
		open: stockAlertOpen,
		title: locales.getText("pisell2.text.sku.detail.modal.stock.alert.title"),
		headerDivider: false,
		footer: /* @__PURE__ */ React.createElement("div", { style: {
			width: "100%",
			display: "flex",
			justifyContent: "flex-end",
			gap: 12
		} }, /* @__PURE__ */ React.createElement(Button, {
			size: "large",
			onClick: handleStockAlertCancel
		}, locales.getText("pisell2.text.sku.detail.modal.stock.alert.btn.cancel")), /* @__PURE__ */ React.createElement(Button, {
			type: "primary",
			size: "large",
			onClick: handleStockAlertContinue
		}, locales.getText("pisell2.text.sku.detail.modal.stock.alert.btn.continue"))),
		width: 520,
		centered: true,
		destroyOnClose: true,
		maskClosable: false,
		zIndex: 2e3,
		onCancel: handleStockAlertCancel
	}, /* @__PURE__ */ React.createElement("div", { style: { padding: "40px 0 0 0" } }, /* @__PURE__ */ React.createElement("div", { style: {
		color: "#344054",
		fontSize: 14,
		lineHeight: "22px"
	} }, locales.getText("pisell2.text.sku.detail.modal.stock.alert.desc")), Number((_bookingState$booking10 = bookingState === null || bookingState === void 0 || (_bookingState$booking11 = bookingState.bookingConfig) === null || _bookingState$booking11 === void 0 || (_bookingState$booking11 = _bookingState$booking11.config) === null || _bookingState$booking11 === void 0 || (_bookingState$booking11 = _bookingState$booking11.stock_setting) === null || _bookingState$booking11 === void 0 ? void 0 : _bookingState$booking11.do_not_show_again_today) !== null && _bookingState$booking10 !== void 0 ? _bookingState$booking10 : 0) === 1 && /* @__PURE__ */ React.createElement("div", { style: { marginTop: 16 } }, /* @__PURE__ */ React.createElement(Checkbox, {
		checked: stockAlertDontShowAgainChecked,
		onChange: (e) => {
			var _e$target;
			setStockAlertDontShowAgainChecked(!!(e === null || e === void 0 || (_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.checked));
		}
	}, locales.getText("pisell2.text.sku.detail.modal.stock.alert.checkbox"))))));
};
var skuDetailModal_default = forwardRef(SkuDetailModal);
/**
* @description 获取本地当天日期 key（本地时区）
*/
function getLocalDayKey() {
	const now = /* @__PURE__ */ new Date();
	return `${String(now.getFullYear())}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
}
function getStockAlertStorageKey(params) {
	return `pisell2_stock_alert_hidden_${params.productId}`;
}
/**
* @description 判断今天是否已对该商品隐藏库存提示
*/
function hasHiddenStockAlertForToday(params) {
	try {
		if (!params.productId) return false;
		if (typeof window === "undefined") return false;
		const key = getStockAlertStorageKey(params);
		return window.localStorage.getItem(key) === getLocalDayKey();
	} catch (error) {
		return false;
	}
}
/**
* @description 设置今天对该商品隐藏库存提示
*/
function setHiddenStockAlertForToday(params) {
	try {
		if (!params.productId) return;
		if (typeof window === "undefined") return;
		const key = getStockAlertStorageKey(params);
		window.localStorage.setItem(key, getLocalDayKey());
	} catch (error) {}
}
/**
* @description
* 根据当前 skuValue（组合规格/单规格/套餐）计算“商品单价”
* 计算规则与 booking/utils.ts 的 getProductTotalPrice 保持一致。
*/
function getSelectedUnitPrice(params) {
	var _ref5, _productData$base_pri, _productData$_extend3;
	const { productData, skuValue } = params;
	if (!productData) return 0;
	let price = new Decimal((_ref5 = (_productData$base_pri = productData === null || productData === void 0 ? void 0 : productData.base_price) !== null && _productData$base_pri !== void 0 ? _productData$base_pri : productData === null || productData === void 0 || (_productData$_extend3 = productData._extend) === null || _productData$_extend3 === void 0 ? void 0 : _productData$_extend3.price) !== null && _ref5 !== void 0 ? _ref5 : 0);
	if (skuValue === null || skuValue === void 0 ? void 0 : skuValue.product_variant_id) {
		var _variant2;
		const variantItem = productData === null || productData === void 0 || (_variant2 = productData.variant) === null || _variant2 === void 0 ? void 0 : _variant2.find((item) => Number(item === null || item === void 0 ? void 0 : item.id) === Number(skuValue.product_variant_id));
		if (variantItem) {
			var _ref6, _variantItem$price;
			price = new Decimal((_ref6 = (_variantItem$price = variantItem === null || variantItem === void 0 ? void 0 : variantItem.price) !== null && _variantItem$price !== void 0 ? _variantItem$price : variantItem === null || variantItem === void 0 ? void 0 : variantItem.base_price) !== null && _ref6 !== void 0 ? _ref6 : 0);
		}
	}
	if (Array.isArray(skuValue === null || skuValue === void 0 ? void 0 : skuValue.bundle) && skuValue.bundle.length > 0) price = skuValue.bundle.reduce((accumulator, currentValue) => {
		const currentPrice = new Decimal((currentValue === null || currentValue === void 0 ? void 0 : currentValue.price) || 0);
		const currentNum = new Decimal((currentValue === null || currentValue === void 0 ? void 0 : currentValue.num) || 0);
		return accumulator.add(currentPrice.mul(currentNum));
	}, price);
	if (Array.isArray(skuValue === null || skuValue === void 0 ? void 0 : skuValue.option) && skuValue.option.length > 0) price = skuValue.option.reduce((accumulator, currentValue) => {
		const currentPrice = new Decimal((currentValue === null || currentValue === void 0 ? void 0 : currentValue.price) || 0);
		const currentNum = new Decimal((currentValue === null || currentValue === void 0 ? void 0 : currentValue.num) || 0);
		return accumulator.add(currentPrice.mul(currentNum));
	}, price);
	return price.toNumber();
}
/**
* @description
* 生成给 booking 侧使用的 other 字段（用于 getProductTotalPrice 按同规则算价）
*/
function getOtherFromSkuValue(params) {
	const { productData, skuValue } = params;
	const other = {
		product_variant_id: (skuValue === null || skuValue === void 0 ? void 0 : skuValue.product_variant_id) || 0,
		bundle: (skuValue === null || skuValue === void 0 ? void 0 : skuValue.bundle) || [],
		option: (skuValue === null || skuValue === void 0 ? void 0 : skuValue.option) || []
	};
	if (other.product_variant_id && productData) {
		var _variant3;
		const variantItem = productData === null || productData === void 0 || (_variant3 = productData.variant) === null || _variant3 === void 0 ? void 0 : _variant3.find((item) => Number(item === null || item === void 0 ? void 0 : item.id) === Number(other.product_variant_id));
		if (variantItem) {
			var _ref7, _variantItem$price2;
			other.price = Number((_ref7 = (_variantItem$price2 = variantItem === null || variantItem === void 0 ? void 0 : variantItem.price) !== null && _variantItem$price2 !== void 0 ? _variantItem$price2 : variantItem === null || variantItem === void 0 ? void 0 : variantItem.base_price) !== null && _ref7 !== void 0 ? _ref7 : 0);
		}
	}
	return other;
}
//#endregion
export { skuDetailModal_default as default };
