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/server/modules/order/index.ts
var order_exports = {};
__export(order_exports, {
  OrderModule: () => OrderModule
});
module.exports = __toCommonJS(order_exports);
var import_lodash_es = require("lodash-es");
var import_dayjs = __toESM(require("dayjs"));
var import_BaseModule = require("../../../modules/BaseModule");
var import_types = require("./types");
var INDEXDB_STORE_NAME = "orders";
var ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY = "server_order_last_full_fetch_at";
var ORDER_SYNC_THROTTLE_MS_STORAGE_KEY = "order_sync_throttle_ms";
var DEFAULT_ORDER_SYNC_THROTTLE_MS = 2e3;
var ORDER_SQLITE_DEDUPE_MS = 15e3;
var ORDER_SILENT_REFRESH_MIN_INTERVAL_MS = 3e4;
var ORDER_BUSINESS_WRITE_SOURCES = /* @__PURE__ */ new Set([
  "upsertOrdersFromRemote",
  "upsertPendingSyncOrders",
  "overwriteExistingOrder",
  "markOrderSyncedByExternalSaleNumber"
]);
var OrderModule = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name, version);
    this.defaultName = "order";
    this.defaultVersion = "1.0.0";
    this.pendingSyncMessages = [];
    this.isProcessingSyncBatch = false;
    this.isIdlePhase = true;
    // Map<resource_id, OrderId[]> 资源到订单的倒排索引
    this.resourceIdIndex = /* @__PURE__ */ new Map();
    this.orderSQLiteSaveQueue = Promise.resolve();
    /** 按 storageKey 记录最近一次 SQLite 写入来源与时间，用于去重 */
    this.recentSqliteWriteByStorageKey = /* @__PURE__ */ new Map();
    /** 最近一次 SSE 全量拉取完成时间 */
    this.lastServerFullFetchAtMs = 0;
  }
  /**
   * 广播订单变更事件，兼容全量列表订阅并额外携带本次变更订单。
   *
   * @example
   * await this.emitOrdersChanged([freshOrder], 'pubsub.bodyUpsert')
   */
  async emitOrdersChanged(changedOrders = [], source) {
    const payload = {
      list: this.store.list,
      changedOrders: changedOrders.map((order) => this.normalizeOrderForMemoryList(order)),
      source
    };
    await this.core.effects.emit(import_types.OrderHooks.onOrdersChanged, payload);
  }
  async initialize(core, options) {
    var _a, _b;
    this.core = core;
    this.store = options == null ? void 0 : options.store;
    if (!this.store.map)
      this.store.map = /* @__PURE__ */ new Map();
    const appPlugin = core.getPlugin("app");
    const app = appPlugin == null ? void 0 : appPlugin.getApp();
    if (app) {
      this.dbManager = app.sqlite;
      this.logger = app.logger;
      this.storage = app.storage;
      const coreData = app.data.store.getStore().getDataByModel("core");
      if (!((_a = this.store.createdAtQuery) == null ? void 0 : _a.sales_time_between) && (coreData == null ? void 0 : coreData.core)) {
        const today = (0, import_dayjs.default)();
        if (coreData == null ? void 0 : coreData.core.operating_day_boundary) {
          const operatingDayBoundary = coreData.core.operating_day_boundary;
          if (operatingDayBoundary.type === "start_time") {
            const boundaryTime = String(operatingDayBoundary.time || "").trim();
            const boundaryStart = (0, import_dayjs.default)(`${today.format("YYYY-MM-DD")} ${boundaryTime}`);
            if (boundaryStart.isValid()) {
              const isAfterBoundary = today.isAfter(boundaryStart);
              const queryStart = isAfterBoundary ? today.startOf("day") : today.subtract(1, "day").startOf("day");
              const queryEnd = isAfterBoundary ? today.add(1, "day").endOf("day") : today.endOf("day");
              this.store.createdAtQuery = {
                sales_time_between: [
                  queryStart.format("YYYY-MM-DD HH:mm:ss"),
                  queryEnd.format("YYYY-MM-DD HH:mm:ss")
                ]
              };
            } else {
              this.store.createdAtQuery = {
                sales_time_between: [
                  today.startOf("day").format("YYYY-MM-DD HH:mm:ss"),
                  today.endOf("day").format("YYYY-MM-DD HH:mm:ss")
                ]
              };
            }
          } else {
            this.store.createdAtQuery = {
              sales_time_between: [
                today.startOf("day").format("YYYY-MM-DD HH:mm:ss"),
                today.endOf("day").format("YYYY-MM-DD HH:mm:ss")
              ]
            };
          }
        } else {
          this.store.createdAtQuery = {
            sales_time_between: [today.startOf("day").format("YYYY-MM-DD HH:mm:ss"), today.endOf("day").format("YYYY-MM-DD HH:mm:ss")]
          };
        }
      }
    }
    if (Array.isArray((_b = options == null ? void 0 : options.initialState) == null ? void 0 : _b.list)) {
      this.store.list = options.initialState.list.map((order) => this.normalizeOrderForMemoryList(order));
      this.syncOrdersMap();
      this.emitOrdersChanged([], "initialState");
    } else {
      this.store.list = [];
      this.store.map = /* @__PURE__ */ new Map();
    }
    this.initOrderDataSource();
    this.setupOrderSync();
    this.logInfo("OrderServer模块初始化完成", {
      hasDbManager: !!this.dbManager,
      hasLogger: !!this.logger,
      initialOrderCount: this.store.list.length
    });
  }
  /**
  * 记录信息日志
  * @param title 日志标题
  * @param metadata 日志元数据
  */
  logInfo(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "info",
          title: `[OrderServerModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
  /**
   * 记录错误日志
   * @param title 日志标题
   * @param metadata 日志元数据
   */
  logError(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "error",
          title: `[OrderServerModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
  /**
   * 记录订单最近一次 SQLite 写入，供 pubsub 回声去重使用。
   *
   * @example
   * this.recordRecentSqliteWrite('upsertOrdersFromRemote', orders)
   */
  recordRecentSqliteWrite(source, orders) {
    const now = Date.now();
    for (const order of orders) {
      const storageKey = this.getOrderStorageKey(order);
      if (!storageKey)
        continue;
      this.recentSqliteWriteByStorageKey.set(storageKey, { source, ts: now });
    }
  }
  /**
   * 过滤 pubsub 触发的冗余 SQLite patch（业务 API 刚写入过的 update 回声）。
   *
   * @example
   * const { toWrite, skipped } = this.filterRedundantPatchOrders('pubsub.bodyUpsert', orders, mergeActions)
   */
  filterRedundantPatchOrders(source, orders, mergeActions) {
    const eligibleSkipSources = /* @__PURE__ */ new Set(["pubsub.bodyUpsert", "pubsub.httpRefresh"]);
    if (!eligibleSkipSources.has(source)) {
      return { toWrite: orders, skipped: [] };
    }
    const now = Date.now();
    const toWrite = [];
    const skipped = [];
    for (const order of orders) {
      const storageKey = this.getOrderStorageKey(order);
      if (!storageKey) {
        toWrite.push(order);
        continue;
      }
      const orderKey = order.order_id !== void 0 && order.order_id !== null ? this.getIdKey(order.order_id) : "";
      const mergeAction = orderKey ? mergeActions[orderKey] : void 0;
      if (mergeAction === "insert") {
        toWrite.push(order);
        continue;
      }
      const recent = this.recentSqliteWriteByStorageKey.get(storageKey);
      if (recent && ORDER_BUSINESS_WRITE_SOURCES.has(recent.source) && now - recent.ts < ORDER_SQLITE_DEDUPE_MS) {
        skipped.push({
          orderId: order.order_id ?? null,
          storageKey,
          reason: "skip_pubsub_echo_after_business_write",
          lastSource: recent.source,
          elapsedMs: now - recent.ts
        });
        continue;
      }
      toWrite.push(order);
    }
    return { toWrite, skipped };
  }
  /**
   * 过滤 pubsub HTTP 增量拉取 ids：本地刚由业务 API 写入的单可跳过 HTTP。
   *
   * @example
   * const ids = this.filterRedundantHttpRefreshIds([99331, 99332])
   */
  filterRedundantHttpRefreshIds(ids) {
    const now = Date.now();
    const toFetch = [];
    const skipped = [];
    for (const id of ids) {
      const existing = this.getOrderByOrderId(id);
      if (!existing) {
        toFetch.push(id);
        continue;
      }
      const storageKey = this.getOrderStorageKey(existing);
      const recent = storageKey ? this.recentSqliteWriteByStorageKey.get(storageKey) : void 0;
      if (recent && recent.source === "upsertOrdersFromRemote" && now - recent.ts < ORDER_SQLITE_DEDUPE_MS) {
        skipped.push({
          orderId: id,
          lastSource: recent.source,
          elapsedMs: now - recent.ts
        });
        continue;
      }
      toFetch.push(id);
    }
    return { toFetch, skipped };
  }
  /**
   * 解析 pubsub 消息会走哪条同步分支，便于对照为何触发 HTTP 重拉或 body 直写。
   *
   * @example
   * this.resolveSyncMessageRoute(msg)
   * // => { route: 'httpRefresh.batchIds', ... }
   */
  resolveSyncMessageRoute(msg) {
    var _a;
    const hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
    const singleIdRaw = msg.id ?? msg.order_id;
    const hasSingleId = !hasBatchIds && singleIdRaw !== void 0 && singleIdRaw !== null;
    const normalizedBody = this.normalizeOrderSyncPayload(msg.body || msg.data);
    if (hasBatchIds) {
      return {
        route: "httpRefresh.batchIds",
        hasBatchIds: true,
        hasSingleId: false,
        hasNormalizedBody: !!normalizedBody,
        singleId: null,
        batchIds: msg.ids || [],
        bodyOrderId: (normalizedBody == null ? void 0 : normalizedBody.order_id) ?? null
      };
    }
    if (hasSingleId && normalizedBody) {
      return {
        route: "bodyUpsert",
        hasBatchIds: false,
        hasSingleId: true,
        hasNormalizedBody: true,
        singleId: singleIdRaw,
        batchIds: [],
        bodyOrderId: normalizedBody.order_id ?? null
      };
    }
    if (hasSingleId) {
      return {
        route: "httpRefresh.singleId",
        hasBatchIds: false,
        hasSingleId: true,
        hasNormalizedBody: !!normalizedBody,
        singleId: singleIdRaw,
        batchIds: [],
        bodyOrderId: (normalizedBody == null ? void 0 : normalizedBody.order_id) ?? null
      };
    }
    if ((_a = msg.relation_order_ids) == null ? void 0 : _a.length) {
      return {
        route: "httpRefresh.relationIds",
        hasBatchIds: false,
        hasSingleId: false,
        hasNormalizedBody: !!normalizedBody,
        singleId: null,
        batchIds: msg.relation_order_ids,
        bodyOrderId: (normalizedBody == null ? void 0 : normalizedBody.order_id) ?? null
      };
    }
    return {
      route: "noop",
      hasBatchIds: false,
      hasSingleId: false,
      hasNormalizedBody: !!normalizedBody,
      singleId: null,
      batchIds: [],
      bodyOrderId: (normalizedBody == null ? void 0 : normalizedBody.order_id) ?? null
    };
  }
  getOrderSyncThrottleMs() {
    const raw = localStorage.getItem(ORDER_SYNC_THROTTLE_MS_STORAGE_KEY);
    if (raw !== null) {
      const parsed = Number(raw);
      if (Number.isFinite(parsed) && parsed >= 0)
        return parsed;
    }
    return DEFAULT_ORDER_SYNC_THROTTLE_MS;
  }
  async preload() {
    const getData = async () => {
      const orders = await this.loadOrdersByServer();
      if (orders.length === 0) {
        return;
      }
      this.store.list = (0, import_lodash_es.cloneDeep)(orders);
      this.syncOrdersMap();
      this.emitOrdersChanged([], "preload");
      this.core.effects.emit(import_types.OrderHooks.onOrdersSyncCompleted, null);
    };
    getData();
  }
  getOrders() {
    return this.store.list;
  }
  getOrderById(id) {
    return this.store.map.get(this.getIdKey(id));
  }
  /** 按 order_id 查询内存订单。 */
  getOrderByOrderId(orderId) {
    return this.store.map.get(this.getIdKey(orderId));
  }
  async getLocalOrderByLookup(lookup) {
    const key = this.getIdKey(lookup);
    const memoryOrderById = this.store.map.get(key);
    if (memoryOrderById)
      return memoryOrderById;
    const memoryOrder = this.store.list.find((order) => this.isOrderLookupMatch(order, key));
    if (memoryOrder)
      return memoryOrder;
    const orders = await this.loadOrdersFromSQLite();
    const localOrder = orders.find((order) => this.isOrderLookupMatch(order, key));
    if (!localOrder)
      return null;
    this.store.list = orders.map((order) => this.normalizeOrderForMemoryList(order));
    this.syncOrdersMap();
    return this.normalizeOrderForMemoryList(localOrder);
  }
  async loadOrdersByServer() {
    var _a;
    let orderList = [];
    this.logInfo("loadOrdersByServer-开始", {
      hasOrderDataSource: !!this.orderDataSource,
      query: ((_a = this.store) == null ? void 0 : _a.createdAtQuery) || null
    });
    if (this.orderDataSource) {
      try {
        const data = await this.orderDataSource.run({
          sse: {
            query: this.store.createdAtQuery
          }
        });
        orderList = data || [];
        this.logInfo("loadOrdersByServer-SSE拉取成功", {
          count: orderList.length
        });
        this.markOrderPulledAtNow();
        this.lastServerFullFetchAtMs = Date.now();
      } catch {
        this.logInfo("loadOrdersByServer-SSE拉取失败，保持当前内存订单");
        return this.store.list;
      }
    }
    const mergedOrders = await this.replaceOrdersSnapshotInSQLite(orderList, "loadOrdersByServer");
    const memoryOrders = mergedOrders.map((order) => this.normalizeOrderForMemoryList(order));
    this.logInfo("loadOrdersByServer-结束", {
      count: memoryOrders.length
    });
    await this.core.effects.emit(import_types.OrderHooks.onOrdersLoaded, memoryOrders);
    return memoryOrders;
  }
  /**
   * 静默全量刷新：后台重新拉取全量 SSE 订单数据并更新本地
   * 拿到完整数据后一次性替换 store，触发订单变更与同步完成事件
   * @returns 刷新后的订单列表
   */
  async silentRefresh() {
    const startTime = Date.now();
    const elapsedSinceFullFetch = Date.now() - this.lastServerFullFetchAtMs;
    if (this.lastServerFullFetchAtMs > 0 && elapsedSinceFullFetch < ORDER_SILENT_REFRESH_MIN_INTERVAL_MS) {
      return this.store.list;
    }
    this.logInfo("silentRefresh 开始");
    try {
      const orders = await this.loadOrdersByServer();
      if (orders.length > 0) {
        this.store.list = (0, import_lodash_es.cloneDeep)(orders);
        this.syncOrdersMap();
        this.emitOrdersChanged([], "silentRefresh");
        await this.core.effects.emit(import_types.OrderHooks.onOrdersSyncCompleted, null);
        this.logInfo("silentRefresh 完成", {
          orderCount: orders.length,
          duration: `${Date.now() - startTime}ms`
        });
      } else {
        this.logInfo("silentRefresh: 服务器未返回数据");
      }
      return this.store.list;
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      this.logError("silentRefresh 失败", {
        duration: `${Date.now() - startTime}ms`,
        error: errorMessage
      });
      return this.store.list;
    }
  }
  getOrdersByResourceId(resourceId) {
    const ids = this.resourceIdIndex.get(String(resourceId)) || [];
    return ids.map((id) => this.store.map.get(id)).filter((order) => !!order);
  }
  normalizeOrderForMemoryList(order) {
    const externalSaleNumber = order == null ? void 0 : order.external_sale_number;
    if ((order == null ? void 0 : order.order_id) !== void 0 && (order == null ? void 0 : order.order_id) !== null && (order == null ? void 0 : order.order_id) !== "") {
      return order;
    }
    if (externalSaleNumber === void 0 || externalSaleNumber === null || externalSaleNumber === "") {
      return order;
    }
    return {
      ...order,
      order_id: externalSaleNumber
    };
  }
  /**
   * 仅覆盖本地已存在的订单；不存在则直接跳过，不落库、不 emit。
   * 适用于"按 order_id 主动刷新本地订单详情"的代理场景。
   */
  async overwriteExistingOrder(fresh) {
    const orderId = fresh == null ? void 0 : fresh.order_id;
    if (orderId === void 0 || orderId === null) {
      this.logError("overwriteExistingOrder-入参缺少 order_id");
      return { overwritten: false };
    }
    const key = this.getIdKey(orderId);
    if (!this.store.map.has(key)) {
      this.logInfo("overwriteExistingOrder-本地不存在该订单，跳过", { orderId });
      return { overwritten: false };
    }
    this.logInfo("overwriteExistingOrder-开始覆盖", {
      orderId,
      storeOrderCountBefore: this.store.list.length
    });
    this.store.list = this.store.list.map((order) => {
      const id = order == null ? void 0 : order.order_id;
      if (id === void 0 || id === null)
        return order;
      return this.getIdKey(id) === key ? fresh : order;
    });
    this.syncOrdersMap();
    await this.updateOrderInSQLite(fresh, "overwriteExistingOrder");
    this.logInfo("overwriteExistingOrder-结束", {
      orderId,
      storeOrderCountAfter: this.store.list.length
    });
    await this.emitOrdersChanged([fresh], "overwriteExistingOrder");
    return { overwritten: true };
  }
  /**
   * 将远端拉取的订单合并进本地 store（已存在则更新，不存在则追加），落库并 emit onOrdersChanged。
   * 供 /update/localOrder 等在「本地尚无该单」时写入新建单。
   */
  async upsertOrdersFromRemote(freshOrders) {
    if (!(freshOrders == null ? void 0 : freshOrders.length)) {
      this.logInfo("upsertOrdersFromRemote-订单列表为空", {});
      return;
    }
    this.logInfo("upsertOrdersFromRemote-开始", { count: freshOrders.length });
    await this.mergeOrdersToStore(freshOrders, "upsertOrdersFromRemote");
  }
  async markOrderSyncedByExternalSaleNumber(params) {
    const externalSaleNumber = params.externalSaleNumber;
    if (externalSaleNumber === void 0 || externalSaleNumber === null || externalSaleNumber === "") {
      this.logError("markOrderSyncedByExternalSaleNumber-缺少 external_sale_number");
      return { updated: false };
    }
    const key = this.getIdKey(externalSaleNumber);
    const targetIndex = this.store.list.findIndex((order) => {
      const value = order == null ? void 0 : order.external_sale_number;
      if (value === void 0 || value === null || value === "")
        return false;
      return this.getIdKey(value) === key;
    });
    if (targetIndex < 0) {
      this.logInfo("markOrderSyncedByExternalSaleNumber-本地订单不存在，跳过", {
        external_sale_number: externalSaleNumber
      });
      return { updated: false };
    }
    const existing = this.store.list[targetIndex];
    const nextOrder = this.normalizeRemoteSyncedOrder({
      ...existing,
      ...params.patch || {},
      external_sale_number: existing.external_sale_number ?? externalSaleNumber,
      need_sync: 0
    });
    const storageKey = this.getOrderStorageKey(nextOrder) || key;
    this.store.list = this.store.list.map((order, index) => {
      if (index !== targetIndex)
        return order;
      return nextOrder;
    });
    this.syncOrdersMap();
    await this.patchOrdersInSQLite(
      [nextOrder],
      "markOrderSyncedByExternalSaleNumber",
      { [storageKey]: "update" }
    );
    this.logInfo("markOrderSyncedByExternalSaleNumber-完成", {
      external_sale_number: externalSaleNumber,
      order_id: nextOrder.order_id ?? null
    });
    await this.emitOrdersChanged([nextOrder], "markOrderSyncedByExternalSaleNumber");
    return { updated: true, order: nextOrder };
  }
  /**
   * 将本地待同步订单按 SQLite storage key 合并进 store 并落库。
   * checkout 离线兜底可能没有 order_id，但通常会有 external_sale_number。
   */
  async upsertPendingSyncOrders(pendingOrders) {
    if (!(pendingOrders == null ? void 0 : pendingOrders.length)) {
      this.logInfo("upsertPendingSyncOrders-订单列表为空", {});
      return;
    }
    const pendingMap = /* @__PURE__ */ new Map();
    const memoryPendingMap = /* @__PURE__ */ new Map();
    for (const order of pendingOrders) {
      const storageKey = this.getOrderStorageKey(order);
      if (!storageKey)
        continue;
      pendingMap.set(storageKey, order);
      memoryPendingMap.set(storageKey, this.normalizeOrderForMemoryList(order));
    }
    if (pendingMap.size === 0) {
      this.logError("upsertPendingSyncOrders-订单缺少可落库标识", {
        count: pendingOrders.length
      });
      return;
    }
    this.logInfo("upsertPendingSyncOrders-开始", { count: pendingMap.size });
    const patchedOrders = [...pendingMap.values()];
    const mergeActions = {};
    const updatedList = this.store.list.map((order) => {
      const storageKey = this.getOrderStorageKey(order);
      if (!storageKey || !pendingMap.has(storageKey))
        return order;
      const pendingOrder = memoryPendingMap.get(storageKey);
      pendingMap.delete(storageKey);
      memoryPendingMap.delete(storageKey);
      mergeActions[storageKey] = "update";
      return pendingOrder;
    });
    for (const [storageKey, order] of memoryPendingMap.entries()) {
      mergeActions[storageKey] = "insert";
      updatedList.push(order);
    }
    this.store.list = updatedList;
    this.syncOrdersMap();
    await this.patchOrdersInSQLite(patchedOrders, "upsertPendingSyncOrders", mergeActions);
    this.logInfo("upsertPendingSyncOrders-结束", {
      count: patchedOrders.length,
      storeOrderCountAfter: this.store.list.length
    });
    this.emitOrdersChanged(patchedOrders, "upsertPendingSyncOrders");
    await this.core.effects.emit(import_types.OrderHooks.onOrdersChanged, {
      list: this.store.list,
      changedOrders: patchedOrders.map((order) => this.normalizeOrderForMemoryList(order)),
      source: "upsertPendingSyncOrders"
    });
  }
  /**
   * 通过 SSE 按自定义 query 拉取订单（支持 select/with 精简字段）
   */
  async fetchOrdersBySSE(query = {}) {
    if (!this.orderDataSource)
      return [];
    try {
      const data = await this.orderDataSource.run({ sse: { query } });
      return data || [];
    } catch (error) {
      this.logError("fetchOrdersBySSE-失败", {
        error: error instanceof Error ? error.message : String(error)
      });
      return [];
    }
  }
  getRoutes() {
    return [];
  }
  destroy() {
    var _a;
    if (this.syncTimer) {
      clearTimeout(this.syncTimer);
      this.syncTimer = void 0;
    }
    this.isProcessingSyncBatch = false;
    this.pendingSyncMessages = [];
    if ((_a = this.orderDataSource) == null ? void 0 : _a.destroy)
      this.orderDataSource.destroy();
    super.destroy();
  }
  syncOrdersMap() {
    this.store.map.clear();
    this.resourceIdIndex.clear();
    for (const order of this.store.list) {
      const identityKeys = this.getOrderIdentityKeys(order);
      if (identityKeys.length === 0)
        continue;
      for (const identityKey of identityKeys) {
        this.store.map.set(identityKey, order);
      }
      const resourceIds = this.extractResourceIds(order);
      const primaryIdentity = identityKeys[0];
      for (const resourceId of resourceIds) {
        const key = String(resourceId);
        const existing = this.resourceIdIndex.get(key) || [];
        if (existing.some((eid) => this.getIdKey(eid) === primaryIdentity))
          continue;
        existing.push(primaryIdentity);
        this.resourceIdIndex.set(key, existing);
      }
    }
  }
  getOrderIdentityKeys(order) {
    const keys = [];
    const id = order.order_id;
    if (id !== void 0 && id !== null && id !== "") {
      keys.push(this.getIdKey(id));
    }
    const externalSaleNumber = order == null ? void 0 : order.external_sale_number;
    if (externalSaleNumber !== void 0 && externalSaleNumber !== null && externalSaleNumber !== "") {
      const externalKey = this.getIdKey(externalSaleNumber);
      if (!keys.includes(externalKey))
        keys.push(externalKey);
    }
    return keys;
  }
  extractResourceIds(order) {
    const ids = /* @__PURE__ */ new Set();
    const visitResources = (resources) => {
      if (!Array.isArray(resources))
        return;
      resources.forEach((resource) => {
        const rid = resource == null ? void 0 : resource.relation_id;
        if (rid !== void 0 && rid !== null && rid !== "")
          ids.add(String(rid));
        if (Array.isArray(resource == null ? void 0 : resource.children))
          visitResources(resource.children);
      });
    };
    if (Array.isArray(order == null ? void 0 : order.bookings)) {
      order.bookings.forEach((booking) => visitResources((booking == null ? void 0 : booking.resources) || []));
    }
    return [...ids];
  }
  getOrderDateKey(order) {
    var _a, _b, _c, _d;
    const candidates = [
      order == null ? void 0 : order.schedule_date,
      order == null ? void 0 : order.create_date,
      order == null ? void 0 : order.created_at,
      (_b = (_a = order == null ? void 0 : order.bookings) == null ? void 0 : _a[0]) == null ? void 0 : _b.start_date,
      (_d = (_c = order == null ? void 0 : order.bookings) == null ? void 0 : _c[0]) == null ? void 0 : _d.select_date
    ];
    for (const v of candidates) {
      if (!v)
        continue;
      const text = String(v);
      if (!text)
        continue;
      return text.split("T")[0].split(" ")[0];
    }
    return void 0;
  }
  /**
   * 初始化 OrderDataSource 实例
   */
  initOrderDataSource() {
    var _a, _b;
    const OrderDataSourceClass = (_b = (_a = this.core.serverOptions) == null ? void 0 : _a.All_DATA_SOURCES) == null ? void 0 : _b.OrderDataSource;
    if (!OrderDataSourceClass)
      return;
    this.orderDataSource = new OrderDataSourceClass();
  }
  /**
   * 初始化 pubsub 订阅，监听订单变更（纯订阅，不拉数据；全量 SSE 由 loadOrdersByServer 负责）
   */
  setupOrderSync() {
    if (!this.orderDataSource)
      return;
    this.orderDataSource.run({
      pubsub: {
        callback: (res) => {
          console.log("orderDataSource", res);
          const pubsubReceivedAt = Date.now();
          const message = this.normalizeOrderSyncMessage(res);
          if (!message)
            return;
          message._pubsubReceivedAt = pubsubReceivedAt;
          this.pendingSyncMessages.push(message);
          const throttleMs = this.getOrderSyncThrottleMs();
          const routeInfo = this.resolveSyncMessageRoute(message);
          this.logInfo("orderSync-收到消息并入队", {
            id: message.id ?? null,
            order_id: message.order_id ?? null,
            type: message.type ?? null,
            pendingCount: this.pendingSyncMessages.length,
            throttleMs,
            pubsubReceivedAt: new Date(pubsubReceivedAt).toISOString()
          });
          this.scheduleOrderSyncThrottle();
        }
      }
    }).catch(() => {
    });
  }
  /**
   * 调度订单同步节流窗口（leading-edge throttle）：
   * - 空闲状态下收到的第一条消息立即触发批处理，无需等待；
   * - 首条处理后进入冷却窗口，窗口期间的后续消息聚合，窗口结束后批量处理；
   * - 若当前批处理执行中，则由批处理结束后决定是否开启下一轮窗口。
   */
  scheduleOrderSyncThrottle() {
    if (this.isProcessingSyncBatch)
      return;
    if (this.isIdlePhase) {
      this.isIdlePhase = false;
      this.logInfo("orderSync-首条消息立即触发处理");
      void this.flushOrderSyncMessagesByThrottle();
      return;
    }
    if (this.syncTimer)
      return;
    const throttleMs = this.getOrderSyncThrottleMs();
    this.syncTimer = setTimeout(() => {
      this.syncTimer = void 0;
      void this.flushOrderSyncMessagesByThrottle();
    }, throttleMs);
  }
  /**
   * 执行一次节流批处理并在需要时续约下一轮窗口。
   * 批处理完成且无后续消息时恢复空闲状态，下一条消息将立即触发。
   */
  async flushOrderSyncMessagesByThrottle() {
    if (this.isProcessingSyncBatch)
      return;
    if (this.pendingSyncMessages.length === 0) {
      this.isIdlePhase = true;
      return;
    }
    this.isProcessingSyncBatch = true;
    try {
      await this.processOrderSyncMessages();
    } finally {
      this.isProcessingSyncBatch = false;
      if (this.pendingSyncMessages.length > 0) {
        this.scheduleOrderSyncThrottle();
      } else {
        this.isIdlePhase = true;
      }
    }
  }
  /**
   * 处理节流窗口内聚合后的同步消息批次
   *
   * 后端统一发送 change 消息，不再区分新增/编辑/删除。
   * - 单条（id/order_id）：若携带 body/data 则直接 upsert 到本地
   * - 批量（ids）：通过 HTTP 按 ids 增量拉取，再 merge 到本地
   *
   * @example
   * // pending 队列中存在 8 条消息时，仅处理一次批次并统一 merge
   * await this.processOrderSyncMessages()
   */
  async processOrderSyncMessages() {
    const messages = [...this.pendingSyncMessages];
    this.pendingSyncMessages = [];
    if (messages.length === 0)
      return;
    const batchProcessStartAt = Date.now();
    const earliestReceivedAt = Math.min(
      ...messages.map((m) => m._pubsubReceivedAt ?? batchProcessStartAt)
    );
    this.logInfo("processOrderSyncMessages-开始", {
      messageCount: messages.length,
      earliestReceivedAt: new Date(earliestReceivedAt).toISOString(),
      batchProcessStartAt: new Date(batchProcessStartAt).toISOString(),
      waitDurationMs: batchProcessStartAt - earliestReceivedAt
    });
    const upsertOrders = /* @__PURE__ */ new Map();
    const refreshIds = [];
    messages.forEach((msg, msgIndex) => {
      const routeInfo = this.resolveSyncMessageRoute(msg);
      const hasBatchIds = routeInfo.hasBatchIds;
      const singleId = routeInfo.singleId;
      const hasSingleId = routeInfo.hasSingleId;
      const normalizedBody = this.normalizeOrderSyncPayload(msg.body || msg.data);
      if (routeInfo.route === "bodyUpsert" && normalizedBody) {
        upsertOrders.set(this.getIdKey(normalizedBody.order_id), normalizedBody);
        return;
      }
      if (hasBatchIds)
        refreshIds.push(...routeInfo.batchIds);
      else if (routeInfo.route === "httpRefresh.singleId" && singleId !== null)
        refreshIds.push(singleId);
      else if (routeInfo.route === "httpRefresh.relationIds")
        refreshIds.push(...routeInfo.batchIds);
    });
    const uniqueRefreshIds = this.uniqueOrderIds(refreshIds);
    const upsertList = [...upsertOrders.values()];
    this.logInfo("processOrderSyncMessages-去重完成", {
      upsertCount: upsertList.length,
      refreshIdCount: uniqueRefreshIds.length
    });
    if (upsertList.length > 0) {
      await this.mergeOrdersToStore(upsertList, "pubsub.bodyUpsert");
    }
    if (uniqueRefreshIds.length > 0) {
      const { toFetch, skipped } = this.filterRedundantHttpRefreshIds(uniqueRefreshIds);
      if (skipped.length > 0) {
      }
      if (toFetch.length > 0) {
        const freshOrders = await this.fetchOrdersByHttp(toFetch);
        if (freshOrders.length > 0) {
          await this.mergeOrdersToStore(freshOrders, "pubsub.httpRefresh");
        } else {
        }
      }
    }
    if (upsertList.length === 0 && uniqueRefreshIds.length === 0) {
      return;
    }
    const batchProcessEndAt = Date.now();
    this.logInfo("processOrderSyncMessages-结束", {
      upsertCount: upsertList.length,
      refreshIdCount: uniqueRefreshIds.length,
      batchProcessDurationMs: batchProcessEndAt - batchProcessStartAt,
      totalFromPubsubToProcessedMs: batchProcessEndAt - earliestReceivedAt
    });
    await this.core.effects.emit(import_types.OrderHooks.onOrdersSyncCompleted, null);
  }
  /**
   * 通过 HTTP 按 ids 批量拉取订单详情（走 orderDataSource）。
   *
   * - 优先使用 `orderDataSource.fetchOrdersByIds`（如适配器实现了该方法）
   * - 否则回退到 `orderDataSource.run({ http: { query: { ids } } })`
   * - 失败统一返回空数组（由调用方按"返回缺失的 id" 判断单笔失败）
   *
   * @example
   * const fresh = await orderModule.fetchOrdersByHttp(['96971', '96972'])
   */
  async fetchOrdersByHttp(ids) {
    if (!this.orderDataSource || ids.length === 0)
      return [];
    try {
      if (typeof this.orderDataSource.fetchOrdersByIds === "function") {
        const orderList2 = await this.orderDataSource.fetchOrdersByIds(ids);
        return orderList2 || [];
      }
      const orderList = await this.orderDataSource.run({
        http: {
          query: { ids }
        }
      });
      return orderList || [];
    } catch {
      return [];
    }
  }
  /**
   * 将增量订单合并到 store
   */
  async mergeOrdersToStore(freshOrders, source) {
    this.logInfo("mergeOrdersToStore-开始", {
      freshOrderCount: freshOrders.length,
      storeOrderCountBefore: this.store.list.length
    });
    const freshMap = /* @__PURE__ */ new Map();
    for (const order of freshOrders) {
      const id = order == null ? void 0 : order.order_id;
      if (id === void 0 || id === null)
        continue;
      freshMap.set(this.getIdKey(id), this.normalizeRemoteSyncedOrder(order));
    }
    const freshStorageKeyMap = /* @__PURE__ */ new Map();
    for (const order of freshMap.values()) {
      const storageKey = this.getOrderStorageKey(order);
      if (!storageKey)
        continue;
      freshStorageKeyMap.set(storageKey, order);
    }
    const uniqueFreshCount = freshMap.size;
    const patchedOrders = [...freshMap.values()];
    const mergeActions = {};
    const updatedList = this.store.list.map((order) => {
      const storageKey = this.getOrderStorageKey(order);
      if (storageKey && freshStorageKeyMap.has(storageKey)) {
        const fresh2 = freshStorageKeyMap.get(storageKey);
        freshStorageKeyMap.delete(storageKey);
        const freshId = fresh2.order_id;
        if (freshId !== void 0 && freshId !== null) {
          freshMap.delete(this.getIdKey(freshId));
          mergeActions[this.getIdKey(freshId)] = "update";
        } else {
          mergeActions[storageKey] = "update";
        }
        return fresh2;
      }
      const id = order.order_id;
      if (id === void 0 || id === null)
        return order;
      const key = this.getIdKey(id);
      if (!freshMap.has(key))
        return order;
      const fresh = freshMap.get(key);
      freshMap.delete(key);
      mergeActions[key] = "update";
      return fresh;
    });
    for (const order of freshMap.values()) {
      const id = order.order_id;
      if (id !== void 0 && id !== null) {
        mergeActions[this.getIdKey(id)] = "insert";
      }
      updatedList.push(order);
    }
    const insertCount = Object.values(mergeActions).filter((v) => v === "insert").length;
    const updateCount = Object.values(mergeActions).filter((v) => v === "update").length;
    this.store.list = updatedList;
    this.syncOrdersMap();
    await this.patchOrdersInSQLite(patchedOrders, source, mergeActions);
    this.logInfo("mergeOrdersToStore-结束", {
      uniqueFreshCount,
      storeOrderCountAfter: this.store.list.length
    });
    this.emitOrdersChanged(patchedOrders, source);
  }
  normalizeOrderSyncMessage(res) {
    const data = (res == null ? void 0 : res.data) || res;
    if (!data)
      return null;
    const payload = (data == null ? void 0 : data.data) && typeof data.data === "object" ? data.data : void 0;
    const normalized = {
      ...data,
      _channelKey: data.module || "sales_sync"
    };
    if (!normalized.type && typeof data.event === "string")
      normalized.type = data.event;
    if (!normalized.id && data.id !== void 0)
      normalized.id = data.id;
    if (!normalized.id && data.order_id !== void 0)
      normalized.id = data.order_id;
    if (!normalized.order_id && data.order_id !== void 0)
      normalized.order_id = data.order_id;
    if (!normalized.order_id && (payload == null ? void 0 : payload.order_id) !== void 0)
      normalized.order_id = payload.order_id;
    if (!normalized.body && (payload == null ? void 0 : payload.order_id) !== void 0)
      normalized.body = payload;
    if (!normalized.data && (payload == null ? void 0 : payload.order_id) !== void 0)
      normalized.data = payload;
    return normalized;
  }
  normalizeOrderSyncPayload(payload) {
    if (!payload)
      return null;
    const orderId = payload.order_id;
    if (orderId === void 0 || orderId === null)
      return null;
    return { ...payload, order_id: orderId };
  }
  uniqueOrderIds(ids) {
    const idMap = /* @__PURE__ */ new Map();
    for (const id of ids) {
      idMap.set(this.getIdKey(id), id);
    }
    return [...idMap.values()];
  }
  getIdKey(id) {
    return String(id);
  }
  isOrderLookupMatch(order, lookupKey) {
    if (!order || !lookupKey)
      return false;
    const candidates = [
      order.order_id,
      order.external_sale_number,
      order.order_number,
      order.shop_order_number,
      order.shop_full_order_number
    ];
    return candidates.some((value) => {
      if (value === void 0 || value === null || value === "")
        return false;
      return this.getIdKey(value) === lookupKey;
    });
  }
  /**
   * 解析订单 SQLite 主键，规则与宿主 OrderDataSource.getOrderStorageKey 一致。
   *
   * @example
   * const key = this.getOrderStorageKey({ order_id: 1001, external_sale_number: 'S-1001' })
   * // => 'S-1001'
   */
  getOrderStorageKey(order) {
    const externalSaleNumber = order == null ? void 0 : order.external_sale_number;
    if (externalSaleNumber !== void 0 && externalSaleNumber !== null && externalSaleNumber !== "") {
      return String(externalSaleNumber);
    }
    const orderId = order == null ? void 0 : order.order_id;
    if (orderId !== void 0 && orderId !== null && orderId !== "") {
      return String(orderId);
    }
    return "";
  }
  /**
   * 当前订单拉取窗口：
   * - 优先使用 createdAtQuery.sales_time_between（已按营业日边界初始化）
   * - 无法解析时退化为自然日窗口
   */
  getCurrentPullWindow() {
    var _a, _b;
    const now = (0, import_dayjs.default)();
    const range = (_b = (_a = this.store) == null ? void 0 : _a.createdAtQuery) == null ? void 0 : _b.sales_time_between;
    if (Array.isArray(range) && range.length >= 2) {
      const startAt2 = (0, import_dayjs.default)(range[0]);
      const endExclusiveAt = (0, import_dayjs.default)(range[1]);
      if (startAt2.isValid() && endExclusiveAt.isValid() && endExclusiveAt.isAfter(startAt2)) {
        return { startAt: startAt2, endExclusiveAt };
      }
    }
    const startAt = now.startOf("day");
    return { startAt, endExclusiveAt: startAt.add(1, "day") };
  }
  hasPulledOrdersToday() {
    const lastFullFetchAt = this.getStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY);
    if (!lastFullFetchAt)
      return false;
    const parsed = (0, import_dayjs.default)(lastFullFetchAt);
    if (!parsed.isValid())
      return false;
    const { startAt, endExclusiveAt } = this.getCurrentPullWindow();
    return (parsed.isAfter(startAt) || parsed.isSame(startAt)) && parsed.isBefore(endExclusiveAt);
  }
  markOrderPulledAtNow() {
    this.setStorageItem(
      ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY,
      (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
    );
  }
  getStorageItem(key) {
    var _a;
    try {
      if ((_a = this.storage) == null ? void 0 : _a.getStorage)
        return this.storage.getStorage(key);
      if (typeof globalThis !== "undefined" && (globalThis == null ? void 0 : globalThis.localStorage)) {
        return globalThis.localStorage.getItem(key);
      }
    } catch {
    }
    return null;
  }
  setStorageItem(key, value) {
    var _a;
    try {
      if ((_a = this.storage) == null ? void 0 : _a.setStorage) {
        this.storage.setStorage(key, value);
        return;
      }
      if (typeof globalThis !== "undefined" && (globalThis == null ? void 0 : globalThis.localStorage)) {
        globalThis.localStorage.setItem(key, value);
      }
    } catch {
    }
  }
  async loadOrdersFromSQLite() {
    if (!this.dbManager)
      return [];
    try {
      const orders = await this.dbManager.getAll(INDEXDB_STORE_NAME);
      return orders || [];
    } catch {
      return [];
    }
  }
  isPendingSyncOrder(order) {
    return Number(order == null ? void 0 : order.need_sync) === 1;
  }
  normalizeRemoteSyncedOrder(order) {
    if (this.isPendingSyncOrder(order))
      return order;
    return {
      ...order,
      need_sync: 0
    };
  }
  mergeRemoteSnapshotWithPendingOrders(remoteOrders, existingOrders) {
    const merged = remoteOrders.map((order) => this.normalizeRemoteSyncedOrder(order));
    const remoteStorageKeys = new Set(
      merged.map((order) => this.getOrderStorageKey(order)).filter(Boolean)
    );
    for (const order of existingOrders) {
      if (!this.isPendingSyncOrder(order))
        continue;
      const storageKey = this.getOrderStorageKey(order);
      if (!storageKey || remoteStorageKeys.has(storageKey))
        continue;
      merged.push(order);
      remoteStorageKeys.add(storageKey);
    }
    return merged;
  }
  /**
   * 串行执行订单 SQLite 写入任务，避免快照替换与增量 upsert 并发交错。
   *
   * @example
   * await this.runInOrderSQLiteSaveQueue(async () => {
   *   await this.dbManager.bulkUpdate(INDEXDB_STORE_NAME, orders)
   * })
   */
  async runInOrderSQLiteSaveQueue(task) {
    const queuedTask = this.orderSQLiteSaveQueue.then(task, task);
    this.orderSQLiteSaveQueue = queuedTask.then(() => void 0, () => void 0);
    return queuedTask;
  }
  /**
   * 批量增量 upsert 订单到 SQLite，不清空表；用于 pubsub / HTTP 增量合并。
   *
   * @example
   * await this.patchOrdersInSQLite(freshOrders)
   */
  async patchOrdersInSQLite(orders, source, mergeActions = {}) {
    if (!this.dbManager || orders.length === 0) {
      return;
    }
    const ordersSnapshot = (0, import_lodash_es.cloneDeep)(orders).filter((order) => this.getOrderStorageKey(order));
    if (ordersSnapshot.length === 0) {
      return;
    }
    const { toWrite, skipped } = this.filterRedundantPatchOrders(
      source,
      ordersSnapshot,
      mergeActions
    );
    if (toWrite.length === 0) {
      return;
    }
    try {
      await this.runInOrderSQLiteSaveQueue(async () => {
        let writeMethod = "none";
        this.logInfo("patchOrdersInSQLite-开始", {
          source,
          count: toWrite.length,
          dedupedCount: skipped.length
        });
        if (typeof this.dbManager.bulkUpdate === "function") {
          writeMethod = "bulkUpdate";
          await this.dbManager.bulkUpdate(INDEXDB_STORE_NAME, toWrite);
        } else if (typeof this.dbManager.bulkAdd === "function") {
          writeMethod = "bulkAdd";
          await this.dbManager.bulkAdd(INDEXDB_STORE_NAME, toWrite);
        } else if (typeof this.dbManager.update === "function") {
          writeMethod = "update";
          for (const order of toWrite) {
            await this.dbManager.update(INDEXDB_STORE_NAME, order);
          }
        }
        this.recordRecentSqliteWrite(source, toWrite);
        this.logInfo("patchOrdersInSQLite-完成", {
          source,
          count: toWrite.length,
          writeMethod,
          dedupedCount: skipped.length
        });
      });
    } catch (error) {
      this.logError("增量保存订单到 SQLite 失败", {
        error: error instanceof Error ? error.message : String(error),
        orderCount: ordersSnapshot.length
      });
    }
  }
  /**
   * 单条 upsert 订单到 SQLite；用于 overwriteExistingOrder 等单条覆盖场景。
   *
   * @example
   * await this.updateOrderInSQLite(freshOrder)
   */
  async updateOrderInSQLite(order, source) {
    if (!this.dbManager || !this.getOrderStorageKey(order)) {
      return;
    }
    const orderSnapshot = (0, import_lodash_es.cloneDeep)(order);
    try {
      await this.runInOrderSQLiteSaveQueue(async () => {
        let writeMethod = "none";
        this.logInfo("updateOrderInSQLite-开始", {
          source,
          orderId: orderSnapshot.order_id ?? null,
          storageKey: this.getOrderStorageKey(orderSnapshot)
        });
        if (typeof this.dbManager.update === "function") {
          writeMethod = "update";
          await this.dbManager.update(INDEXDB_STORE_NAME, orderSnapshot);
        } else if (typeof this.dbManager.bulkUpdate === "function") {
          writeMethod = "bulkUpdate";
          await this.dbManager.bulkUpdate(INDEXDB_STORE_NAME, [orderSnapshot]);
        } else if (typeof this.dbManager.bulkAdd === "function") {
          writeMethod = "bulkAdd";
          await this.dbManager.bulkAdd(INDEXDB_STORE_NAME, [orderSnapshot]);
        }
        this.recordRecentSqliteWrite(source, [orderSnapshot]);
        this.logInfo("updateOrderInSQLite-完成", {
          source,
          orderId: orderSnapshot.order_id ?? null,
          writeMethod
        });
      });
    } catch (error) {
      this.logError("单条保存订单到 SQLite 失败", {
        error: error instanceof Error ? error.message : String(error),
        orderId: orderSnapshot.order_id ?? null
      });
    }
  }
  /**
   * 全量快照替换 orders 表（clear + bulkAdd），用于 SSE 全量拉取与营业日窗口裁剪。
   *
   * @example
   * await this.replaceOrdersSnapshotInSQLite(orderList)
   */
  async replaceOrdersSnapshotInSQLite(orderList, source) {
    if (!this.dbManager) {
      return orderList.map((order) => this.normalizeRemoteSyncedOrder(order));
    }
    const remoteSnapshot = (0, import_lodash_es.cloneDeep)(orderList);
    let mergedSnapshot = remoteSnapshot.map((order) => this.normalizeRemoteSyncedOrder(order));
    try {
      await this.runInOrderSQLiteSaveQueue(async () => {
        const existingOrders = typeof this.dbManager.getAll === "function" ? await this.dbManager.getAll(INDEXDB_STORE_NAME) : [];
        const orderListSnapshot = this.mergeRemoteSnapshotWithPendingOrders(
          remoteSnapshot,
          existingOrders || []
        );
        mergedSnapshot = orderListSnapshot;
        this.logInfo("replaceOrdersSnapshotInSQLite-开始", {
          source,
          count: orderListSnapshot.length,
          remoteCount: remoteSnapshot.length,
          preservedPendingCount: orderListSnapshot.length - remoteSnapshot.length
        });
        await this.dbManager.clear(INDEXDB_STORE_NAME);
        this.logInfo("replaceOrdersSnapshotInSQLite-clear完成", {
          count: orderListSnapshot.length
        });
        if (orderListSnapshot.length === 0) {
          return;
        }
        await this.dbManager.bulkAdd(INDEXDB_STORE_NAME, orderListSnapshot);
        this.recordRecentSqliteWrite(source, orderListSnapshot);
        this.logInfo("replaceOrdersSnapshotInSQLite-bulkAdd完成", {
          source,
          count: orderListSnapshot.length
        });
      });
    } catch (error) {
      this.logError("全量保存订单到 SQLite 失败", {
        error: error instanceof Error ? error.message : String(error),
        orderList: remoteSnapshot.length
      });
    }
    return mergedSnapshot;
  }
  /**
   * 清空订单模块的内存数据和本地 SQLite 订单表。
   *
   * @example
   * await orderModule.clear()
   */
  async clear() {
    this.store.list = [];
    this.store.map = /* @__PURE__ */ new Map();
    this.resourceIdIndex.clear();
    if (this.dbManager) {
      await this.runInOrderSQLiteSaveQueue(async () => {
        await this.dbManager.clear(INDEXDB_STORE_NAME);
      });
    }
    this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, "");
    this.emitOrdersChanged([], "clear");
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  OrderModule
});
