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/hooks/useSalesSdkTempOrderSync.ts
var useSalesSdkTempOrderSync_exports = {};
__export(useSalesSdkTempOrderSync_exports, {
  useSalesSdkTempOrderSync: () => useSalesSdkTempOrderSync
});
module.exports = __toCommonJS(useSalesSdkTempOrderSync_exports);
var import_react = require("react");
var import_ahooks = require("ahooks");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var TEMP_ORDER_SYNC_MESSAGE_TYPE = "sales_sdk_temp_order_sync";
function createSourceId() {
  return `sales-sdk-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function getPayload(event) {
  var _a, _b;
  const payload = (_b = (_a = event == null ? void 0 : event.data) == null ? void 0 : _a.payload) == null ? void 0 : _b.data;
  if ((payload == null ? void 0 : payload.type) !== TEMP_ORDER_SYNC_MESSAGE_TYPE) return null;
  return payload;
}
function useSalesSdkTempOrderSync({
  enabled,
  isActive = true,
  osKey,
  bookingTicket,
  refreshRootSnapshot
}) {
  var _a, _b, _c, _d, _e;
  const context = (0, import_useEngineContext.default)();
  const app = (_c = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.getApp) == null ? void 0 : _c.call(_b);
  const unifiedCommunication = (_d = app == null ? void 0 : app.getPlugin) == null ? void 0 : _d.call(app, "unifiedCommunication");
  const { runtime } = ((_e = unifiedCommunication == null ? void 0 : unifiedCommunication.useRuntime) == null ? void 0 : _e.call(unifiedCommunication)) || {};
  const isSecondaryScreen = (runtime == null ? void 0 : runtime.role) === "secondary-screen";
  const sourceIdRef = (0, import_react.useRef)(createSourceId());
  const prevIsActiveRef = (0, import_react.useRef)(isActive);
  const { run: debouncedPublish } = (0, import_ahooks.useDebounceFn)(
    async (tempOrder) => {
      var _a2, _b2;
      if (!enabled || isSecondaryScreen || !tempOrder) return;
      try {
        await ((_b2 = (_a2 = unifiedCommunication == null ? void 0 : unifiedCommunication.sdk) == null ? void 0 : _a2.publishData) == null ? void 0 : _b2.call(_a2, {
          target: { type: "secondary-screen" },
          data: {
            type: TEMP_ORDER_SYNC_MESSAGE_TYPE,
            osKey,
            sourceId: sourceIdRef.current,
            timestamp: Date.now(),
            tempOrder
          },
          meta: {}
        }));
      } catch (error) {
        console.warn("[SalesSdk] tempOrder 同步到副屏失败", error);
      }
    },
    { wait: 500, leading: true, trailing: true }
  );
  const publishTempOrder = (0, import_ahooks.useMemoizedFn)((tempOrder) => {
    if (!enabled || isSecondaryScreen || !tempOrder) return;
    debouncedPublish(tempOrder);
  });
  (0, import_react.useEffect)(() => {
    var _a2;
    if (!enabled || isSecondaryScreen) {
      prevIsActiveRef.current = isActive;
      return;
    }
    if (isActive && !prevIsActiveRef.current) {
      const tempOrder = ((_a2 = bookingTicket == null ? void 0 : bookingTicket.getTempOrder) == null ? void 0 : _a2.call(bookingTicket)) ?? null;
      publishTempOrder(tempOrder);
    }
    prevIsActiveRef.current = isActive;
  }, [isActive, enabled, isSecondaryScreen, bookingTicket, publishTempOrder]);
  const { run: debouncedApply } = (0, import_ahooks.useDebounceFn)(
    async (tempOrder) => {
      if (!(bookingTicket == null ? void 0 : bookingTicket.replaceTempOrder)) {
        console.warn("[SalesSdk] 当前 BookingTicket 不支持 replaceTempOrder，已跳过副屏同步");
        return;
      }
      try {
        await bookingTicket.replaceTempOrder(tempOrder);
        refreshRootSnapshot();
      } catch (error) {
        console.warn("[SalesSdk] 副屏应用 tempOrder 同步失败", error);
      }
    },
    { wait: 100 }
  );
  (0, import_react.useEffect)(() => {
    var _a2, _b2;
    if (!enabled || !isSecondaryScreen || !bookingTicket) return;
    const handleMessage = (event) => {
      const payload = getPayload(event);
      if (!payload) return;
      if (payload.osKey !== osKey) return;
      if (payload.sourceId === sourceIdRef.current) return;
      if (!payload.tempOrder) return;
      debouncedApply(payload.tempOrder);
    };
    const listenerHandle = (_b2 = (_a2 = unifiedCommunication == null ? void 0 : unifiedCommunication.sdk) == null ? void 0 : _a2.onMessage) == null ? void 0 : _b2.call(_a2, handleMessage);
    return () => {
      var _a3;
      if (listenerHandle && typeof listenerHandle.then === "function") {
        listenerHandle.then((handle) => {
          var _a4;
          return (_a4 = handle == null ? void 0 : handle.remove) == null ? void 0 : _a4.call(handle);
        }).catch(() => {
        });
      } else {
        (_a3 = listenerHandle == null ? void 0 : listenerHandle.remove) == null ? void 0 : _a3.call(listenerHandle);
      }
    };
  }, [
    enabled,
    isSecondaryScreen,
    bookingTicket,
    osKey,
    debouncedApply,
    unifiedCommunication
  ]);
  return { publishTempOrder, isSecondaryScreen };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useSalesSdkTempOrderSync
});
