var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/pro/skuDetailModal/index.tsx
var skuDetailModal_exports = {};
__export(skuDetailModal_exports, {
  default: () => skuDetailModal_default
});
module.exports = __toCommonJS(skuDetailModal_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_decimal = __toESM(require("decimal.js"));
var import_utils = require("@pisell/utils");
var import_Delete_wght300_24px = __toESM(require("@pisell/icon/es/Delete_wght300_24px"));
var import_locales = __toESM(require("./locales"));
var import_stock = __toESM(require("../../shared/locales/stock"));
var import_index = require("./index.less");
var import_NumericStepper = __toESM(require("../NumericStepper"));
var import_noteModal = __toESM(require("../../plus/noteModal"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_priceKeyboard = require("../priceKeyboard");
var import_skuOptionsSelection = __toESM(require("../../plus/skuOptionsSelection"));
var import_serve = require("../../components/booking/info/service/serve");
var import_utils2 = require("./utils");
var import_model = require("../../components/booking/info/model");
var import_useToast = __toESM(require("../../hooks/useToast"));
var import_useLogger = __toESM(require("../../hooks/useLogger"));
var import_utils3 = require("../../components/shoppingCart/utils");
var import_lodash = require("lodash");
var import_responsive = require("../../responsive");
var import_weighing = __toESM(require("./components/weighing"));
var import_utils4 = require("./components/weighing/utils");
var import_useWeighing = require("./components/weighing/useWeighing");
var import_classnames = __toESM(require("classnames"));
var import_compensatedPisellContainer = __toESM(require("../compensatedPisellContainer"));
var DeleteIcon = import_Delete_wght300_24px.default;
var PisellProcedureComponent = import_materials.PisellProcedure;
var getBodyScaleY = () => {
  if (typeof window === "undefined" || typeof document === "undefined") {
    return 1;
  }
  const transform = window.getComputedStyle(document.body).transform;
  if (!transform || transform === "none") {
    return 1;
  }
  const matrix = new DOMMatrixReadOnly(transform);
  return Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d) || 1;
};
var PcActionButtons = ({
  isCreateMode,
  isShowNote,
  confirmLabel,
  onCancel,
  onRemove,
  onManualPriceChange,
  onOpenNote,
  onConfirm
}) => {
  const auxiliaryActions = [
    isShowNote ? /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        key: "note",
        type: "default",
        size: "large",
        className: "sku-detail-side-actions-btn",
        onClick: onOpenNote
      },
      import_utils.locales.getText("pisell2.text.sku.detail.modal.btn.add.note")
    ) : null,
    /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        key: "manual-price",
        type: "default",
        size: "large",
        onClick: onManualPriceChange,
        className: "sku-detail-side-actions-btn sku-detail-side-actions-price-btn"
      },
      /* @__PURE__ */ import_react.default.createElement("span", { className: "sku-detail-content-footer-price-btn-text" }, import_utils.locales.getText(
        "pisell2.text.sku.detail.modal.btn.manual.price.change"
      ))
    )
  ].filter(Boolean);
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-side-actions" }, auxiliaryActions.length > 0 && /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-side-actions-list" }, auxiliaryActions), /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-side-actions-primary" }, isCreateMode ? /* @__PURE__ */ import_react.default.createElement(
    import_materials.Button,
    {
      type: "default",
      size: "large",
      className: "sku-detail-side-actions-btn",
      onClick: onCancel
    },
    import_utils.locales.getText("pisell2.text.cancel") || "Cancel"
  ) : /* @__PURE__ */ import_react.default.createElement(
    import_materials.Button,
    {
      type: "primary",
      danger: true,
      size: "large",
      icon: /* @__PURE__ */ import_react.default.createElement(DeleteIcon, null),
      className: "sku-detail-side-actions-btn",
      onClick: onRemove
    },
    import_utils.locales.getText("pisell2.text.sku.detail.modal.btn.remove")
  ), /* @__PURE__ */ import_react.default.createElement(
    import_materials.Button,
    {
      type: "primary",
      size: "large",
      onClick: onConfirm,
      className: "sku-detail-side-actions-btn sku-detail-side-actions-confirm-btn"
    },
    /* @__PURE__ */ import_react.default.createElement("span", { className: "sku-detail-content-footer-confirm-btn-text" }, confirmLabel)
  )));
};
var SkuDetailModal = ({
  onConfirm,
  onRemove,
  onClose,
  variant
}, ref) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
  const isMobile = variant === "phone";
  const [open, setOpen] = (0, import_react.useState)(false);
  const [productData, setProductData] = (0, import_react.useState)(null);
  const [note, setNote] = (0, import_react.useState)("");
  const [quantity, setQuantity] = (0, import_react.useState)(1);
  const [priceOverride, setPriceOverride] = (0, import_react.useState)(null);
  const [showPriceAdjustModal, setShowPriceAdjustModal] = (0, import_react.useState)(false);
  const [discounts, setDiscounts] = (0, import_react.useState)([]);
  const [noteModalOpen, setNoteModalOpen] = (0, import_react.useState)(false);
  const [weighingData, setWeighingData] = (0, import_react.useState)(null);
  const [skuValue, setSkuValue] = (0, import_react.useState)({
    price: 0,
    product_id: 0,
    product_variant_id: 0,
    bundle: [],
    option: []
  });
  const [skuDefaultValue, setSkuDefaultValue] = (0, import_react.useState)({
    product_id: 0,
    price: 0,
    product_variant_id: 0,
    bundle: [],
    option: []
  });
  const openParamsRef = (0, import_react.useRef)(null);
  const leftTopRef = (0, import_react.useRef)(null);
  const Toast = (0, import_useToast.default)();
  const logger = (0, import_useLogger.default)();
  const skuOptionsSelectionRef = (0, import_react.useRef)(null);
  const [stockAlertOpen, setStockAlertOpen] = (0, import_react.useState)(false);
  const [stockAlertDontShowAgainChecked, setStockAlertDontShowAgainChecked] = (0, import_react.useState)(false);
  const pendingConfirmDataRef = (0, import_react.useRef)(null);
  const [currentStep, setCurrentStep] = (0, import_react.useState)(0);
  const procedureRef = (0, import_react.useRef)(null);
  const [skuDetailConfig, setSkuDetailConfig] = (0, import_react.useState)({
    isShowStepper: true,
    isShowNote: true
  });
  const [bodyScaleY, setBodyScaleY] = (0, import_react.useState)(getBodyScaleY);
  const context = (0, import_useEngineContext.default)();
  const { store, getData, isWebPos } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  const { state: bookingState } = (0, import_react.useContext)(import_model.Context) || {};
  const symbol = getData("shop_symbol");
  import_utils.locales.init(import_locales.default, ((_c = (_b = context == null ? void 0 : context.engine) == null ? void 0 : _b.props) == null ? void 0 : _c.locale) || "en");
  import_utils.locales.init(import_stock.default, ((_e = (_d = context == null ? void 0 : context.engine) == null ? void 0 : _d.props) == null ? void 0 : _e.locale) || "en");
  (0, import_react.useEffect)(() => {
    const updateBodyScale = () => {
      setBodyScaleY(getBodyScaleY());
    };
    updateBodyScale();
    window.addEventListener("resize", updateBodyScale);
    const bodyObserver = new MutationObserver(updateBodyScale);
    bodyObserver.observe(document.body, {
      attributes: true,
      attributeFilter: ["style", "class"]
    });
    return () => {
      window.removeEventListener("resize", updateBodyScale);
      bodyObserver.disconnect();
    };
  }, []);
  const getDetailData = async (data, open_deposit) => {
    var _a2;
    const isCallProductDetail = ((_a2 = data == null ? void 0 : data.skuDetailConfig) == null ? void 0 : _a2.isCallProductDetail) ?? false;
    const isEject = (data == null ? void 0 : data.is_eject) ?? 0;
    const canUseLocalData = !(isCallProductDetail && isEject === 1);
    if (isWebPos && data.productData && canUseLocalData) {
      return {
        data: data.productData
      };
    } else {
      return await (0, import_serve.getProductDetail)(String(data.id), {
        schedule_date: data.date,
        is_eject: data.is_eject,
        open_deposit
      });
    }
  };
  const stockValidation = (0, import_react.useMemo)(
    () => {
      var _a2, _b2, _c2;
      return Number(
        ((_c2 = (_b2 = (_a2 = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.stock_setting) == null ? void 0 : _c2.stock_validation) ?? 0
      );
    },
    [(_g = (_f = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _f.config) == null ? void 0 : _g.stock_setting]
  );
  const allowAddToCartWhenOutStock = (0, import_react.useMemo)(
    () => {
      var _a2, _b2, _c2;
      return Number(
        ((_c2 = (_b2 = (_a2 = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.stock_setting) == null ? void 0 : _c2.allow_add_to_cart_when_out_stock) ?? 0
      );
    },
    [(_i = (_h = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _h.config) == null ? void 0 : _i.stock_setting]
  );
  const hasSkuOptions = (0, import_react.useMemo)(() => {
    const data = productData;
    const hasVariantGroup = Array.isArray(data == null ? void 0 : data.variant_group) && data.variant_group.length > 0;
    const hasOptionGroup = Array.isArray(data == null ? void 0 : data.option_group) && data.option_group.length > 0;
    const hasBundleGroup = Array.isArray(data == null ? void 0 : data.bundle_group) && data.bundle_group.length > 0;
    return hasVariantGroup || hasOptionGroup || hasBundleGroup;
  }, [productData]);
  const procedureSteps = (0, import_react.useMemo)(() => {
    const items = [
      {
        title: import_utils.locales.getText("pisell2.text.sku.detail.modal.step.details"),
        description: ""
      }
    ];
    if (hasSkuOptions) {
      items.push({
        title: import_utils.locales.getText(
          "pisell2.text.sku.detail.modal.step.select.bundle"
        ),
        description: ""
      });
    }
    return items;
  }, [hasSkuOptions]);
  const maxStepIndex = (0, import_react.useMemo)(
    () => Math.max(0, procedureSteps.length - 1),
    [procedureSteps]
  );
  const formatVariant = (config, _variant, apiData) => {
    var _a2, _b2, _c2;
    let variantData;
    if ((_a2 = config == null ? void 0 : config.externalVariant) == null ? void 0 : _a2.isCustom) {
      let variant2 = _variant || [];
      if ((_b2 = config == null ? void 0 : config.externalVariant) == null ? void 0 : _b2.formatVariant) {
        variant2 = (_c2 = config == null ? void 0 : config.externalVariant) == null ? void 0 : _c2.formatVariant(_variant || []);
      }
      const mergeData = { ...apiData, variant: variant2 };
      variantData = {
        variant: variant2,
        variant_group: (0, import_utils3.filterVariantGroupByVariants)(mergeData) || []
      };
    }
    return variantData;
  };
  (0, import_react.useImperativeHandle)(ref, () => ({
    open: async (data) => {
      var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2;
      setCurrentStep(0);
      setNoteModalOpen(false);
      logger == null ? void 0 : logger.addLog({
        type: "info",
        title: "sku_detail_modal_open",
        metadata: {
          data
        }
      });
      const dataWithConfig = data;
      const skuDetailConfig2 = dataWithConfig.skuDetailConfig || {};
      const config = {
        isShowStepper: (skuDetailConfig2 == null ? void 0 : skuDetailConfig2.isShowStepper) ?? true,
        isShowNote: (skuDetailConfig2 == null ? void 0 : skuDetailConfig2.isShowNote) ?? true,
        externalVariant: (skuDetailConfig2 == null ? void 0 : skuDetailConfig2.externalVariant) ?? {},
        useCustomData: (skuDetailConfig2 == null ? void 0 : skuDetailConfig2.useCustomData) ?? false,
        customData: (skuDetailConfig2 == null ? void 0 : skuDetailConfig2.customData) ?? {},
        isCallProductDetail: (skuDetailConfig2 == null ? void 0 : skuDetailConfig2.isCallProductDetail) ?? false
      };
      setSkuDetailConfig(config);
      if ("date" in data && !("_extend" in data)) {
        logger == null ? void 0 : logger.addLog({
          type: "info",
          title: "sku_detail_modal_open_create",
          metadata: {}
        });
        openParamsRef.current = data;
        const open_deposit = (getData == null ? void 0 : getData("bookingv2_deposit")) || 0;
        const productDetail = await getDetailData(data, open_deposit);
        let apiData = (productDetail == null ? void 0 : productDetail.data) || {};
        if ((config == null ? void 0 : config.useCustomData) && (config == null ? void 0 : config.customData)) {
          apiData = {
            ...apiData,
            ...(config == null ? void 0 : config.customData) || {}
          };
        }
        const basePrice = Number((apiData == null ? void 0 : apiData.price) || 0);
        let variantData2 = formatVariant(
          config,
          (_a2 = data == null ? void 0 : data.productData) == null ? void 0 : _a2.variant,
          apiData
        );
        const hydratedData = {
          ...apiData,
          id: (apiData == null ? void 0 : apiData.id) || data.id,
          product_id: (apiData == null ? void 0 : apiData.product_id) || data.id,
          ...variantData2 || {},
          _extend: {
            ...(apiData == null ? void 0 : apiData._extend) || {},
            product_name: (apiData == null ? void 0 : apiData.title) || (apiData == null ? void 0 : apiData.product_name) || "",
            quantity: 1,
            price: basePrice,
            total: basePrice,
            origin_total: basePrice,
            note: "",
            skuValue: {
              product_id: (apiData == null ? void 0 : apiData.id) || data.id,
              product_variant_id: 0,
              bundle: [],
              option: []
            }
          }
        };
        const isEject = Number((apiData == null ? void 0 : apiData.is_eject) ?? data.is_eject ?? 0) === 1 || (apiData == null ? void 0 : apiData.open_sold_weight);
        if (!isEject) {
          const stockResult = (0, import_utils2.getStockValidationResult)({
            value: (_b2 = hydratedData == null ? void 0 : hydratedData._extend) == null ? void 0 : _b2.skuValue,
            data: hydratedData,
            bookingConfig: (_c2 = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _c2.config
          });
          if (stockResult.shouldBlock) {
            Toast == null ? void 0 : Toast.fail(
              import_utils.locales.getText(
                "pisell2.skuOptionsSelection.variantItemCard.soldOut"
              )
            );
            return;
          }
          if (stockResult.shouldShowAlert) {
            setProductData(hydratedData);
            pendingConfirmDataRef.current = hydratedData;
            setStockAlertDontShowAgainChecked(false);
            setStockAlertOpen(true);
            return;
          }
          onConfirm == null ? void 0 : onConfirm(hydratedData);
          modalCloseAction();
          return;
        }
        setProductData(hydratedData);
        setNote("");
        setQuantity(
          (0, import_utils4.isWeighingProduct)(apiData) ? 1 : (apiData == null ? void 0 : apiData.min_num_unit) || 1
        );
        setDiscounts([]);
        setWeighingData(null);
        setSkuValue({
          product_id: hydratedData.id,
          product_variant_id: 0,
          bundle: [],
          option: []
        });
        setSkuDefaultValue({
          product_id: hydratedData.id,
          product_variant_id: 0,
          bundle: [],
          option: [],
          price: ((_d2 = hydratedData == null ? void 0 : hydratedData._extend) == null ? void 0 : _d2.price) || 0
        });
        setPriceOverride(null);
        setShowPriceAdjustModal(false);
        const hydratedAny = hydratedData;
        const initialHasSkuOptions2 = Array.isArray(hydratedAny == null ? void 0 : hydratedAny.variant_group) && hydratedAny.variant_group.length > 0 || Array.isArray(hydratedAny == null ? void 0 : hydratedAny.option_group) && hydratedAny.option_group.length > 0 || Array.isArray(hydratedAny == null ? void 0 : hydratedAny.bundle_group) && hydratedAny.bundle_group.length > 0;
        setCurrentStep(initialHasSkuOptions2 ? 1 : 0);
        setOpen(true);
        return;
      }
      logger == null ? void 0 : logger.addLog({
        type: "info",
        title: "sku_detail_modal_open_edit",
        metadata: {}
      });
      openParamsRef.current = null;
      const _data = (0, import_lodash.cloneDeep)(data);
      const variantData = formatVariant(config, _data == null ? void 0 : _data.variant, _data);
      if (variantData) {
        _data.variant_group = (variantData == null ? void 0 : variantData.variant_group) || [];
        _data.variant = (variantData == null ? void 0 : variantData.variant) || [];
      }
      setProductData(_data);
      console.log(_data, "_data");
      setNote(((_e2 = _data == null ? void 0 : _data._extend) == null ? void 0 : _e2.note) || "");
      setQuantity(
        (0, import_utils4.isWeighingProduct)(_data) ? 1 : ((_f2 = _data == null ? void 0 : _data._extend) == null ? void 0 : _f2.quantity) || 1
      );
      setDiscounts((_data == null ? void 0 : _data.discount_list) || []);
      setWeighingData(((_g2 = _data == null ? void 0 : _data._extend) == null ? void 0 : _g2.weighing) || null);
      const recordSkuValue = ((_h2 = _data == null ? void 0 : _data._extend) == null ? void 0 : _h2._skuValue) || ((_i2 = _data == null ? void 0 : _data._extend) == null ? void 0 : _i2.other) || {
        product_id: _data == null ? void 0 : _data.product_id,
        product_variant_id: 0,
        bundle: [],
        option: []
      };
      console.log(recordSkuValue, "skuValue");
      setSkuValue(recordSkuValue);
      setSkuDefaultValue(recordSkuValue);
      setPriceOverride(((_j2 = _data == null ? void 0 : _data._extend) == null ? void 0 : _j2.priceOverride) ?? null);
      setShowPriceAdjustModal(false);
      const dataAny = _data;
      const initialHasSkuOptions = Array.isArray(dataAny == null ? void 0 : dataAny.variant_group) && dataAny.variant_group.length > 0 || Array.isArray(dataAny == null ? void 0 : dataAny.option_group) && dataAny.option_group.length > 0 || Array.isArray(dataAny == null ? void 0 : dataAny.bundle_group) && dataAny.bundle_group.length > 0;
      setCurrentStep(initialHasSkuOptions ? 1 : 0);
      setTimeout(() => {
        logger == null ? void 0 : logger.addLog({
          type: "info",
          title: "sku_detail_modal_open_edit_show",
          metadata: {}
        });
        setOpen(true);
      }, 0);
    }
  }));
  const priceText = (0, import_react.useMemo)(() => {
    var _a2;
    const price = ((_a2 = productData == null ? void 0 : productData._extend) == null ? void 0 : _a2.price) || 0;
    const priceSign = Number(price) < 0 ? "-" : "";
    return `${priceSign}${symbol}${Math.abs(Number(price))}`;
  }, [(_j = productData == null ? void 0 : productData._extend) == null ? void 0 : _j.price, symbol]);
  const activeSkuValue = (0, import_react.useMemo)(() => {
    return (skuValue == null ? void 0 : skuValue.product_id) ? skuValue : skuDefaultValue;
  }, [skuDefaultValue, skuValue]);
  const { isWeighingProduct, scalePriceProduct } = (0, import_useWeighing.useWeighing)({
    productData,
    skuValue: activeSkuValue
  });
  const unitPrice = (0, import_react.useMemo)(() => {
    if (isWeighingProduct) {
      return (0, import_utils4.getWeighedUnitPrice)({
        weighedTotalAmount: (weighingData == null ? void 0 : weighingData.total_amount) || 0,
        productData,
        skuValue: activeSkuValue
      });
    }
    return getSelectedUnitPrice({ productData, skuValue: activeSkuValue });
  }, [
    activeSkuValue,
    isWeighingProduct,
    productData,
    weighingData == null ? void 0 : weighingData.total_amount
  ]);
  const displayUnitPrice = (0, import_react.useMemo)(() => {
    if (priceOverride === null || typeof priceOverride === "undefined")
      return unitPrice;
    return priceOverride;
  }, [priceOverride, unitPrice]);
  const showQuantityStepper = Boolean(
    (skuDetailConfig == null ? void 0 : skuDetailConfig.isShowStepper) && !isWeighingProduct
  );
  const subtotal = (0, import_react.useMemo)(() => {
    return new import_decimal.default(unitPrice || 0);
  }, [unitPrice]);
  const subtotalText = (0, import_react.useMemo)(() => {
    const priceSign = subtotal.toNumber() < 0 ? "-" : "";
    return `${priceSign}${symbol}${subtotal.abs().toNumber().toFixed(2)}`;
  }, [subtotal, symbol]);
  const discountsCount = (0, import_react.useMemo)(() => {
    return (discounts == null ? void 0 : discounts.length) || 0;
  }, [discounts]);
  const totalDiscounts = (0, import_react.useMemo)(() => {
    if ((discounts == null ? void 0 : discounts.length) > 0) {
      return discounts.reduce((sum, discount) => {
        const includeType = ["discount_card", "product_discount_card"];
        const _quantity = includeType.includes((discount == null ? void 0 : discount.type) || "") ? quantity : 1;
        return sum.plus(new import_decimal.default((discount == null ? void 0 : discount.amount) || 0).mul(_quantity));
      }, new import_decimal.default(0)).toNumber().toFixed(2);
    }
    return "0.00";
  }, [discounts, quantity]);
  const finalTotal = (0, import_react.useMemo)(() => {
    const deTotal = new import_decimal.default(displayUnitPrice || "0");
    const deQuantity = new import_decimal.default(quantity || "1");
    return deTotal.mul(deQuantity).minus(new import_decimal.default(totalDiscounts || 0));
  }, [displayUnitPrice, quantity, totalDiscounts]);
  const totalText = (0, import_react.useMemo)(() => {
    const priceSign = finalTotal.toNumber() < 0 ? "-" : "";
    return `${priceSign}${symbol}${finalTotal.abs().toNumber().toFixed(2)}`;
  }, [finalTotal, symbol]);
  const priceOverrideText = (0, import_react.useMemo)(() => {
    if (priceOverride === null || typeof priceOverride === "undefined")
      return "";
    const prefix = `(${import_utils.locales.getText(
      "pisell2.text.sku.detail.modal.price.override"
    )} `;
    const overrideNumber = new import_decimal.default(priceOverride || 0);
    const sign = overrideNumber.toNumber() < 0 ? "-" : "";
    const absValue = overrideNumber.abs().toNumber().toFixed(2);
    return `${prefix}${sign}${symbol}${absValue})`;
  }, [priceOverride, symbol]);
  const priceChangeText = (0, import_react.useMemo)(() => {
    if (priceOverride === null || typeof priceOverride === "undefined")
      return "";
    const diff = new import_decimal.default(priceOverride || 0).minus(new import_decimal.default(unitPrice || 0)).mul(new import_decimal.default(quantity || 1));
    const diffNumber = diff.toNumber();
    const diffSign = diffNumber > 0 ? "+" : diffNumber < 0 ? "-" : "";
    const absDiff = diff.abs().toNumber().toFixed(2);
    return `${diffSign}${symbol}${absDiff}`;
  }, [priceOverride, unitPrice, quantity, symbol]);
  const selectedSpecificationItems = (0, import_react.useMemo)(() => {
    return (0, import_utils2.formatSelectedSkuItems)(activeSkuValue, symbol);
  }, [activeSkuValue, symbol]);
  const selectedSpecificationText = (0, import_react.useMemo)(() => {
    return (0, import_utils2.formatSelectedSkuMessage)(activeSkuValue, symbol);
  }, [activeSkuValue, symbol]);
  const pcConfirmButtonText = (0, import_react.useMemo)(() => {
    if (currentStep === 0 && hasSkuOptions) {
      return import_utils.locales.getText("pisell2.text.sku.detail.modal.btn.next");
    }
    return import_utils.locales.getText("pisell2.text.sku.detail.modal.btn.confirm");
  }, [currentStep, hasSkuOptions]);
  const modalCloseAction = () => {
    setOpen(false);
    setProductData(null);
    setNote("");
    setQuantity(1);
    setNoteModalOpen(false);
    setPriceOverride(null);
    setShowPriceAdjustModal(false);
    setDiscounts([]);
    setWeighingData(null);
    openParamsRef.current = null;
    setCurrentStep(0);
  };
  const handleCancel = () => {
    modalCloseAction();
    onClose == null ? void 0 : onClose();
  };
  const handleConfirm = async () => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2;
    if (!isMobile && currentStep === 0 && hasSkuOptions) {
      (_b2 = (_a2 = procedureRef.current) == null ? void 0 : _a2.goToStep) == null ? void 0 : _b2.call(_a2, 1);
      setCurrentStep(1);
      return;
    }
    const requiredOptionValidation = (_e2 = (_d2 = (_c2 = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _c2.config) == null ? void 0 : _d2.product_setting_tab) == null ? void 0 : _e2.required_option_validation;
    const shouldValidate = Number(requiredOptionValidation ?? 1) !== 0;
    if (shouldValidate && hasSkuOptions) {
      try {
        const isValid = await ((_g2 = (_f2 = skuOptionsSelectionRef.current) == null ? void 0 : _f2.validate) == null ? void 0 : _g2.call(_f2));
        if (!isValid) return;
      } catch (error) {
        console.log("sku_detail_modal_validate_error>>>>>", error);
        return;
      }
    }
    if (productData && onConfirm) {
      const latestSkuValue = ((_i2 = (_h2 = skuOptionsSelectionRef.current) == null ? void 0 : _h2.getTransformValues) == null ? void 0 : _i2.call(_h2)) || skuValue || skuDefaultValue;
      const originTotal = new import_decimal.default(unitPrice ?? 0).toNumber();
      const weighing = isWeighingProduct && weighingData ? weighingData : void 0;
      const updatedData = {
        ...productData,
        discount_list: discounts || [],
        _extend: {
          ...(productData == null ? void 0 : productData._extend) || {},
          quantity,
          note,
          // 上层 getProductTotalPrice 依赖 other 来计算（组合规格/套餐/单规格）
          other: getOtherFromSkuValue({
            productData,
            skuValue: latestSkuValue
          }),
          skuValue: getOtherFromSkuValue({
            productData,
            skuValue: latestSkuValue
          }),
          origin_total: originTotal,
          weighing,
          ...priceOverride !== null && typeof priceOverride !== "undefined" ? { priceOverride } : {}
        }
      };
      console.log(
        "updatedData>>>>>>",
        updatedData,
        (_j2 = updatedData == null ? void 0 : updatedData._extend) == null ? void 0 : _j2.origin_total
      );
      const stockResult = (0, import_utils2.getStockValidationResult)({
        value: latestSkuValue,
        data: productData,
        bookingConfig: (_k2 = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _k2.config
      });
      if (stockResult.shouldBlock) {
        Toast == null ? void 0 : Toast.fail(
          import_utils.locales.getText("pisell2.skuOptionsSelection.variantItemCard.soldOut")
        );
        return;
      }
      if (stockResult.shouldShowAlert) {
        pendingConfirmDataRef.current = updatedData;
        setStockAlertDontShowAgainChecked(false);
        setStockAlertOpen(true);
        return;
      }
      onConfirm(updatedData);
      modalCloseAction();
    }
  };
  const handleStockAlertCancel = () => {
    pendingConfirmDataRef.current = null;
    setStockAlertOpen(false);
    setStockAlertDontShowAgainChecked(false);
  };
  const handleStockAlertContinue = () => {
    var _a2, _b2, _c2;
    const pendingData = pendingConfirmDataRef.current;
    if (!pendingData) {
      setStockAlertOpen(false);
      return;
    }
    const enableDontShowAgainToday = Number(
      ((_c2 = (_b2 = (_a2 = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.stock_setting) == null ? void 0 : _c2.do_not_show_again_today) ?? 0
    );
    if (enableDontShowAgainToday === 1 && stockAlertDontShowAgainChecked) {
      const productId = Number((productData == null ? void 0 : productData.product_id) || 0);
      (0, import_utils2.setHiddenStockAlertForToday)({ productId });
    }
    onConfirm == null ? void 0 : onConfirm(pendingData);
    pendingConfirmDataRef.current = null;
    setStockAlertOpen(false);
    modalCloseAction();
  };
  const handleRemove = () => {
    if (productData && onRemove) {
      onRemove(productData);
      modalCloseAction();
    }
  };
  const handleQuantityChange = (value) => {
    if (isWeighingProduct) {
      return;
    }
    if (value && value > 0) {
      setQuantity(value);
    }
  };
  (0, import_react.useEffect)(() => {
    if (isWeighingProduct && quantity !== 1) {
      setQuantity(1);
    }
  }, [isWeighingProduct, quantity]);
  (0, import_react.useEffect)(() => {
    if (!open) return;
    if (isMobile) return;
    if (!isWeighingProduct) return;
    if (!productData) return;
    let raf1 = 0;
    let raf2 = 0;
    raf1 = requestAnimationFrame(() => {
      raf2 = requestAnimationFrame(() => {
        const el = leftTopRef.current;
        if (!el) return;
        el.scrollTop = el.scrollHeight;
      });
    });
    return () => {
      cancelAnimationFrame(raf1);
      cancelAnimationFrame(raf2);
    };
  }, [open, isMobile, isWeighingProduct, productData == null ? void 0 : productData._id, productData == null ? void 0 : productData.id]);
  const onNoteConfirm = (note2) => {
    setNote(note2);
    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 = (0, import_react.useMemo)(() => {
    var _a2;
    const title = ((_a2 = productData == null ? void 0 : productData.title) == null ? void 0 : _a2.trim()) || "";
    if (!title) return "";
    return Array.from(title).slice(0, 2).join("");
  }, [productData == null ? void 0 : productData.title]);
  const isCreateMode = !!openParamsRef.current;
  const _containerClass = variant === "phone" ? ".pisell-sku-detail-drawer" : ".pisell-sku-detail-modal";
  const skuScrollParentSelector = `${_containerClass} .sku-detail-right-content`;
  const productDescription = (productData == null ? void 0 : productData.description) || "";
  const renderWeighingSection = () => {
    if (!isWeighingProduct) {
      return null;
    }
    return /* @__PURE__ */ import_react.default.createElement(
      import_weighing.default,
      {
        key: String((productData == null ? void 0 : productData._id) || (productData == null ? void 0 : productData.id) || "weighing"),
        scalePriceProduct,
        currencySymbol: symbol,
        initialValue: weighingData ?? void 0,
        onChange: setWeighingData
      }
    );
  };
  const leftContent = () => {
    return (
      /* 左侧商品图片和操作 */
      /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-left" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-left-top", ref: leftTopRef }, /* @__PURE__ */ import_react.default.createElement("div", { className: "product-image" }, (productData == null ? void 0 : productData.cover) ? /* @__PURE__ */ import_react.default.createElement("img", { src: (productData == null ? void 0 : productData.cover) || "" }) : /* @__PURE__ */ import_react.default.createElement("div", { className: "product-cover-text" }, coverText)), /* @__PURE__ */ import_react.default.createElement("div", { className: "product-info" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "product-info-left" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "product-name" }, (productData == null ? void 0 : productData.title) || ""))), renderWeighingSection(), selectedSpecificationText && /* @__PURE__ */ import_react.default.createElement("div", { className: "selected-specification-section" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "selected-specification-list" }, selectedSpecificationItems.map((item) => {
        if (item.type === "bundle") {
          return /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              key: item.key,
              className: "selected-specification-group selected-specification-group-bundle"
            },
            /* @__PURE__ */ import_react.default.createElement("div", { className: "selected-specification-item selected-specification-item-bundle" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "selected-specification-item-main" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "selected-specification-item-label" }, item.label), item.meta ? /* @__PURE__ */ import_react.default.createElement("span", { className: "selected-specification-item-meta" }, item.meta) : null)),
            item.children && item.children.length > 0 ? /* @__PURE__ */ import_react.default.createElement("div", { className: "selected-specification-group-children" }, item.children.map((child) => /* @__PURE__ */ import_react.default.createElement(
              "div",
              {
                key: child.key,
                className: "selected-specification-item selected-specification-item-bundleOption"
              },
              /* @__PURE__ */ import_react.default.createElement("div", { className: "selected-specification-item-main" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "selected-specification-item-label" }, child.label), child.meta ? /* @__PURE__ */ import_react.default.createElement("span", { className: "selected-specification-item-meta" }, child.meta) : null)
            ))) : null
          );
        }
        return /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            key: item.key,
            className: `selected-specification-item selected-specification-item-${item.type}`
          },
          /* @__PURE__ */ import_react.default.createElement("div", { className: "selected-specification-item-main" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "selected-specification-item-label" }, item.label), item.meta ? /* @__PURE__ */ import_react.default.createElement("span", { className: "selected-specification-item-meta" }, item.meta) : null)
        );
      })))), /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-left-bottom" }, (note || showQuantityStepper) && /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-side-meta" }, showQuantityStepper && /* @__PURE__ */ import_react.default.createElement("div", { className: "quantity-section quantity-section-right" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "quantity-section-title" }, import_utils.locales.getText("pisell2.text.sku.detail.modal.quantity")), /* @__PURE__ */ import_react.default.createElement(
        import_NumericStepper.default,
        {
          variant: "capsule",
          value: quantity,
          onChange: handleQuantityChange,
          min: 1,
          max: 99999
        }
      )), note && /* @__PURE__ */ import_react.default.createElement("div", { className: "note-section note-section-right" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "note-label" }, import_utils.locales.getText("pisell2.text.sku.detail.modal.note")), /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: "note-text",
          onClick: () => setNoteModalOpen(true)
        },
        note
      ))), /* @__PURE__ */ import_react.default.createElement("div", { className: "price-summary-section" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "price-item" }, /* @__PURE__ */ import_react.default.createElement("div", null, import_utils.locales.getText("pisell2.text.sku.detail.modal.subtotal")), /* @__PURE__ */ import_react.default.createElement("div", null, subtotalText)), /* @__PURE__ */ import_react.default.createElement("div", { className: "price-item" }, /* @__PURE__ */ import_react.default.createElement("div", null, import_utils.locales.getText("pisell2.text.sku.detail.modal.discount"), discountsCount > 0 && /* @__PURE__ */ import_react.default.createElement("span", { className: "price-item-danger" }, " (", discountsCount, ")")), /* @__PURE__ */ import_react.default.createElement("div", { className: "price-item-danger" }, discountsCount > 0 ? "-" : "", symbol, totalDiscounts)), priceOverride !== null && typeof priceOverride !== "undefined" && /* @__PURE__ */ import_react.default.createElement("div", { className: "price-item" }, /* @__PURE__ */ import_react.default.createElement("div", { onClick: handleManualPriceChange }, import_utils.locales.getText(
        "pisell2.text.sku.detail.modal.manual.price.change"
      ), /* @__PURE__ */ import_react.default.createElement("span", { className: "price-item-override" }, priceOverrideText)), /* @__PURE__ */ import_react.default.createElement("div", { className: "price-item-danger" }, priceChangeText)), /* @__PURE__ */ import_react.default.createElement("div", { className: "price-item-total" }, /* @__PURE__ */ import_react.default.createElement("div", null, import_utils.locales.getText("pisell2.text.sku.detail.modal.total"), /* @__PURE__ */ import_react.default.createElement("span", { className: "price-item-total-gst" }, "（", (productData == null ? void 0 : productData.is_charge_tax) ? import_utils.locales.getText("pisell2.text.sku.detail.modal.gst.incl") : import_utils.locales.getText("pisell2.text.sku.detail.modal.gst.excl"), "）")), /* @__PURE__ */ import_react.default.createElement("div", null, totalText))), /* @__PURE__ */ import_react.default.createElement(
        PcActionButtons,
        {
          isCreateMode,
          isShowNote: !!(skuDetailConfig == null ? void 0 : skuDetailConfig.isShowNote),
          confirmLabel: pcConfirmButtonText,
          onCancel: handleCancel,
          onRemove: handleRemove,
          onManualPriceChange: handleManualPriceChange,
          onOpenNote: () => setNoteModalOpen(true),
          onConfirm: handleConfirm
        }
      )))
    );
  };
  if (!productData) return null;
  const rightContent = () => {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-right-content" }, !isMobile && currentStep === 0 && /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-right-content-detail" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-right-content-detail-description" }, (productData == null ? void 0 : productData.subtitle) ? /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-right-content-detail-subtitle" }, productData.subtitle) : null, productDescription ? /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "sku-detail-right-content-detail-description-html",
        dangerouslySetInnerHTML: {
          __html: productDescription
        }
      }
    ) : null, productDescription === "" && !hasSkuOptions && /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-right-content-detail-placeholder" }, /* @__PURE__ */ import_react.default.createElement(
      "img",
      {
        width: 300,
        height: 300,
        src: "https://static.pisellcdn.com/sku_empty.png",
        alt: "placeholder"
      }
    ), /* @__PURE__ */ import_react.default.createElement("p", null, import_utils.locales.getText(
      "pisell2.text.sku.detail.modal.no.additional.options"
    ))))), (isMobile || currentStep === 1) && hasSkuOptions && /* @__PURE__ */ import_react.default.createElement(
      import_skuOptionsSelection.default,
      {
        ref: skuOptionsSelectionRef,
        dataSource: productData,
        value: skuDefaultValue,
        skuCardConfig: {
          title: {
            lineClamp: 1
          },
          subTitle: {
            lineClamp: 1
          }
        },
        customConfig: {
          modalWidth: isMobile ? "100%" : "680px",
          selectorLayout: {
            type: "antdGrid",
            columns: isMobile ? 1 : 2,
            gutter: isMobile ? [12, 12] : [16, 16]
          }
        },
        config: {
          overSold: stockValidation === 0 || allowAddToCartWhenOutStock === 1 ? 1 : 0
        },
        onChange: (v) => {
          console.log("SKUOptionsSelectionOnChange", v);
          setSkuValue(v);
        },
        customScrollParent: skuScrollParentSelector
      }
    ));
  };
  const leftHeaderClose = () => {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-left-close", onClick: handleCancel }, /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-x-close" }), import_utils.locales.getText("pisell2.text.sku.detail.modal.btn.close"));
  };
  const leftHeaderBack = () => {
    if (currentStep === 0) {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "sku-detail-left-back-placeholder" });
    }
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "sku-detail-left-back",
        onClick: () => {
          var _a2, _b2;
          (_b2 = (_a2 = procedureRef.current) == null ? void 0 : _a2.goToStep) == null ? void 0 : _b2.call(_a2, 0);
          setCurrentStep(0);
        }
      },
      /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-arrow-left" }),
      import_utils.locales.getText("pisell2.text.sku.detail.modal.btn.back")
    );
  };
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_compensatedPisellContainer.default,
    {
      platform: "pc",
      renderType: variant === "phone" ? "drawer" : "modal",
      props: {
        open,
        onCancel: handleCancel,
        header: null,
        headerDivider: false,
        footer: null,
        closable: false,
        destroyOnClose: true,
        style: {
          maxHeight: variant === "phone" ? "95dvh" : void 0
        },
        height: variant === "phone" && hasSkuOptions ? "95%" : void 0,
        width: variant === "phone" ? "100%" : "80%",
        className: (0, import_classnames.default)({
          "pisell-sku-detail-modal": variant !== "phone",
          "pisell-sku-detail-drawer": variant === "phone",
          "aside-full": isWeighingProduct && !hasSkuOptions
        }),
        placement: variant === "phone" ? "bottom" : void 0
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      PisellProcedureComponent,
      {
        ref: procedureRef,
        className: "pisell-sku-procedure",
        mode: "modal",
        defaultCurrent: currentStep,
        layoutMode: "ratio",
        onStepsChange: (result) => {
          const nextStep = Math.min(
            Number(result.currentStep || 0),
            maxStepIndex
          );
          setCurrentStep(nextStep);
        },
        headerProps: {
          showBackOnFirstStep: true,
          showSteps: procedureSteps.length > 1,
          left: leftHeaderBack(),
          right: leftHeaderClose(),
          stepsProps: {
            items: procedureSteps
          }
        },
        onFirstStepBack: () => {
          handleCancel();
        },
        showSideBar: true,
        showFooter: false,
        bodyProps: {
          direction: variant === "phone" ? "vertical" : "horizontal",
          contentOrder: "content-first",
          contentSlot: rightContent(),
          sidebarSlot: leftContent(),
          sidebarContainerSelector: _containerClass
        }
      }
    ),
    noteModalOpen && /* @__PURE__ */ import_react.default.createElement(
      import_noteModal.default,
      {
        open: noteModalOpen,
        value: note,
        onCancel: onNoteCancel,
        onConfirm: onNoteConfirm,
        onDelete: onNoteDelete
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(
      import_priceKeyboard.DiscountKeyboard,
      {
        containerProps: {
          renderType: "modal",
          open: showPriceAdjustModal,
          onCancel: () => setShowPriceAdjustModal(false)
        },
        enableExceedMaxAmount: true,
        originalValue: subtotal.toNumber() || 0,
        defaultValue: displayUnitPrice || 0,
        onEnter: (discountAmount) => {
          const nextUnitPrice = subtotal.minus(Number(discountAmount) || 0).toNumber();
          handlePriceAdjustConfirm(nextUnitPrice);
        },
        selectType: "dark"
      }
    )
  ), /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      platform: "pc",
      open: stockAlertOpen,
      title: import_utils.locales.getText(
        "pisell2.text.sku.detail.modal.stock.alert.title"
      ),
      headerDivider: false,
      footer: /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            width: "100%",
            display: "flex",
            justifyContent: "flex-end",
            gap: 12
          }
        },
        /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { size: "large", onClick: handleStockAlertCancel }, import_utils.locales.getText(
          "pisell2.text.sku.detail.modal.stock.alert.btn.cancel"
        )),
        /* @__PURE__ */ import_react.default.createElement(
          import_materials.Button,
          {
            type: "primary",
            size: "large",
            onClick: handleStockAlertContinue
          },
          import_utils.locales.getText(
            "pisell2.text.sku.detail.modal.stock.alert.btn.continue"
          )
        )
      ),
      width: 520,
      centered: true,
      destroyOnClose: true,
      maskClosable: false,
      zIndex: 2e3,
      onCancel: handleStockAlertCancel
    },
    /* @__PURE__ */ import_react.default.createElement("div", { style: { padding: "40px 0 0 0" } }, /* @__PURE__ */ import_react.default.createElement("div", { style: { color: "#344054", fontSize: 14, lineHeight: "22px" } }, import_utils.locales.getText("pisell2.text.sku.detail.modal.stock.alert.desc")), Number(
      ((_m = (_l = (_k = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _k.config) == null ? void 0 : _l.stock_setting) == null ? void 0 : _m.do_not_show_again_today) ?? 0
    ) === 1 && /* @__PURE__ */ import_react.default.createElement("div", { style: { marginTop: 16 } }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.Checkbox,
      {
        checked: stockAlertDontShowAgainChecked,
        onChange: (e) => {
          var _a2;
          setStockAlertDontShowAgainChecked(!!((_a2 = e == null ? void 0 : e.target) == null ? void 0 : _a2.checked));
        }
      },
      import_utils.locales.getText(
        "pisell2.text.sku.detail.modal.stock.alert.checkbox"
      )
    )))
  ));
};
var ForwardedSkuDetailModal = (0, import_react.forwardRef)(SkuDetailModal);
ForwardedSkuDetailModal.displayName = `SkuDetailModal`;
var skuDetailModal_default = (0, import_responsive.withResponsive)(ForwardedSkuDetailModal);
function getSelectedUnitPrice(params) {
  var _a, _b;
  const { productData, skuValue } = params;
  if (!productData) return 0;
  let price = new import_decimal.default(
    (productData == null ? void 0 : productData.base_price) ?? ((_a = productData == null ? void 0 : productData._extend) == null ? void 0 : _a.price) ?? 0
  );
  if (skuValue == null ? void 0 : skuValue.product_variant_id) {
    const variantItem = (_b = productData == null ? void 0 : productData.variant) == null ? void 0 : _b.find(
      (item) => Number(item == null ? void 0 : item.id) === Number(skuValue.product_variant_id)
    );
    if (variantItem) {
      price = new import_decimal.default(
        (variantItem == null ? void 0 : variantItem.base_price) ?? (variantItem == null ? void 0 : variantItem.original_price) ?? 0
      );
    }
  }
  if (Array.isArray(skuValue == null ? void 0 : skuValue.bundle) && skuValue.bundle.length > 0) {
    price = skuValue.bundle.reduce(
      (accumulator, currentValue) => {
        const currentPrice = new import_decimal.default(
          (currentValue == null ? void 0 : currentValue.original_price) ?? (currentValue == null ? void 0 : currentValue.price) ?? 0
        );
        const currentNum = new import_decimal.default((currentValue == null ? void 0 : currentValue.num) || 0);
        return accumulator.add(currentPrice.mul(currentNum));
      },
      price
    );
  }
  if (Array.isArray(skuValue == null ? void 0 : skuValue.option) && skuValue.option.length > 0) {
    price = skuValue.option.reduce(
      (accumulator, currentValue) => {
        const currentPrice = new import_decimal.default(
          (currentValue == null ? void 0 : currentValue.original_price) ?? (currentValue == null ? void 0 : currentValue.price) ?? 0
        );
        const currentNum = new import_decimal.default((currentValue == null ? void 0 : currentValue.num) || 0);
        return accumulator.add(currentPrice.mul(currentNum));
      },
      price
    );
  }
  return price.toNumber();
}
function getOtherFromSkuValue(params) {
  var _a;
  const { productData, skuValue } = params;
  const other = {
    ...skuValue || {},
    product_variant_id: (skuValue == null ? void 0 : skuValue.product_variant_id) || 0,
    bundle: (skuValue == null ? void 0 : skuValue.bundle) || [],
    option: (skuValue == null ? void 0 : skuValue.option) || []
  };
  if (other.product_variant_id && productData) {
    const variantItem = (_a = productData == null ? void 0 : productData.variant) == null ? void 0 : _a.find(
      (item) => Number(item == null ? void 0 : item.id) === Number(other.product_variant_id)
    );
    if (variantItem) {
      other.price = Number((variantItem == null ? void 0 : variantItem.price) ?? (variantItem == null ? void 0 : variantItem.base_price) ?? 0);
    }
  }
  return other;
}
