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 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();
  }
  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;
      this.syncOrdersMap();
      this.core.effects.emit(import_types.OrderHooks.onOrdersChanged, this.store.list);
    } 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 {
    }
  }
  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.core.effects.emit(import_types.OrderHooks.onOrdersChanged, this.store.list);
      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 getLocalOrderByOrderId(orderId) {
    const key = this.getIdKey(orderId);
    const memoryOrder = this.store.map.get(key);
    if (memoryOrder)
      return memoryOrder;
    const orders = await this.loadOrdersFromSQLite();
    const localOrder = orders.find((order) => {
      const shopOrderNumber = order == null ? void 0 : order.shop_order_number;
      if (shopOrderNumber && this.getIdKey(shopOrderNumber) === key)
        return true;
      const id = order == null ? void 0 : order.order_id;
      if (id === void 0 || id === null)
        return false;
      return this.getIdKey(id) === key;
    });
    if (!localOrder)
      return null;
    this.store.list = orders;
    this.syncOrdersMap();
    return 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();
      } catch {
        orderList = [];
        this.logInfo("loadOrdersByServer-SSE拉取失败，回退为空数组");
      }
    }
    await this.saveOrdersToSQLite(orderList);
    this.logInfo("loadOrdersByServer-结束", {
      count: orderList.length
    });
    await this.core.effects.emit(import_types.OrderHooks.onOrdersLoaded, orderList);
    return orderList;
  }
  /**
   * 静默全量刷新：后台重新拉取全量 SSE 订单数据并更新本地
   * 拿到完整数据后一次性替换 store，触发订单变更与同步完成事件
   * @returns 刷新后的订单列表
   */
  async silentRefresh() {
    const startTime = Date.now();
    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.core.effects.emit(import_types.OrderHooks.onOrdersChanged, this.store.list);
        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);
  }
  /**
   * 仅覆盖本地已存在的订单；不存在则直接跳过，不落库、不 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.saveOrdersToSQLite(this.store.list);
    this.logInfo("overwriteExistingOrder-结束", {
      orderId,
      storeOrderCountAfter: this.store.list.length
    });
    await this.core.effects.emit(import_types.OrderHooks.onOrdersChanged, this.store.list);
    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);
  }
  /**
   * 通过 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 id = order.order_id;
      if (id === void 0 || id === null)
        continue;
      this.store.map.set(this.getIdKey(id), order);
      const resourceIds = this.extractResourceIds(order);
      for (const resourceId of resourceIds) {
        const key = String(resourceId);
        const existing = this.resourceIdIndex.get(key) || [];
        if (existing.some((eid) => this.getIdKey(eid) === this.getIdKey(id)))
          continue;
        existing.push(id);
        this.resourceIdIndex.set(key, existing);
      }
    }
  }
  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");
          const pubsubReceivedAt = Date.now();
          const message = this.normalizeOrderSyncMessage(res);
          if (!message)
            return;
          message._pubsubReceivedAt = pubsubReceivedAt;
          this.pendingSyncMessages.push(message);
          const throttleMs = this.getOrderSyncThrottleMs();
          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() {
    var _a;
    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 = [];
    for (const msg of messages) {
      const hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
      const singleId = msg.id ?? msg.order_id;
      const hasSingleId = !hasBatchIds && singleId !== void 0 && singleId !== null;
      const rawBody = msg.body || msg.data;
      const normalizedBody = this.normalizeOrderSyncPayload(rawBody);
      if (hasSingleId && normalizedBody) {
        upsertOrders.set(this.getIdKey(normalizedBody.order_id), normalizedBody);
        continue;
      }
      if (hasBatchIds)
        refreshIds.push(...msg.ids);
      else if (hasSingleId)
        refreshIds.push(singleId);
      else if ((_a = msg.relation_order_ids) == null ? void 0 : _a.length)
        refreshIds.push(...msg.relation_order_ids);
    }
    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);
    if (uniqueRefreshIds.length > 0) {
      const freshOrders = await this.fetchOrdersByHttp(uniqueRefreshIds);
      if (freshOrders.length > 0)
        await this.mergeOrdersToStore(freshOrders);
    }
    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) {
    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), order);
    }
    const uniqueFreshCount = freshMap.size;
    const updatedList = this.store.list.map((order) => {
      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);
      return fresh;
    });
    for (const order of freshMap.values()) {
      updatedList.push(order);
    }
    this.store.list = updatedList;
    this.syncOrdersMap();
    await this.saveOrdersToSQLite(this.store.list);
    this.logInfo("mergeOrdersToStore-结束", {
      uniqueFreshCount,
      storeOrderCountAfter: this.store.list.length
    });
    this.core.effects.emit(import_types.OrderHooks.onOrdersChanged, this.store.list);
  }
  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);
  }
  /**
   * 当前订单拉取窗口：
   * - 优先使用 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 [];
    }
  }
  async saveOrdersToSQLite(orderList) {
    if (!this.dbManager)
      return;
    try {
      this.logInfo("saveOrdersToSQLite-开始", {
        count: orderList.length
      });
      await this.dbManager.clear(INDEXDB_STORE_NAME);
      this.logInfo("saveOrdersToSQLite-clear完成", {
        count: orderList.length
      });
      if (orderList.length === 0)
        return;
      await this.dbManager.bulkAdd(INDEXDB_STORE_NAME, orderList);
      this.logInfo("saveOrdersToSQLite-bulkAdd完成", {
        count: orderList.length
      });
    } catch (error) {
      this.logError("保存订单到 SQLite 失败", {
        error: error instanceof Error ? error.message : String(error),
        orderList: orderList.length
      });
    }
  }
  async clear() {
    this.store.list = [];
    this.store.map = /* @__PURE__ */ new Map();
    this.resourceIdIndex.clear();
    if (this.dbManager) {
      await this.dbManager.clear(INDEXDB_STORE_NAME);
    }
    this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, "");
    this.core.effects.emit(import_types.OrderHooks.onOrdersChanged, this.store.list);
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  OrderModule
});
