function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { cloneDeep } from 'lodash-es';
import dayjs from 'dayjs';
import { BaseModule } from "../../../modules/BaseModule";
import { OrderHooks } from "./types";

/**
 * SQLite 存储名称
 */
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 = 2000;

/**
 * Order 模块 - 基础框架
 */
export var OrderModule = /*#__PURE__*/function (_BaseModule) {
  _inherits(OrderModule, _BaseModule);
  var _super = _createSuper(OrderModule);
  function OrderModule(name, version) {
    var _this;
    _classCallCheck(this, OrderModule);
    _this = _super.call(this, name, version);
    _defineProperty(_assertThisInitialized(_this), "defaultName", 'order');
    _defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0');
    _defineProperty(_assertThisInitialized(_this), "store", void 0);
    _defineProperty(_assertThisInitialized(_this), "dbManager", void 0);
    _defineProperty(_assertThisInitialized(_this), "orderDataSource", void 0);
    _defineProperty(_assertThisInitialized(_this), "pendingSyncMessages", []);
    _defineProperty(_assertThisInitialized(_this), "syncTimer", void 0);
    _defineProperty(_assertThisInitialized(_this), "isProcessingSyncBatch", false);
    _defineProperty(_assertThisInitialized(_this), "isIdlePhase", true);
    // Map<resource_id, OrderId[]> 资源到订单的倒排索引
    _defineProperty(_assertThisInitialized(_this), "resourceIdIndex", new Map());
    _defineProperty(_assertThisInitialized(_this), "logger", void 0);
    // LoggerManager 实例
    _defineProperty(_assertThisInitialized(_this), "storage", void 0);
    return _this;
  }
  _createClass(OrderModule, [{
    key: "initialize",
    value: function () {
      var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) {
        var _options$initialState;
        var appPlugin, app, _this$store$createdAt, coreData, today, operatingDayBoundary, boundaryTime, boundaryStart, isAfterBoundary, queryStart, queryEnd;
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              this.core = core;
              this.store = options === null || options === void 0 ? void 0 : options.store;
              if (!this.store.map) this.store.map = new Map();
              appPlugin = core.getPlugin('app');
              app = appPlugin === null || appPlugin === void 0 ? void 0 : appPlugin.getApp();
              if (app) {
                this.dbManager = app.sqlite;
                this.logger = app.logger;
                this.storage = app.storage;
                coreData = app.data.store.getStore().getDataByModel('core');
                if (!((_this$store$createdAt = this.store.createdAtQuery) !== null && _this$store$createdAt !== void 0 && _this$store$createdAt.sales_time_between) && coreData !== null && coreData !== void 0 && coreData.core) {
                  today = dayjs();
                  if (coreData !== null && coreData !== void 0 && coreData.core.operating_day_boundary) {
                    operatingDayBoundary = coreData.core.operating_day_boundary;
                    if (operatingDayBoundary.type === 'start_time') {
                      boundaryTime = String(operatingDayBoundary.time || '').trim();
                      boundaryStart = dayjs("".concat(today.format('YYYY-MM-DD'), " ").concat(boundaryTime));
                      if (boundaryStart.isValid()) {
                        isAfterBoundary = today.isAfter(boundaryStart);
                        queryStart = isAfterBoundary ? today.startOf('day') : today.subtract(1, 'day').startOf('day');
                        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 {
                        // 边界时间异常时回退到自然日，避免 createdAtQuery 为空导致后续查询异常
                        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 {
                    // TODO: 这里后续可能需要使用店铺营业时间查询
                    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(options === null || options === void 0 || (_options$initialState = options.initialState) === null || _options$initialState === void 0 ? void 0 : _options$initialState.list)) {
                this.store.list = options.initialState.list;
                this.syncOrdersMap();
                this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
              } else {
                this.store.list = [];
                this.store.map = new Map();
              }
              this.initOrderDataSource();
              this.setupOrderSync();
              this.logInfo('OrderServer模块初始化完成', {
                hasDbManager: !!this.dbManager,
                hasLogger: !!this.logger,
                initialOrderCount: this.store.list.length
              });
            case 10:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function initialize(_x, _x2) {
        return _initialize.apply(this, arguments);
      }
      return initialize;
    }()
    /**
    * 记录信息日志
    * @param title 日志标题
    * @param metadata 日志元数据
    */
  }, {
    key: "logInfo",
    value: function logInfo(title, metadata) {
      try {
        if (this.logger) {
          this.logger.addLog({
            type: 'info',
            title: "[OrderServerModule] ".concat(title),
            metadata: metadata || {}
          });
        }
      } catch (_unused) {
        // 日志记录失败不影响主流程
      }
    }

    /**
     * 记录错误日志
     * @param title 日志标题
     * @param metadata 日志元数据
     */
  }, {
    key: "logError",
    value: function logError(title, metadata) {
      try {
        if (this.logger) {
          this.logger.addLog({
            type: 'error',
            title: "[OrderServerModule] ".concat(title),
            metadata: metadata || {}
          });
        }
      } catch (_unused2) {
        // 日志记录失败不影响主流程
      }
    }
  }, {
    key: "getOrderSyncThrottleMs",
    value: function getOrderSyncThrottleMs() {
      var raw = localStorage.getItem(ORDER_SYNC_THROTTLE_MS_STORAGE_KEY);
      if (raw !== null) {
        var parsed = Number(raw);
        if (Number.isFinite(parsed) && parsed >= 0) return parsed;
      }
      return DEFAULT_ORDER_SYNC_THROTTLE_MS;
    }
  }, {
    key: "preload",
    value: function () {
      var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
        var _this2 = this;
        var getData;
        return _regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              // const cachedOrders = await this.loadOrdersFromSQLite()
              // const hasPulledInCurrentWindow = this.hasPulledOrdersToday()
              // // 仅当缓存属于当前统计窗口时才直接复用，避免跨天/跨营业日窗口继续使用旧数据
              // if (cachedOrders.length > 0 && hasPulledInCurrentWindow) {
              //   this.store.list = cloneDeep(cachedOrders)
              //   this.syncOrdersMap()
              //   this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list)
              //   return
              // }
              // if (hasPulledInCurrentWindow) {
              //   this.logInfo('当天已完成全量订单拉取，跳过本次全量拉取', {
              //     lastFullFetchAt: this.getStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY),
              //   })
              //   return
              // }
              getData = /*#__PURE__*/function () {
                var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
                  var orders;
                  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
                    while (1) switch (_context2.prev = _context2.next) {
                      case 0:
                        _context2.next = 2;
                        return _this2.loadOrdersByServer();
                      case 2:
                        orders = _context2.sent;
                        if (!(orders.length === 0)) {
                          _context2.next = 5;
                          break;
                        }
                        return _context2.abrupt("return");
                      case 5:
                        _this2.store.list = cloneDeep(orders);
                        _this2.syncOrdersMap();
                        _this2.core.effects.emit(OrderHooks.onOrdersChanged, _this2.store.list);
                        _this2.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
                      case 9:
                      case "end":
                        return _context2.stop();
                    }
                  }, _callee2);
                }));
                return function getData() {
                  return _ref.apply(this, arguments);
                };
              }();
              getData();
            case 2:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }));
      function preload() {
        return _preload.apply(this, arguments);
      }
      return preload;
    }()
  }, {
    key: "getOrders",
    value: function getOrders() {
      return this.store.list;
    }
  }, {
    key: "getOrderById",
    value: function getOrderById(id) {
      return this.store.map.get(this.getIdKey(id));
    }

    /** 按 order_id 查询（推荐） */
  }, {
    key: "getOrderByOrderId",
    value: function getOrderByOrderId(orderId) {
      return this.store.map.get(this.getIdKey(orderId));
    }
  }, {
    key: "getLocalOrderByOrderId",
    value: function () {
      var _getLocalOrderByOrderId = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(orderId) {
        var _this3 = this;
        var key, memoryOrder, orders, localOrder;
        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              key = this.getIdKey(orderId);
              memoryOrder = this.store.map.get(key);
              if (!memoryOrder) {
                _context4.next = 4;
                break;
              }
              return _context4.abrupt("return", memoryOrder);
            case 4:
              _context4.next = 6;
              return this.loadOrdersFromSQLite();
            case 6:
              orders = _context4.sent;
              localOrder = orders.find(function (order) {
                var shopOrderNumber = order === null || order === void 0 ? void 0 : order.shop_order_number;
                if (shopOrderNumber && _this3.getIdKey(shopOrderNumber) === key) return true;
                var id = order === null || order === void 0 ? void 0 : order.order_id;
                if (id === undefined || id === null) return false;
                return _this3.getIdKey(id) === key;
              });
              if (localOrder) {
                _context4.next = 10;
                break;
              }
              return _context4.abrupt("return", null);
            case 10:
              this.store.list = orders;
              this.syncOrdersMap();
              return _context4.abrupt("return", localOrder);
            case 13:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this);
      }));
      function getLocalOrderByOrderId(_x3) {
        return _getLocalOrderByOrderId.apply(this, arguments);
      }
      return getLocalOrderByOrderId;
    }()
  }, {
    key: "loadOrdersByServer",
    value: function () {
      var _loadOrdersByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
        var _this$store;
        var orderList, data;
        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              orderList = [];
              this.logInfo('loadOrdersByServer-开始', {
                hasOrderDataSource: !!this.orderDataSource,
                query: ((_this$store = this.store) === null || _this$store === void 0 ? void 0 : _this$store.createdAtQuery) || null
              });
              if (!this.orderDataSource) {
                _context5.next = 16;
                break;
              }
              _context5.prev = 3;
              _context5.next = 6;
              return this.orderDataSource.run({
                sse: {
                  query: this.store.createdAtQuery
                }
              });
            case 6:
              data = _context5.sent;
              orderList = data || [];
              this.logInfo('loadOrdersByServer-SSE拉取成功', {
                count: orderList.length
              });
              this.markOrderPulledAtNow();
              _context5.next = 16;
              break;
            case 12:
              _context5.prev = 12;
              _context5.t0 = _context5["catch"](3);
              orderList = [];
              this.logInfo('loadOrdersByServer-SSE拉取失败，回退为空数组');
            case 16:
              _context5.next = 18;
              return this.saveOrdersToSQLite(orderList);
            case 18:
              this.logInfo('loadOrdersByServer-结束', {
                count: orderList.length
              });
              _context5.next = 21;
              return this.core.effects.emit(OrderHooks.onOrdersLoaded, orderList);
            case 21:
              return _context5.abrupt("return", orderList);
            case 22:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this, [[3, 12]]);
      }));
      function loadOrdersByServer() {
        return _loadOrdersByServer.apply(this, arguments);
      }
      return loadOrdersByServer;
    }()
    /**
     * 静默全量刷新：后台重新拉取全量 SSE 订单数据并更新本地
     * 拿到完整数据后一次性替换 store，触发订单变更与同步完成事件
     * @returns 刷新后的订单列表
     */
  }, {
    key: "silentRefresh",
    value: (function () {
      var _silentRefresh = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
        var startTime, orders, errorMessage;
        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              startTime = Date.now();
              this.logInfo('silentRefresh 开始');
              _context6.prev = 2;
              _context6.next = 5;
              return this.loadOrdersByServer();
            case 5:
              orders = _context6.sent;
              if (!(orders.length > 0)) {
                _context6.next = 15;
                break;
              }
              this.store.list = cloneDeep(orders);
              this.syncOrdersMap();
              this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
              _context6.next = 12;
              return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
            case 12:
              this.logInfo('silentRefresh 完成', {
                orderCount: orders.length,
                duration: "".concat(Date.now() - startTime, "ms")
              });
              _context6.next = 16;
              break;
            case 15:
              this.logInfo('silentRefresh: 服务器未返回数据');
            case 16:
              return _context6.abrupt("return", this.store.list);
            case 19:
              _context6.prev = 19;
              _context6.t0 = _context6["catch"](2);
              errorMessage = _context6.t0 instanceof Error ? _context6.t0.message : String(_context6.t0);
              this.logError('silentRefresh 失败', {
                duration: "".concat(Date.now() - startTime, "ms"),
                error: errorMessage
              });
              return _context6.abrupt("return", this.store.list);
            case 24:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this, [[2, 19]]);
      }));
      function silentRefresh() {
        return _silentRefresh.apply(this, arguments);
      }
      return silentRefresh;
    }())
  }, {
    key: "getOrdersByResourceId",
    value: function getOrdersByResourceId(resourceId) {
      var _this4 = this;
      var ids = this.resourceIdIndex.get(String(resourceId)) || [];
      return ids.map(function (id) {
        return _this4.store.map.get(id);
      }).filter(function (order) {
        return !!order;
      });
    }

    /**
     * 仅覆盖本地已存在的订单；不存在则直接跳过，不落库、不 emit。
     * 适用于"按 order_id 主动刷新本地订单详情"的代理场景。
     */
  }, {
    key: "overwriteExistingOrder",
    value: (function () {
      var _overwriteExistingOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(fresh) {
        var _this5 = this;
        var orderId, key;
        return _regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              orderId = fresh === null || fresh === void 0 ? void 0 : fresh.order_id;
              if (!(orderId === undefined || orderId === null)) {
                _context7.next = 4;
                break;
              }
              this.logError('overwriteExistingOrder-入参缺少 order_id');
              return _context7.abrupt("return", {
                overwritten: false
              });
            case 4:
              key = this.getIdKey(orderId);
              if (this.store.map.has(key)) {
                _context7.next = 8;
                break;
              }
              this.logInfo('overwriteExistingOrder-本地不存在该订单，跳过', {
                orderId: orderId
              });
              return _context7.abrupt("return", {
                overwritten: false
              });
            case 8:
              this.logInfo('overwriteExistingOrder-开始覆盖', {
                orderId: orderId,
                storeOrderCountBefore: this.store.list.length
              });
              this.store.list = this.store.list.map(function (order) {
                var id = order === null || order === void 0 ? void 0 : order.order_id;
                if (id === undefined || id === null) return order;
                return _this5.getIdKey(id) === key ? fresh : order;
              });
              this.syncOrdersMap();
              _context7.next = 13;
              return this.saveOrdersToSQLite(this.store.list);
            case 13:
              this.logInfo('overwriteExistingOrder-结束', {
                orderId: orderId,
                storeOrderCountAfter: this.store.list.length
              });
              _context7.next = 16;
              return this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
            case 16:
              return _context7.abrupt("return", {
                overwritten: true
              });
            case 17:
            case "end":
              return _context7.stop();
          }
        }, _callee7, this);
      }));
      function overwriteExistingOrder(_x4) {
        return _overwriteExistingOrder.apply(this, arguments);
      }
      return overwriteExistingOrder;
    }()
    /**
     * 将远端拉取的订单合并进本地 store（已存在则更新，不存在则追加），落库并 emit onOrdersChanged。
     * 供 /update/localOrder 等在「本地尚无该单」时写入新建单。
     */
    )
  }, {
    key: "upsertOrdersFromRemote",
    value: (function () {
      var _upsertOrdersFromRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(freshOrders) {
        return _regeneratorRuntime().wrap(function _callee8$(_context8) {
          while (1) switch (_context8.prev = _context8.next) {
            case 0:
              if (freshOrders !== null && freshOrders !== void 0 && freshOrders.length) {
                _context8.next = 3;
                break;
              }
              this.logInfo('upsertOrdersFromRemote-订单列表为空', {});
              return _context8.abrupt("return");
            case 3:
              this.logInfo('upsertOrdersFromRemote-开始', {
                count: freshOrders.length
              });
              _context8.next = 6;
              return this.mergeOrdersToStore(freshOrders);
            case 6:
            case "end":
              return _context8.stop();
          }
        }, _callee8, this);
      }));
      function upsertOrdersFromRemote(_x5) {
        return _upsertOrdersFromRemote.apply(this, arguments);
      }
      return upsertOrdersFromRemote;
    }()
    /**
     * 通过 SSE 按自定义 query 拉取订单（支持 select/with 精简字段）
     */
    )
  }, {
    key: "fetchOrdersBySSE",
    value: (function () {
      var _fetchOrdersBySSE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
        var query,
          data,
          _args9 = arguments;
        return _regeneratorRuntime().wrap(function _callee9$(_context9) {
          while (1) switch (_context9.prev = _context9.next) {
            case 0:
              query = _args9.length > 0 && _args9[0] !== undefined ? _args9[0] : {};
              if (this.orderDataSource) {
                _context9.next = 3;
                break;
              }
              return _context9.abrupt("return", []);
            case 3:
              _context9.prev = 3;
              _context9.next = 6;
              return this.orderDataSource.run({
                sse: {
                  query: query
                }
              });
            case 6:
              data = _context9.sent;
              return _context9.abrupt("return", data || []);
            case 10:
              _context9.prev = 10;
              _context9.t0 = _context9["catch"](3);
              this.logError('fetchOrdersBySSE-失败', {
                error: _context9.t0 instanceof Error ? _context9.t0.message : String(_context9.t0)
              });
              return _context9.abrupt("return", []);
            case 14:
            case "end":
              return _context9.stop();
          }
        }, _callee9, this, [[3, 10]]);
      }));
      function fetchOrdersBySSE() {
        return _fetchOrdersBySSE.apply(this, arguments);
      }
      return fetchOrdersBySSE;
    }())
  }, {
    key: "getRoutes",
    value: function getRoutes() {
      return [];
    }
  }, {
    key: "destroy",
    value: function destroy() {
      var _this$orderDataSource;
      if (this.syncTimer) {
        clearTimeout(this.syncTimer);
        this.syncTimer = undefined;
      }
      this.isProcessingSyncBatch = false;
      this.pendingSyncMessages = [];
      if ((_this$orderDataSource = this.orderDataSource) !== null && _this$orderDataSource !== void 0 && _this$orderDataSource.destroy) this.orderDataSource.destroy();
      _get(_getPrototypeOf(OrderModule.prototype), "destroy", this).call(this);
    }
  }, {
    key: "syncOrdersMap",
    value: function syncOrdersMap() {
      var _this6 = this;
      this.store.map.clear();
      this.resourceIdIndex.clear();
      var _iterator = _createForOfIteratorHelper(this.store.list),
        _step;
      try {
        var _loop = function _loop() {
          var order = _step.value;
          var id = order.order_id;
          if (id === undefined || id === null) return 1; // continue
          _this6.store.map.set(_this6.getIdKey(id), order);
          var resourceIds = _this6.extractResourceIds(order);
          var _iterator2 = _createForOfIteratorHelper(resourceIds),
            _step2;
          try {
            for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
              var resourceId = _step2.value;
              var key = String(resourceId);
              var existing = _this6.resourceIdIndex.get(key) || [];
              if (existing.some(function (eid) {
                return _this6.getIdKey(eid) === _this6.getIdKey(id);
              })) continue;
              existing.push(id);
              _this6.resourceIdIndex.set(key, existing);
            }
          } catch (err) {
            _iterator2.e(err);
          } finally {
            _iterator2.f();
          }
        };
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          if (_loop()) continue;
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }
  }, {
    key: "extractResourceIds",
    value: function extractResourceIds(order) {
      var ids = new Set();
      var visitResources = function visitResources(resources) {
        if (!Array.isArray(resources)) return;
        resources.forEach(function (resource) {
          var rid = resource === null || resource === void 0 ? void 0 : resource.relation_id;
          if (rid !== undefined && rid !== null && rid !== '') ids.add(String(rid));
          if (Array.isArray(resource === null || resource === void 0 ? void 0 : resource.children)) visitResources(resource.children);
        });
      };
      if (Array.isArray(order === null || order === void 0 ? void 0 : order.bookings)) {
        order.bookings.forEach(function (booking) {
          return visitResources((booking === null || booking === void 0 ? void 0 : booking.resources) || []);
        });
      }
      return _toConsumableArray(ids);
    }
  }, {
    key: "getOrderDateKey",
    value: function getOrderDateKey(order) {
      var _order$bookings, _order$bookings2;
      var candidates = [order === null || order === void 0 ? void 0 : order.schedule_date, order === null || order === void 0 ? void 0 : order.create_date, order === null || order === void 0 ? void 0 : order.created_at, order === null || order === void 0 || (_order$bookings = order.bookings) === null || _order$bookings === void 0 || (_order$bookings = _order$bookings[0]) === null || _order$bookings === void 0 ? void 0 : _order$bookings.start_date, order === null || order === void 0 || (_order$bookings2 = order.bookings) === null || _order$bookings2 === void 0 || (_order$bookings2 = _order$bookings2[0]) === null || _order$bookings2 === void 0 ? void 0 : _order$bookings2.select_date];
      for (var _i = 0, _candidates = candidates; _i < _candidates.length; _i++) {
        var v = _candidates[_i];
        if (!v) continue;
        var text = String(v);
        if (!text) continue;
        return text.split('T')[0].split(' ')[0];
      }
      return undefined;
    }

    /**
     * 初始化 OrderDataSource 实例
     */
  }, {
    key: "initOrderDataSource",
    value: function initOrderDataSource() {
      var _serverOptions;
      var OrderDataSourceClass = (_serverOptions = this.core.serverOptions) === null || _serverOptions === void 0 || (_serverOptions = _serverOptions.All_DATA_SOURCES) === null || _serverOptions === void 0 ? void 0 : _serverOptions.OrderDataSource;
      if (!OrderDataSourceClass) return;
      this.orderDataSource = new OrderDataSourceClass();
    }

    /**
     * 初始化 pubsub 订阅，监听订单变更（纯订阅，不拉数据；全量 SSE 由 loadOrdersByServer 负责）
     */
  }, {
    key: "setupOrderSync",
    value: function setupOrderSync() {
      var _this7 = this;
      if (!this.orderDataSource) return;
      this.orderDataSource.run({
        pubsub: {
          callback: function callback(res) {
            var _message$id, _message$order_id, _message$type;
            console.log('orderDataSource');
            var pubsubReceivedAt = Date.now();
            var message = _this7.normalizeOrderSyncMessage(res);
            if (!message) return;
            message._pubsubReceivedAt = pubsubReceivedAt;
            _this7.pendingSyncMessages.push(message);
            var throttleMs = _this7.getOrderSyncThrottleMs();
            _this7.logInfo('orderSync-收到消息并入队', {
              id: (_message$id = message.id) !== null && _message$id !== void 0 ? _message$id : null,
              order_id: (_message$order_id = message.order_id) !== null && _message$order_id !== void 0 ? _message$order_id : null,
              type: (_message$type = message.type) !== null && _message$type !== void 0 ? _message$type : null,
              pendingCount: _this7.pendingSyncMessages.length,
              throttleMs: throttleMs,
              pubsubReceivedAt: new Date(pubsubReceivedAt).toISOString()
            });
            _this7.scheduleOrderSyncThrottle();
          }
        }
      }).catch(function () {
        // 忽略同步初始化异常，避免影响主流程
      });
    }

    /**
     * 调度订单同步节流窗口（leading-edge throttle）：
     * - 空闲状态下收到的第一条消息立即触发批处理，无需等待；
     * - 首条处理后进入冷却窗口，窗口期间的后续消息聚合，窗口结束后批量处理；
     * - 若当前批处理执行中，则由批处理结束后决定是否开启下一轮窗口。
     */
  }, {
    key: "scheduleOrderSyncThrottle",
    value: function scheduleOrderSyncThrottle() {
      var _this8 = this;
      if (this.isProcessingSyncBatch) return;
      if (this.isIdlePhase) {
        this.isIdlePhase = false;
        this.logInfo('orderSync-首条消息立即触发处理');
        void this.flushOrderSyncMessagesByThrottle();
        return;
      }
      if (this.syncTimer) return;
      var throttleMs = this.getOrderSyncThrottleMs();
      this.syncTimer = setTimeout(function () {
        _this8.syncTimer = undefined;
        void _this8.flushOrderSyncMessagesByThrottle();
      }, throttleMs);
    }

    /**
     * 执行一次节流批处理并在需要时续约下一轮窗口。
     * 批处理完成且无后续消息时恢复空闲状态，下一条消息将立即触发。
     */
  }, {
    key: "flushOrderSyncMessagesByThrottle",
    value: (function () {
      var _flushOrderSyncMessagesByThrottle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
        return _regeneratorRuntime().wrap(function _callee10$(_context10) {
          while (1) switch (_context10.prev = _context10.next) {
            case 0:
              if (!this.isProcessingSyncBatch) {
                _context10.next = 2;
                break;
              }
              return _context10.abrupt("return");
            case 2:
              if (!(this.pendingSyncMessages.length === 0)) {
                _context10.next = 5;
                break;
              }
              this.isIdlePhase = true;
              return _context10.abrupt("return");
            case 5:
              this.isProcessingSyncBatch = true;
              _context10.prev = 6;
              _context10.next = 9;
              return this.processOrderSyncMessages();
            case 9:
              _context10.prev = 9;
              this.isProcessingSyncBatch = false;
              if (this.pendingSyncMessages.length > 0) {
                this.scheduleOrderSyncThrottle();
              } else {
                this.isIdlePhase = true;
              }
              return _context10.finish(9);
            case 13:
            case "end":
              return _context10.stop();
          }
        }, _callee10, this, [[6,, 9, 13]]);
      }));
      function flushOrderSyncMessagesByThrottle() {
        return _flushOrderSyncMessagesByThrottle.apply(this, arguments);
      }
      return flushOrderSyncMessagesByThrottle;
    }()
    /**
     * 处理节流窗口内聚合后的同步消息批次
     *
     * 后端统一发送 change 消息，不再区分新增/编辑/删除。
     * - 单条（id/order_id）：若携带 body/data 则直接 upsert 到本地
     * - 批量（ids）：通过 HTTP 按 ids 增量拉取，再 merge 到本地
     *
     * @example
     * // pending 队列中存在 8 条消息时，仅处理一次批次并统一 merge
     * await this.processOrderSyncMessages()
     */
    )
  }, {
    key: "processOrderSyncMessages",
    value: (function () {
      var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
        var messages, batchProcessStartAt, earliestReceivedAt, upsertOrders, refreshIds, _iterator3, _step3, _msg$id, _msg$relation_order_i, msg, hasBatchIds, singleId, hasSingleId, rawBody, normalizedBody, uniqueRefreshIds, upsertList, freshOrders, batchProcessEndAt;
        return _regeneratorRuntime().wrap(function _callee11$(_context11) {
          while (1) switch (_context11.prev = _context11.next) {
            case 0:
              messages = _toConsumableArray(this.pendingSyncMessages);
              this.pendingSyncMessages = [];
              if (!(messages.length === 0)) {
                _context11.next = 4;
                break;
              }
              return _context11.abrupt("return");
            case 4:
              batchProcessStartAt = Date.now();
              earliestReceivedAt = Math.min.apply(Math, _toConsumableArray(messages.map(function (m) {
                var _m$_pubsubReceivedAt;
                return (_m$_pubsubReceivedAt = m._pubsubReceivedAt) !== null && _m$_pubsubReceivedAt !== void 0 ? _m$_pubsubReceivedAt : batchProcessStartAt;
              })));
              this.logInfo('processOrderSyncMessages-开始', {
                messageCount: messages.length,
                earliestReceivedAt: new Date(earliestReceivedAt).toISOString(),
                batchProcessStartAt: new Date(batchProcessStartAt).toISOString(),
                waitDurationMs: batchProcessStartAt - earliestReceivedAt
              });
              upsertOrders = new Map();
              refreshIds = [];
              _iterator3 = _createForOfIteratorHelper(messages);
              _context11.prev = 10;
              _iterator3.s();
            case 12:
              if ((_step3 = _iterator3.n()).done) {
                _context11.next = 25;
                break;
              }
              msg = _step3.value;
              hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
              singleId = (_msg$id = msg.id) !== null && _msg$id !== void 0 ? _msg$id : msg.order_id;
              hasSingleId = !hasBatchIds && singleId !== undefined && singleId !== null;
              rawBody = msg.body || msg.data;
              normalizedBody = this.normalizeOrderSyncPayload(rawBody);
              if (!(hasSingleId && normalizedBody)) {
                _context11.next = 22;
                break;
              }
              upsertOrders.set(this.getIdKey(normalizedBody.order_id), normalizedBody);
              return _context11.abrupt("continue", 23);
            case 22:
              if (hasBatchIds) refreshIds.push.apply(refreshIds, _toConsumableArray(msg.ids));else if (hasSingleId) refreshIds.push(singleId);else if ((_msg$relation_order_i = msg.relation_order_ids) !== null && _msg$relation_order_i !== void 0 && _msg$relation_order_i.length) refreshIds.push.apply(refreshIds, _toConsumableArray(msg.relation_order_ids));
            case 23:
              _context11.next = 12;
              break;
            case 25:
              _context11.next = 30;
              break;
            case 27:
              _context11.prev = 27;
              _context11.t0 = _context11["catch"](10);
              _iterator3.e(_context11.t0);
            case 30:
              _context11.prev = 30;
              _iterator3.f();
              return _context11.finish(30);
            case 33:
              uniqueRefreshIds = this.uniqueOrderIds(refreshIds);
              upsertList = _toConsumableArray(upsertOrders.values());
              this.logInfo('processOrderSyncMessages-去重完成', {
                upsertCount: upsertList.length,
                refreshIdCount: uniqueRefreshIds.length
              });
              if (!(upsertList.length > 0)) {
                _context11.next = 39;
                break;
              }
              _context11.next = 39;
              return this.mergeOrdersToStore(upsertList);
            case 39:
              if (!(uniqueRefreshIds.length > 0)) {
                _context11.next = 46;
                break;
              }
              _context11.next = 42;
              return this.fetchOrdersByHttp(uniqueRefreshIds);
            case 42:
              freshOrders = _context11.sent;
              if (!(freshOrders.length > 0)) {
                _context11.next = 46;
                break;
              }
              _context11.next = 46;
              return this.mergeOrdersToStore(freshOrders);
            case 46:
              if (!(upsertList.length === 0 && uniqueRefreshIds.length === 0)) {
                _context11.next = 48;
                break;
              }
              return _context11.abrupt("return");
            case 48:
              batchProcessEndAt = Date.now();
              this.logInfo('processOrderSyncMessages-结束', {
                upsertCount: upsertList.length,
                refreshIdCount: uniqueRefreshIds.length,
                batchProcessDurationMs: batchProcessEndAt - batchProcessStartAt,
                totalFromPubsubToProcessedMs: batchProcessEndAt - earliestReceivedAt
              });
              _context11.next = 52;
              return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
            case 52:
            case "end":
              return _context11.stop();
          }
        }, _callee11, this, [[10, 27, 30, 33]]);
      }));
      function processOrderSyncMessages() {
        return _processOrderSyncMessages.apply(this, arguments);
      }
      return processOrderSyncMessages;
    }()
    /**
     * 通过 HTTP 按 ids 批量拉取订单详情（走 orderDataSource）。
     *
     * - 优先使用 `orderDataSource.fetchOrdersByIds`（如适配器实现了该方法）
     * - 否则回退到 `orderDataSource.run({ http: { query: { ids } } })`
     * - 失败统一返回空数组（由调用方按"返回缺失的 id" 判断单笔失败）
     *
     * @example
     * const fresh = await orderModule.fetchOrdersByHttp(['96971', '96972'])
     */
    )
  }, {
    key: "fetchOrdersByHttp",
    value: (function () {
      var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(ids) {
        var _orderList, orderList;
        return _regeneratorRuntime().wrap(function _callee12$(_context12) {
          while (1) switch (_context12.prev = _context12.next) {
            case 0:
              if (!(!this.orderDataSource || ids.length === 0)) {
                _context12.next = 2;
                break;
              }
              return _context12.abrupt("return", []);
            case 2:
              _context12.prev = 2;
              if (!(typeof this.orderDataSource.fetchOrdersByIds === 'function')) {
                _context12.next = 8;
                break;
              }
              _context12.next = 6;
              return this.orderDataSource.fetchOrdersByIds(ids);
            case 6:
              _orderList = _context12.sent;
              return _context12.abrupt("return", _orderList || []);
            case 8:
              _context12.next = 10;
              return this.orderDataSource.run({
                http: {
                  query: {
                    ids: ids
                  }
                }
              });
            case 10:
              orderList = _context12.sent;
              return _context12.abrupt("return", orderList || []);
            case 14:
              _context12.prev = 14;
              _context12.t0 = _context12["catch"](2);
              return _context12.abrupt("return", []);
            case 17:
            case "end":
              return _context12.stop();
          }
        }, _callee12, this, [[2, 14]]);
      }));
      function fetchOrdersByHttp(_x6) {
        return _fetchOrdersByHttp.apply(this, arguments);
      }
      return fetchOrdersByHttp;
    }()
    /**
     * 将增量订单合并到 store
     */
    )
  }, {
    key: "mergeOrdersToStore",
    value: (function () {
      var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(freshOrders) {
        var _this9 = this;
        var freshMap, _iterator4, _step4, order, id, uniqueFreshCount, updatedList, _iterator5, _step5, _order;
        return _regeneratorRuntime().wrap(function _callee13$(_context13) {
          while (1) switch (_context13.prev = _context13.next) {
            case 0:
              this.logInfo('mergeOrdersToStore-开始', {
                freshOrderCount: freshOrders.length,
                storeOrderCountBefore: this.store.list.length
              });
              freshMap = new Map();
              _iterator4 = _createForOfIteratorHelper(freshOrders);
              _context13.prev = 3;
              _iterator4.s();
            case 5:
              if ((_step4 = _iterator4.n()).done) {
                _context13.next = 13;
                break;
              }
              order = _step4.value;
              id = order === null || order === void 0 ? void 0 : order.order_id;
              if (!(id === undefined || id === null)) {
                _context13.next = 10;
                break;
              }
              return _context13.abrupt("continue", 11);
            case 10:
              freshMap.set(this.getIdKey(id), order);
            case 11:
              _context13.next = 5;
              break;
            case 13:
              _context13.next = 18;
              break;
            case 15:
              _context13.prev = 15;
              _context13.t0 = _context13["catch"](3);
              _iterator4.e(_context13.t0);
            case 18:
              _context13.prev = 18;
              _iterator4.f();
              return _context13.finish(18);
            case 21:
              uniqueFreshCount = freshMap.size;
              updatedList = this.store.list.map(function (order) {
                var id = order.order_id;
                if (id === undefined || id === null) return order;
                var key = _this9.getIdKey(id);
                if (!freshMap.has(key)) return order;
                var fresh = freshMap.get(key);
                freshMap.delete(key);
                return fresh;
              });
              _iterator5 = _createForOfIteratorHelper(freshMap.values());
              try {
                for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
                  _order = _step5.value;
                  updatedList.push(_order);
                }
              } catch (err) {
                _iterator5.e(err);
              } finally {
                _iterator5.f();
              }
              this.store.list = updatedList;
              this.syncOrdersMap();
              _context13.next = 29;
              return this.saveOrdersToSQLite(this.store.list);
            case 29:
              this.logInfo('mergeOrdersToStore-结束', {
                uniqueFreshCount: uniqueFreshCount,
                storeOrderCountAfter: this.store.list.length
              });
              this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
            case 31:
            case "end":
              return _context13.stop();
          }
        }, _callee13, this, [[3, 15, 18, 21]]);
      }));
      function mergeOrdersToStore(_x7) {
        return _mergeOrdersToStore.apply(this, arguments);
      }
      return mergeOrdersToStore;
    }())
  }, {
    key: "normalizeOrderSyncMessage",
    value: function normalizeOrderSyncMessage(res) {
      var data = (res === null || res === void 0 ? void 0 : res.data) || res;
      if (!data) return null;
      var payload = data !== null && data !== void 0 && data.data && _typeof(data.data) === 'object' ? data.data : undefined;
      var normalized = _objectSpread(_objectSpread({}, data), {}, {
        _channelKey: data.module || 'sales_sync'
      });
      if (!normalized.type && typeof data.event === 'string') normalized.type = data.event;
      if (!normalized.id && data.id !== undefined) normalized.id = data.id;
      if (!normalized.id && data.order_id !== undefined) normalized.id = data.order_id;
      if (!normalized.order_id && data.order_id !== undefined) normalized.order_id = data.order_id;
      if (!normalized.order_id && (payload === null || payload === void 0 ? void 0 : payload.order_id) !== undefined) normalized.order_id = payload.order_id;
      if (!normalized.body && (payload === null || payload === void 0 ? void 0 : payload.order_id) !== undefined) normalized.body = payload;
      if (!normalized.data && (payload === null || payload === void 0 ? void 0 : payload.order_id) !== undefined) normalized.data = payload;
      return normalized;
    }
  }, {
    key: "normalizeOrderSyncPayload",
    value: function normalizeOrderSyncPayload(payload) {
      if (!payload) return null;
      var orderId = payload.order_id;
      if (orderId === undefined || orderId === null) return null;
      return _objectSpread(_objectSpread({}, payload), {}, {
        order_id: orderId
      });
    }
  }, {
    key: "uniqueOrderIds",
    value: function uniqueOrderIds(ids) {
      var idMap = new Map();
      var _iterator6 = _createForOfIteratorHelper(ids),
        _step6;
      try {
        for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
          var id = _step6.value;
          idMap.set(this.getIdKey(id), id);
        }
      } catch (err) {
        _iterator6.e(err);
      } finally {
        _iterator6.f();
      }
      return _toConsumableArray(idMap.values());
    }
  }, {
    key: "getIdKey",
    value: function getIdKey(id) {
      return String(id);
    }

    /**
     * 当前订单拉取窗口：
     * - 优先使用 createdAtQuery.sales_time_between（已按营业日边界初始化）
     * - 无法解析时退化为自然日窗口
     */
  }, {
    key: "getCurrentPullWindow",
    value: function getCurrentPullWindow() {
      var _this$store2;
      var now = dayjs();
      var range = (_this$store2 = this.store) === null || _this$store2 === void 0 || (_this$store2 = _this$store2.createdAtQuery) === null || _this$store2 === void 0 ? void 0 : _this$store2.sales_time_between;
      if (Array.isArray(range) && range.length >= 2) {
        var _startAt = dayjs(range[0]);
        var endExclusiveAt = dayjs(range[1]);
        if (_startAt.isValid() && endExclusiveAt.isValid() && endExclusiveAt.isAfter(_startAt)) {
          return {
            startAt: _startAt,
            endExclusiveAt: endExclusiveAt
          };
        }
      }
      var startAt = now.startOf('day');
      return {
        startAt: startAt,
        endExclusiveAt: startAt.add(1, 'day')
      };
    }
  }, {
    key: "hasPulledOrdersToday",
    value: function hasPulledOrdersToday() {
      var lastFullFetchAt = this.getStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY);
      if (!lastFullFetchAt) return false;
      var parsed = dayjs(lastFullFetchAt);
      if (!parsed.isValid()) return false;

      // 按当前拉取窗口判断，而不是自然日判断。
      // 这样在营业日跨日边界（start_time）场景下也能正确判定是否需要重新拉取。
      var _this$getCurrentPullW = this.getCurrentPullWindow(),
        startAt = _this$getCurrentPullW.startAt,
        endExclusiveAt = _this$getCurrentPullW.endExclusiveAt;
      return (parsed.isAfter(startAt) || parsed.isSame(startAt)) && parsed.isBefore(endExclusiveAt);
    }
  }, {
    key: "markOrderPulledAtNow",
    value: function markOrderPulledAtNow() {
      this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, dayjs().format('YYYY-MM-DD HH:mm:ss'));
    }
  }, {
    key: "getStorageItem",
    value: function getStorageItem(key) {
      try {
        var _this$storage;
        if ((_this$storage = this.storage) !== null && _this$storage !== void 0 && _this$storage.getStorage) return this.storage.getStorage(key);
        if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
          return globalThis.localStorage.getItem(key);
        }
      } catch (_unused5) {
        // 忽略存储异常，避免影响主流程
      }
      return null;
    }
  }, {
    key: "setStorageItem",
    value: function setStorageItem(key, value) {
      try {
        var _this$storage2;
        if ((_this$storage2 = this.storage) !== null && _this$storage2 !== void 0 && _this$storage2.setStorage) {
          this.storage.setStorage(key, value);
          return;
        }
        if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
          globalThis.localStorage.setItem(key, value);
        }
      } catch (_unused6) {
        // 忽略存储异常，避免影响主流程
      }
    }
  }, {
    key: "loadOrdersFromSQLite",
    value: function () {
      var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
        var orders;
        return _regeneratorRuntime().wrap(function _callee14$(_context14) {
          while (1) switch (_context14.prev = _context14.next) {
            case 0:
              if (this.dbManager) {
                _context14.next = 2;
                break;
              }
              return _context14.abrupt("return", []);
            case 2:
              _context14.prev = 2;
              _context14.next = 5;
              return this.dbManager.getAll(INDEXDB_STORE_NAME);
            case 5:
              orders = _context14.sent;
              return _context14.abrupt("return", orders || []);
            case 9:
              _context14.prev = 9;
              _context14.t0 = _context14["catch"](2);
              return _context14.abrupt("return", []);
            case 12:
            case "end":
              return _context14.stop();
          }
        }, _callee14, this, [[2, 9]]);
      }));
      function loadOrdersFromSQLite() {
        return _loadOrdersFromSQLite.apply(this, arguments);
      }
      return loadOrdersFromSQLite;
    }()
  }, {
    key: "saveOrdersToSQLite",
    value: function () {
      var _saveOrdersToSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(orderList) {
        return _regeneratorRuntime().wrap(function _callee15$(_context15) {
          while (1) switch (_context15.prev = _context15.next) {
            case 0:
              if (this.dbManager) {
                _context15.next = 2;
                break;
              }
              return _context15.abrupt("return");
            case 2:
              _context15.prev = 2;
              this.logInfo('saveOrdersToSQLite-开始', {
                count: orderList.length
              });
              _context15.next = 6;
              return this.dbManager.clear(INDEXDB_STORE_NAME);
            case 6:
              this.logInfo('saveOrdersToSQLite-clear完成', {
                count: orderList.length
              });
              if (!(orderList.length === 0)) {
                _context15.next = 9;
                break;
              }
              return _context15.abrupt("return");
            case 9:
              _context15.next = 11;
              return this.dbManager.bulkAdd(INDEXDB_STORE_NAME, orderList);
            case 11:
              this.logInfo('saveOrdersToSQLite-bulkAdd完成', {
                count: orderList.length
              });
              _context15.next = 17;
              break;
            case 14:
              _context15.prev = 14;
              _context15.t0 = _context15["catch"](2);
              // SQLite 异常，避免影响主流程
              this.logError('保存订单到 SQLite 失败', {
                error: _context15.t0 instanceof Error ? _context15.t0.message : String(_context15.t0),
                orderList: orderList.length
              });
            case 17:
            case "end":
              return _context15.stop();
          }
        }, _callee15, this, [[2, 14]]);
      }));
      function saveOrdersToSQLite(_x8) {
        return _saveOrdersToSQLite.apply(this, arguments);
      }
      return saveOrdersToSQLite;
    }()
  }, {
    key: "clear",
    value: function () {
      var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16() {
        return _regeneratorRuntime().wrap(function _callee16$(_context16) {
          while (1) switch (_context16.prev = _context16.next) {
            case 0:
              this.store.list = [];
              this.store.map = new Map();
              this.resourceIdIndex.clear();
              if (!this.dbManager) {
                _context16.next = 6;
                break;
              }
              _context16.next = 6;
              return this.dbManager.clear(INDEXDB_STORE_NAME);
            case 6:
              this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, '');
              this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
            case 8:
            case "end":
              return _context16.stop();
          }
        }, _callee16, this);
      }));
      function clear() {
        return _clear.apply(this, arguments);
      }
      return clear;
    }()
  }]);
  return OrderModule;
}(BaseModule);