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/hosts/BookingEditHostRenderer.tsx
var BookingEditHostRenderer_exports = {};
__export(BookingEditHostRenderer_exports, {
  BookingEditHostRenderer: () => BookingEditHostRenderer
});
module.exports = __toCommonJS(BookingEditHostRenderer_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_useSalesSdk = require("../hooks/useSalesSdk");
var import_BookingEditServiceDrawer = require("../bookingEditService/BookingEditServiceDrawer");
var import_buildBookingEditDrawerState = require("../bookingEditService/buildBookingEditDrawerState");
var import_prepareCacheItemForBookingEdit = require("../bookingEditService/prepareCacheItemForBookingEdit");
var import_prepareCacheItemForCartBookingEditDrawer = require("../utils/prepareCacheItemForCartBookingEditDrawer");
var import_multiDayPriceCache = require("../utils/multiDayPriceCache");
var import_resolveIsMultiDayProduct = require("../utils/resolveIsMultiDayProduct");
var import_SalesSdkHostBridgesContext = require("../context/SalesSdkHostBridgesContext");
function normalizeCacheItemForDrawer(rawItem, bookingTicket, forceOpen) {
  let item = rawItem;
  if ((0, import_multiDayPriceCache.isMultiDayQuotationExpanded)(item)) {
    item = { ...item, new: 0 };
  }
  if (typeof bookingTicket.getProductExtend === "function") {
    try {
      item = bookingTicket.getProductExtend(item);
    } catch (e) {
      console.warn("[SalesSdk] getProductExtend 失败，使用原始 cacheItem", e);
    }
  }
  item = (0, import_prepareCacheItemForBookingEdit.prepareCacheItemForBookingEdit)(item);
  if (forceOpen) {
    item = { ...item, autoClose: false };
  }
  return item;
}
var BookingEditHostRenderer = () => {
  var _a, _b, _c;
  const bridges = (0, import_SalesSdkHostBridgesContext.useSalesSdkHostBridges)();
  const bridge = bridges.bookingEdit;
  const pending = (0, import_react.useSyncExternalStore)(bridge.subscribe, bridge.getSnapshot, () => null);
  const { bookingTicket, tempOrder } = (0, import_useSalesSdk.useSalesSdk)();
  const [cacheItem, setCacheItem] = (0, import_react.useState)(null);
  const [multiDayExpanding, setMultiDayExpanding] = (0, import_react.useState)(false);
  const open = !!pending;
  const payload = pending == null ? void 0 : pending.payload;
  (0, import_react.useEffect)(() => {
    if (!open) {
      setCacheItem(null);
      setMultiDayExpanding(false);
      return;
    }
    if (!(payload == null ? void 0 : payload.cacheItem)) {
      console.error("[SalesSdk] openBookingEdit: 缺少 cacheItem");
      bridge.complete(null);
      return;
    }
    if (!bookingTicket) {
      setCacheItem(null);
      return;
    }
    let item = normalizeCacheItemForDrawer(
      payload.cacheItem,
      bookingTicket,
      payload.forceOpen
    );
    if (item.autoClose && !payload.forceOpen) {
      bridge.complete(item);
      return;
    }
    setCacheItem(item);
  }, [open, payload == null ? void 0 : payload.cacheItem, payload == null ? void 0 : payload.forceOpen, bookingTicket]);
  (0, import_react.useEffect)(() => {
    if (!open || !bookingTicket || !(payload == null ? void 0 : payload.cacheItem)) {
      return;
    }
    const catalogCandidate = payload.sourceProduct ?? payload.catalogProduct ?? null;
    const isMultiDay = (0, import_resolveIsMultiDayProduct.resolveIsMultiDayProduct)(payload.cacheItem, catalogCandidate);
    const alreadyExpanded = (0, import_multiDayPriceCache.isMultiDayQuotationExpanded)(payload.cacheItem);
    if (!isMultiDay || alreadyExpanded) {
      return;
    }
    let cancelled = false;
    setMultiDayExpanding(true);
    (async () => {
      var _a2;
      try {
        const liveTempOrder = ((_a2 = bookingTicket.getTempOrder) == null ? void 0 : _a2.call(bookingTicket)) ?? tempOrder;
        const expanded = await (0, import_prepareCacheItemForCartBookingEditDrawer.prepareCacheItemForCartBookingEditDrawer)({
          cacheItem: payload.cacheItem,
          bookingTicket,
          tempOrder: liveTempOrder,
          sourceProduct: catalogCandidate,
          date: payload.date ?? void 0
        });
        if (cancelled) return;
        const item = normalizeCacheItemForDrawer(
          expanded,
          bookingTicket,
          payload.forceOpen
        );
        setCacheItem(item);
      } catch (err) {
        if (!cancelled) {
          console.warn(
            "[SalesSdk] 跨日补拉报价失败，抽屉以单条模式展示",
            err
          );
        }
      } finally {
        if (!cancelled) {
          setMultiDayExpanding(false);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [
    open,
    payload == null ? void 0 : payload.cacheItem,
    payload == null ? void 0 : payload.sourceProduct,
    payload == null ? void 0 : payload.catalogProduct,
    payload == null ? void 0 : payload.date,
    payload == null ? void 0 : payload.forceOpen,
    bookingTicket,
    tempOrder
  ]);
  (0, import_react.useEffect)(() => {
    if (!open || bookingTicket) return;
    const timer = setTimeout(() => {
      if (bridge.getSnapshot()) {
        console.error("[SalesSdk] openBookingEdit: bookingTicket 未就绪，已取消");
        bridge.complete(null);
      }
    }, 8e3);
    return () => clearTimeout(timer);
  }, [open, bookingTicket, bridge]);
  const resourcesOrigin = (0, import_react.useMemo)(() => {
    var _a2;
    if (!open || !bookingTicket) {
      return [];
    }
    return ((_a2 = bookingTicket.getResourcesOrigin) == null ? void 0 : _a2.call(bookingTicket)) ?? [];
  }, [
    open,
    bookingTicket,
    payload == null ? void 0 : payload.date,
    (_a = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a.start_date,
    (_c = (_b = cacheItem == null ? void 0 : cacheItem._data) == null ? void 0 : _b.resources) == null ? void 0 : _c.length
  ]);
  const bookingState = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d, _e, _f, _g;
    if (!cacheItem) {
      return null;
    }
    const bookingConfig = ((_a2 = bookingTicket == null ? void 0 : bookingTicket.getBookingConfig) == null ? void 0 : _a2.call(bookingTicket)) ?? null;
    const date = (payload == null ? void 0 : payload.date) ?? ((_b2 = bookingTicket == null ? void 0 : bookingTicket.getBookingDate) == null ? void 0 : _b2.call(bookingTicket)) ?? (0, import_dayjs.default)().format("YYYY-MM-DD");
    const liveTempOrder = ((_c2 = bookingTicket == null ? void 0 : bookingTicket.getTempOrder) == null ? void 0 : _c2.call(bookingTicket)) ?? tempOrder;
    const customerId = (0, import_buildBookingEditDrawerState.resolveBookingEditCustomerId)(
      liveTempOrder,
      payload == null ? void 0 : payload.customerId,
      (_e = (_d = bookingTicket == null ? void 0 : bookingTicket.getOrderCustomerSnapshot) == null ? void 0 : _d.call(bookingTicket)) == null ? void 0 : _e.id
    );
    return (0, import_buildBookingEditDrawerState.buildBookingEditDrawerState)({
      cacheItem,
      bookingConfig,
      date,
      customerId,
      amountSymbol: (liveTempOrder == null ? void 0 : liveTempOrder.currency_symbol) || (bookingConfig == null ? void 0 : bookingConfig.currency_symbol) || "$",
      locale: import_utils.locales.locale,
      resourcesOrigin,
      isFranchisee: Boolean((_g = (_f = bookingTicket == null ? void 0 : bookingTicket.getOtherParams) == null ? void 0 : _f.call(bookingTicket)) == null ? void 0 : _g.isFranchisee)
    });
  }, [cacheItem, payload, bookingTicket, tempOrder, resourcesOrigin]);
  if (!open || !cacheItem || !bookingState) {
    return null;
  }
  return /* @__PURE__ */ import_react.default.createElement(
    import_BookingEditServiceDrawer.BookingEditServiceDrawer,
    {
      open,
      cacheItem,
      bookingState,
      onCacheItemChange: setCacheItem,
      onConfirm: (edited) => bridge.complete(edited),
      onCancel: () => bridge.complete(null),
      showNoteButton: true,
      multiDayExpanding
    }
  );
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BookingEditHostRenderer
});
