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/modules/Order/index.ts
var Order_exports = {};
__export(Order_exports, {
  OrderModule: () => OrderModule
});
module.exports = __toCommonJS(Order_exports);
var import_BaseModule = require("../BaseModule");
var import_types = require("./types");
var import_utils = require("./utils");
var import_utils2 = require("../Product/utils");
var import_dayjs = __toESM(require("dayjs"));
var import_utils3 = require("../../solution/ScanOrder/utils");
var import_manualProductDiscount = require("./utils/manualProductDiscount");
var import_Discount = require("../Discount");
var import_Rules = require("../Rules");
var import_types2 = require("../Rules/types");
var import_decimal = __toESM(require("decimal.js"));
var import_lodash_es = require("lodash-es");
var LOCAL_ORDER_STORE_NAME = "orders";
var OrderModule = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name || "order", version);
    this.defaultName = "order";
    this.defaultVersion = "1.0.0";
    /** 是否将 tempOrder 写入 localStorage；默认 true，SalesSdk 等内存态场景可关闭。 */
    this.enableTempOrderPersist = true;
  }
  /**
   * Populate `savedAmount` on each discount based on product-level discount details.
   * Only selected discounts get a non-zero value.
   */
  static populateSavedAmounts(productList, discountList) {
    var _a, _b;
    const savedMap = /* @__PURE__ */ new Map();
    for (const product of productList) {
      const qty = product.num || 1;
      for (const pd of product.discount_list || []) {
        const discountKey = ((_a = pd.discount) == null ? void 0 : _a.resource_id) || pd.id;
        if (discountKey == null)
          continue;
        const amount = new import_decimal.default(pd.amount || 0).times(qty).plus(((_b = pd.metadata) == null ? void 0 : _b.product_discount_difference) || 0);
        savedMap.set(
          discountKey,
          (savedMap.get(discountKey) || new import_decimal.default(0)).plus(amount)
        );
      }
    }
    for (const d of discountList) {
      const key = d.id;
      d.savedAmount = d.isSelected && key != null && savedMap.has(key) ? savedMap.get(key).toNumber() : 0;
    }
  }
  async initialize(core, options) {
    var _a, _b, _c;
    this.core = core;
    this.store = options.store;
    if (!this.store.tempOrder) {
      this.store.tempOrder = null;
    }
    if (!this.store.summary) {
      this.store.summary = (0, import_utils.createEmptySummary)();
    }
    this.request = this.core.getPlugin("request");
    const appPlugin = this.core.getPlugin("app");
    if (!appPlugin) {
      throw new Error("Order 模块需要 app 插件支持");
    }
    const app = appPlugin.getApp();
    this.logger = app.logger;
    this.dbManager = app.sqlite;
    this.window = this.core.getPlugin("window");
    const otherParams = options.otherParams || {};
    this.cacheId = otherParams.cacheId;
    this.salesSummaryModuleName = otherParams.salesSummaryModuleName;
    this.rulesHooksOverride = (_a = otherParams.rules) == null ? void 0 : _a.hooks;
    this.orderHooks = options.hooks || ((_b = otherParams.order) == null ? void 0 : _b.hooks) || ((_c = otherParams.hooks) == null ? void 0 : _c.order);
    this.otherParams = otherParams;
    this.enableTempOrderPersist = otherParams.enableTempOrderPersist !== false;
    this.registerDiscountModules(options);
    if (this.enableTempOrderPersist) {
      this.restoreTempOrderFromStorage();
    }
    this.logInfo("OrderModule initialized successfully");
  }
  /**
   * 记录信息日志
   */
  logInfo(title, metadata) {
    if (this.logger) {
      this.logger.addLog({
        type: "info",
        title: `[OrderModule] ${title}`,
        metadata: metadata || {}
      });
    }
  }
  /**
   * 记录警告日志
   */
  logWarning(title, metadata) {
    if (this.logger) {
      this.logger.addLog({
        type: "warning",
        title: `[OrderModule] ${title}`,
        metadata: metadata || {}
      });
    }
  }
  /**
   * 记录错误日志
   */
  logError(title, metadata) {
    if (this.logger) {
      this.logger.addLog({
        type: "error",
        title: `[OrderModule] ${title}`,
        metadata: metadata || {}
      });
    }
  }
  // ─── Discount: 子模块注册 ───
  registerDiscountModules(options) {
    let targetCacheData = {};
    if (this.cacheId && this.window) {
      const sessionData = this.window.sessionStorage.getItem(this.name);
      if (sessionData) {
        try {
          const data = JSON.parse(sessionData);
          targetCacheData = (data == null ? void 0 : data[this.cacheId]) || {};
        } catch {
        }
      }
    }
    const discount = new import_Discount.DiscountModule(`${this.name}_discount`);
    this.core.registerModule(discount, {
      initialState: targetCacheData == null ? void 0 : targetCacheData[discount.name],
      otherParams: {
        fatherModule: this.name,
        openCache: !!this.cacheId,
        cacheId: this.cacheId
      }
    });
    this.store.discount = discount;
    const rules = new import_Rules.RulesModule(`${this.name}_rules`);
    this.core.registerModule(rules, {
      hooks: this.rulesHooksOverride || this.createDefaultRulesHooks()
    });
    this.store.rules = rules;
  }
  createDefaultRulesHooks() {
    return (0, import_utils.createDefaultOrderRulesHooks)();
  }
  // ─── Discount: 公共 API ───
  async loadDiscountConfig(params) {
    var _a, _b, _c, _d, _e, _f;
    const orderId = params.orderId || ((_a = this.store.tempOrder) == null ? void 0 : _a.order_id) || void 0;
    const discountList = await ((_b = this.store.discount) == null ? void 0 : _b.loadPrepareConfig({
      customer_id: params.customerId,
      action: params.action || (orderId ? "edit" : "create"),
      with_good_pass: 1,
      with_discount_card: 1,
      with_wallet_pass_holder: 1,
      request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      ...orderId ? { order_id: orderId } : {}
    }));
    if (discountList) {
      await ((_c = this.store.discount) == null ? void 0 : _c.setOriginalDiscountList(discountList));
      await ((_d = this.store.discount) == null ? void 0 : _d.setDiscountList(discountList));
    }
    if (params.apply !== false && ((_f = (_e = this.store.tempOrder) == null ? void 0 : _e.products) == null ? void 0 : _f.length)) {
      this.applyDiscount();
    }
    return this.getDiscountList();
  }
  getDiscountList() {
    var _a;
    return ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList()) || [];
  }
  async scanCode(code, customerId) {
    var _a, _b, _c, _d, _e;
    const resultDiscountList = await ((_a = this.store.discount) == null ? void 0 : _a.batchSearch(code, { customerId })) || [];
    const rulesModule = this.store.rules;
    if (!rulesModule) {
      return {
        type: "clientCalc",
        isAvailable: false,
        discountList: this.getDiscountList(),
        scannedDiscountList: resultDiscountList,
        unavailableReason: import_types2.UnavailableReason.Unknown
      };
    }
    if (!resultDiscountList.length) {
      return {
        type: "server",
        isAvailable: false,
        discountList: this.getDiscountList(),
        scannedDiscountList: resultDiscountList
      };
    }
    const withScanList = resultDiscountList.map((item) => ({
      ...item,
      isScan: true
    }));
    const currentSelected = this.getDiscountList().filter((n) => n.isSelected);
    if (currentSelected.length && currentSelected.some((n) => withScanList.some((m) => m.id === n.id))) {
      return {
        type: "clientCalc",
        isAvailable: true,
        discountList: this.getDiscountList(),
        scannedDiscountList: resultDiscountList
      };
    }
    const tempOrder = this.store.tempOrder;
    const holders = ((_b = tempOrder == null ? void 0 : tempOrder.holder) == null ? void 0 : _b.form_record_id) ? [{ form_record_id: tempOrder.holder.form_record_id }] : [];
    const { isAvailable, discountList: newDiscountList, unavailableReason } = rulesModule.isDiscountListAvailable({
      productList: (tempOrder == null ? void 0 : tempOrder.products) || [],
      oldDiscountList: this.getDiscountList(),
      newDiscountList: withScanList,
      orderTotalAmount: Number(((_c = this.store.summary) == null ? void 0 : _c.total_amount) || 0),
      holders,
      isFormSubject: !!((_d = tempOrder == null ? void 0 : tempOrder.holder) == null ? void 0 : _d.type) && tempOrder.holder.type === "form"
    }) || { isAvailable: false, discountList: this.getDiscountList() };
    if (isAvailable && newDiscountList) {
      (_e = this.store.discount) == null ? void 0 : _e.setDiscountList(newDiscountList);
      this.applyDiscount();
    }
    return {
      type: "clientCalc",
      isAvailable: isAvailable || false,
      discountList: newDiscountList || this.getDiscountList(),
      scannedDiscountList: resultDiscountList,
      unavailableReason
    };
  }
  applyDiscount() {
    var _a, _b, _c, _d, _e;
    const tempOrder = this.store.tempOrder;
    if (!tempOrder)
      return;
    delete tempOrder.discount_list;
    const rulesModule = this.store.rules;
    if (!rulesModule)
      return;
    const discountList = ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList()) || [];
    const holders = ((_b = tempOrder.holder) == null ? void 0 : _b.form_record_id) ? [{ form_record_id: tempOrder.holder.form_record_id }] : [];
    const result = rulesModule.calcDiscount({
      productList: tempOrder.products,
      discountList,
      holders,
      isFormSubject: !!((_c = tempOrder.holder) == null ? void 0 : _c.type) && tempOrder.holder.type === "form",
      orderTotalAmount: Number(((_d = this.store.summary) == null ? void 0 : _d.total_amount) || 0)
    });
    if (result == null ? void 0 : result.productList) {
      tempOrder.products = (result.productList || []).map((product) => ({
        ...product,
        discount_list: (0, import_utils.normalizeOrderProductDiscountList)(
          (0, import_manualProductDiscount.syncManualProductDiscountProductNum)(
            product.discount_list,
            product.num
          )
        )
      }));
    }
    if (result == null ? void 0 : result.discountList) {
      OrderModule.populateSavedAmounts(
        result.productList || tempOrder.products,
        result.discountList
      );
      (_e = this.store.discount) == null ? void 0 : _e.setDiscountList(result.discountList);
    }
  }
  // ─── TempOrder: 初始化入口 ───
  initTempOrder(params) {
    if (params.cacheId !== void 0)
      this.cacheId = params.cacheId;
    if (params.salesSummaryModuleName !== void 0)
      this.salesSummaryModuleName = params.salesSummaryModuleName;
    this.restoreTempOrderFromStorage();
  }
  // ─── TempOrder: localStorage 持久化 ───
  getTempOrderStorageKey() {
    if (!this.cacheId)
      return null;
    return `scanOrder:tempOrder:${this.cacheId}`;
  }
  restoreTempOrderFromStorage() {
    var _a, _b;
    const key = this.getTempOrderStorageKey();
    if (!key)
      return;
    if (!this.window)
      return;
    const cachedData = this.window.localStorage.getItem(key);
    if (!cachedData)
      return;
    try {
      const parsedData = JSON.parse(cachedData);
      if (!(0, import_utils.isTempOrder)(parsedData)) {
        this.window.localStorage.removeItem(key);
        return;
      }
      if (Array.isArray(parsedData.products)) {
        for (let i = 0; i < parsedData.products.length; i++) {
          const p = parsedData.products[i];
          if (!p || typeof p !== "object")
            continue;
          if (!Array.isArray(p.product_option_item)) {
            p.product_option_item = [];
          }
          if (!Array.isArray(p.product_bundle)) {
            p.product_bundle = [];
          }
          const row = p;
          const normalized = (0, import_utils3.normalizeOrderProduct)(row);
          normalized.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
            normalized.discount_list
          );
          parsedData.products[i] = normalized;
        }
      }
      delete parsedData.discount_list;
      const parsedRecord = parsedData;
      this.store.summary = parsedRecord.summary || (0, import_utils.createEmptySummary)();
      delete parsedData.summary;
      if (parsedRecord.lastOrderInfo) {
        this.store.lastOrderInfo = parsedRecord.lastOrderInfo;
        delete parsedData.lastOrderInfo;
      }
      if (!parsedData._extend || typeof parsedData._extend !== "object") {
        parsedData._extend = { productsByUid: {} };
      } else if (!parsedData._extend.productsByUid) {
        parsedData._extend.productsByUid = {};
      }
      this.store.tempOrder = parsedData;
    } catch {
      (_b = (_a = this.window) == null ? void 0 : _a.localStorage) == null ? void 0 : _b.removeItem(key);
    }
  }
  /**
   * 运行时切换 tempOrder localStorage 持久化。
   *
   * @example
   * orderModule.setEnableTempOrderPersist(false);
   * orderModule.addProductToOrder(product); // 不会写入 localStorage
   */
  setEnableTempOrderPersist(enabled) {
    this.enableTempOrderPersist = enabled;
  }
  /**
   * 读取当前是否启用 tempOrder localStorage 持久化。
   *
   * @example
   * if (orderModule.isTempOrderPersistEnabled()) {
   *   orderModule.persistTempOrder();
   * }
   */
  isTempOrderPersistEnabled() {
    return this.enableTempOrderPersist;
  }
  persistTempOrder() {
    if (!this.enableTempOrderPersist)
      return;
    const key = this.getTempOrderStorageKey();
    if (!key || !this.store.tempOrder)
      return;
    if (!this.window)
      return;
    this.window.localStorage.setItem(key, JSON.stringify(this.store.tempOrder));
  }
  // ─── TempOrder: 创建 & 获取 ───
  createDefaultTempOrderInstance() {
    return (0, import_utils.createDefaultTempOrder)({
      now: (0, import_utils.formatDateTime)(/* @__PURE__ */ new Date())
    });
  }
  createExternalSaleNumber() {
    var _a;
    const timestamp = (0, import_dayjs.default)().format("YYYYMMDDHHmmssSSS");
    const random6 = String(Math.floor(Math.random() * 1e6)).padStart(6, "0");
    const parts = ["LOCAL"];
    const context = (_a = this.core) == null ? void 0 : _a.context;
    const getData = context == null ? void 0 : context.getData;
    if (typeof getData === "function") {
      const shopId = getData.call(context, "shop_id");
      const deviceId = getData.call(context, "device_id");
      if (shopId !== void 0 && shopId !== null && shopId !== "") {
        parts.push(String(shopId));
      }
      if (deviceId !== void 0 && deviceId !== null && deviceId !== "") {
        parts.push(String(deviceId).slice(-8));
      }
    } else {
      this.logWarning("external_sale_number context getData unavailable", { key: "shop_id" });
      this.logWarning("external_sale_number context getData unavailable", { key: "device_id" });
    }
    parts.push(timestamp, random6);
    return parts.join("_");
  }
  ensureExternalSaleNumber(tempOrder) {
    if (!tempOrder.external_sale_number) {
      tempOrder.external_sale_number = this.createExternalSaleNumber();
    }
    this.ensureRequestUniqueIdempotencyToken(tempOrder);
    return tempOrder.external_sale_number;
  }
  ensureRequestUniqueIdempotencyToken(tempOrder) {
    if (!tempOrder.request_unique_idempotency_token) {
      tempOrder.request_unique_idempotency_token = `${tempOrder.external_sale_number}_${Date.now()}`;
    }
    return tempOrder.request_unique_idempotency_token;
  }
  hasLocalDatabase() {
    return !!this.dbManager;
  }
  buildLocalOrderRecord(tempOrder) {
    const externalSaleNumber = this.ensureExternalSaleNumber(tempOrder);
    return {
      ...tempOrder,
      id: tempOrder.order_id ?? externalSaleNumber,
      external_sale_number: externalSaleNumber,
      summary: this.store.summary || (0, import_utils.createEmptySummary)(),
      lastOrderInfo: this.store.lastOrderInfo
    };
  }
  async getLocalOrderByOrderId(orderId) {
    var _a, _b, _c, _d;
    if (!this.dbManager || orderId === void 0 || orderId === null)
      return null;
    try {
      const direct = await ((_b = (_a = this.dbManager).get) == null ? void 0 : _b.call(
        _a,
        LOCAL_ORDER_STORE_NAME,
        orderId
      ));
      if (direct)
        return direct;
      const orders = await ((_d = (_c = this.dbManager).getAll) == null ? void 0 : _d.call(_c, LOCAL_ORDER_STORE_NAME));
      return (orders || []).find(
        (order) => String(order == null ? void 0 : order.order_id) === String(orderId)
      ) || null;
    } catch (error) {
      this.logWarning("getLocalOrderByOrderId failed", {
        orderId,
        error: error instanceof Error ? error.message : String(error)
      });
      return null;
    }
  }
  async getLocalOrderByOrderNumber(orderNumber) {
    var _a, _b, _c, _d;
    if (!this.dbManager || !orderNumber)
      return null;
    try {
      const direct = await ((_b = (_a = this.dbManager).get) == null ? void 0 : _b.call(
        _a,
        LOCAL_ORDER_STORE_NAME,
        orderNumber
      ));
      if (direct)
        return direct;
      const orders = await ((_d = (_c = this.dbManager).getAll) == null ? void 0 : _d.call(_c, LOCAL_ORDER_STORE_NAME));
      return (orders || []).find(
        (order) => String(order == null ? void 0 : order.order_number) === String(orderNumber)
      ) || null;
    } catch (error) {
      this.logWarning("getLocalOrderByOrderNumber failed", {
        orderNumber,
        error: error instanceof Error ? error.message : String(error)
      });
      return null;
    }
  }
  async getLocalOrderByExternalSaleNumber(externalSaleNumber) {
    var _a, _b, _c, _d;
    if (!this.dbManager || !externalSaleNumber)
      return null;
    try {
      const direct = await ((_b = (_a = this.dbManager).get) == null ? void 0 : _b.call(
        _a,
        LOCAL_ORDER_STORE_NAME,
        externalSaleNumber
      ));
      if (direct)
        return direct;
      const orders = await ((_d = (_c = this.dbManager).getAll) == null ? void 0 : _d.call(_c, LOCAL_ORDER_STORE_NAME));
      return (orders || []).find(
        (order) => String(order == null ? void 0 : order.external_sale_number) === String(externalSaleNumber)
      ) || null;
    } catch (error) {
      this.logWarning("getLocalOrderByExternalSaleNumber failed", {
        externalSaleNumber,
        error: error instanceof Error ? error.message : String(error)
      });
      return null;
    }
  }
  async saveDraft() {
    var _a, _b;
    if (!this.dbManager)
      return;
    const tempOrder = this.ensureTempOrder();
    const record = this.buildLocalOrderRecord(tempOrder);
    try {
      await ((_b = (_a = this.dbManager).update) == null ? void 0 : _b.call(_a, LOCAL_ORDER_STORE_NAME, record));
    } catch (error) {
      this.logWarning("saveDraft failed", {
        externalSaleNumber: tempOrder.external_sale_number,
        orderNumber: tempOrder.order_number,
        orderId: tempOrder.order_id,
        error: error instanceof Error ? error.message : String(error)
      });
    }
  }
  saveDraftInBackground() {
    void this.saveDraft();
  }
  async hydrateTempOrderFromLocalRecord(record) {
    return this.hydrateTempOrderFromRecord(record);
  }
  extractOrderIdFromSubmitResult(result) {
    var _a, _b;
    return ((_a = result == null ? void 0 : result.data) == null ? void 0 : _a.order_id) ?? (result == null ? void 0 : result.order_id) ?? ((_b = result == null ? void 0 : result.data) == null ? void 0 : _b.id) ?? (result == null ? void 0 : result.id) ?? null;
  }
  calculatePaymentTotal(payments) {
    return (0, import_utils.mapPaymentItemsToOrderPayments)(payments, {
      includeVoided: false
    }).reduce((sum, payment) => {
      const amount = new import_decimal.default(payment.amount || 0);
      const rounding = new import_decimal.default(payment.rounding_amount || 0);
      return sum.plus(amount.minus(rounding));
    }, new import_decimal.default(0));
  }
  calculatePaidPaymentSummary(payments) {
    return (payments || []).reduce(
      (summary, payment) => {
        const paymentRecord = payment;
        if ((paymentRecord == null ? void 0 : paymentRecord.status) !== "paid")
          return summary;
        return {
          customerPaidAmount: summary.customerPaidAmount.plus(paymentRecord.amount || 0),
          orderPaidAmount: summary.orderPaidAmount.plus(paymentRecord.origin_amount || 0),
          payServiceChargeAmount: summary.payServiceChargeAmount.plus(this.calculatePaymentServiceFee(paymentRecord))
        };
      },
      {
        customerPaidAmount: new import_decimal.default(0),
        orderPaidAmount: new import_decimal.default(0),
        payServiceChargeAmount: new import_decimal.default(0)
      }
    );
  }
  calculatePaymentServiceFee(payment) {
    if (payment.service_fee !== void 0 && payment.service_fee !== null && payment.service_fee !== "") {
      return new import_decimal.default(payment.service_fee || 0);
    }
    const serviceCharge = payment.service_charge && typeof payment.service_charge === "object" ? payment.service_charge : {};
    const percentage = new import_decimal.default(serviceCharge.percentage || 0);
    const fixedAmount = new import_decimal.default(serviceCharge.amount || 0);
    return new import_decimal.default(payment.amount || 0).times(percentage).plus(fixedAmount);
  }
  getPaymentTargetAmount() {
    const tempOrder = this.ensureTempOrder();
    const summary = this.store.summary || (0, import_utils.createEmptySummary)();
    if (tempOrder.is_deposit === 1) {
      return new import_decimal.default(
        tempOrder.deposit_amount || summary.deposit_amount || 0
      );
    }
    return new import_decimal.default(summary.total_amount || summary.expect_amount || 0);
  }
  ensureTempOrder() {
    if (this.store.tempOrder) {
      this.ensureExternalSaleNumber(this.store.tempOrder);
      return this.store.tempOrder;
    }
    const newOrder = this.createDefaultTempOrderInstance();
    this.ensureExternalSaleNumber(newOrder);
    this.store.tempOrder = newOrder;
    this.persistTempOrder();
    return newOrder;
  }
  restoreOrder() {
    var _a, _b;
    const freshTempOrder = this.createDefaultTempOrderInstance();
    this.ensureExternalSaleNumber(freshTempOrder);
    this.store.tempOrder = freshTempOrder;
    this.store.summary = (0, import_utils.createEmptySummary)();
    this.store.lastOrderInfo = void 0;
    this.store.syncState = void 0;
    void ((_a = this.store.discount) == null ? void 0 : _a.setOriginalDiscountList([]));
    void ((_b = this.store.discount) == null ? void 0 : _b.setDiscountList([]));
    this.persistTempOrder();
    return freshTempOrder;
  }
  getTempOrder() {
    return this.store.tempOrder;
  }
  async replaceTempOrder(tempOrder, options) {
    if (!(0, import_utils.isTempOrder)(tempOrder)) {
      throw new Error("无效的 tempOrder 数据");
    }
    const nextTempOrder = this.normalizeTempOrderForRuntime(
      (0, import_lodash_es.cloneDeep)(tempOrder),
      { ensureIdentity: false }
    );
    this.store.tempOrder = nextTempOrder;
    if ((options == null ? void 0 : options.recalculateSummary) !== false) {
      await this.recalculateSummary({ createIfMissing: false });
    } else {
      this.store.summary = (0, import_utils.createEmptySummary)();
    }
    if ((options == null ? void 0 : options.persist) !== false) {
      this.persistTempOrder();
    }
    if (options == null ? void 0 : options.saveDraft) {
      await this.saveDraft();
    }
    return nextTempOrder;
  }
  getOrderIdentity() {
    var _a;
    const tempOrder = this.store.tempOrder;
    if (!tempOrder)
      return null;
    const lastOrderInfo = this.store.lastOrderInfo || {};
    const orderId = tempOrder.order_id ?? lastOrderInfo.order_id ?? lastOrderInfo.id ?? null;
    return {
      localId: this.cacheId || ((_a = tempOrder._extend) == null ? void 0 : _a.localId),
      orderId,
      externalSaleNumber: tempOrder.external_sale_number || lastOrderInfo.external_sale_number || "",
      orderNumber: tempOrder.order_number || lastOrderInfo.order_number || "",
      shopOrderNumber: tempOrder.shop_order_number || lastOrderInfo.shop_order_number || "",
      shopFullOrderNumber: tempOrder.shop_full_order_number || lastOrderInfo.shop_full_order_number || "",
      isSubmitted: orderId !== null && orderId !== void 0
    };
  }
  getOrderSyncState() {
    const tempOrder = this.store.tempOrder;
    if (!tempOrder)
      return "local";
    if (this.store.syncState)
      return this.store.syncState;
    if (this.store.lastOrderInfo)
      return "remoteLoaded";
    if (tempOrder.order_id)
      return "submitted";
    return "local";
  }
  getOrderAmountSnapshot() {
    const tempOrder = this.store.tempOrder;
    if (!tempOrder)
      return null;
    const summary = this.store.summary || (0, import_utils.createEmptySummary)();
    const depositAmount = tempOrder.deposit_amount || summary.deposit_amount || "0.00";
    const targetAmount = tempOrder.is_deposit === 1 ? new import_decimal.default(depositAmount || 0) : new import_decimal.default(summary.total_amount || summary.expect_amount || 0);
    const paymentTotal = this.calculatePaymentTotal(tempOrder.payments || []);
    const amountGap = import_decimal.default.max(0, targetAmount.minus(paymentTotal)).toFixed(2);
    return {
      isDeposit: tempOrder.is_deposit === 1 || depositAmount !== "0.00",
      depositAmount,
      expectAmount: summary.expect_amount || "0.00",
      totalAmount: summary.total_amount || "0.00",
      amountGap,
      summary
    };
  }
  getOrderSnapshot() {
    var _a;
    const tempOrder = this.store.tempOrder;
    if (!tempOrder)
      return null;
    const identity = this.getOrderIdentity();
    const amount = this.getOrderAmountSnapshot();
    if (!identity || !amount)
      return null;
    return {
      identity,
      syncState: this.getOrderSyncState(),
      amount,
      status: tempOrder.status || "",
      paymentStatus: tempOrder.payment_status || "",
      shippingStatus: tempOrder.shipping_status || "",
      note: tempOrder.note || "",
      customer: {
        customerId: tempOrder.customer_id ?? null,
        customerName: tempOrder.customer_name || "",
        phone: tempOrder.phone || "",
        email: tempOrder.email || ""
      },
      productCount: ((_a = tempOrder.products) == null ? void 0 : _a.length) || 0,
      lastOrderInfo: this.store.lastOrderInfo,
      tempOrder
    };
  }
  async addNewOrder() {
    const tempOrder = this.ensureTempOrder();
    this.ensureExternalSaleNumber(tempOrder);
    await this.recalculateSummary({ createIfMissing: true });
    this.persistTempOrder();
    await this.saveDraft();
    return tempOrder;
  }
  getOrderProducts() {
    const tempOrder = this.ensureTempOrder();
    return tempOrder.products;
  }
  getProductUid(product) {
    const metadata = product.metadata && typeof product.metadata === "object" ? product.metadata : {};
    const uid = metadata.unique_identification_number || product.unique_identification_number || (0, import_utils.createUuidV4)();
    metadata.unique_identification_number = String(uid);
    product.metadata = metadata;
    return String(uid);
  }
  ensureExtend(tempOrder) {
    if (!tempOrder._extend || typeof tempOrder._extend !== "object") {
      tempOrder._extend = { productsByUid: {} };
    }
    if (!tempOrder._extend.productsByUid) {
      tempOrder._extend.productsByUid = {};
    }
    return tempOrder._extend;
  }
  captureProductRuntime(tempOrder, rawProduct, normalizedProduct, existedUid) {
    var _a;
    const uid = existedUid || this.getProductUid(normalizedProduct);
    const extend = this.ensureExtend(tempOrder);
    const existed = ((_a = extend.productsByUid) == null ? void 0 : _a[uid]) || {};
    const origin = rawProduct._origin ?? normalizedProduct._origin ?? existed.origin;
    extend.productsByUid[uid] = {
      ...existed,
      ...origin !== void 0 ? { origin } : {}
    };
    delete normalizedProduct._origin;
    delete normalizedProduct.unique_identification_number;
  }
  createLinkedProductAndBooking(params) {
    const productMetadata = params.product.metadata && typeof params.product.metadata === "object" ? { ...params.product.metadata } : {};
    const bookingMetadata = params.booking.metadata && typeof params.booking.metadata === "object" ? { ...params.booking.metadata } : {};
    const productUid = String(
      productMetadata.unique_identification_number || params.product.unique_identification_number || (0, import_utils.createUuidV4)()
    );
    const bookingUid = String(
      bookingMetadata.unique_identification_number || (0, import_utils.createUuidV4)()
    );
    productMetadata.unique_identification_number = productUid;
    bookingMetadata.unique_identification_number = bookingUid;
    return {
      productUid,
      bookingUid,
      product: {
        ...params.product,
        unique_identification_number: productUid,
        metadata: {
          ...productMetadata,
          booking_uid: bookingUid
        },
        booking_uid: bookingUid
      },
      booking: {
        ...params.booking,
        is_all: (0, import_utils.normalizeBookingIsAll)(params.booking),
        product_uid: productUid,
        sub_type: (0, import_utils.normalizeBookingSubType)(params.booking),
        metadata: bookingMetadata
      }
    };
  }
  getBookingUniqueIdentificationNumber(booking) {
    var _a;
    const uid = (_a = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a.unique_identification_number;
    if (uid === void 0 || uid === null || uid === "")
      return null;
    return String(uid);
  }
  findBookingIndexByUniqueIdentificationNumber(tempOrder, uniqueIdentificationNumber) {
    return (tempOrder.bookings || []).findIndex((booking) => {
      return this.getBookingUniqueIdentificationNumber(booking) === uniqueIdentificationNumber;
    });
  }
  removeLinkedBookingsForProduct(tempOrder, product) {
    var _a, _b;
    const productUid = ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a.unique_identification_number) || (product == null ? void 0 : product.unique_identification_number);
    const bookingUid = (product == null ? void 0 : product.booking_uid) || ((_b = product == null ? void 0 : product.metadata) == null ? void 0 : _b.booking_uid);
    if (!productUid && !bookingUid)
      return;
    tempOrder.bookings = (tempOrder.bookings || []).filter((booking) => {
      const currentBookingUid = this.getBookingUniqueIdentificationNumber(booking);
      if (bookingUid && currentBookingUid === String(bookingUid))
        return false;
      if (productUid && String((booking == null ? void 0 : booking.product_uid) || "") === String(productUid))
        return false;
      return true;
    });
  }
  // ─── TempOrder: 金额汇总 ───
  getSalesSummary() {
    if (!this.salesSummaryModuleName)
      return null;
    return this.core.getModule(this.salesSummaryModuleName);
  }
  async recalculateSummary(options) {
    const tempOrder = (options == null ? void 0 : options.createIfMissing) ? this.ensureTempOrder() : this.store.tempOrder;
    if (!tempOrder)
      return null;
    const salesSummary = this.getSalesSummary();
    const existedSummary = this.store.summary || (0, import_utils.createEmptySummary)();
    const paidPaymentSummary = this.calculatePaidPaymentSummary(
      tempOrder.payments || []
    );
    if (!salesSummary) {
      const emptySummary = {
        ...(0, import_utils.createEmptySummary)(),
        total_refund_amount: existedSummary.total_refund_amount || "0.00",
        customer_paid_amount: paidPaymentSummary.customerPaidAmount.toFixed(2),
        order_paid_amount: paidPaymentSummary.orderPaidAmount.toFixed(2),
        pay_service_charge_amount: paidPaymentSummary.payServiceChargeAmount.toFixed(2)
      };
      this.store.summary = emptySummary;
      tempOrder.surcharge_fee = emptySummary.surcharge_fee;
      return this.store.summary;
    }
    const salesSummaryResult = await salesSummary.getSummary({
      products: tempOrder.products,
      isPriceIncludeTax: tempOrder.is_price_include_tax,
      shopDiscount: tempOrder.shop_discount
    });
    const summary = {
      ...salesSummaryResult,
      total_refund_amount: existedSummary.total_refund_amount || "0.00",
      customer_paid_amount: paidPaymentSummary.customerPaidAmount.toFixed(2),
      order_paid_amount: paidPaymentSummary.orderPaidAmount.toFixed(2),
      pay_service_charge_amount: paidPaymentSummary.payServiceChargeAmount.toFixed(2)
    };
    this.store.summary = summary;
    if (summary.is_price_include_tax !== void 0) {
      tempOrder.is_price_include_tax = summary.is_price_include_tax;
    }
    if (typeof summary.tax_title === "string" && summary.tax_title) {
      tempOrder.tax_title = summary.tax_title;
    }
    tempOrder.surcharge_fee = summary.surcharge_fee;
    tempOrder.surcharges = summary.surcharges || [];
    tempOrder.deposit_amount = summary.deposit_amount || "0.00";
    tempOrder.is_deposit = summary.deposit_amount !== "0.00" ? 1 : 0;
    return this.store.summary;
  }
  async getOrderSummary() {
    const summary = await this.recalculateSummary({ createIfMissing: true });
    if (!summary)
      return (0, import_utils.createEmptySummary)();
    this.persistTempOrder();
    return summary;
  }
  updateTempOrderNote(note, sync = false) {
    const tempOrder = this.ensureTempOrder();
    tempOrder.note = String(note || "");
    this.persistTempOrder();
    if (sync) {
      const orderId = tempOrder.order_id;
      if (!orderId)
        return tempOrder.note;
      return this.syncTempOrderNoteToRemote(orderId, tempOrder.note);
    }
    return tempOrder.note;
  }
  async syncTempOrderNoteToRemote(orderId, note) {
    await this.request.put(`/order/order/${orderId}/note`, { note });
    return note;
  }
  getTempOrderNote() {
    var _a;
    return ((_a = this.store.tempOrder) == null ? void 0 : _a.note) || "";
  }
  updateTempOrderShopDiscount(amount) {
    const tempOrder = this.ensureTempOrder();
    const discount = import_decimal.default.max(new import_decimal.default(Number(amount) || 0), 0).toDecimalPlaces(2).toFixed(2);
    tempOrder.shop_discount = discount;
    this.persistTempOrder();
    return tempOrder.shop_discount;
  }
  updateTempOrderBuzzer(buzzer) {
    const tempOrder = this.ensureTempOrder();
    tempOrder.buzzer = String(buzzer || "");
    this.persistTempOrder();
    return tempOrder.buzzer;
  }
  updateTempOrderContactsInfo(contactsInfo) {
    const tempOrder = this.ensureTempOrder();
    tempOrder.contacts_info = contactsInfo && typeof contactsInfo === "object" && !Array.isArray(contactsInfo) ? contactsInfo : null;
    this.persistTempOrder();
    return tempOrder.contacts_info;
  }
  buildTempOrderCustomer(params) {
    if (!params.customerId)
      return null;
    const source = params.source ? (0, import_lodash_es.cloneDeep)(params.source) : {};
    const name = source.name ?? source.display_name ?? source.customerName ?? source.customer_name ?? params.customerName;
    const customerName = source.customer_name ?? source.customerName ?? source.display_name ?? source.name ?? params.customerName;
    return {
      ...source,
      id: source.id ?? params.customerId,
      customer_id: source.customer_id ?? params.customerId,
      name: String(name || ""),
      customer_name: String(customerName || ""),
      country_calling_code: String(
        source.country_calling_code ?? source.countryCallingCode ?? params.countryCallingCode
      ),
      phone: String(source.phone ?? params.phone),
      email: String(source.email ?? params.email)
    };
  }
  /**
   * 更新当前 tempOrder 的客户协议字段。
   *
   * PaymentModal 只需要修改订单里的客户事实；如果外部还有客户模块需要同步，
   * 应由调用方通过回调处理，不能把外部 UI 状态写进 tempOrder。
   */
  updateTempOrderCustomer(customer) {
    const tempOrder = this.ensureTempOrder();
    const customerId = customer.customer_id ?? customer.customerId ?? customer.id ?? null;
    const customerName = customer.customer_name ?? customer.customerName ?? customer.display_name ?? customer.name ?? "";
    tempOrder.customer_id = customerId === null || customerId === void 0 || customerId === "" ? null : Number(customerId);
    tempOrder.customer_name = String(customerName || "");
    tempOrder.country_calling_code = String(
      customer.country_calling_code ?? customer.countryCallingCode ?? ""
    );
    tempOrder.phone = String(customer.phone || "");
    tempOrder.email = String(customer.email || "");
    tempOrder.customer = this.buildTempOrderCustomer({
      source: customer,
      customerId: tempOrder.customer_id,
      customerName: tempOrder.customer_name,
      countryCallingCode: tempOrder.country_calling_code,
      phone: tempOrder.phone,
      email: tempOrder.email
    });
    this.persistTempOrder();
    return {
      customerId: tempOrder.customer_id,
      customerName: tempOrder.customer_name,
      phone: tempOrder.phone,
      email: tempOrder.email
    };
  }
  setOrderCustomer(patch, snapshot) {
    if (!patch) {
      this.clearOrderCustomer();
      return;
    }
    const tempOrder = this.ensureTempOrder();
    tempOrder.customer_id = patch.customer_id || patch.id || null;
    tempOrder.customer_name = String(patch.customer_name || "");
    tempOrder.country_calling_code = String(patch.country_calling_code || "");
    tempOrder.phone = String(patch.phone || "");
    tempOrder.email = String(patch.email || "");
    tempOrder.customer = this.buildTempOrderCustomer({
      source: snapshot || null,
      customerId: tempOrder.customer_id,
      customerName: tempOrder.customer_name,
      countryCallingCode: tempOrder.country_calling_code,
      phone: tempOrder.phone,
      email: tempOrder.email
    });
    if (snapshot !== void 0) {
      const extend = this.ensureExtend(tempOrder);
      if (snapshot === null)
        delete extend.customerSnapshot;
      else
        extend.customerSnapshot = (0, import_lodash_es.cloneDeep)(snapshot);
    }
    this.persistTempOrder();
    this.saveDraftInBackground();
    this.emitOrderCustomerChange();
  }
  getOrderCustomer() {
    const tempOrder = this.store.tempOrder;
    if (!tempOrder || !tempOrder.customer_id) {
      return null;
    }
    return {
      customer_id: tempOrder.customer_id,
      customer_name: tempOrder.customer_name || "",
      country_calling_code: tempOrder.country_calling_code || "",
      phone: tempOrder.phone || "",
      email: tempOrder.email || ""
    };
  }
  getOrderCustomerSnapshot() {
    var _a, _b;
    const snapshot = (_b = (_a = this.store.tempOrder) == null ? void 0 : _a._extend) == null ? void 0 : _b.customerSnapshot;
    return snapshot ? (0, import_lodash_es.cloneDeep)(snapshot) : null;
  }
  clearOrderCustomer() {
    const tempOrder = this.ensureTempOrder();
    tempOrder.customer_id = null;
    tempOrder.customer_name = "";
    tempOrder.country_calling_code = "";
    tempOrder.phone = "";
    tempOrder.email = "";
    tempOrder.customer = null;
    if (tempOrder._extend)
      delete tempOrder._extend.customerSnapshot;
    this.persistTempOrder();
    this.saveDraftInBackground();
    this.core.effects.emit(import_types.OrderHooks.OnOrderCustomerChange, null);
  }
  emitOrderCustomerChange() {
    const patch = this.getOrderCustomer();
    if (!patch) {
      this.core.effects.emit(import_types.OrderHooks.OnOrderCustomerChange, null);
      return;
    }
    const payload = {
      patch,
      snapshot: this.getOrderCustomerSnapshot()
    };
    this.core.effects.emit(import_types.OrderHooks.OnOrderCustomerChange, payload);
  }
  /**
   * 读取当前订单的 Sales 协议支付项。
   *
   * 这里返回的是 tempOrder.payments，而不是旧 PaymentModule 的本地
   * payment order / tender session。Sales checkout 以该数组为提交事实来源。
   */
  getOrderPayments() {
    const tempOrder = this.ensureTempOrder();
    return tempOrder.payments || [];
  }
  /**
   * 用一组支付来源覆盖当前订单支付项。
   *
   * 入参允许来自 PaymentModule 的 PaymentItem，内部统一映射为 Sales 协议：
   * uuid -> metadata.unique_payment_number，id -> custom_payment_id，
   * isSynced 等运行态字段不会进入 tempOrder.payments。
   */
  setOrderPayments(payments) {
    const tempOrder = this.ensureTempOrder();
    tempOrder.payments = (0, import_utils.mapPaymentItemsToOrderPayments)(payments);
    this.persistTempOrder();
    return tempOrder.payments;
  }
  /** 追加单个支付项，并立即持久化当前 tempOrder。 */
  addOrderPayment(payment) {
    this.logInfo("addOrderPayment", {
      payment
    });
    const tempOrder = this.ensureTempOrder();
    const mapped = (0, import_utils.mapPaymentItemsToOrderPayments)([payment]);
    tempOrder.payments = [...tempOrder.payments || [], ...mapped];
    this.persistTempOrder();
    return tempOrder.payments;
  }
  /**
   * 按支付唯一号、后端支付 ID、自定义支付方式 ID 或旧 uuid 更新支付项。
   *
   * 该方法服务 PaymentModal 的 void / 编辑场景；更新 metadata 时会做浅合并，
   * 避免覆盖 unique_payment_number、现金实付/找零等已有元数据。
   */
  updateOrderPayment(paymentIdentity, updates) {
    const tempOrder = this.ensureTempOrder();
    const identity = String(paymentIdentity);
    tempOrder.payments = (tempOrder.payments || []).map((payment) => {
      var _a;
      const uniquePaymentNumber = (_a = payment == null ? void 0 : payment.metadata) == null ? void 0 : _a.unique_payment_number;
      const orderPaymentId = payment == null ? void 0 : payment.order_payment_id;
      const customPaymentId = payment == null ? void 0 : payment.custom_payment_id;
      const uuid = payment == null ? void 0 : payment.uuid;
      const matched = [
        uniquePaymentNumber,
        orderPaymentId,
        customPaymentId,
        uuid
      ].some((value) => value !== void 0 && String(value) === identity);
      if (!matched)
        return payment;
      return {
        ...payment,
        ...updates,
        metadata: {
          ...payment.metadata || {},
          ...updates.metadata || {}
        }
      };
    });
    this.persistTempOrder();
    return tempOrder.payments;
  }
  /** 从当前订单支付项中移除指定支付项。 */
  deleteOrderPayment(paymentIdentity) {
    const tempOrder = this.ensureTempOrder();
    const identity = String(paymentIdentity);
    tempOrder.payments = (tempOrder.payments || []).filter((payment) => {
      var _a;
      const uniquePaymentNumber = (_a = payment == null ? void 0 : payment.metadata) == null ? void 0 : _a.unique_payment_number;
      const orderPaymentId = payment == null ? void 0 : payment.order_payment_id;
      const customPaymentId = payment == null ? void 0 : payment.custom_payment_id;
      const uuid = payment == null ? void 0 : payment.uuid;
      return ![
        uniquePaymentNumber,
        orderPaymentId,
        customPaymentId,
        uuid
      ].some((value) => value !== void 0 && String(value) === identity);
    });
    this.persistTempOrder();
    return tempOrder.payments;
  }
  /**
   * 覆盖当前订单中的 wallet pass 支付项。
   *
   * 判断口径与 PaymentModal 保持一致：voucher_id 存在且不为 0 的支付项
   * 视为 wallet pass；其它支付项保持不变。
   */
  updateVoucherOrderPayments(payments) {
    const tempOrder = this.ensureTempOrder();
    const mappedVouchers = (0, import_utils.mapPaymentItemsToOrderPayments)(payments).filter(
      (payment) => payment.voucher_id !== void 0 && Number(payment.voucher_id) !== 0
    );
    const nonVoucherPayments = (tempOrder.payments || []).filter((payment) => {
      return payment.voucher_id === void 0 || Number(payment.voucher_id) === 0;
    });
    tempOrder.payments = [...nonVoucherPayments, ...mappedVouchers];
    this.persistTempOrder();
    return tempOrder.payments;
  }
  async shouldMergeProductToOrder(params) {
    var _a;
    const onBeforeMergeProductToOrder = (_a = this.orderHooks) == null ? void 0 : _a.onBeforeMergeProductToOrder;
    if (!onBeforeMergeProductToOrder)
      return true;
    const result = await onBeforeMergeProductToOrder({
      ...params,
      defaultShouldMerge: true
    });
    if (typeof result === "boolean")
      return result;
    if (result && typeof result === "object" && typeof result.shouldMerge === "boolean") {
      return result.shouldMerge;
    }
    return true;
  }
  // ─── TempOrder: 商品 CRUD ───
  async addProductToOrder(product, booking) {
    var _a;
    const tempOrder = this.ensureTempOrder();
    const linked = booking ? this.createLinkedProductAndBooking({ product, booking }) : null;
    const productToAdd = (linked == null ? void 0 : linked.product) || product;
    const incomingFingerprint = (0, import_utils3.buildProductLineFingerprint)(
      productToAdd.product_option_item,
      productToAdd.product_bundle
    );
    const normalizedIncoming = (0, import_utils3.normalizeOrderProduct)(productToAdd);
    normalizedIncoming.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
      normalizedIncoming.discount_list
    );
    const hasIncomingGoodPass = this.hasGoodPassDiscount(
      normalizedIncoming
    );
    const shouldForceNewLine = !!booking;
    const matchedIndex = hasIncomingGoodPass || shouldForceNewLine ? -1 : tempOrder.products.findIndex((item) => {
      if (this.hasGoodPassDiscount(item))
        return false;
      if (item.product_id !== productToAdd.product_id)
        return false;
      if (item.product_variant_id !== productToAdd.product_variant_id)
        return false;
      const existedFingerprint2 = (0, import_utils3.buildProductLineFingerprint)(
        item.product_option_item,
        item.product_bundle
      );
      return existedFingerprint2 === incomingFingerprint;
    });
    const matchedProduct = matchedIndex === -1 ? null : tempOrder.products[matchedIndex];
    const existedFingerprint = matchedProduct ? (0, import_utils3.buildProductLineFingerprint)(
      matchedProduct.product_option_item,
      matchedProduct.product_bundle
    ) : "";
    const shouldMerge = matchedProduct ? await this.shouldMergeProductToOrder({
      incomingProduct: productToAdd,
      normalizedIncoming,
      matchedProduct,
      matchedIndex,
      incomingFingerprint,
      existedFingerprint,
      tempOrder,
      booking
    }) : false;
    if (matchedIndex === -1 || !matchedProduct || !shouldMerge) {
      this.captureProductRuntime(
        tempOrder,
        productToAdd,
        normalizedIncoming
      );
      if (linked) {
        normalizedIncoming.booking_uid = linked.bookingUid;
        normalizedIncoming.metadata = {
          ...normalizedIncoming.metadata || {},
          booking_uid: linked.bookingUid
        };
      }
      tempOrder.products.push(normalizedIncoming);
    } else {
      const targetProduct = matchedProduct;
      const targetUid = (_a = targetProduct.metadata) == null ? void 0 : _a.unique_identification_number;
      const normalizedProduct = (0, import_utils3.normalizeOrderProduct)({
        ...productToAdd,
        metadata: {
          ...productToAdd.metadata || {},
          unique_identification_number: targetUid
        }
      });
      normalizedProduct.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
        normalizedProduct.discount_list
      );
      tempOrder.products[matchedIndex] = {
        ...targetProduct,
        ...normalizedProduct,
        metadata: {
          ...targetProduct.metadata || {},
          ...normalizedProduct.metadata || {},
          unique_identification_number: targetUid
        },
        note: targetProduct.note,
        order_detail_id: targetProduct.order_detail_id,
        num: (0, import_utils3.getSafeProductNum)(targetProduct.num + normalizedProduct.num)
      };
      this.captureProductRuntime(
        tempOrder,
        productToAdd,
        tempOrder.products[matchedIndex],
        targetUid
      );
    }
    if (linked) {
      tempOrder.bookings = [...tempOrder.bookings || [], linked.booking];
    }
    this.applyDiscount();
    await this.recalculateSummary({ createIfMissing: true });
    this.persistTempOrder();
    return tempOrder.products;
  }
  hasGoodPassDiscount(product) {
    var _a, _b;
    const hasMainGoodPass = (product.discount_list || []).some(
      (item) => (item == null ? void 0 : item.type) === "good_pass" || (item == null ? void 0 : item.tag) === "good_pass"
    );
    if (hasMainGoodPass)
      return true;
    const bundleDiscountList = [];
    (product.product_bundle || []).forEach((item) => {
      bundleDiscountList.push(...(item == null ? void 0 : item.discount_list) || []);
    });
    (((_b = (_a = product == null ? void 0 : product._extend) == null ? void 0 : _a.other) == null ? void 0 : _b.bundle) || []).forEach((item) => {
      bundleDiscountList.push(...(item == null ? void 0 : item.discount_list) || []);
    });
    return bundleDiscountList.some(
      (item) => (item == null ? void 0 : item.type) === "good_pass" || (item == null ? void 0 : item.tag) === "good_pass"
    );
  }
  async updateOrderProduct(params) {
    var _a, _b, _c, _d, _e, _f, _g;
    const {
      product_id,
      product_variant_id,
      updates,
      unique_identification_number,
      identity_key,
      product_option_item,
      product_bundle,
      booking
    } = params;
    const tempOrder = this.ensureTempOrder();
    const identityLookup = {
      product_id,
      product_variant_id
    };
    if (unique_identification_number !== void 0) {
      identityLookup.unique_identification_number = unique_identification_number;
      if (identity_key === void 0) {
        identityLookup.identity_key = unique_identification_number;
      }
    }
    if (identity_key !== void 0) {
      identityLookup.identity_key = identity_key;
    }
    if (product_option_item !== void 0)
      identityLookup.product_option_item = product_option_item;
    if (product_bundle !== void 0)
      identityLookup.product_bundle = product_bundle;
    let productIndex = -1;
    if (unique_identification_number !== void 0) {
      const targetUid = String(unique_identification_number);
      productIndex = tempOrder.products.findIndex((item) => {
        var _a2;
        return String(
          ((_a2 = item.metadata) == null ? void 0 : _a2.unique_identification_number) || item.unique_identification_number || ""
        ) === targetUid;
      });
    }
    if (productIndex === -1) {
      productIndex = (0, import_utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
    }
    if (productIndex === -1) {
      throw new Error("[Order] 目标商品不存在，无法更新");
    }
    const targetProduct = tempOrder.products[productIndex];
    const nextProduct = {
      ...targetProduct,
      ...updates,
      product_id,
      product_variant_id,
      metadata: {
        ...targetProduct.metadata || {},
        ...(updates == null ? void 0 : updates.metadata) || {},
        unique_identification_number: ((_a = targetProduct.metadata) == null ? void 0 : _a.unique_identification_number) || unique_identification_number
      }
    };
    nextProduct.num = (0, import_utils3.getSafeProductNum)(nextProduct.num);
    const callerUpdatesTopPrice = Object.prototype.hasOwnProperty.call(updates || {}, "selling_price") || Object.prototype.hasOwnProperty.call(updates || {}, "original_price");
    const callerUpdatesMainMeta = ((_b = updates == null ? void 0 : updates.metadata) == null ? void 0 : _b.main_product_selling_price) !== void 0 || ((_c = updates == null ? void 0 : updates.metadata) == null ? void 0 : _c.main_product_original_price) !== void 0 || ((_d = updates == null ? void 0 : updates.metadata) == null ? void 0 : _d.source_product_price) !== void 0;
    if (callerUpdatesTopPrice && !callerUpdatesMainMeta) {
      const existedMeta = nextProduct.metadata || {};
      nextProduct.metadata = { ...existedMeta };
      delete nextProduct.metadata.source_product_price;
      delete nextProduct.metadata.main_product_selling_price;
      delete nextProduct.metadata.main_product_original_price;
      delete nextProduct.metadata.price_schema_version;
    }
    let normalizedProduct = (0, import_utils3.normalizeOrderProduct)(nextProduct);
    normalizedProduct.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
      normalizedProduct.discount_list
    );
    if (booking) {
      const productUid = String(
        ((_e = normalizedProduct.metadata) == null ? void 0 : _e.unique_identification_number) || ((_f = targetProduct.metadata) == null ? void 0 : _f.unique_identification_number) || unique_identification_number || (0, import_utils.createUuidV4)()
      );
      normalizedProduct.metadata = {
        ...normalizedProduct.metadata || {},
        unique_identification_number: productUid
      };
      const linked = this.createLinkedProductAndBooking({
        product: {
          ...normalizedProduct,
          unique_identification_number: productUid
        },
        booking
      });
      this.removeLinkedBookingsForProduct(tempOrder, targetProduct);
      normalizedProduct = {
        ...normalizedProduct,
        booking_uid: linked.bookingUid,
        metadata: {
          ...normalizedProduct.metadata || {},
          booking_uid: linked.bookingUid,
          unique_identification_number: productUid
        }
      };
      tempOrder.bookings = [...tempOrder.bookings || [], linked.booking];
    }
    tempOrder.products[productIndex] = normalizedProduct;
    this.captureProductRuntime(
      tempOrder,
      updates,
      tempOrder.products[productIndex],
      (_g = tempOrder.products[productIndex].metadata) == null ? void 0 : _g.unique_identification_number
    );
    this.applyDiscount();
    await this.recalculateSummary({ createIfMissing: true });
    this.persistTempOrder();
    return tempOrder.products;
  }
  async updateOrderProductQuantity(params) {
    var _a;
    const {
      product_id,
      product_variant_id,
      num,
      unique_identification_number,
      identity_key,
      product_option_item,
      product_bundle
    } = params;
    const tempOrder = this.ensureTempOrder();
    const identityLookup = {
      product_id,
      product_variant_id
    };
    if (unique_identification_number !== void 0) {
      identityLookup.unique_identification_number = unique_identification_number;
      if (identity_key === void 0) {
        identityLookup.identity_key = unique_identification_number;
      }
    }
    if (identity_key !== void 0)
      identityLookup.identity_key = identity_key;
    if (product_option_item !== void 0)
      identityLookup.product_option_item = product_option_item;
    if (product_bundle !== void 0)
      identityLookup.product_bundle = product_bundle;
    let productIndex = -1;
    if (unique_identification_number !== void 0) {
      const targetUid = String(unique_identification_number);
      productIndex = tempOrder.products.findIndex((item) => {
        var _a2;
        return String(
          ((_a2 = item.metadata) == null ? void 0 : _a2.unique_identification_number) || item.unique_identification_number || ""
        ) === targetUid;
      });
    }
    if (productIndex === -1) {
      productIndex = (0, import_utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
    }
    if (productIndex === -1) {
      throw new Error("[Order] 目标商品不存在，无法更新数量");
    }
    const targetProduct = tempOrder.products[productIndex];
    const normalizedProduct = (0, import_utils3.normalizeOrderProduct)({
      ...targetProduct,
      num: (0, import_utils3.getSafeProductNum)(num),
      metadata: {
        ...targetProduct.metadata || {},
        unique_identification_number: ((_a = targetProduct.metadata) == null ? void 0 : _a.unique_identification_number) || unique_identification_number
      }
    });
    normalizedProduct.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
      normalizedProduct.discount_list
    );
    tempOrder.products[productIndex] = normalizedProduct;
    this.applyDiscount();
    await this.recalculateSummary({ createIfMissing: true });
    this.persistTempOrder();
    return tempOrder.products;
  }
  updateOrderBooking(params) {
    const { unique_identification_number, updates } = params;
    const tempOrder = this.ensureTempOrder();
    const bookingUid = String(unique_identification_number || "");
    const bookingIndex = this.findBookingIndexByUniqueIdentificationNumber(
      tempOrder,
      bookingUid
    );
    if (!bookingUid || bookingIndex === -1) {
      throw new Error("[Order] 目标 booking 不存在，无法更新");
    }
    const targetBooking = tempOrder.bookings[bookingIndex] || {};
    const nextBooking = {
      ...targetBooking,
      ...updates,
      metadata: {
        ...targetBooking.metadata || {},
        ...updates.metadata || {},
        unique_identification_number: bookingUid
      }
    };
    nextBooking.is_all = (0, import_utils.normalizeBookingIsAll)(nextBooking);
    nextBooking.sub_type = (0, import_utils.normalizeBookingSubType)(nextBooking);
    tempOrder.bookings[bookingIndex] = nextBooking;
    this.persistTempOrder();
    return tempOrder.bookings;
  }
  async removeProductFromOrder(identity) {
    const tempOrder = this.ensureTempOrder();
    const removedProducts = [];
    tempOrder.products = tempOrder.products.filter((item) => {
      const shouldRemove = (0, import_utils3.isIdentityMatch)(item, identity);
      if (shouldRemove)
        removedProducts.push(item);
      return !shouldRemove;
    });
    for (const product of removedProducts) {
      this.removeLinkedBookingsForProduct(tempOrder, product);
    }
    this.applyDiscount();
    await this.recalculateSummary({ createIfMissing: true });
    this.persistTempOrder();
    return tempOrder.products;
  }
  /**
   * 仅清空购物车行（products / bookings），不重置整单。
   * 用于「仅清空商品」；客户、备注、支付等协议字段保持不变。
   */
  async clearOrderCartLines() {
    const tempOrder = this.ensureTempOrder();
    tempOrder.products = [];
    tempOrder.bookings = [];
    if (tempOrder._extend && typeof tempOrder._extend === "object") {
      tempOrder._extend = {
        ...tempOrder._extend,
        productsByUid: {}
      };
    }
    this.applyDiscount();
    await this.recalculateSummary({ createIfMissing: true });
    this.persistTempOrder();
    return tempOrder;
  }
  // ─── TempOrder: 提交 ───
  /**
   * 提交当前 Sales tempOrder。
   *
   * smallTicketDataFlag 用于 B 端 checkout 小票数据返回。PaymentModal 在支付提交时
   * 应传 1，确保 /order/sales/checkout 返回打印所需数据。
   */
  async submitTempOrder(params) {
    var _a, _b, _c;
    const tempOrder = this.ensureTempOrder();
    this.persistTempOrder();
    const effectiveCacheId = (params == null ? void 0 : params.cacheId) ?? this.cacheId;
    const hasPaymentOverride = (params == null ? void 0 : params.payments) !== void 0;
    const hasPaymentStatusOverride = (params == null ? void 0 : params.paymentStatus) !== void 0;
    const hasSmallTicketDataFlagOverride = (params == null ? void 0 : params.smallTicketDataFlag) !== void 0;
    const enhancePayload = hasPaymentOverride || hasPaymentStatusOverride || hasSmallTicketDataFlagOverride || (params == null ? void 0 : params.enhancePayload) ? (payload2, ctx) => {
      const nextPayload = {
        ...payload2,
        ...hasPaymentOverride ? {
          payments: (0, import_utils.mapPaymentItemsToOrderPayments)(
            (params == null ? void 0 : params.payments) || []
          )
        } : {},
        ...hasPaymentStatusOverride ? { payment_status: params == null ? void 0 : params.paymentStatus } : {},
        ...hasSmallTicketDataFlagOverride ? { small_ticket_data_flag: params == null ? void 0 : params.smallTicketDataFlag } : {}
      };
      return (params == null ? void 0 : params.enhancePayload) ? params.enhancePayload(nextPayload, ctx) : nextPayload;
    } : void 0;
    const payload = (0, import_utils.buildSubmitPayload)({
      tempOrder,
      cacheId: effectiveCacheId,
      platform: (params == null ? void 0 : params.platform) || ((_a = this.otherParams) == null ? void 0 : _a.platform),
      businessCode: params == null ? void 0 : params.businessCode,
      channel: params == null ? void 0 : params.channel,
      type: params == null ? void 0 : params.type,
      enhance: enhancePayload
    });
    await this.saveDraft();
    let result;
    try {
      this.logInfo("submitTempOrder calling sales checkout", {
        orderId: payload.order_id,
        externalSaleNumber: payload.external_sale_number,
        paymentStatus: payload.payment_status,
        paymentsCount: ((_b = payload.payments) == null ? void 0 : _b.length) || 0,
        smallTicketDataFlag: payload.small_ticket_data_flag
      });
      result = await this.submitSalesOrder({
        query: payload
      });
    } catch (error) {
      const backendErrorResponse = this.extractSubmitErrorResponse(error);
      if (backendErrorResponse) {
        this.store.syncState = "failed";
        this.logSubmitBackendRejected(backendErrorResponse, payload);
        return backendErrorResponse;
      }
      this.store.syncState = "failed";
      this.logError("submitTempOrder failed", {
        error: error instanceof Error ? error.message : String(error),
        orderId: payload.order_id,
        externalSaleNumber: payload.external_sale_number,
        paymentStatus: payload.payment_status,
        paymentsCount: ((_c = payload.payments) == null ? void 0 : _c.length) || 0
      });
      throw error;
    }
    if (this.isSubmitResponseRejected(result)) {
      this.store.syncState = "failed";
      this.logSubmitBackendRejected(result, payload);
      return result;
    }
    const submittedOrderId = this.extractOrderIdFromSubmitResult(result);
    if (submittedOrderId !== null && submittedOrderId !== void 0) {
      tempOrder.order_id = submittedOrderId;
      const resultRecord = result;
      await this.markLocalOrderSynced(
        submittedOrderId,
        (resultRecord == null ? void 0 : resultRecord.data) || resultRecord || {}
      );
    }
    return result;
  }
  async markLocalOrderSynced(orderId, remoteOrder) {
    const tempOrder = this.ensureTempOrder();
    tempOrder.order_id = orderId;
    this.store.lastOrderInfo = remoteOrder;
    this.store.syncState = "submitted";
    this.persistTempOrder();
    await this.saveDraft();
  }
  isSubmitResponseRejected(response) {
    const isErrorCode = (response == null ? void 0 : response.code) !== void 0 && response.code !== 200 && response.code !== "200";
    const isErrorStatus = (response == null ? void 0 : response.status) === false || typeof (response == null ? void 0 : response.status) === "number" && response.status >= 400;
    const isErrorSuccess = (response == null ? void 0 : response.success) === false;
    return isErrorCode || isErrorStatus || isErrorSuccess;
  }
  isSubmitErrorResponse(response) {
    if (!response || typeof response !== "object")
      return false;
    return this.isSubmitResponseRejected(response) || response.message !== void 0 || response.msg !== void 0 || response.error !== void 0;
  }
  extractSubmitErrorResponse(error) {
    var _a, _b;
    const candidates = [
      (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.data,
      error == null ? void 0 : error.data,
      (_b = error == null ? void 0 : error.response) == null ? void 0 : _b.body,
      error == null ? void 0 : error.body
    ];
    return candidates.find((candidate) => this.isSubmitErrorResponse(candidate)) || null;
  }
  logSubmitBackendRejected(response, payload) {
    var _a;
    this.logError("submitTempOrder backend rejected", {
      response,
      payload: {
        order_id: payload.order_id,
        external_sale_number: payload.external_sale_number,
        payment_status: payload.payment_status,
        paymentsCount: ((_a = payload.payments) == null ? void 0 : _a.length) || 0
      }
    });
  }
  async syncPaymentsToOrder(params) {
    const tempOrder = this.ensureTempOrder();
    const mappedPayments = (0, import_utils.mapPaymentItemsToOrderPayments)(
      params.payments || []
    );
    const paymentTotal = this.calculatePaymentTotal(mappedPayments);
    const targetAmount = this.getPaymentTargetAmount();
    const isFullyPaid = targetAmount.lte(0) ? false : paymentTotal.gte(targetAmount);
    const paymentStatus = isFullyPaid ? params.paymentStatus || "paid" : "partially_paid";
    tempOrder.payments = mappedPayments;
    tempOrder.payment_status = paymentStatus;
    this.persistTempOrder();
    await this.saveDraft();
    if (!params.submitWhenPaid) {
      return { isFullyPaid };
    }
    if (this.store.syncState === "submitting") {
      return { isFullyPaid };
    }
    this.store.syncState = "submitting";
    const submitResult = await this.submitTempOrder({
      payments: mappedPayments,
      paymentStatus,
      smallTicketDataFlag: params.smallTicketDataFlag,
      channel: params.channel
    });
    return { isFullyPaid, submitResult };
  }
  createOrder(params) {
    var _a;
    const order = {
      type: (params == null ? void 0 : params.type) || "appointment_booking",
      // 要从外面拿，virtual
      platform: (params == null ? void 0 : params.platform) === "pc" ? "PC" : "H5",
      sales_channel: "my_pisel",
      order_sales_channel: "online_store",
      bookings: [],
      shop_note: "",
      schedule_date: "",
      is_deposit: 0,
      relation_products: [],
      relation_forms: [],
      ...(params == null ? void 0 : params.extraData) || {}
    };
    let is_deposit = 0;
    if (params.cartItems.length > 0) {
      params.cartItems.forEach((item) => {
        if (!item._origin.duration) {
          const { duration, durationType } = (0, import_utils.generateDuration)(item);
          item._origin.duration = duration;
          item._origin.sub_type = durationType;
        }
        item._origin.sub_type = (0, import_utils.normalizeBookingSubType)(item._origin);
        const discountList = (0, import_utils.getAllDiscountList)(item);
        item._origin.product.discount_list = discountList;
        if ((0, import_utils2.isNormalProduct)(item._origin)) {
          order.relation_products.push(item._origin.product);
          const relationForms = item._origin.relation_forms || [];
          order.relation_forms.push(...relationForms);
          delete item._origin.relation_forms;
        } else {
          const relationForms = (0, import_utils.mergeRelationForms)(
            item._origin.relation_forms || []
          );
          item._origin.relation_forms = relationForms;
          order.bookings.push(item._origin);
        }
        if (item == null ? void 0 : item.deposit) {
          is_deposit = 1;
        }
      });
      if (order.type === "appointment_booking") {
        const firstAppointmentCartItem = (_a = params.cartItems.filter(
          (n) => !(0, import_utils2.isNormalProduct)(n._productOrigin)
        )) == null ? void 0 : _a[0];
        if (firstAppointmentCartItem) {
          order.schedule_date = firstAppointmentCartItem.start_date + " " + firstAppointmentCartItem.start_time + ":00";
        }
      }
      order.is_deposit = is_deposit;
    }
    return order;
  }
  checkBeforeSubmitOrder(params) {
    var _a;
    this.logInfo("checkBeforeSubmitOrder called", {
      cartItemsCount: ((_a = params.cartItems) == null ? void 0 : _a.length) || 0,
      type: params.type
    });
    const { cartItems, type } = params;
    if (type === "holder") {
      const hasNoHolderId = cartItems.some((item) => !item.holder_id);
      if (hasNoHolderId) {
        return false;
      }
    }
    return true;
  }
  async submitOrder(order) {
    var _a, _b, _c;
    this.logInfo("submitOrder called", {
      url: order.url,
      orderType: order.query.type,
      platform: order.query.platform,
      cartItemsCount: ((_a = order.query.cartItems) == null ? void 0 : _a.length) || 0
    });
    const { url, query } = order;
    const fetchUrl = url || "/order/appointment";
    const params = this.createOrder(query);
    this.logInfo("Calling backend order API", {
      url: fetchUrl,
      orderType: params.type,
      platform: params.platform,
      isDeposit: params.is_deposit,
      bookingsCount: ((_b = params.bookings) == null ? void 0 : _b.length) || 0,
      relationProductsCount: ((_c = params.relation_products) == null ? void 0 : _c.length) || 0,
      scheduleDate: params.schedule_date
    });
    return this.request.post(fetchUrl, params);
  }
  async cancelOrder(params) {
    if (!Array.isArray(params.order_ids) || params.order_ids.length === 0) {
      throw new Error("取消订单失败：order_ids 不能为空");
    }
    const payload = {
      order_ids: params.order_ids,
      status: "cancelled",
      change_schedule_event_appointment_status: 1,
      is_void: 1
    };
    this.logInfo("cancelOrder called", {
      url: "/order/update-status",
      method: "PUT",
      orderIdsCount: params.order_ids.length
    });
    return this.request.put("/order/update-status", payload, { isShopApi: true });
  }
  async changeBookingStatus(params) {
    if (!params.booking_id) {
      throw new Error("变更预约状态失败：booking_id 不能为空");
    }
    if (!params.appointment_status) {
      throw new Error("变更预约状态失败：appointment_status 不能为空");
    }
    const url = `/schedule/booking/appointment-status/${params.booking_id}`;
    const payload = {
      appointment_status: params.appointment_status
    };
    this.logInfo("changeBookingStatus called", {
      url,
      method: "PUT",
      bookingId: params.booking_id,
      appointmentStatus: params.appointment_status
    });
    return this.request.put(url, payload, { isShopApi: true });
  }
  /**
   * Checkout 专用：创建订单到后端
   *
   * 专门为 Checkout 模块设计的订单创建方法，
   * 直接调用 /order/checkout 接口创建订单
   * 接收已经处理好的订单数据，无需再处理购物车
   *
   * @param params Checkout 订单参数（已处理的订单数据）
   * @returns 后端返回的订单数据（包含订单ID等）
   */
  async createOrderByCheckout(params) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
    const onlineStorePaymentCodeList = [
      "WXPAY",
      "WECHAT",
      "ALIPAY",
      "APPLE_PAY",
      "CREDIT_CARD_3DS",
      "CREDIT_CARD_TOKEN",
      "GOOGLE_PAY",
      "GOOGLE_PAY_3DS",
      "CREDIT_CARD"
    ];
    params.payments = (_a = params.payments) == null ? void 0 : _a.filter(
      (p) => !onlineStorePaymentCodeList.includes(p.code)
    );
    this.logInfo("createOrderByCheckout called", {
      type: params.type,
      platform: params.platform,
      is_deposit: params.is_deposit,
      customer_id: params.customer_id,
      bookingsCount: ((_b = params.bookings) == null ? void 0 : _b.length) || 0,
      relationProductsCount: ((_c = params.relation_products) == null ? void 0 : _c.length) || 0,
      paymentsCount: ((_d = params.payments) == null ? void 0 : _d.length) || 0,
      depositAmount: params.deposit_amount,
      productTaxFee: params.product_tax_fee,
      note: params.note,
      scheduleDate: params.schedule_date,
      hasOrderId: !!params.order_id,
      orderIdIncluded: params.order_id,
      paymentMethods: ((_e = params.payments) == null ? void 0 : _e.map((p) => p.code)) || []
    });
    console.log("[Order] createOrderByCheckout 开始创建订单:", {
      type: params.type,
      platform: params.platform,
      is_deposit: params.is_deposit,
      customer_id: params.customer_id,
      bookingsCount: ((_f = params.bookings) == null ? void 0 : _f.length) || 0,
      relationProductsCount: ((_g = params.relation_products) == null ? void 0 : _g.length) || 0,
      paymentsCount: ((_h = params.payments) == null ? void 0 : _h.length) || 0
    });
    try {
      const orderData = {
        sales_channel: "my_pisel",
        order_sales_channel: "online_store",
        shop_note: "",
        schedule_date: "",
        is_deposit: 0,
        bookings: [],
        relation_products: [],
        relation_forms: [],
        payments: [],
        is_full_overwrite_flag: 1,
        ...params
        // 使用传入的参数覆盖默认值
      };
      if ((_i = orderData.payments) == null ? void 0 : _i.length) {
        orderData.small_ticket_data_flag = 1;
      }
      if (!params.order_id && !orderData.schedule_date) {
        orderData.schedule_date = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
      }
      console.log("[Order] 调用后端接口创建订单:", {
        url: "/order/checkout",
        orderType: orderData.type,
        platform: orderData.platform,
        isDeposit: orderData.is_deposit,
        customerId: orderData.customer_id,
        bookingsCount: ((_j = orderData.bookings) == null ? void 0 : _j.length) || 0,
        relationProductsCount: ((_k = orderData.relation_products) == null ? void 0 : _k.length) || 0,
        paymentsCount: ((_l = orderData.payments) == null ? void 0 : _l.length) || 0,
        paymentsMethods: ((_m = orderData.payments) == null ? void 0 : _m.map((p) => p.code)) || []
      });
      this.logInfo("Calling backend checkout API", {
        url: "/order/checkout",
        orderType: orderData.type,
        platform: orderData.platform,
        isDeposit: orderData.is_deposit,
        customerId: orderData.customer_id,
        depositAmount: orderData.deposit_amount,
        bookingsCount: ((_n = orderData.bookings) == null ? void 0 : _n.length) || 0,
        relationProductsCount: ((_o = orderData.relation_products) == null ? void 0 : _o.length) || 0,
        paymentsCount: ((_p = orderData.payments) == null ? void 0 : _p.length) || 0,
        paymentMethods: ((_q = orderData.payments) == null ? void 0 : _q.map((p) => ({
          code: p.code,
          amount: p.amount,
          type: p.type,
          hasVoucherId: !!p.voucher_id,
          orderPaymentType: p.order_payment_type
        }))) || [],
        productTaxFee: orderData.product_tax_fee,
        note: orderData.note,
        scheduleDate: orderData.schedule_date,
        hasOrderId: !!orderData.order_id,
        smallTicketDataFlag: orderData.small_ticket_data_flag
      });
      const response = await this.request.post("/order/checkout", orderData);
      this.logInfo("Order API called successfully", {
        response
      });
      console.log("[Order] 订单创建成功，后端响应:", {
        success: !!response,
        hasOrderId: !!(((_r = response == null ? void 0 : response.data) == null ? void 0 : _r.order_id) || (response == null ? void 0 : response.order_id))
      });
      return response;
    } catch (error) {
      console.error("[Order] createOrderByCheckout 创建订单失败:", error);
      this.logInfo("Order API called failed", {
        error: error instanceof Error ? error.message : String(error)
      });
      throw error;
    }
  }
  async submitSalesOrder(params) {
    const { url, query } = params;
    const fetchUrl = url || "/order/sales/checkout";
    return this.request.post(fetchUrl, query, { customToast: () => {
    } });
  }
  /**
   * 发送支付链接邮件。
   *
   * 调用前必须已经有远端 order_id。BaseSales 会在需要时先提交本地订单，
   * OrderModule 只负责校验 order_ids 并调用 /order/batch-email。
   */
  async sendCustomerPayLink(params) {
    var _a;
    const orderIds = params.order_ids || params.orderIds || [];
    if (!orderIds.length) {
      throw new Error("发送支付链接前必须先提交本地订单并取得订单 ID");
    }
    if (!((_a = params.emails) == null ? void 0 : _a.length)) {
      throw new Error("发送支付链接需要至少一个邮箱");
    }
    return this.request.post("/order/batch-email", {
      order_ids: orderIds,
      notify_action: params.notify_action || "order_payment_reminder",
      emails: params.emails
    });
  }
  // TODO 获取详情的接口
  async getOrderInfoByRemote(order_id) {
    const res = await this.request.get(`/order/sales/${order_id}`, {
      with: ["products", "bookings", "payments", "customer", "summary", "contacts_info"]
    });
    if (res.code === 200) {
      this.store.lastOrderInfo = res.data;
    }
    return res;
  }
  /**
   * 把 sqlite / 后端返回的订单记录直接恢复为 tempOrder。
   *
   * 数据源应尽量返回 tempOrder 所需结构；这里仅做 SDK 运行必须字段兜底，
   * 例如数组字段、商品行唯一值、价格 metadata、summary 派生状态和 _extend。
   */
  async hydrateTempOrderFromRecord(record, options) {
    const raw = record && typeof record === "object" && record.data && record.order_id == null ? record.data : record || {};
    const nextTempOrder = this.normalizeTempOrderForRuntime(raw, {
      ensureIdentity: true
    });
    this.store.tempOrder = nextTempOrder;
    this.store.summary = raw.summary && typeof raw.summary === "object" ? { ...(0, import_utils.createEmptySummary)(), ...raw.summary } : (0, import_utils.createEmptySummary)();
    this.store.lastOrderInfo = raw.lastOrderInfo || raw;
    if (options == null ? void 0 : options.recalcOnHydrate) {
      await this.recalculateSummary({ createIfMissing: false });
    }
    this.persistTempOrder();
    return nextTempOrder;
  }
  normalizeTempOrderForRuntime(raw, options) {
    const nextTempOrder = {
      ...this.createDefaultTempOrderInstance(),
      ...raw || {}
    };
    delete nextTempOrder.summary;
    delete nextTempOrder.lastOrderInfo;
    delete nextTempOrder.discount_list;
    nextTempOrder.metadata = raw.metadata && typeof raw.metadata === "object" ? { ...raw.metadata } : {};
    nextTempOrder.holder = raw.holder && typeof raw.holder === "object" ? { ...raw.holder } : null;
    nextTempOrder.products = Array.isArray(raw.products) ? raw.products.map((p) => this.normalizeHydratedOrderProduct(p)) : [];
    nextTempOrder.bookings = Array.isArray(raw.bookings) ? raw.bookings.map((b) => ({
      ...b || {},
      is_all: (0, import_utils.normalizeBookingIsAll)(b || {}),
      sub_type: (0, import_utils.normalizeBookingSubType)(b || {})
    })) : [];
    nextTempOrder.payments = Array.isArray(raw.payments) ? raw.payments.map((p) => ({ ...p || {} })) : [];
    nextTempOrder.surcharges = Array.isArray(raw.surcharges) ? raw.surcharges.map((s) => ({ ...s || {} })) : [];
    nextTempOrder.relation_forms = Array.isArray(raw.relation_forms) ? raw.relation_forms.map((f) => ({ ...f || {} })) : [];
    nextTempOrder.contacts = Array.isArray(raw.contacts) ? raw.contacts.map((c) => ({ ...c || {} })) : [];
    nextTempOrder.contacts_info = raw.contacts_info && typeof raw.contacts_info === "object" && !Array.isArray(raw.contacts_info) ? { ...raw.contacts_info } : null;
    nextTempOrder._extend = raw._extend && typeof raw._extend === "object" ? {
      ...raw._extend,
      productsByUid: raw._extend.productsByUid || {}
    } : { productsByUid: {} };
    if ((options == null ? void 0 : options.ensureIdentity) !== false) {
      this.ensureExternalSaleNumber(nextTempOrder);
    }
    return nextTempOrder;
  }
  normalizeHydratedOrderProduct(product) {
    const row = { ...product || {} };
    if (row.num === void 0 && row.product_quantity !== void 0) {
      row.num = row.product_quantity;
    }
    if (!Array.isArray(row.product_option_item))
      row.product_option_item = [];
    if (!Array.isArray(row.product_bundle))
      row.product_bundle = [];
    if (!row.metadata || typeof row.metadata !== "object")
      row.metadata = {};
    const existingIdentity = row.metadata.unique_identification_number || row.unique_identification_number;
    if (!existingIdentity) {
      row.metadata.unique_identification_number = (0, import_utils.createUuidV4)();
    }
    const normalized = (0, import_utils3.normalizeOrderProduct)(row);
    normalized.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
      normalized.discount_list
    );
    const result = {
      ...row,
      ...normalized,
      metadata: {
        ...row.metadata,
        ...normalized.metadata
      }
    };
    if (result.metadata)
      delete result.metadata.price_schema_version;
    return result;
  }
  getLastOrderInfo() {
    var _a;
    return (_a = this.store) == null ? void 0 : _a.lastOrderInfo;
  }
  async getOrderInfo(order_id) {
    const res = await this.request.get(`/order/sales/${order_id}`, {
      with: ["products", "bookings"]
    });
    return res;
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  OrderModule
});
