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/SalesSdkProvider.tsx
var SalesSdkProvider_exports = {};
__export(SalesSdkProvider_exports, {
  SalesSdkProvider: () => SalesSdkProvider,
  SalesSdkRootRefreshContext: () => SalesSdkRootRefreshContext
});
module.exports = __toCommonJS(SalesSdkProvider_exports);
var import_react = __toESM(require("react"));
var import_ahooks = require("ahooks");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_utils = require("../../../components/ticketBooking/utils");
var import_SalesSdkContext = require("./SalesSdkContext");
var import_SalesSdkProductContext = require("./SalesSdkProductContext");
var import_SalesSdkCartContext = require("./SalesSdkCartContext");
var import_SalesSdkCustomerContext = require("./SalesSdkCustomerContext");
var import_SalesSdkSummaryContext = require("./SalesSdkSummaryContext");
var EMPTY_ROOT_SNAPSHOT = {
  tempOrder: null,
  salesDetail: null
};
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 readRootSnapshot(bookingTicket) {
  var _a, _b;
  if (!bookingTicket) return EMPTY_ROOT_SNAPSHOT;
  try {
    return {
      tempOrder: cloneTempOrder(((_a = bookingTicket.getTempOrder) == null ? void 0 : _a.call(bookingTicket)) ?? null),
      salesDetail: ((_b = bookingTicket.getSalesOrder) == null ? void 0 : _b.call(bookingTicket)) ?? null
    };
  } catch (e) {
    console.warn("[SalesSdk] readRootSnapshot 失败", e);
    return EMPTY_ROOT_SNAPSHOT;
  }
}
var SalesSdkRootRefreshContext = (0, import_react.createContext)(null);
SalesSdkRootRefreshContext.displayName = "SalesSdkRootRefreshContext";
var SalesSdkProvider = ({
  osKey,
  businessCode,
  otherParams,
  rulesHooks,
  orderId,
  autoBootstrap = true,
  children
}) => {
  var _a;
  const context = (0, import_useEngineContext.default)();
  const utils = ((_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) || {};
  const { pisellos, pisellosAllModule, businessUtils, action } = utils;
  const { BookingTicket } = pisellosAllModule || {};
  const bookingTicket = (0, import_react.useMemo)(() => {
    var _a2;
    if (!pisellos || !BookingTicket) return null;
    const moduleKey = (0, import_utils.getBookingTicketKey)(osKey);
    let mod = pisellos.getModule(moduleKey);
    if (!mod) {
      mod = new BookingTicket(moduleKey);
      pisellos.registerModule(mod, {
        otherParams: {
          cacheId: moduleKey,
          platform: (otherParams == null ? void 0 : otherParams.platform) || "shop",
          businessCode,
          isFranchisee: (_a2 = businessUtils == null ? void 0 : businessUtils.getAppByModal) == null ? void 0 : _a2.call(businessUtils, "franchisee"),
          rules: rulesHooks ? { hooks: rulesHooks } : void 0,
          ...otherParams || {}
        }
      });
    }
    return mod;
  }, [pisellos, BookingTicket, osKey]);
  const [status, setStatus] = (0, import_react.useState)("idle");
  const [error, setError] = (0, import_react.useState)(null);
  const [rootSnapshot, setRootSnapshot] = (0, import_react.useState)(EMPTY_ROOT_SNAPSHOT);
  const refreshRootSnapshot = (0, import_ahooks.useMemoizedFn)(() => {
    setRootSnapshot(readRootSnapshot(bookingTicket));
  });
  (0, import_react.useEffect)(() => {
    setRootSnapshot(readRootSnapshot(bookingTicket));
  }, [bookingTicket]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
      refreshRootSnapshot();
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, refreshRootSnapshot]);
  const loadDetail = (0, import_ahooks.useMemoizedFn)(async (id) => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    setStatus("loading");
    setError(null);
    try {
      const sales = await bookingTicket.loadSalesDetail(id);
      refreshRootSnapshot();
      setStatus("ready");
      return sales;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      setStatus("error");
      throw err;
    }
  });
  const loadDetailByRemote = (0, import_ahooks.useMemoizedFn)(async (id) => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    setStatus("loading");
    setError(null);
    try {
      const sales = await bookingTicket.loadSalesDetail({
        orderId: id,
        forceRemote: true
      });
      refreshRootSnapshot();
      setStatus("ready");
      return sales;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      setStatus("error");
      throw err;
    }
  });
  const refreshSalesDetail = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    setError(null);
    try {
      const sales = await bookingTicket.refreshSalesDetail();
      refreshRootSnapshot();
      return sales;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      throw err;
    }
  });
  const createNew = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    try {
      const tempOrder = await bookingTicket.addNewOrder();
      refreshRootSnapshot();
      setStatus("ready");
      setError(null);
      return tempOrder;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      setStatus("error");
      throw err;
    }
  });
  const restore = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    try {
      const tempOrder = await bookingTicket.restoreOrder();
      refreshRootSnapshot();
      setStatus("ready");
      setError(null);
      return tempOrder;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      setStatus("error");
      throw err;
    }
  });
  const destroy = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) return;
    await bookingTicket.destroy();
    setRootSnapshot(EMPTY_ROOT_SNAPSHOT);
    setStatus("idle");
    setError(null);
  });
  const openCheckout = (0, import_ahooks.useMemoizedFn)(async () => {
    var _a2;
    if (typeof action !== "function") {
      throw new Error("[SalesSdk] appHelper.utils.action is not available.");
    }
    if (!bookingTicket) {
      throw new Error("[SalesSdk] bookingTicket 未初始化");
    }
    const tempOrder = (_a2 = bookingTicket.getTempOrder) == null ? void 0 : _a2.call(bookingTicket);
    const orderIdFromTemp = tempOrder == null ? void 0 : tempOrder.order_id;
    if (orderIdFromTemp === void 0 || orderIdFromTemp === null) {
      throw new Error(
        "[SalesSdk] openCheckout: tempOrder.order_id 缺失（请先 loadDetail 或提交订单）"
      );
    }
    return new Promise((resolve) => {
      let settled = false;
      action({
        type: "pisell1.handleOpenPayment",
        data: { order: { id: orderIdFromTemp } },
        callback: (res = {}) => {
          var _a3;
          if ((_a3 = res == null ? void 0 : res.data) == null ? void 0 : _a3.isCallbackFromToast) return;
          if (typeof res.reset === "boolean" && res.reset) {
            void refreshSalesDetail().then(() => {
              action({
                type: "webpos.updateLocalOrderApi",
                data: { order_id: orderIdFromTemp }
              });
            });
          }
          if (settled) return;
          settled = true;
          resolve(res);
        }
      });
    });
  });
  const setBookingStatus = (0, import_ahooks.useMemoizedFn)(async (status2) => {
    var _a2;
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    try {
      const data = await bookingTicket.setBookingStatus(status2);
      const tempOrder = (_a2 = bookingTicket.getTempOrder) == null ? void 0 : _a2.call(bookingTicket);
      const orderIdFromTemp = tempOrder == null ? void 0 : tempOrder.order_id;
      action({
        type: "webpos.updateLocalOrderApi",
        data: { order_id: orderIdFromTemp }
      });
      setError(null);
      return data;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      throw err;
    }
  });
  function runTempOrderMutation(exec) {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    try {
      const result = exec(bookingTicket);
      refreshRootSnapshot();
      setError(null);
      return result;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      throw err;
    }
  }
  const setOrderNote = (0, import_ahooks.useMemoizedFn)(
    (note) => runTempOrderMutation((handle) => handle.updateTempOrderNote(note))
  );
  const setShopDiscount = (0, import_ahooks.useMemoizedFn)(
    (amount) => runTempOrderMutation((handle) => handle.updateOrderShopDiscount(amount))
  );
  const setContactsInfo = (0, import_ahooks.useMemoizedFn)(
    (contactsInfo) => runTempOrderMutation((handle) => handle.updateTempOrderContactsInfo(contactsInfo))
  );
  (0, import_react.useEffect)(() => {
    if (!autoBootstrap || !orderId || !bookingTicket) return;
    loadDetail(orderId).catch(() => {
    });
  }, [autoBootstrap, orderId, bookingTicket, loadDetail]);
  const value = (0, import_react.useMemo)(
    () => {
      var _a2;
      return {
        bookingTicket,
        osKey,
        status,
        error,
        isReady: status === "ready",
        shop_full_order_number: ((_a2 = rootSnapshot.tempOrder) == null ? void 0 : _a2.shop_full_order_number) || "",
        tempOrder: rootSnapshot.tempOrder,
        salesDetail: rootSnapshot.salesDetail,
        loadDetail,
        loadDetailByRemote,
        refreshSalesDetail,
        createNew,
        restore,
        destroy,
        setBookingStatus,
        setOrderNote,
        setShopDiscount,
        setContactsInfo,
        openCheckout
      };
    },
    // actions 引用稳定（useMemoizedFn）；不进 deps 也安全，但显式列出便于阅读
    [
      bookingTicket,
      osKey,
      status,
      error,
      rootSnapshot,
      loadDetail,
      loadDetailByRemote,
      refreshSalesDetail,
      createNew,
      restore,
      destroy,
      setBookingStatus,
      setOrderNote,
      setShopDiscount,
      setContactsInfo,
      openCheckout
    ]
  );
  return /* @__PURE__ */ import_react.default.createElement(import_SalesSdkContext.SalesSdkContext.Provider, { value }, /* @__PURE__ */ import_react.default.createElement(SalesSdkRootRefreshContext.Provider, { value: refreshRootSnapshot }, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkProductContext.SalesSdkProductProvider, null, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkSummaryContext.SalesSdkSummaryProvider, null, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkCartContext.SalesSdkCartProvider, null, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkCustomerContext.SalesSdkCustomerProvider, null, children))))));
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SalesSdkProvider,
  SalesSdkRootRefreshContext
});
