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_utils = require("../../../components/booking/utils");
var import_SalesSdkContext = require("./SalesSdkContext");
var import_enrichCartLineHolderDisplay = require("../utils/enrichCartLineHolderDisplay");
var import_formatHolderOptions = require("../utils/formatHolderOptions");
var import_holderOptionsSyncBridge = require("../utils/holderOptionsSyncBridge");
var SalesSdkHolderContext = (0, import_react.createContext)(null);
SalesSdkHolderContext.displayName = "SalesSdkHolderContext";
var EMPTY_HOLDER_OPTIONS = [];
var DEFAULT_DISPLAY_CONFIG = (0, import_enrichCartLineHolderDisplay.resolveHolderDisplayConfig)(null);
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 [serverHolderOptions, setServerHolderOptions] = (0, import_react.useState)(EMPTY_HOLDER_OPTIONS);
  const [optimisticHolderOptions, setOptimisticHolderOptions] = (0, import_react.useState)(EMPTY_HOLDER_OPTIONS);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [reloadToken, setReloadToken] = (0, import_react.useState)(0);
  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, _c, _d;
    const subject = (_b = (_a2 = bookingConfig == null ? void 0 : bookingConfig.config) == null ? void 0 : _a2.basic) == null ? void 0 : _b.appointment_subject;
    const holder = bookingConfig == null ? void 0 : bookingConfig.holder;
    return [
      subject == null ? void 0 : subject.type,
      subject == null ? void 0 : subject.form_id,
      holder == null ? void 0 : holder.data_range,
      (_c = holder == null ? void 0 : holder.form) == null ? void 0 : _c.id,
      (_d = holder == null ? void 0 : holder.form) == null ? void 0 : _d.is_franchisor
    ].join("|");
  }, [bookingConfig]);
  const displayConfig = (0, import_react.useMemo)(
    () => (0, import_enrichCartLineHolderDisplay.resolveHolderDisplayConfig)(bookingConfig),
    [holderConfigKey]
  );
  const holderOptions = (0, import_react.useMemo)(
    () => (0, import_formatHolderOptions.mergeHolderOptions)(optimisticHolderOptions, serverHolderOptions),
    [optimisticHolderOptions, serverHolderOptions]
  );
  (0, import_react.useEffect)(() => {
    setOptimisticHolderOptions(EMPTY_HOLDER_OPTIONS);
  }, [holderConfigKey, customerId]);
  const reload = (0, import_ahooks.useMemoizedFn)(() => {
    setReloadToken((token) => token + 1);
  });
  const upsertHolderOptions = (0, import_ahooks.useMemoizedFn)((rawHolders) => {
    const incoming = (0, import_formatHolderOptions.formatHolderOptions)(rawHolders);
    if (incoming.length === 0) return;
    setOptimisticHolderOptions((prev) => (0, import_formatHolderOptions.mergeHolderOptions)(prev, incoming));
  });
  (0, import_react.useEffect)(() => {
    return (0, import_holderOptionsSyncBridge.registerHolderOptionsSyncBridge)({ upsertHolderOptions, reload });
  }, [upsertHolderOptions, reload]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) {
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
      return;
    }
    const holder = bookingConfig == null ? void 0 : bookingConfig.holder;
    if (!holder) {
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
      return;
    }
    if ((holder == null ? void 0 : holder.data_range) === "customer" && (0, import_utils.isWalkIn)(customerId)) {
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
      return;
    }
    const params = (0, import_enrichCartLineHolderDisplay.buildHolderListRequestParams)({ bookingConfig, customerId });
    if (!params) {
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
      return;
    }
    let cancelled = false;
    setLoading(true);
    (0, import_serve.getPetsData)(params).then((data) => {
      if (cancelled) return;
      const fromServer = (0, import_formatHolderOptions.formatHolderOptions)((data == null ? void 0 : data.list) || []);
      setServerHolderOptions(fromServer);
      const serverIds = new Set(fromServer.map((option) => String(option.id)));
      setOptimisticHolderOptions(
        (prev) => prev.filter((option) => !serverIds.has(String(option.id)))
      );
    }).catch((err) => {
      if (cancelled) return;
      console.warn("[SalesSdk] load holderOptions failed", err);
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
    }).finally(() => {
      if (!cancelled) setLoading(false);
    });
    return () => {
      cancelled = true;
    };
  }, [bookingTicket, holderConfigKey, customerId, reloadToken]);
  (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,
      reload,
      upsertHolderOptions
    }),
    [holderOptions, loading, displayConfig, 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,
    reload: () => void 0,
    upsertHolderOptions: () => void 0
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SalesSdkHolderContext,
  SalesSdkHolderProvider,
  useSalesSdkHolder,
  useSalesSdkHolderOptional
});
