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/plus/salesSdk/context/SalesSdkCartContext.tsx
var SalesSdkCartContext_exports = {};
__export(SalesSdkCartContext_exports, {
  SalesSdkCartContext: () => SalesSdkCartContext,
  SalesSdkCartProvider: () => SalesSdkCartProvider
});
module.exports = __toCommonJS(SalesSdkCartContext_exports);
var import_react = __toESM(require("react"));
var import_ahooks = require("ahooks");
var import_materials = require("@pisell/materials");
var import_SalesSdkContext = require("./SalesSdkContext");
var import_SalesSdkProvider = require("./SalesSdkProvider");
var import_SalesSdkSummaryContext = require("./SalesSdkSummaryContext");
var import_SalesSdkUIHostsContext = require("./SalesSdkUIHostsContext");
var import_SalesSdkHostBridgesContext = require("./SalesSdkHostBridgesContext");
var import_resolveCacheItemForResourceCheck = require("../bookingEditService/resolveCacheItemForResourceCheck");
var import_buildBookingEditDrawerState = require("../bookingEditService/buildBookingEditDrawerState");
var import_runAddProductFlow = require("../utils/runAddProductFlow");
var import_addProductWithFlowDebounced = require("../utils/addProductWithFlowDebounced");
var import_applyExplicitAddQuantityToCacheItem = require("../utils/applyExplicitAddQuantityToCacheItem");
var import_resolveConfirmDetailQuantity = require("../utils/resolveConfirmDetailQuantity");
var import_enrichCacheItemBeforeAdd = require("../utils/enrichCacheItemBeforeAdd");
var import_patchCacheItemDateRange = require("../utils/patchCacheItemDateRange");
var import_mergeCatalogDurationIntoCacheItem = require("../utils/mergeCatalogDurationIntoCacheItem");
var import_bookingDate = require("../utils/bookingDate");
var import_utils = require("@pisell/utils");
var import_locales = __toESM(require("../../../components/ticketBooking/locales"));
var import_editCartLine = require("../utils/editCartLine");
var import_editCartLineBooking = require("../utils/editCartLineBooking");
var import_editCartLineProduct = require("../utils/editCartLineProduct");
var import_buildCustomOrderProductFromCustomiseItem = require("../utils/buildCustomOrderProductFromCustomiseItem");
var import_enrich = require("../utils/enrich");
var import_identity = require("../utils/identity");
var import_productSkuOptions = require("../utils/productSkuOptions");
var import_mergeBookingsForDisplay = require("../utils/mergeBookingsForDisplay");
var import_createOpenGiftSelectHost = require("../giftSelect/createOpenGiftSelectHost");
var import_enrichCartLineHolderDisplay = require("../utils/enrichCartLineHolderDisplay");
var import_enrichCartBookingResourceDisplay = require("../utils/enrichCartBookingResourceDisplay");
var import_SalesSdkHolderContext = require("./SalesSdkHolderContext");
var import_ensureHoldersBeforeSubmit = require("../utils/ensureHoldersBeforeSubmit");
var import_createHolderConfirmBridge = require("../holderConfirm/createHolderConfirmBridge");
var import_discountCard = require("../utils/discountCard");
var SalesSdkCartContext = (0, import_react.createContext)(null);
SalesSdkCartContext.displayName = "SalesSdkCartContext";
var EMPTY_DISCOUNT_LIST = [];
var EMPTY_ITEMS = [];
var EMPTY_BOOKINGS = [];
var EMPTY_SNAPSHOT = {
  tempOrder: null,
  salesDetail: null,
  bookings: EMPTY_BOOKINGS,
  items: EMPTY_ITEMS,
  discountList: EMPTY_DISCOUNT_LIST
};
function cloneArray(value, fallback) {
  return Array.isArray(value) ? [...value] : fallback;
}
function cloneTempOrder(tempOrder) {
  if (!tempOrder) return null;
  return {
    ...tempOrder,
    products: cloneArray(tempOrder.products, []),
    bookings: cloneArray(tempOrder.bookings, []),
    payments: cloneArray(tempOrder.payments, []),
    surcharges: cloneArray(tempOrder.surcharges, []),
    discount_list: cloneArray(tempOrder.discount_list, []),
    relation_forms: cloneArray(tempOrder.relation_forms, []),
    contacts: cloneArray(tempOrder.contacts, []),
    contacts_info: tempOrder.contacts_info,
    summary: tempOrder.summary ? { ...tempOrder.summary } : tempOrder.summary
  };
}
function indexBookingsByProductUid(bookings) {
  if (!Array.isArray(bookings) || bookings.length === 0) return {};
  return bookings.reduce((acc, booking) => {
    const uid = booking == null ? void 0 : booking.product_uid;
    if (uid === void 0 || uid === null || uid === "") return acc;
    const key = String(uid);
    if (!acc[key]) acc[key] = [];
    acc[key].push(booking);
    return acc;
  }, {});
}
function readSnapshot(bookingTicket, holderOptions = []) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
  if (!bookingTicket) return EMPTY_SNAPSHOT;
  try {
    const tempOrder = cloneTempOrder(((_a = bookingTicket.getTempOrder) == null ? void 0 : _a.call(bookingTicket)) ?? null);
    const salesDetail = ((_b = bookingTicket.getSalesOrder) == null ? void 0 : _b.call(bookingTicket)) ?? null;
    const catalog = ((_d = (_c = bookingTicket.getProductCatalog) == null ? void 0 : _c.call(bookingTicket)) == null ? void 0 : _d.products) ?? [];
    const rawBookings = (salesDetail == null ? void 0 : salesDetail.bookings) ?? (tempOrder == null ? void 0 : tempOrder.bookings) ?? [];
    const bookingDetailMap = indexBookingsByProductUid(rawBookings);
    const productsByUid = (_e = tempOrder == null ? void 0 : tempOrder._extend) == null ? void 0 : _e.productsByUid;
    const enrichCtx = {
      bookingDetailMap,
      productsCatalog: catalog,
      productsByUid
    };
    const holderDisplayConfig = (0, import_enrichCartLineHolderDisplay.resolveHolderDisplayConfig)(
      ((_f = bookingTicket.getBookingConfig) == null ? void 0 : _f.call(bookingTicket)) ?? null
    );
    const resourcesOriginMap = ((_g = bookingTicket.getResourcesOriginMap) == null ? void 0 : _g.call(bookingTicket)) ?? {};
    const allRawProducts = (tempOrder == null ? void 0 : tempOrder.products) ?? [];
    const allEnrichedProducts = (0, import_enrich.attachGiftDataToCartItems)(
      allRawProducts.map((line) => (0, import_enrich.enrichCartItem)(line, enrichCtx))
    );
    const enrichedByUid = allEnrichedProducts.reduce(
      (acc, line) => {
        var _a2;
        const uid = (_a2 = line.metadata) == null ? void 0 : _a2.unique_identification_number;
        if (uid !== void 0 && uid !== null && uid !== "") {
          acc[String(uid)] = line;
        }
        return acc;
      },
      {}
    );
    const resolveEnrichedLine = (line) => {
      var _a2;
      const uid = (_a2 = line.metadata) == null ? void 0 : _a2.unique_identification_number;
      if (uid !== void 0 && uid !== null && enrichedByUid[String(uid)]) {
        return enrichedByUid[String(uid)];
      }
      const enriched = (0, import_enrich.enrichCartItem)(line, enrichCtx);
      const merged = (0, import_enrich.attachGiftDataToCartItems)([...allEnrichedProducts, enriched]);
      return merged.find(
        (item) => {
          var _a3;
          return String((_a3 = item.metadata) == null ? void 0 : _a3.unique_identification_number) === String(uid);
        }
      ) || enriched;
    };
    const cartView = ((_h = bookingTicket.getCart) == null ? void 0 : _h.call(bookingTicket)) ?? { bookings: [], items: (tempOrder == null ? void 0 : tempOrder.products) ?? [] };
    const items = cartView.items.map((line) => resolveEnrichedLine(line));
    const bookings = cartView.bookings.map((booking) => {
      var _a2;
      const product = ((_a2 = booking._extend) == null ? void 0 : _a2.product) ? resolveEnrichedLine(booking._extend.product) : null;
      return (0, import_enrichCartBookingResourceDisplay.enrichCartBookingResourceDisplay)(
        (0, import_enrichCartLineHolderDisplay.enrichCartBookingHolderDisplay)(
          {
            ...booking,
            ...(product == null ? void 0 : product.giftData) ? { giftData: product.giftData } : {},
            _extend: {
              product
            }
          },
          {
            holderOptions,
            displayConfig: holderDisplayConfig
          }
        ),
        resourcesOriginMap
      );
    });
    const shouldMergeBookingsForDisplay = !salesDetail && !(tempOrder == null ? void 0 : tempOrder.order_id);
    const displayBookings = shouldMergeBookingsForDisplay ? (0, import_mergeBookingsForDisplay.mergeBookingsForDisplay)(bookings) : bookings;
    return {
      tempOrder,
      salesDetail,
      bookings: displayBookings,
      items,
      discountList: cloneArray((_i = bookingTicket.getDiscountList) == null ? void 0 : _i.call(bookingTicket), EMPTY_DISCOUNT_LIST)
    };
  } catch (e) {
    console.warn("[SalesSdk] CartProvider readSnapshot 失败", e);
    return EMPTY_SNAPSHOT;
  }
}
function toPriceString(value) {
  const parsed = Number(value);
  return (Number.isFinite(parsed) ? parsed : 0).toFixed(2);
}
function resolveLineSourcePrice(line) {
  const optionSum = (0, import_productSkuOptions.sumLineOptionUnitPrice)(line);
  const metadata = line.metadata || {};
  if (metadata.source_product_price !== void 0) return String(metadata.source_product_price);
  if (metadata.main_product_original_price !== void 0) {
    return toPriceString(Number(metadata.main_product_original_price) - optionSum);
  }
  return String(line.original_price ?? line.selling_price ?? "0.00");
}
function isManualPriceLine(line) {
  const metadata = line.metadata || {};
  return !!(metadata.is_manual_discount || metadata.price_override !== void 0 && metadata.price_override !== null && metadata.price_override !== "");
}
function getLineUid(line) {
  var _a;
  const uid = ((_a = line.metadata) == null ? void 0 : _a.unique_identification_number) ?? line.unique_identification_number;
  if (uid === void 0 || uid === null || uid === "") return void 0;
  return String(uid);
}
function findBookingForLine(line, tempOrder) {
  const uid = getLineUid(line);
  const bookings = tempOrder == null ? void 0 : tempOrder.bookings;
  if (!uid || !Array.isArray(bookings)) return void 0;
  return bookings.find((booking) => String(booking == null ? void 0 : booking.product_uid) === uid);
}
function normalizeDurationConfig(raw) {
  if (!raw || typeof raw !== "object") return void 0;
  const duration = raw;
  const value = Number(duration.value);
  if (!duration.type || !Number.isFinite(value) || value <= 0) return void 0;
  return {
    ...duration,
    type: String(duration.type),
    value
  };
}
function getBundleId(bundle) {
  return bundle.bundle_id ?? bundle.id;
}
function getBundleProductId(bundle) {
  return bundle.bundle_product_id ?? bundle._bundle_product_id ?? bundle.product_id;
}
function getBundleVariantId(bundle) {
  return bundle.bundle_variant_id ?? bundle.variant_id ?? bundle.product_variant_id ?? 0;
}
function normalizeBundleForPriceQuery(bundle) {
  const bundleProductId = getBundleProductId(bundle);
  const bundleVariantId = getBundleVariantId(bundle);
  return {
    ...bundle,
    ...bundleProductId !== void 0 && bundleProductId !== null ? { bundle_product_id: bundleProductId } : {},
    ...bundleVariantId !== void 0 && bundleVariantId !== null ? { bundle_variant_id: bundleVariantId } : {}
  };
}
function buildCartLinePriceQuery(input) {
  var _a, _b, _c;
  const { line, tempOrder, fallbackDate } = input;
  if (line.product_id === null || line.product_id === void 0) return null;
  const booking = findBookingForLine(line, tempOrder);
  const duration = normalizeDurationConfig(
    ((_a = line.metadata) == null ? void 0 : _a.duration) ?? ((_c = (_b = line.metadata) == null ? void 0 : _b.origin) == null ? void 0 : _c.duration)
  );
  const query = {
    product: {
      ...line,
      id: line.product_id,
      price: resolveLineSourcePrice(line),
      quantity: line.num,
      product_bundle: Array.isArray(line.product_bundle) ? line.product_bundle.map(normalizeBundleForPriceQuery) : line.product_bundle
    },
    ...booking ? { booking } : {},
    ...duration ? { duration } : {},
    fallback_price: resolveLineSourcePrice(line),
    ...fallbackDate ? { datetime: fallbackDate } : {}
  };
  return query;
}
function isSameBundleItem(bundle, price) {
  const bundleId = getBundleId(bundle);
  const priceBundleId = price.bundle_id;
  if (bundleId != null && priceBundleId != null && String(bundleId) === String(priceBundleId)) {
    return true;
  }
  const bundleProductId = getBundleProductId(bundle);
  const priceProductId = price.bundle_product_id;
  const bundleVariantId = getBundleVariantId(bundle);
  const priceVariantId = price.bundle_variant_id ?? 0;
  return bundleProductId != null && priceProductId != null && String(bundleProductId) === String(priceProductId) && String(bundleVariantId) === String(priceVariantId);
}
function mergeBundleQuotationPrices(bundles, result) {
  if (!Array.isArray(bundles) || !Array.isArray(result.product_bundle)) return bundles;
  return bundles.map((bundle) => {
    var _a;
    const price = (_a = result.product_bundle) == null ? void 0 : _a.find((item) => isSameBundleItem(bundle, item));
    if (!price) return bundle;
    const unitPrice = toPriceString(price.unit_price);
    return {
      ...bundle,
      price: unitPrice,
      bundle_selling_price: unitPrice,
      original_price: unitPrice,
      product_price: unitPrice,
      custom_price: unitPrice,
      bundle_sum_price: unitPrice,
      bundle_payment_price: unitPrice,
      quotation_shelf_id: price.quotation_shelf_id
    };
  });
}
function buildCartLineRepriceParams(input) {
  var _a;
  const { line, result } = input;
  const sourcePrice = toPriceString(result.unit_price);
  const mainProductOriginalPrice = toPriceString(
    Number(sourcePrice) + (0, import_productSkuOptions.sumLineOptionUnitPrice)(line)
  );
  const productBundle = mergeBundleQuotationPrices(line.product_bundle, result);
  const lineOptions = (0, import_productSkuOptions.getLineProductOptions)(line);
  return {
    product_id: line.product_id,
    product_variant_id: line.product_variant_id,
    unique_identification_number: (_a = line.metadata) == null ? void 0 : _a.unique_identification_number,
    product_sku: (0, import_productSkuOptions.buildProductSkuPatch)(line, lineOptions),
    product_bundle: line.product_bundle,
    updates: {
      num: line.num,
      product_sku: (0, import_productSkuOptions.buildProductSkuPatch)(line, lineOptions),
      product_bundle: productBundle,
      discount_list: line.discount_list,
      metadata: {
        ...line.metadata || {},
        source_product_price: sourcePrice,
        main_product_original_price: mainProductOriginalPrice,
        main_product_selling_price: mainProductOriginalPrice,
        quotation_shelf_id: result.quotation_shelf_id,
        price_schema_version: 2
      }
    }
  };
}
var SalesSdkCartProvider = ({ children }) => {
  const sales = (0, import_react.useContext)(import_SalesSdkContext.SalesSdkContext);
  const bookingTicket = (sales == null ? void 0 : sales.bookingTicket) ?? null;
  const uiHosts = (0, import_react.useContext)(import_SalesSdkUIHostsContext.SalesSdkUIHostsContext);
  const hostBridges = (0, import_SalesSdkHostBridgesContext.useSalesSdkHostBridges)();
  const refreshSummary = (0, import_react.useContext)(import_SalesSdkSummaryContext.SalesSdkSummaryRefreshContext);
  const refreshRoot = (0, import_react.useContext)(import_SalesSdkProvider.SalesSdkRootRefreshContext);
  const { holderOptions, reload: reloadHolderOptions } = (0, import_SalesSdkHolderContext.useSalesSdkHolderOptional)();
  const Toast = (0, import_materials.useToast)();
  const [snapshot, setSnapshot] = (0, import_react.useState)(EMPTY_SNAPSHOT);
  const cartItemsRef = (0, import_react.useRef)(EMPTY_ITEMS);
  const repriceRequestSeqRef = (0, import_react.useRef)(0);
  cartItemsRef.current = snapshot.items;
  const [unfulfilledPromotions, setUnfulfilledPromotions] = (0, import_react.useState)([]);
  const [lastGiftActions, setLastGiftActions] = (0, import_react.useState)(
    null
  );
  const readCartSnapshot = (0, import_ahooks.useMemoizedFn)(() => readSnapshot(bookingTicket, holderOptions));
  const lastRepriceCustomerIdRef = (0, import_react.useRef)(null);
  console.log(snapshot, "snapsho12354t");
  const syncPromotionStateFromOs = (0, import_ahooks.useMemoizedFn)(() => {
    var _a, _b;
    if (!bookingTicket) {
      setUnfulfilledPromotions([]);
      setLastGiftActions(null);
      return;
    }
    try {
      setUnfulfilledPromotions(
        ((_a = bookingTicket.getUnfulfilledPromotions) == null ? void 0 : _a.call(bookingTicket)) ?? []
      );
      setLastGiftActions(
        ((_b = bookingTicket.getLastGiftActions) == null ? void 0 : _b.call(bookingTicket)) ?? null
      );
    } catch (e) {
      console.warn("[SalesSdk] syncPromotionStateFromOs 失败", e);
    }
  });
  (0, import_react.useEffect)(() => {
    import_utils.locales.init(import_locales.default, import_utils.locales.locale || "en");
  }, []);
  (0, import_react.useEffect)(() => {
    lastRepriceCustomerIdRef.current = null;
    setSnapshot(readCartSnapshot());
  }, [bookingTicket, holderOptions, readCartSnapshot]);
  (0, import_react.useEffect)(() => {
    if ((sales == null ? void 0 : sales.status) === "loading") {
      setSnapshot(EMPTY_SNAPSHOT);
      setUnfulfilledPromotions([]);
      setLastGiftActions(null);
    }
  }, [sales == null ? void 0 : sales.status]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
      setSnapshot(readCartSnapshot());
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, readCartSnapshot]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onProductsLoaded", () => {
      setSnapshot(readCartSnapshot());
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, readCartSnapshot]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onTempOrderReplaced", () => {
      setSnapshot(readCartSnapshot());
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, readCartSnapshot]);
  (0, import_react.useEffect)(() => {
    var _a;
    if (!bookingTicket) return;
    const orderModule = (_a = bookingTicket.store) == null ? void 0 : _a.order;
    if (!orderModule || typeof orderModule.effectsOn !== "function") {
      return;
    }
    const off = orderModule.effectsOn("onPromotionApplied", (payload) => {
      var _a2, _b;
      const next = Array.isArray(payload == null ? void 0 : payload.unfulfilledPromotions) ? payload.unfulfilledPromotions : ((_a2 = bookingTicket.getUnfulfilledPromotions) == null ? void 0 : _a2.call(bookingTicket)) ?? [];
      setUnfulfilledPromotions(next);
      const giftActions = (payload == null ? void 0 : payload.giftActions) ?? ((_b = bookingTicket.getLastGiftActions) == null ? void 0 : _b.call(bookingTicket)) ?? null;
      setLastGiftActions(giftActions);
      setSnapshot(readCartSnapshot());
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, readCartSnapshot]);
  (0, import_react.useEffect)(() => {
    var _a, _b;
    if (!bookingTicket) {
      setUnfulfilledPromotions([]);
      setLastGiftActions(null);
      return;
    }
    try {
      setUnfulfilledPromotions(
        ((_a = bookingTicket.getUnfulfilledPromotions) == null ? void 0 : _a.call(bookingTicket)) ?? []
      );
      setLastGiftActions(
        ((_b = bookingTicket.getLastGiftActions) == null ? void 0 : _b.call(bookingTicket)) ?? null
      );
    } catch (e) {
      console.warn("[SalesSdk] 初始读取 unfulfilledPromotions / lastGiftActions 失败", e);
    }
  }, [bookingTicket]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onDiscountApplied", () => {
      setSnapshot(readCartSnapshot());
      syncSummary();
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, readCartSnapshot]);
  const syncSummary = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!refreshSummary) return null;
    try {
      return await refreshSummary();
    } catch (e) {
      console.warn("[SalesSdk] CartProvider 同步 summary 失败", e);
      return null;
    }
  });
  const refreshAfterMutation = (0, import_ahooks.useMemoizedFn)(() => {
    setSnapshot(readCartSnapshot());
    syncPromotionStateFromOs();
    refreshRoot == null ? void 0 : refreshRoot();
  });
  const recalculateCartPricesForCustomerChange = (0, import_ahooks.useMemoizedFn)(async () => {
    var _a, _b;
    if (!bookingTicket) return;
    const requestSeq = repriceRequestSeqRef.current + 1;
    repriceRequestSeqRef.current = requestSeq;
    const liveTempOrder = ((_a = bookingTicket.getTempOrder) == null ? void 0 : _a.call(bookingTicket)) ?? null;
    const liveProducts = liveTempOrder == null ? void 0 : liveTempOrder.products;
    const lines = Array.isArray(liveProducts) ? liveProducts : [];
    if (lines.length === 0) {
      refreshAfterMutation();
      return;
    }
    if (typeof bookingTicket.calculateProductBookingPrice !== "function") {
      console.warn("[SalesSdk] bookingTicket.calculateProductBookingPrice 不可用，跳过购物车商品价格重算");
      refreshAfterMutation();
      return;
    }
    const fallbackDate = (0, import_bookingDate.formatBookingDateTime)((_b = bookingTicket.getBookingDate) == null ? void 0 : _b.call(bookingTicket));
    let hasUpdated = false;
    for (const line of lines) {
      if (repriceRequestSeqRef.current !== requestSeq) return;
      if (isManualPriceLine(line)) continue;
      if ((0, import_discountCard.shouldSkipCustomerRepriceForDiscountedLine)(line)) {
        continue;
      }
      const query = buildCartLinePriceQuery({
        line,
        tempOrder: liveTempOrder,
        fallbackDate
      });
      if (!query) continue;
      const result = await bookingTicket.calculateProductBookingPrice(query);
      const updateParams = buildCartLineRepriceParams({ line, result });
      await bookingTicket.updateOrderProduct(updateParams);
      hasUpdated = true;
    }
    if (repriceRequestSeqRef.current !== requestSeq) return;
    refreshAfterMutation();
    if (hasUpdated) await syncSummary();
  });
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onOrderCustomerChange", (payload) => {
      var _a, _b;
      const nextCustomerId = ((_a = payload == null ? void 0 : payload.snapshot) == null ? void 0 : _a.id) !== void 0 && ((_b = payload == null ? void 0 : payload.snapshot) == null ? void 0 : _b.id) !== null ? String(payload.snapshot.id) : null;
      setSnapshot(readCartSnapshot());
      if (lastRepriceCustomerIdRef.current === nextCustomerId) {
        return;
      }
      lastRepriceCustomerIdRef.current = nextCustomerId;
      void recalculateCartPricesForCustomerChange().catch((e) => {
        console.warn("[SalesSdk] 客户变更后重算购物车商品价格失败", e);
      });
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, readCartSnapshot, recalculateCartPricesForCustomerChange]);
  const getAddFlowContext = (0, import_ahooks.useMemoizedFn)(() => {
    var _a, _b, _c, _d, _e;
    const rawDate = (_a = bookingTicket == null ? void 0 : bookingTicket.getBookingDate) == null ? void 0 : _a.call(bookingTicket);
    const date = (0, import_bookingDate.formatBookingDateTime)(rawDate);
    const liveTempOrder = cloneTempOrder(((_b = bookingTicket == null ? void 0 : bookingTicket.getTempOrder) == null ? void 0 : _b.call(bookingTicket)) ?? null) ?? snapshot.tempOrder;
    const customerId = (0, import_buildBookingEditDrawerState.resolveAddFlowCustomerId)(
      liveTempOrder,
      void 0,
      (_d = (_c = bookingTicket == null ? void 0 : bookingTicket.getOrderCustomerSnapshot) == null ? void 0 : _c.call(bookingTicket)) == null ? void 0 : _d.id
    );
    return {
      bookingConfig: ((_e = bookingTicket == null ? void 0 : bookingTicket.getBookingConfig) == null ? void 0 : _e.call(bookingTicket)) ?? null,
      customerId,
      tempOrder: liveTempOrder,
      locale: import_utils.locales.locale,
      date
    };
  });
  const addCustomProduct = (0, import_ahooks.useMemoizedFn)(
    async (input) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const orderLine = (0, import_buildCustomOrderProductFromCustomiseItem.buildCustomOrderProductFromCustomiseItem)(input);
      const products = await bookingTicket.addProductToOrder(orderLine);
      refreshAfterMutation();
      await syncSummary();
      return products;
    }
  );
  const addProductToOrderFromCache = (0, import_ahooks.useMemoizedFn)(
    async (item, cacheItem, options) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      if (typeof bookingTicket.transformDetailToProductAndBooking !== "function") {
        throw new Error("[SalesSdk] Cart: bookingTicket.transformDetailToProductAndBooking 不可用");
      }
      const flowCtx = getAddFlowContext();
      const { product: orderLine, booking } = bookingTicket.transformDetailToProductAndBooking({
        item,
        cacheItem: (0, import_resolveCacheItemForResourceCheck.resolveCacheItemForResourceCheck)(cacheItem),
        options: { quantity: options == null ? void 0 : options.quantity, date: flowCtx.date ?? void 0 }
      });
      const products = await bookingTicket.addProductToOrder(orderLine, booking);
      refreshAfterMutation();
      await syncSummary();
      return products;
    }
  );
  const addProduct = (0, import_ahooks.useMemoizedFn)(
    async (product, options) => {
      var _a, _b, _c;
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      if (typeof bookingTicket.decideAddProduct !== "function") {
        throw new Error("[SalesSdk] Cart: bookingTicket.decideAddProduct 不可用，请升级 pisellos");
      }
      const flowCtx = getAddFlowContext();
      const decision = bookingTicket.decideAddProduct(product, {
        type: (options == null ? void 0 : options.type) || "select",
        quantity: options == null ? void 0 : options.quantity,
        date: flowCtx.date ?? void 0,
        customerId: flowCtx.customerId
      });
      if (decision.action === "requiresDetail") {
        const payload = decision.payload ?? ((_a = bookingTicket.buildRequiresDetailPayload) == null ? void 0 : _a.call(bookingTicket, product, {
          type: (options == null ? void 0 : options.type) || "select",
          quantity: options == null ? void 0 : options.quantity,
          date: flowCtx.date ?? void 0,
          customerId: flowCtx.customerId
        }));
        return { status: "requiresDetail", payload };
      }
      if (decision.action === "requiresBookingEdit") {
        const payload = {
          ...decision.payload ?? { date: flowCtx.date ?? null },
          cacheItem: decision.cacheItem,
          date: flowCtx.date ?? ((_b = decision.payload) == null ? void 0 : _b.date) ?? null,
          customerId: flowCtx.customerId ?? ((_c = decision.payload) == null ? void 0 : _c.customerId)
        };
        return { status: "requiresBookingEdit", payload };
      }
      const addQty = (options == null ? void 0 : options.quantity) != null && options.quantity > 0 ? options.quantity : 1;
      const cacheItemWithQty = (0, import_applyExplicitAddQuantityToCacheItem.applyExplicitAddQuantityToCacheItem)(
        decision.cacheItem,
        addQty
      );
      const enriched = await (0, import_enrichCacheItemBeforeAdd.enrichCacheItemBeforeAdd)({
        cacheItem: cacheItemWithQty,
        catalogItem: product,
        uiHosts,
        ...flowCtx,
        mode: "direct"
      });
      if (enriched.status !== "ok") {
        throw new Error("[SalesSdk] addProduct: 加车前校验未通过（Holder / 跨日 Host 未配置或用户取消）");
      }
      const products = await addProductToOrderFromCache(product, enriched.cacheItem, {
        quantity: addQty
      });
      return { status: "added", products };
    }
  );
  const confirmDetail = (0, import_ahooks.useMemoizedFn)(
    async (input) => {
      var _a, _b, _c;
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      if (typeof bookingTicket.transformDetailToProductAndBooking !== "function") {
        throw new Error("[SalesSdk] Cart: bookingTicket.transformDetailToProductAndBooking 不可用");
      }
      const confirmQuantity = (0, import_resolveConfirmDetailQuantity.resolveConfirmDetailQuantity)(input);
      const flowCtx = getAddFlowContext();
      const draft = bookingTicket.transformDetailToProductAndBooking({
        item: input.item,
        detailResult: input.detailResult,
        options: {
          quantity: confirmQuantity,
          date: flowCtx.date ?? void 0,
          customerId: flowCtx.customerId
        }
      });
      const catalogItem = input.item;
      let cacheItem = (0, import_mergeCatalogDurationIntoCacheItem.mergeCatalogDurationIntoCacheItem)(draft.cacheItem, catalogItem);
      if ((_a = input.options) == null ? void 0 : _a.multiDayRange) {
        cacheItem = (0, import_patchCacheItemDateRange.patchCacheItemDateRange)(cacheItem, input.options.multiDayRange);
      } else {
        cacheItem = (0, import_patchCacheItemDateRange.applyDefaultMultiDayRangeIfNeeded)(
          cacheItem,
          catalogItem,
          flowCtx.date
        );
      }
      if (typeof bookingTicket.decideAfterDetail === "function") {
        const decision = bookingTicket.decideAfterDetail(cacheItem, {
          quantity: confirmQuantity,
          customerId: flowCtx.customerId,
          date: flowCtx.date ?? void 0,
          bookingConfig: flowCtx.bookingConfig ?? void 0
        });
        if (decision.action === "requiresBookingEdit") {
          const payload = {
            ...decision.payload ?? {
              cacheItem: decision.cacheItem,
              date: flowCtx.date
            },
            cacheItem: decision.cacheItem,
            date: flowCtx.date ?? ((_b = decision.payload) == null ? void 0 : _b.date) ?? null,
            customerId: flowCtx.customerId ?? ((_c = decision.payload) == null ? void 0 : _c.customerId)
          };
          return { status: "requiresBookingEdit", payload };
        }
        const enriched2 = await (0, import_enrichCacheItemBeforeAdd.enrichCacheItemBeforeAdd)({
          cacheItem: decision.cacheItem,
          catalogItem: input.item,
          uiHosts,
          ...flowCtx,
          mode: "direct"
        });
        if (enriched2.status !== "ok") {
          throw new Error(
            "[SalesSdk] confirmDetail: 加车前校验未通过（Holder / 跨日 Host 未配置或用户取消）"
          );
        }
        const products2 = await addProductToOrderFromCache(
          input.item,
          enriched2.cacheItem,
          {
            quantity: (0, import_resolveConfirmDetailQuantity.resolveAddQuantityFromCacheItem)(
              enriched2.cacheItem,
              confirmQuantity
            )
          }
        );
        return { status: "added", products: products2 };
      }
      const enriched = await (0, import_enrichCacheItemBeforeAdd.enrichCacheItemBeforeAdd)({
        cacheItem,
        catalogItem: input.item,
        uiHosts,
        ...flowCtx,
        mode: "direct"
      });
      if (enriched.status !== "ok") {
        throw new Error(
          "[SalesSdk] confirmDetail: 加车前校验未通过（Holder / 跨日 Host 未配置或用户取消）"
        );
      }
      const products = await addProductToOrderFromCache(
        input.item,
        enriched.cacheItem,
        {
          quantity: (0, import_resolveConfirmDetailQuantity.resolveAddQuantityFromCacheItem)(enriched.cacheItem, confirmQuantity)
        }
      );
      return { status: "added", products };
    }
  );
  const confirmBookingEdit = (0, import_ahooks.useMemoizedFn)(
    async (input) => {
      var _a;
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const products = await addProductToOrderFromCache(
        input.cacheItem,
        input.cacheItem,
        {
          quantity: (0, import_resolveConfirmDetailQuantity.resolveAddQuantityFromCacheItem)(
            input.cacheItem,
            (_a = input.options) == null ? void 0 : _a.quantity
          )
        }
      );
      reloadHolderOptions();
      return { products };
    }
  );
  const runAddProductFlowBase = (0, import_ahooks.useMemoizedFn)(
    async (product, options) => {
      return (0, import_runAddProductFlow.runAddProductFlow)(
        { addProduct, confirmDetail, confirmBookingEdit },
        uiHosts,
        product,
        {
          ...options,
          ...getAddFlowContext()
        }
      );
    }
  );
  const addProductRef = (0, import_react.useRef)(addProduct);
  addProductRef.current = addProduct;
  const runFlowRef = (0, import_react.useRef)(runAddProductFlowBase);
  runFlowRef.current = runAddProductFlowBase;
  const bookingTicketRef = (0, import_react.useRef)(bookingTicket);
  bookingTicketRef.current = bookingTicket;
  const getAddFlowContextRef = (0, import_react.useRef)(getAddFlowContext);
  getAddFlowContextRef.current = getAddFlowContext;
  const debouncedAddRef = (0, import_react.useRef)(
    (0, import_addProductWithFlowDebounced.createAddProductWithFlowDebounced)({
      decideAddProduct: (product, opts) => {
        const ticket = bookingTicketRef.current;
        if (!ticket || typeof ticket.decideAddProduct !== "function") {
          return { action: "requiresDetail" };
        }
        const flowCtx = getAddFlowContextRef.current();
        return ticket.decideAddProduct(product, {
          ...opts,
          date: flowCtx.date ?? void 0,
          customerId: flowCtx.customerId
        });
      },
      runAddProductFlow: (product, opts) => runFlowRef.current(product, opts),
      addProductDirect: (product, opts) => addProductRef.current(product, opts),
      getCartItems: () => cartItemsRef.current,
      Toast
    })
  );
  const addProductWithFlow = (0, import_ahooks.useMemoizedFn)(
    async (product, options) => {
      if (!bookingTicketRef.current) {
        throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      }
      return debouncedAddRef.current.addProductWithFlow(product, options);
    }
  );
  const removeItem = (0, import_ahooks.useMemoizedFn)(
    async (item) => {
      var _a;
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const mergedSources = (0, import_mergeBookingsForDisplay.getMergedBookingSources)(item);
      if (mergedSources.length > 1) {
        let result2 = [];
        for (const source of mergedSources) {
          result2 = await bookingTicket.removeProductFromOrder(source.identity);
        }
        refreshAfterMutation();
        await syncSummary();
        return result2;
      }
      const productItem = ((_a = item == null ? void 0 : item._extend) == null ? void 0 : _a.product) ?? item;
      if (!productItem) {
        throw new Error("[SalesSdk] Cart: 无法解析商品行，无法删除");
      }
      const identity = (0, import_identity.pickIdentity)(productItem);
      const result = await bookingTicket.removeProductFromOrder(identity);
      refreshAfterMutation();
      await syncSummary();
      return result;
    }
  );
  const updateItem = (0, import_ahooks.useMemoizedFn)(
    async (params) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      if (typeof bookingTicket.updateOrderProduct !== "function") {
        throw new Error("[SalesSdk] Cart: updateOrderProduct 不可用");
      }
      const result = await bookingTicket.updateOrderProduct(params);
      refreshAfterMutation();
      await syncSummary();
      return result;
    }
  );
  const updateItemQuantity = (0, import_ahooks.useMemoizedFn)(
    async (item, num) => {
      var _a, _b, _c;
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      if (typeof bookingTicket.updateOrderProductQuantity !== "function") {
        throw new Error("[SalesSdk] Cart: updateOrderProductQuantity 不可用");
      }
      const productItem = ((_a = item == null ? void 0 : item._extend) == null ? void 0 : _a.product) ?? item;
      if (!productItem) {
        throw new Error("[SalesSdk] Cart: 无法解析商品行，无法更新数量");
      }
      const mergedSources = (0, import_mergeBookingsForDisplay.getMergedBookingSources)(item);
      if (mergedSources.length > 1) {
        const nextNum = Math.max(0, Math.floor(Number(num) || 0));
        const currentNum = mergedSources.reduce((total, source) => {
          var _a2;
          const lineNum = Number((_a2 = source.product) == null ? void 0 : _a2.num);
          return total + (Number.isFinite(lineNum) && lineNum > 0 ? lineNum : 1);
        }, 0);
        let result2 = [];
        if (nextNum < currentNum) {
          const removeCount = currentNum - nextNum;
          const targets = mergedSources.slice(-removeCount);
          for (const source of targets) {
            result2 = await bookingTicket.removeProductFromOrder(source.identity);
          }
        } else if (nextNum > currentNum) {
          const appendCount = nextNum - currentNum;
          const source = mergedSources[0];
          for (let i = 0; i < appendCount; i += 1) {
            result2 = await bookingTicket.addProductToOrder(
              (0, import_mergeBookingsForDisplay.cloneProductForMergedBookingAppend)(source.product),
              (0, import_mergeBookingsForDisplay.cloneBookingForMergedBookingAppend)(source.booking)
            );
          }
        } else {
          result2 = ((_c = (_b = bookingTicket.getTempOrder) == null ? void 0 : _b.call(bookingTicket)) == null ? void 0 : _c.products) ?? [];
        }
        refreshAfterMutation();
        await syncSummary();
        return result2;
      }
      const result = await bookingTicket.updateOrderProductQuantity({
        ...(0, import_identity.pickIdentity)(productItem),
        num
      });
      refreshAfterMutation();
      await syncSummary();
      return result;
    }
  );
  const editCartLineBooking = (0, import_ahooks.useMemoizedFn)(async (item) => {
    var _a, _b;
    if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
    return (0, import_editCartLineBooking.editCartLineBooking)({
      item,
      bookingTicket,
      tempOrder: snapshot.tempOrder,
      uiHosts,
      productsCatalog: (_b = (_a = bookingTicket.getProductCatalog) == null ? void 0 : _a.call(bookingTicket)) == null ? void 0 : _b.products,
      bookingConfigParams: sales == null ? void 0 : sales.bookingConfigParams,
      updateItem
    });
  });
  const editCartLineProduct = (0, import_ahooks.useMemoizedFn)(async (item) => {
    if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
    return (0, import_editCartLineProduct.editCartLineProduct)({
      item,
      bookingTicket,
      tempOrder: snapshot.tempOrder,
      updateItem,
      normalProductDetailBridge: hostBridges.normalProductDetail
    });
  });
  const editCartLine = (0, import_ahooks.useMemoizedFn)(
    async (target) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const item = (0, import_editCartLine.resolveEditCartLineTarget)(target, snapshot.items);
      if ((0, import_editCartLine.shouldEditCartLineAsBooking)(item)) {
        return editCartLineBooking(item);
      }
      return editCartLineProduct(item);
    }
  );
  const selectGiftForItem = (0, import_ahooks.useMemoizedFn)(
    async (target) => {
      var _a, _b, _c, _d, _e, _f, _g;
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const mainItem = (0, import_editCartLine.resolveEditCartLineTarget)(target, snapshot.items);
      const promotion = (_a = mainItem.metadata) == null ? void 0 : _a._promotion;
      const giftInfo = promotion == null ? void 0 : promotion.giftInfo;
      const sourceUid = (_b = mainItem.metadata) == null ? void 0 : _b.unique_identification_number;
      if (!((_c = giftInfo == null ? void 0 : giftInfo.giftOptions) == null ? void 0 : _c.length) || !sourceUid || !(promotion == null ? void 0 : promotion.strategyId)) {
        return;
      }
      const ctx = {
        strategyId: promotion.strategyId,
        strategyName: ((_d = promotion.strategyMetadata) == null ? void 0 : _d.name) || promotion.strategyName || "",
        giftCount: giftInfo.giftCount,
        giftOptions: giftInfo.giftOptions,
        sourceProductIds: [String(sourceUid)],
        mode: "edit",
        _selectedOriginGifts: (_e = mainItem.giftData) == null ? void 0 : _e._selectedOriginGifts,
        initialChoices: (_g = (_f = mainItem.giftData) == null ? void 0 : _f._selectedOriginGifts) == null ? void 0 : _g.filter((gift) => gift.product_id != null).map((gift) => ({
          product_id: Number(gift.product_id),
          product_variant_id: Number(gift.product_variant_id) || 0,
          quantity: Number(gift.num) || 1
        }))
      };
      const choices = await hostBridges.giftSelect.request(ctx);
      if (!(choices == null ? void 0 : choices.length)) return;
      await (0, import_createOpenGiftSelectHost.replaceStrategyGiftsForMainItem)(bookingTicket, mainItem, choices);
      refreshAfterMutation();
      await syncSummary();
    }
  );
  const setOrderNote = (0, import_ahooks.useMemoizedFn)((note) => {
    if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
    const result = bookingTicket.updateTempOrderNote(note);
    setSnapshot(readSnapshot(bookingTicket));
    return result;
  });
  const setLineNote = (0, import_ahooks.useMemoizedFn)(
    async (identity, note) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const result = await bookingTicket.setOrderProductLineNote(identity, note);
      refreshAfterMutation();
      return result;
    }
  );
  const setDiscount = (0, import_ahooks.useMemoizedFn)(
    async (params) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      await bookingTicket.setDiscountSelected(params);
      refreshAfterMutation();
      await syncSummary();
    }
  );
  const scanCode = (0, import_ahooks.useMemoizedFn)(
    async (code, customerId) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const result = await bookingTicket.scanPromotionCode(code, customerId);
      if (result == null ? void 0 : result.isAvailable) {
        refreshAfterMutation();
      }
      await syncSummary();
      return result;
    }
  );
  const submit = (0, import_ahooks.useMemoizedFn)(
    async (params) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const canProceed = await (0, import_ensureHoldersBeforeSubmit.ensureHoldersBeforeSubmit)({
        bookingTicket,
        onMutate: refreshAfterMutation,
        holderConfirmBridge: hostBridges.holderConfirm
      });
      if (!canProceed) {
        throw import_createHolderConfirmBridge.HOLDER_CONFIRM_CANCELLED;
      }
      return bookingTicket.submitSalesOrder(params);
    }
  );
  const recalcSummary = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
    const summary = await syncSummary();
    refreshAfterMutation();
    return summary ?? null;
  });
  const value = (0, import_react.useMemo)(
    () => ({
      tempOrder: snapshot.tempOrder,
      salesDetail: snapshot.salesDetail,
      discountList: snapshot.discountList,
      unfulfilledPromotions,
      lastGiftActions,
      bookings: snapshot.bookings,
      items: snapshot.items,
      addProduct,
      addProductWithFlow,
      addCustomProduct,
      confirmDetail,
      confirmBookingEdit,
      removeItem,
      updateItem,
      updateItemQuantity,
      setOrderNote,
      setLineNote,
      setDiscount,
      scanCode,
      submit,
      recalcSummary,
      editCartLineBooking,
      editCartLineProduct,
      editCartLine,
      selectGiftForItem
    }),
    [
      snapshot,
      unfulfilledPromotions,
      lastGiftActions,
      addProduct,
      addProductWithFlow,
      addCustomProduct,
      confirmDetail,
      confirmBookingEdit,
      removeItem,
      updateItem,
      updateItemQuantity,
      editCartLineBooking,
      editCartLineProduct,
      editCartLine,
      selectGiftForItem,
      setOrderNote,
      setLineNote,
      setDiscount,
      scanCode,
      submit,
      recalcSummary
    ]
  );
  return /* @__PURE__ */ import_react.default.createElement(SalesSdkCartContext.Provider, { value }, children);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SalesSdkCartContext,
  SalesSdkCartProvider
});
