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/components/bigSale/dialog.tsx
var dialog_exports = {};
__export(dialog_exports, {
  default: () => dialog_default
});
module.exports = __toCommonJS(dialog_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_classnames = __toESM(require("classnames"));
var import_materials = require("@pisell/materials");
var import_compensatedPisellContainer = __toESM(require("../../pro/compensatedPisellContainer"));
var import_responsive = require("../../responsive");
var import_salesSdk = require("../../plus/salesSdk");
var import_SalesSdkProvider = require("../../plus/salesSdk/context/SalesSdkProvider");
var import_SalesSdkSummaryContext = require("../../plus/salesSdk/context/SalesSdkSummaryContext");
var import_buildDefaultLoadProductsParams = require("../../plus/salesSdk/utils/buildDefaultLoadProductsParams");
var import_seedDineInReservationToCart = require("../../plus/pisellReservation/utils/seedDineInReservationToCart");
var import_index = require("./index");
var import_dialog = require("./dialog.less");
function isTempOrderBoundToRemoteOrder(tempOrder) {
  const orderId = tempOrder == null ? void 0 : tempOrder.order_id;
  if (orderId === void 0 || orderId === null) {
    return false;
  }
  return !String(orderId).startsWith("local_order");
}
function isBigSaleDialogEditReady(sales, orderId) {
  var _a;
  if (sales.status === "loading" || !sales.isReady) {
    return false;
  }
  const tempOrderId = (_a = sales.tempOrder) == null ? void 0 : _a.order_id;
  if (tempOrderId === void 0 || tempOrderId === null) {
    return false;
  }
  return Number(tempOrderId) === Number(orderId);
}
function buildBigSaleCreateSeedKey(createSeed) {
  var _a, _b;
  if (!createSeed) return "";
  return `${((_a = createSeed.row) == null ? void 0 : _a.id) ?? ""}-${((_b = createSeed.reservationRuleProduct) == null ? void 0 : _b.id) ?? ""}`;
}
async function prepareFreshOrderForCreateSeed(sales) {
  var _a, _b, _c, _d, _e, _f, _g;
  const tempOrder = ((_b = (_a = sales.bookingTicket) == null ? void 0 : _a.getTempOrder) == null ? void 0 : _b.call(_a)) ?? sales.tempOrder ?? null;
  const salesDetailOrderId = ((_d = (_c = sales.salesDetail) == null ? void 0 : _c.header) == null ? void 0 : _d.order_id) ?? ((_e = sales.salesDetail) == null ? void 0 : _e.order_id);
  const boundEditOrder = isTempOrderBoundToRemoteOrder(tempOrder) || Boolean(salesDetailOrderId);
  const productCount = ((_f = tempOrder == null ? void 0 : tempOrder.products) == null ? void 0 : _f.length) ?? 0;
  const bookingCount = ((_g = tempOrder == null ? void 0 : tempOrder.bookings) == null ? void 0 : _g.length) ?? 0;
  const hasCartLines = productCount > 0 || bookingCount > 0;
  if (boundEditOrder) {
    await sales.restore();
    return;
  }
  if (hasCartLines && typeof sales.clearCartItemsOnly === "function") {
    await sales.clearCartItemsOnly();
  }
  await sales.createNew();
}
function BigSaleDialogLifecycle({
  open,
  openNonce = 0,
  orderId,
  createSeed,
  bookingConfigParams,
  onCreateSeedReady,
  onCreateSeedError,
  onEditReady
}) {
  const sales = (0, import_salesSdk.useSalesSdk)();
  const cart = (0, import_salesSdk.useSalesSdkCart)();
  const refreshRoot = import_react.default.useContext(import_SalesSdkProvider.SalesSdkRootRefreshContext);
  const prepareOrderSwitch = import_react.default.useContext(import_SalesSdkProvider.SalesSdkPrepareOrderSwitchContext);
  const refreshSummary = import_react.default.useContext(import_SalesSdkSummaryContext.SalesSdkSummaryRefreshContext);
  const seededRef = (0, import_react.useRef)(false);
  const seedGenerationRef = (0, import_react.useRef)(0);
  const editLoadGenerationRef = (0, import_react.useRef)(0);
  const editReadyNotifiedRef = (0, import_react.useRef)(false);
  const closeCleanupGenerationRef = (0, import_react.useRef)(0);
  const salesRef = (0, import_react.useRef)(sales);
  salesRef.current = sales;
  const cartRef = (0, import_react.useRef)(cart);
  cartRef.current = cart;
  const createSeedRef = (0, import_react.useRef)(createSeed);
  createSeedRef.current = createSeed;
  const bookingConfigParamsRef = (0, import_react.useRef)(bookingConfigParams);
  bookingConfigParamsRef.current = bookingConfigParams;
  const refreshRootRef = (0, import_react.useRef)(refreshRoot);
  refreshRootRef.current = refreshRoot;
  const prepareOrderSwitchRef = (0, import_react.useRef)(prepareOrderSwitch);
  prepareOrderSwitchRef.current = prepareOrderSwitch;
  const refreshSummaryRef = (0, import_react.useRef)(refreshSummary);
  refreshSummaryRef.current = refreshSummary;
  const onCreateSeedReadyRef = (0, import_react.useRef)(onCreateSeedReady);
  onCreateSeedReadyRef.current = onCreateSeedReady;
  const onCreateSeedErrorRef = (0, import_react.useRef)(onCreateSeedError);
  onCreateSeedErrorRef.current = onCreateSeedError;
  const onEditReadyRef = (0, import_react.useRef)(onEditReady);
  onEditReadyRef.current = onEditReady;
  const createSeedKey = buildBigSaleCreateSeedKey(createSeed);
  const hasBookingTicket = Boolean(sales.bookingTicket);
  (0, import_react.useEffect)(() => {
    if (!open) {
      seededRef.current = false;
      seedGenerationRef.current += 1;
      editLoadGenerationRef.current += 1;
      editReadyNotifiedRef.current = false;
      return;
    }
    seededRef.current = false;
    seedGenerationRef.current += 1;
    editLoadGenerationRef.current += 1;
  }, [open, openNonce, createSeedKey]);
  (0, import_react.useEffect)(() => {
    if (open) {
      closeCleanupGenerationRef.current += 1;
      return;
    }
    const cleanupGen = closeCleanupGenerationRef.current;
    (async () => {
      var _a, _b, _c, _d;
      try {
        await ((_b = (_a = salesRef.current).restore) == null ? void 0 : _b.call(_a));
        if (cleanupGen !== closeCleanupGenerationRef.current) {
          return;
        }
        (_c = refreshRootRef.current) == null ? void 0 : _c.call(refreshRootRef);
        await ((_d = refreshSummaryRef.current) == null ? void 0 : _d.call(refreshSummaryRef));
      } catch (error) {
        console.warn("[BigSaleDialog] close cleanup failed", error);
      }
    })();
  }, [open]);
  (0, import_react.useEffect)(() => {
    var _a;
    if (!open || !orderId || createSeed) {
      return;
    }
    const liveSales = salesRef.current;
    if (!liveSales.bookingTicket) {
      return;
    }
    const loadGeneration = editLoadGenerationRef.current;
    editReadyNotifiedRef.current = false;
    (_a = prepareOrderSwitchRef.current) == null ? void 0 : _a.call(prepareOrderSwitchRef);
    const isStaleEditLoad = () => loadGeneration !== editLoadGenerationRef.current;
    (async () => {
      var _a2, _b, _c, _d, _e, _f, _g, _h;
      try {
        if (typeof liveSales.loadDetailByRemote === "function") {
          await liveSales.loadDetailByRemote(orderId);
        } else {
          await liveSales.loadDetail(orderId);
        }
        if (isStaleEditLoad()) {
          return;
        }
        const liveTempOrder = ((_b = (_a2 = liveSales.bookingTicket) == null ? void 0 : _a2.getTempOrder) == null ? void 0 : _b.call(_a2)) ?? liveSales.tempOrder;
        const bookingIds = (0, import_buildDefaultLoadProductsParams.collectBookingIdsFromTempOrder)(liveTempOrder ?? null);
        await ((_d = (_c = liveSales.bookingTicket) == null ? void 0 : _c.initBookingContext) == null ? void 0 : _d.call(
          _c,
          (0, import_buildDefaultLoadProductsParams.buildInitBookingContextParams)(bookingConfigParamsRef.current, {
            date: (0, import_dayjs.default)(),
            bookingIds: bookingIds.length ? bookingIds : void 0,
            loadResources: true
          })
        ));
        if (isStaleEditLoad()) {
          return;
        }
        (_e = refreshRootRef.current) == null ? void 0 : _e.call(refreshRootRef);
        await cartRef.current.recalcSummary();
        if (isStaleEditLoad()) {
          return;
        }
        await ((_f = refreshSummaryRef.current) == null ? void 0 : _f.call(refreshSummaryRef));
        editReadyNotifiedRef.current = true;
        (_g = onEditReadyRef.current) == null ? void 0 : _g.call(onEditReadyRef);
      } catch (error) {
        if (isStaleEditLoad()) {
          return;
        }
        (_h = onCreateSeedErrorRef.current) == null ? void 0 : _h.call(onCreateSeedErrorRef, error);
      }
    })();
    return () => {
      if (loadGeneration === editLoadGenerationRef.current) {
        editLoadGenerationRef.current += 1;
      }
    };
  }, [open, openNonce, orderId, createSeedKey, hasBookingTicket]);
  (0, import_react.useEffect)(() => {
    const currentSeed = createSeedRef.current;
    if (!open || orderId || !currentSeed || !createSeedKey) {
      return;
    }
    const liveSales = salesRef.current;
    if (!liveSales.bookingTicket) {
      return;
    }
    if (liveSales.status === "loading") {
      return;
    }
    if (seededRef.current) {
      return;
    }
    const seedGeneration = seedGenerationRef.current;
    const isStaleSeed = () => seedGeneration !== seedGenerationRef.current;
    (async () => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i;
      try {
        await prepareFreshOrderForCreateSeed(salesRef.current);
        if (isStaleSeed()) {
          return;
        }
        await (0, import_seedDineInReservationToCart.seedDineInReservationToCart)({
          bookingTicket: salesRef.current.bookingTicket,
          reservationRuleProduct: currentSeed.reservationRuleProduct,
          row: currentSeed.row,
          appointmentStatus: currentSeed.appointmentStatus ?? "started",
          bookingConfig: ((_b = (_a = salesRef.current.bookingTicket) == null ? void 0 : _a.getBookingConfig) == null ? void 0 : _b.call(_a)) ?? null,
          tempOrder: salesRef.current.tempOrder,
          date: (0, import_dayjs.default)().format("YYYY-MM-DD")
        });
        if (isStaleSeed()) {
          return;
        }
        const liveTempOrder = ((_d = (_c = salesRef.current.bookingTicket) == null ? void 0 : _c.getTempOrder) == null ? void 0 : _d.call(_c)) ?? salesRef.current.tempOrder;
        const bookingIds = (0, import_buildDefaultLoadProductsParams.collectBookingIdsFromTempOrder)(liveTempOrder ?? null);
        await ((_f = (_e = salesRef.current.bookingTicket) == null ? void 0 : _e.initBookingContext) == null ? void 0 : _f.call(
          _e,
          (0, import_buildDefaultLoadProductsParams.buildInitBookingContextParams)(bookingConfigParamsRef.current, {
            date: (0, import_dayjs.default)(),
            bookingIds: bookingIds.length ? bookingIds : void 0,
            /** dine_in seed 已写入桌位资源，打开时无需全量拉 resources。 */
            loadResources: false
          })
        ));
        if (isStaleSeed()) {
          return;
        }
        (_g = refreshRootRef.current) == null ? void 0 : _g.call(refreshRootRef);
        await cartRef.current.recalcSummary();
        if (isStaleSeed()) {
          return;
        }
        if (refreshSummaryRef.current) {
          await refreshSummaryRef.current();
        }
        if (isStaleSeed()) {
          return;
        }
        seededRef.current = true;
        (_h = onCreateSeedReadyRef.current) == null ? void 0 : _h.call(onCreateSeedReadyRef);
      } catch (error) {
        if (isStaleSeed()) {
          return;
        }
        seededRef.current = false;
        (_i = onCreateSeedErrorRef.current) == null ? void 0 : _i.call(onCreateSeedErrorRef, error);
      }
    })();
    return () => {
      if (seedGeneration === seedGenerationRef.current) {
        seedGenerationRef.current += 1;
      }
    };
  }, [open, openNonce, orderId, createSeedKey, hasBookingTicket]);
  (0, import_react.useEffect)(() => {
    if (!open || !orderId || createSeed) return;
    if (!isBigSaleDialogEditReady(sales, orderId)) return;
    if (editReadyNotifiedRef.current) return;
    editReadyNotifiedRef.current = true;
    onEditReady == null ? void 0 : onEditReady();
  }, [
    open,
    orderId,
    createSeed,
    sales.isReady,
    sales.status,
    sales.tempOrder,
    onEditReady
  ]);
  return null;
}
function BigSaleDialogHeaderBar({
  onClose,
  fallbackTitle,
  variant
}) {
  const sales = (0, import_salesSdk.useSalesSdk)();
  const orderIdLabel = (0, import_react.useMemo)(() => {
    var _a, _b, _c, _d;
    const tempOrder = sales.tempOrder;
    const fromTempOrder = (tempOrder == null ? void 0 : tempOrder.shop_full_order_number) || (tempOrder == null ? void 0 : tempOrder.shop_order_number) || ((tempOrder == null ? void 0 : tempOrder.order_number) ? String(tempOrder.order_number) : "");
    if (fromTempOrder) return String(fromTempOrder);
    const fromDetail = ((_b = (_a = sales.salesDetail) == null ? void 0 : _a.header) == null ? void 0 : _b.shop_full_order_number) || ((_d = (_c = sales.salesDetail) == null ? void 0 : _c.header) == null ? void 0 : _d.shop_order_number);
    if (fromDetail) return String(fromDetail);
    return fallbackTitle || "";
  }, [sales.tempOrder, sales.salesDetail, fallbackTitle]);
  if (!orderIdLabel) {
    return null;
  }
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)("big-sale-dialog-header-bar", {
        "big-sale-dialog-header-bar--phone": variant === "phone"
      })
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "big-sale-dialog-header-bar__content" }, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "big-sale-dialog-header-bar__order-id",
        title: orderIdLabel
      },
      orderIdLabel
    )),
    /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        type: "button",
        className: "big-sale-dialog-header-bar__close",
        "aria-label": "Close",
        onClick: onClose
      },
      /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-x-close" })
    )
  );
}
function BigSaleDialogBootstrap({
  open,
  openNonce,
  orderId,
  createSeed,
  bookingConfigParams,
  onCreateSeedReady
}) {
  return /* @__PURE__ */ import_react.default.createElement(
    BigSaleDialogLifecycle,
    {
      open,
      openNonce,
      orderId,
      createSeed,
      bookingConfigParams,
      onCreateSeedReady
    }
  );
}
function BigSaleDialog(props) {
  var _a, _b;
  const {
    open,
    orderId,
    createSeed,
    onClose,
    callback,
    rulesHooks,
    title,
    preloaded,
    osKey = "cached-dine-in-dialog",
    mode = "retail",
    businessCode,
    bookingConfigParams,
    productDisplayConfig,
    productLoadParams,
    orderType = "table-order",
    variant,
    openNonce = 0
  } = props;
  const isPhoneVariant = variant === "phone";
  const isEditMode = Boolean(orderId);
  const resolvedFallbackTitle = title || (orderId ? `#${orderId}` : "New Order");
  const bigSaleInstanceKey = (0, import_react.useMemo)(() => `${osKey}-${mode}`, [osKey, mode]);
  const handleClose = (0, import_react.useCallback)(() => {
    callback == null ? void 0 : callback({ type: "close" });
    onClose == null ? void 0 : onClose();
  }, [callback, onClose]);
  const handleOrderComplete = (0, import_react.useCallback)(
    (result) => {
      if (result.reset === false) {
        return;
      }
      callback == null ? void 0 : callback({
        type: result.type,
        data: result.data,
        order_id: result.order_id,
        reset: true
      });
      onClose == null ? void 0 : onClose();
    },
    [callback, onClose]
  );
  const otherParams = (0, import_react.useMemo)(
    () => orderType ? { type: orderType } : void 0,
    [orderType]
  );
  const shouldMountBigSale = preloaded ? true : open;
  const saleDetailHeaderSlot = (0, import_react.useMemo)(() => {
    if (!open) return null;
    return /* @__PURE__ */ import_react.default.createElement(
      BigSaleDialogHeaderBar,
      {
        onClose: handleClose,
        fallbackTitle: resolvedFallbackTitle,
        variant
      }
    );
  }, [open, handleClose, resolvedFallbackTitle, variant]);
  const overlaySlot = null;
  const [createCatalogPhase, setCreateCatalogPhase] = (0, import_react.useState)(0);
  (0, import_react.useEffect)(() => {
    if (!open) {
      setCreateCatalogPhase(0);
    }
  }, [open]);
  (0, import_react.useEffect)(() => {
    if (!isEditMode) {
      setCreateCatalogPhase(0);
    }
  }, [openNonce, (_a = createSeed == null ? void 0 : createSeed.row) == null ? void 0 : _a.id, isEditMode]);
  const handleCreateSeedReady = (0, import_react.useCallback)(() => {
    setCreateCatalogPhase((phase) => phase + 1);
  }, []);
  const productCatalogSessionKey = isEditMode ? `edit-${orderId ?? "new"}` : `create-${openNonce}-${((_b = createSeed == null ? void 0 : createSeed.row) == null ? void 0 : _b.id) ?? "new"}-p${createCatalogPhase}`;
  const bootstrapSlot = (0, import_react.useMemo)(
    () => /* @__PURE__ */ import_react.default.createElement(
      BigSaleDialogBootstrap,
      {
        open,
        openNonce,
        orderId,
        createSeed,
        bookingConfigParams,
        onCreateSeedReady: handleCreateSeedReady
      }
    ),
    [
      open,
      openNonce,
      orderId,
      createSeed,
      bookingConfigParams,
      handleCreateSeedReady
    ]
  );
  return /* @__PURE__ */ import_react.default.createElement(
    import_compensatedPisellContainer.default,
    {
      renderType: isPhoneVariant ? "drawer" : "modal",
      showHandlerBar: false,
      onHandlerBarClick: handleClose,
      props: isPhoneVariant ? {
        open,
        onClose: handleClose,
        placement: "bottom",
        title: void 0,
        width: "100%",
        height: "95%",
        className: "big-sale-dialog-drawer-phone",
        rootClassName: "big-sale-dialog-drawer-phone-root",
        destroyOnClose: false,
        maskClosable: false,
        footer: null,
        closable: false,
        bodyStyle: {
          padding: 0,
          height: "100%",
          position: "relative"
        }
      } : {
        open,
        onCancel: handleClose,
        title: null,
        width: "99%",
        className: "big-sale-dialog-modal",
        destroyOnClose: false,
        header: false,
        maskClosable: false,
        footer: null,
        closeIcon: null,
        wrapClassName: "big-sale-dialog-wrapper",
        size: "large",
        bodyStyle: {
          padding: 0,
          height: "100%",
          position: "relative"
        }
      }
    },
    shouldMountBigSale ? /* @__PURE__ */ import_react.default.createElement(
      import_index.BigSale,
      {
        key: bigSaleInstanceKey,
        osKey,
        mode,
        isActive: open,
        autoCreate: false,
        autoBootstrap: false,
        autoRestoreOnInit: false,
        autoInitBookingContext: false,
        orderId,
        businessCode,
        bookingConfigParams,
        productDisplayConfig,
        productLoadParams,
        productCatalogSessionKey,
        rulesHooks,
        otherParams,
        enableTempOrderPersist: false,
        className: "pisell-big-sale--dialog-host",
        bootstrapSlot,
        saleDetailHeaderSlot,
        overlaySlot,
        onOrderComplete: handleOrderComplete
      }
    ) : null
  );
}
BigSaleDialog.displayName = "BigSaleDialog";
var dialog_default = (0, import_responsive.withResponsive)(BigSaleDialog);
