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/SalesSdkHolderContext.tsx
var SalesSdkHolderContext_exports = {};
__export(SalesSdkHolderContext_exports, {
  SalesSdkHolderContext: () => SalesSdkHolderContext,
  SalesSdkHolderProvider: () => SalesSdkHolderProvider,
  useSalesSdkHolder: () => useSalesSdkHolder,
  useSalesSdkHolderOptional: () => useSalesSdkHolderOptional
});
module.exports = __toCommonJS(SalesSdkHolderContext_exports);
var import_react = __toESM(require("react"));
var import_ahooks = require("ahooks");
var import_serve = require("../../../components/ticketBooking/serve");
var import_SalesSdkContext = require("./SalesSdkContext");
var import_enrichCartLineHolderDisplay = require("../utils/enrichCartLineHolderDisplay");
var import_formatHolderOptions = require("../utils/formatHolderOptions");
var import_holderOptionsSyncBridge = require("../utils/holderOptionsSyncBridge");
var import_productHolderConfig = require("../utils/productHolderConfig");
var SalesSdkHolderContext = (0, import_react.createContext)(null);
SalesSdkHolderContext.displayName = "SalesSdkHolderContext";
var EMPTY_HOLDER_OPTIONS = [];
var DEFAULT_DISPLAY_CONFIG = (0, import_enrichCartLineHolderDisplay.resolveHolderDisplayConfig)(null);
function mergeHolderOptionsStable(optimistic = EMPTY_HOLDER_OPTIONS, server = EMPTY_HOLDER_OPTIONS) {
  if (optimistic.length === 0 && server.length === 0) return EMPTY_HOLDER_OPTIONS;
  if (optimistic.length === 0) return server;
  if (server.length === 0) return optimistic;
  return (0, import_formatHolderOptions.mergeHolderOptions)(optimistic, server);
}
function collectHolderSources(bookingTicket) {
  var _a, _b, _c;
  const cart = (_a = bookingTicket == null ? void 0 : bookingTicket.getCart) == null ? void 0 : _a.call(bookingTicket);
  const catalog = ((_c = (_b = bookingTicket == null ? void 0 : bookingTicket.getProductCatalog) == null ? void 0 : _b.call(bookingTicket)) == null ? void 0 : _c.products) ?? [];
  const resolveCatalogSource = (line) => catalog.find((product) => String(product == null ? void 0 : product.id) === String(line == null ? void 0 : line.product_id)) ?? line;
  const sources = [
    ...((cart == null ? void 0 : cart.bookings) || []).map(
      (booking) => {
        var _a2;
        return resolveCatalogSource(((_a2 = booking == null ? void 0 : booking._extend) == null ? void 0 : _a2.product) || booking);
      }
    ),
    ...((cart == null ? void 0 : cart.items) || []).map((item) => resolveCatalogSource(item))
  ];
  const seenFormIds = /* @__PURE__ */ new Set();
  return sources.filter((source) => {
    const holderConfig = (0, import_productHolderConfig.resolveProductHolderConfig)(source);
    if (!holderConfig.enabled || holderConfig.formId === void 0) return false;
    const key = String(holderConfig.formId);
    if (seenFormIds.has(key)) return false;
    seenFormIds.add(key);
    return true;
  });
}
function resolveHolderCustomerId(bookingTicket) {
  var _a, _b, _c, _d;
  const fromSnapshot = (_b = (_a = bookingTicket == null ? void 0 : bookingTicket.getOrderCustomerSnapshot) == null ? void 0 : _a.call(bookingTicket)) == null ? void 0 : _b.id;
  const fromTempOrder = (_d = (_c = bookingTicket == null ? void 0 : bookingTicket.getTempOrder) == null ? void 0 : _c.call(bookingTicket)) == null ? void 0 : _d.customer_id;
  const resolved = fromSnapshot ?? fromTempOrder;
  if (resolved === void 0 || resolved === null || resolved === "") return void 0;
  return resolved;
}
var SalesSdkHolderProvider = ({ children }) => {
  var _a;
  const sales = (0, import_react.useContext)(import_SalesSdkContext.SalesSdkContext);
  const bookingTicket = (sales == null ? void 0 : sales.bookingTicket) ?? null;
  const [serverHolderOptionsByKey, setServerHolderOptionsByKey] = (0, import_react.useState)({});
  const [optimisticHolderOptionsByKey, setOptimisticHolderOptionsByKey] = (0, import_react.useState)({});
  const [holderOptionsRequestKey, setHolderOptionsRequestKey] = (0, import_react.useState)(null);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [reloadToken, setReloadToken] = (0, import_react.useState)(0);
  const loadingKeysRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
  const mergedHolderOptionsCacheRef = (0, import_react.useRef)(
    /* @__PURE__ */ new Map()
  );
  const bookingConfig = ((_a = bookingTicket == null ? void 0 : bookingTicket.getBookingConfig) == null ? void 0 : _a.call(bookingTicket)) ?? null;
  const customerId = resolveHolderCustomerId(bookingTicket);
  const holderConfigKey = (0, import_react.useMemo)(() => {
    var _a2, _b;
    const holder = bookingConfig == null ? void 0 : bookingConfig.holder;
    return [
      (_a2 = holder == null ? void 0 : holder.form) == null ? void 0 : _a2.id,
      (_b = holder == null ? void 0 : holder.form) == null ? void 0 : _b.is_franchisor
    ].join("|");
  }, [bookingConfig]);
  const displayConfig = (0, import_react.useMemo)(
    () => (0, import_enrichCartLineHolderDisplay.resolveHolderDisplayConfig)(bookingConfig),
    [holderConfigKey]
  );
  const resolveRequestParams = (0, import_ahooks.useMemoizedFn)((source) => {
    return (0, import_enrichCartLineHolderDisplay.buildHolderListRequestParams)({ bookingConfig, customerId, source });
  });
  const getHolderOptionsRequestKeyForSource = (0, import_ahooks.useMemoizedFn)((source) => {
    return (0, import_enrichCartLineHolderDisplay.buildHolderListRequestKey)(resolveRequestParams(source));
  });
  const getHolderOptionsForSource = (0, import_ahooks.useMemoizedFn)((source) => {
    const requestKey = getHolderOptionsRequestKeyForSource(source);
    if (!requestKey) return EMPTY_HOLDER_OPTIONS;
    const optimistic = optimisticHolderOptionsByKey[requestKey] || EMPTY_HOLDER_OPTIONS;
    const server = serverHolderOptionsByKey[requestKey] || EMPTY_HOLDER_OPTIONS;
    const cached = mergedHolderOptionsCacheRef.current.get(requestKey);
    if ((cached == null ? void 0 : cached.optimistic) === optimistic && cached.server === server) {
      return cached.merged;
    }
    const merged = mergeHolderOptionsStable(optimistic, server);
    mergedHolderOptionsCacheRef.current.set(requestKey, {
      optimistic,
      server,
      merged
    });
    return merged;
  });
  const holderOptions = (0, import_react.useMemo)(() => {
    const requestKey = Object.keys(serverHolderOptionsByKey)[0] || Object.keys(optimisticHolderOptionsByKey)[0];
    if (!requestKey) return EMPTY_HOLDER_OPTIONS;
    return mergeHolderOptionsStable(
      optimisticHolderOptionsByKey[requestKey] || EMPTY_HOLDER_OPTIONS,
      serverHolderOptionsByKey[requestKey] || EMPTY_HOLDER_OPTIONS
    );
  }, [optimisticHolderOptionsByKey, serverHolderOptionsByKey]);
  (0, import_react.useEffect)(() => {
    setOptimisticHolderOptionsByKey({});
    mergedHolderOptionsCacheRef.current.clear();
  }, [holderConfigKey, customerId]);
  const reload = (0, import_ahooks.useMemoizedFn)(() => {
    setReloadToken((token) => token + 1);
  });
  const upsertHolderOptions = (0, import_ahooks.useMemoizedFn)((rawHolders, source) => {
    const incoming = (0, import_formatHolderOptions.formatHolderOptions)(rawHolders);
    if (incoming.length === 0) return;
    const requestKey = getHolderOptionsRequestKeyForSource(source);
    setOptimisticHolderOptionsByKey((prev) => {
      if (requestKey) {
        return {
          ...prev,
          [requestKey]: (0, import_formatHolderOptions.mergeHolderOptions)(prev[requestKey] || EMPTY_HOLDER_OPTIONS, incoming)
        };
      }
      const keys = /* @__PURE__ */ new Set([
        ...Object.keys(prev),
        ...Object.keys(serverHolderOptionsByKey)
      ]);
      return Array.from(keys).reduce((acc, key) => {
        acc[key] = (0, import_formatHolderOptions.mergeHolderOptions)(prev[key] || EMPTY_HOLDER_OPTIONS, incoming);
        return acc;
      }, {});
    });
  });
  const ensureHolderOptionsForSource = (0, import_ahooks.useMemoizedFn)(async (source) => {
    const params = resolveRequestParams(source);
    const requestKey = (0, import_enrichCartLineHolderDisplay.buildHolderListRequestKey)(params);
    if (!params || !requestKey) return EMPTY_HOLDER_OPTIONS;
    const cached = mergeHolderOptionsStable(
      optimisticHolderOptionsByKey[requestKey] || EMPTY_HOLDER_OPTIONS,
      serverHolderOptionsByKey[requestKey] || EMPTY_HOLDER_OPTIONS
    );
    if (cached.length) {
      setHolderOptionsRequestKey(requestKey);
      if (!loadingKeysRef.current.has(requestKey)) {
        loadingKeysRef.current.add(requestKey);
        setLoading(true);
        void (0, import_serve.getPetsData)(params).then((data) => {
          const rawList = Array.isArray(data == null ? void 0 : data.list) ? data.list : [];
          const fromServer = (0, import_formatHolderOptions.formatHolderOptions)(rawList);
          setServerHolderOptionsByKey((prev) => ({ ...prev, [requestKey]: fromServer }));
        }).catch((err) => {
          console.warn("[SalesSdk] refresh holderOptions failed", err);
        }).finally(() => {
          loadingKeysRef.current.delete(requestKey);
          setLoading(loadingKeysRef.current.size > 0);
        });
      }
      return cached;
    }
    if (loadingKeysRef.current.has(requestKey)) return cached;
    loadingKeysRef.current.add(requestKey);
    setLoading(true);
    try {
      const data = await (0, import_serve.getPetsData)(params);
      const rawList = Array.isArray(data == null ? void 0 : data.list) ? data.list : [];
      const fromServer = (0, import_formatHolderOptions.formatHolderOptions)(rawList);
      setServerHolderOptionsByKey((prev) => ({ ...prev, [requestKey]: fromServer }));
      setHolderOptionsRequestKey(requestKey);
      return mergeHolderOptionsStable(
        optimisticHolderOptionsByKey[requestKey] || EMPTY_HOLDER_OPTIONS,
        fromServer
      );
    } catch (err) {
      console.warn("[SalesSdk] load holderOptions failed", err);
      setHolderOptionsRequestKey(null);
      return EMPTY_HOLDER_OPTIONS;
    } finally {
      loadingKeysRef.current.delete(requestKey);
      setLoading(loadingKeysRef.current.size > 0);
    }
  });
  (0, import_react.useEffect)(() => {
    return (0, import_holderOptionsSyncBridge.registerHolderOptionsSyncBridge)({ upsertHolderOptions, reload });
  }, [upsertHolderOptions, reload]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) {
      setServerHolderOptionsByKey({});
      setHolderOptionsRequestKey(null);
      loadingKeysRef.current.clear();
      setLoading(false);
      return;
    }
    let cancelled = false;
    const sources = collectHolderSources(bookingTicket);
    sources.forEach((source) => {
      const params = resolveRequestParams(source);
      const requestKey = (0, import_enrichCartLineHolderDisplay.buildHolderListRequestKey)(params);
      if (!params || !requestKey) return;
      if (serverHolderOptionsByKey[requestKey] || loadingKeysRef.current.has(requestKey)) {
        return;
      }
      loadingKeysRef.current.add(requestKey);
      setLoading(true);
      (0, import_serve.getPetsData)(params).then((data) => {
        if (cancelled) return;
        const rawList = Array.isArray(data == null ? void 0 : data.list) ? data.list : [];
        const fromServer = (0, import_formatHolderOptions.formatHolderOptions)(rawList);
        setServerHolderOptionsByKey((prev) => ({ ...prev, [requestKey]: fromServer }));
        setHolderOptionsRequestKey(requestKey);
      }).catch((err) => {
        if (cancelled) return;
        console.warn("[SalesSdk] load holderOptions failed", err);
      }).finally(() => {
        loadingKeysRef.current.delete(requestKey);
        if (!cancelled) setLoading(loadingKeysRef.current.size > 0);
      });
    });
    return () => {
      cancelled = true;
    };
  }, [
    bookingTicket,
    holderConfigKey,
    customerId,
    reloadToken,
    resolveRequestParams,
    serverHolderOptionsByKey
  ]);
  (0, import_react.useEffect)(() => {
    var _a2, _b;
    if (!bookingTicket) return;
    const refresh = () => {
      reload();
    };
    const offs = [
      (_a2 = bookingTicket.effectsOn) == null ? void 0 : _a2.call(bookingTicket, "onOrderCustomerChange", refresh),
      (_b = bookingTicket.effectsOn) == null ? void 0 : _b.call(bookingTicket, "onSalesOrderLoaded", refresh)
    ].filter(Boolean);
    return () => {
      offs.forEach((off) => {
        try {
          off == null ? void 0 : off();
        } catch {
        }
      });
    };
  }, [bookingTicket, reload]);
  const value = (0, import_react.useMemo)(
    () => ({
      holderOptions,
      loading,
      displayConfig,
      holderOptionsRequestKey,
      getHolderOptionsForSource,
      getHolderOptionsRequestKeyForSource,
      ensureHolderOptionsForSource,
      reload,
      upsertHolderOptions
    }),
    [
      holderOptions,
      loading,
      displayConfig,
      holderOptionsRequestKey,
      getHolderOptionsForSource,
      getHolderOptionsRequestKeyForSource,
      ensureHolderOptionsForSource,
      reload,
      upsertHolderOptions
    ]
  );
  return /* @__PURE__ */ import_react.default.createElement(SalesSdkHolderContext.Provider, { value }, children);
};
function useSalesSdkHolder() {
  const ctx = (0, import_react.useContext)(SalesSdkHolderContext);
  if (!ctx) {
    throw new Error("[SalesSdk] useSalesSdkHolder 必须在 <SalesSdkHolderProvider> 内调用");
  }
  return ctx;
}
function useSalesSdkHolderOptional() {
  const ctx = (0, import_react.useContext)(SalesSdkHolderContext);
  return ctx ?? {
    holderOptions: EMPTY_HOLDER_OPTIONS,
    loading: false,
    displayConfig: DEFAULT_DISPLAY_CONFIG,
    holderOptionsRequestKey: null,
    getHolderOptionsForSource: () => EMPTY_HOLDER_OPTIONS,
    getHolderOptionsRequestKeyForSource: () => null,
    ensureHolderOptionsForSource: async () => EMPTY_HOLDER_OPTIONS,
    reload: () => void 0,
    upsertHolderOptions: () => void 0
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SalesSdkHolderContext,
  SalesSdkHolderProvider,
  useSalesSdkHolder,
  useSalesSdkHolderOptional
});
