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_SalesSdkContext = require("./SalesSdkContext");
var import_SalesSdkProvider = require("./SalesSdkProvider");
var import_SalesSdkSummaryContext = require("./SalesSdkSummaryContext");
var SalesSdkCartContext = (0, import_react.createContext)(null);
SalesSdkCartContext.displayName = "SalesSdkCartContext";
var EMPTY_DISCOUNT_LIST = [];
var EMPTY_ITEMS = [];
var EMPTY_BOOKINGS = [];
var EMPTY_SNAPSHOT = {
  bookings: EMPTY_BOOKINGS,
  items: EMPTY_ITEMS,
  discountList: EMPTY_DISCOUNT_LIST
};
function cloneArray(value, fallback) {
  return Array.isArray(value) ? [...value] : fallback;
}
function readSnapshot(bookingTicket) {
  var _a, _b;
  if (!bookingTicket) return EMPTY_SNAPSHOT;
  try {
    const cart = (_a = bookingTicket.getCart) == null ? void 0 : _a.call(bookingTicket);
    return {
      bookings: cloneArray(cart == null ? void 0 : cart.bookings, EMPTY_BOOKINGS),
      items: cloneArray(cart == null ? void 0 : cart.items, EMPTY_ITEMS),
      discountList: cloneArray((_b = bookingTicket.getDiscountList) == null ? void 0 : _b.call(bookingTicket), EMPTY_DISCOUNT_LIST)
    };
  } catch (e) {
    console.warn("[SalesSdk] CartProvider readSnapshot 失败", e);
    return EMPTY_SNAPSHOT;
  }
}
var SalesSdkCartProvider = ({ children }) => {
  const sales = (0, import_react.useContext)(import_SalesSdkContext.SalesSdkContext);
  const bookingTicket = (sales == null ? void 0 : sales.bookingTicket) ?? null;
  const refreshSummary = (0, import_react.useContext)(import_SalesSdkSummaryContext.SalesSdkSummaryRefreshContext);
  const refreshRoot = (0, import_react.useContext)(import_SalesSdkProvider.SalesSdkRootRefreshContext);
  const [snapshot, setSnapshot] = (0, import_react.useState)(EMPTY_SNAPSHOT);
  (0, import_react.useEffect)(() => {
    setSnapshot(readSnapshot(bookingTicket));
  }, [bookingTicket]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
      setSnapshot(readSnapshot(bookingTicket));
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket]);
  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(readSnapshot(bookingTicket));
    refreshRoot == null ? void 0 : refreshRoot();
  });
  const addProduct = (0, import_ahooks.useMemoizedFn)(
    async (input) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const result = await bookingTicket.addProductToOrder(input);
      refreshAfterMutation();
      await syncSummary();
      return result;
    }
  );
  const removeItem = (0, import_ahooks.useMemoizedFn)(
    async (item) => {
      if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
      const identity = {
        product_id: item.product_id,
        product_variant_id: item.product_variant_id,
        unique_identification_number: item.metadata.unique_identification_number,
        product_option_item: item.product_option_item,
        product_bundle: item.product_bundle
      };
      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 未初始化");
      const result = await bookingTicket.updateProductInOrder(params);
      refreshAfterMutation();
      await syncSummary();
      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 () => {
    if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
    return bookingTicket.submitScanOrder();
  });
  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)(
    () => ({
      discountList: snapshot.discountList,
      bookings: snapshot.bookings,
      items: snapshot.items,
      addProduct,
      removeItem,
      updateItem,
      setLineNote,
      setDiscount,
      scanCode,
      submit,
      recalcSummary
    }),
    [
      snapshot,
      addProduct,
      removeItem,
      updateItem,
      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
});
