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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
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/solution/BaseSales/index.ts
var BaseSales_exports = {};
__export(BaseSales_exports, {
  BaseSalesImpl: () => BaseSalesImpl
});
module.exports = __toCommonJS(BaseSales_exports);
var import_BaseModule = require("../../modules/BaseModule");
var import_types = require("./types");
var import_Order = require("../../modules/Order");
var import_decimal = __toESM(require("decimal.js"));
var import_types2 = require("../BookingByStep/types");
var import_utils = require("../../modules/Order/utils");
var import_dayjs = __toESM(require("dayjs"));
__reExport(BaseSales_exports, require("./types"), module.exports);
var import_Quotation = require("../../modules/Quotation");
var import_transformBaseProductToOrderProduct = require("./utils/transformBaseProductToOrderProduct");
var import_quotationPrice = require("./utils/quotationPrice");
var BaseSalesImpl = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name, version);
    this.defaultName = "baseSales";
    this.defaultVersion = "1.0.0";
    this.isSolution = true;
    this.initializeOptions = {};
    this.store = {
      order: void 0
    };
    this.otherParams = {};
    // 当前缓存中已加载的最新 SalesDetail；只读 getter 走它对外暴露详情数据。
    this.currentSalesDetail = null;
  }
  /**
   * 子类可覆盖此方法以追加/收敛要注册的子模块。
   * 默认包含通用销售模块：products / order / salesSummary / schedule / payment / quotation。
   */
  getRegisteredModuleNames() {
    return ["products", "order", "salesSummary", "schedule", "payment", "quotation"];
  }
  /**
   * 记录信息日志
   */
  logInfo(title, metadata) {
    if (this.logger) {
      const tempOrder = this.getTempOrder();
      this.logger.addLog({
        type: "info",
        title: `[BaseSales]  ${tempOrder == null ? void 0 : tempOrder.order_id} ${tempOrder == null ? void 0 : tempOrder.external_sale_number} ${title}`,
        metadata: metadata || {}
      });
    }
  }
  /**
   * 记录警告日志
   */
  logWarning(title, metadata) {
    if (this.logger) {
      const tempOrder = this.getTempOrder();
      this.logger.addLog({
        type: "warning",
        title: `[BaseSales] ${tempOrder == null ? void 0 : tempOrder.order_id} ${tempOrder == null ? void 0 : tempOrder.external_sale_number} ${title}`,
        metadata: metadata || {}
      });
    }
  }
  /**
   * 记录错误日志
   */
  logError(title, metadata) {
    if (this.logger) {
      const tempOrder = this.getTempOrder();
      this.logger.addLog({
        type: "error",
        title: `[BaseSales] ${tempOrder == null ? void 0 : tempOrder.order_id} ${tempOrder == null ? void 0 : tempOrder.external_sale_number} ${title}`,
        metadata: metadata || {}
      });
    }
  }
  get payment() {
    return this.store.payment;
  }
  getCurrentOrderCustomerId() {
    var _a, _b;
    const tempOrder = (_b = (_a = this.store.order) == null ? void 0 : _a.getTempOrder) == null ? void 0 : _b.call(_a);
    const customerId = tempOrder == null ? void 0 : tempOrder.customer_id;
    if (customerId === null || customerId === void 0)
      return void 0;
    return customerId;
  }
  applyQuotationScheduleResolver(quotation) {
    const scheduleModule = this.store.schedule;
    if (!scheduleModule)
      return;
    quotation.setScheduleResolver((id) => {
      var _a;
      const schedules = ((_a = scheduleModule.getScheduleListByIds) == null ? void 0 : _a.call(scheduleModule, [id])) || [];
      return schedules[0];
    });
  }
  async loadQuotationForPriceQuery(params) {
    var _a;
    if (!params.quotation)
      return;
    this.applyQuotationScheduleResolver(params.quotation);
    await params.quotation.loadQuotations({
      channel: params.channel || ((_a = this.otherParams) == null ? void 0 : _a.channel),
      customer_id: params.customer_id
    });
  }
  getSubmitOrderSalesChannel() {
    var _a;
    return (_a = this.otherParams) == null ? void 0 : _a.channel;
  }
  /**
   * 工厂入口：根据子模块名实例化对应模块。
   * 默认使用 BookingByStep 公共 `createModule`。子类若需引入额外类型（如 customer），
   * 可覆盖此方法并把未识别的 name 委托给 `super.createSubModule(name)`。
   */
  createSubModule(moduleName) {
    if (moduleName === "quotation") {
      return new import_Quotation.QuotationModule(`${this.name}_quotation`);
    }
    return (0, import_types2.createModule)(moduleName, this.name);
  }
  getSubModuleHooks(moduleName) {
    var _a, _b;
    const optionHooks = this.initializeOptions.hooks || {};
    const otherHooks = this.otherParams.hooks || {};
    if (moduleName === "order") {
      const directOrderHooks = optionHooks;
      return optionHooks.order || ((_a = this.otherParams.order) == null ? void 0 : _a.hooks) || otherHooks.order || (directOrderHooks.onBeforeMergeProductToOrder ? directOrderHooks : void 0);
    }
    return optionHooks[moduleName] || ((_b = this.otherParams[moduleName]) == null ? void 0 : _b.hooks) || otherHooks[moduleName];
  }
  /**
   * 读取 sessionStorage[this.name][cacheId]，作为子模块 initialState 的来源。
   * sessionStorage 损坏时静默忽略，按空状态注册。
   */
  readSessionCacheData() {
    if (!this.cacheId || !this.window)
      return {};
    try {
      const sessionData = this.window.sessionStorage.getItem(this.name);
      if (!sessionData)
        return {};
      const data = JSON.parse(sessionData);
      return data && data[this.cacheId] || {};
    } catch {
      return {};
    }
  }
  getAppData(key) {
    var _a, _b, _c, _d, _e, _f;
    const getData = (_b = (_a = this.appPlugin).getData) == null ? void 0 : _b.call(_a);
    if (typeof getData === "function")
      return getData(key);
    const app = this.appPlugin.getApp();
    const coreData = (_f = (_d = (_c = app == null ? void 0 : app.models) == null ? void 0 : _c.getStore) == null ? void 0 : (_e = _d.call(_c)).getDataByModel) == null ? void 0 : _f.call(_e, "core", "core");
    return coreData == null ? void 0 : coreData[key];
  }
  syncAppDataToTempOrder(tempOrder) {
    const taxCountryCode = this.getAppData("tax_country_code");
    const currencyCode = this.getAppData("shop_currency_code");
    const currencySymbol = this.getAppData("shop_symbol");
    let isChanged = false;
    if (taxCountryCode !== void 0) {
      const nextTaxCountryCode = String(taxCountryCode || "");
      if (tempOrder.tax_country_code !== nextTaxCountryCode) {
        tempOrder.tax_country_code = nextTaxCountryCode;
        isChanged = true;
      }
    }
    if (currencyCode !== void 0) {
      const nextCurrencyCode = String(currencyCode || "");
      if (tempOrder.currency_code !== nextCurrencyCode) {
        tempOrder.currency_code = nextCurrencyCode;
        isChanged = true;
      }
    }
    if (currencySymbol !== void 0) {
      const nextCurrencySymbol = String(currencySymbol || "");
      if (tempOrder.currency_symbol !== nextCurrencySymbol) {
        tempOrder.currency_symbol = nextCurrencySymbol;
        isChanged = true;
      }
    }
    return isChanged;
  }
  async initialize(core, options = {}) {
    var _a;
    this.core = core;
    this.initializeOptions = options || {};
    this.otherParams = options.otherParams || {};
    this.cacheId = (_a = this.otherParams) == null ? void 0 : _a.cacheId;
    this.window = core.getPlugin("window");
    this.request = core.getPlugin("request");
    this.appPlugin = core.getPlugin("app");
    if (!this.appPlugin) {
      throw new Error("Checkout 解决方案需要 app 插件支持");
    }
    const app = this.appPlugin.getApp();
    this.logger = app.logger;
    const targetCacheData = this.readSessionCacheData();
    const moduleNames = this.getRegisteredModuleNames();
    moduleNames.forEach((step) => {
      const targetModule = this.createSubModule(step);
      if (!targetModule) {
        throw new Error(`模块 ${step} 不存在`);
      }
      const hooks = this.getSubModuleHooks(step);
      this.store[step] = targetModule;
      this.core.registerModule(targetModule, {
        initialState: (targetCacheData == null ? void 0 : targetCacheData[targetModule.name]) || {},
        ...hooks ? { hooks } : {},
        otherParams: {
          ...this.otherParams,
          salesSummaryModuleName: `${this.name}_salesSummary`,
          fatherModule: this.name,
          openCache: this.cacheId ? true : false,
          cacheId: this.cacheId
        }
      });
    });
    if (this.store.schedule) {
      await this.store.schedule.loadAllSchedule();
    }
    this.core.effects.emit(`${this.name}:onInited`, {});
  }
  async destroy() {
    Object.keys(this.store).forEach((key) => {
      const sub = this.store[key];
      if (sub && typeof sub.destroy === "function") {
        try {
          sub.destroy();
        } catch (error) {
          console.warn(`[BaseSales] 子模块 ${key} 销毁失败`, error);
        }
      }
    });
    this.currentSalesDetail = null;
    await this.core.effects.emit(`${this.name}:onDestroy`, {});
    super.destroy();
  }
  /**
   * 加载销售订单到统一 tempOrder 工作区。
   * 有 app.sqlite 时优先读取本地记录；本地未命中或 forceRemote=true 时再拉云端。
   *
   * 子类可在 `super.loadSalesDetail` 之后基于返回的 `sales` 做业务侧装配
   * （比如把 `sales.customer` 写入 CustomerModule、emit 业务 hook 等）。
   */
  async loadSalesDetail(orderIdOrParams) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    const params = typeof orderIdOrParams === "object" ? orderIdOrParams : { orderId: orderIdOrParams };
    const externalSaleNumber = params.externalSaleNumber || params.external_sale_number;
    if (!params.forceRemote) {
      const localRecord = params.orderId !== void 0 ? await this.store.order.getLocalOrderByOrderId(params.orderId) : externalSaleNumber ? await this.store.order.getLocalOrderByExternalSaleNumber(externalSaleNumber) : params.orderNumber ? await this.store.order.getLocalOrderByOrderNumber(params.orderNumber) : null;
      if (localRecord) {
        const sales2 = await this.store.order.hydrateTempOrderFromRecord(localRecord, { recalcOnHydrate: false });
        this.currentSalesDetail = sales2;
        await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, { sales: sales2 });
        return sales2;
      }
    }
    if (params.orderId === void 0 || params.orderId === null) {
      throw new Error("加载销售详情需要 orderId，或本地库中存在对应 externalSaleNumber/orderNumber");
    }
    const res = await this.store.order.getOrderInfoByRemote(Number(params.orderId));
    if (!res || res.code !== 200) {
      const message = res && (res.message || res.msg) || `加载销售详情失败: ${params.orderId}`;
      throw new Error(message);
    }
    const sales = await this.store.order.hydrateTempOrderFromRecord(res.data, { recalcOnHydrate: false });
    await this.store.order.saveDraft();
    this.currentSalesDetail = sales;
    await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, { sales });
    return sales;
  }
  /** 获取当前已加载的销售详情（只读快照）。未加载过则返回 null。 */
  getSalesOrder() {
    return this.currentSalesDetail;
  }
  /** 获取销售详情顶部业务字段（订单号/状态/金额等通用字段集合）。 */
  getOrderHeader() {
    if (!this.currentSalesDetail)
      return null;
    return this.currentSalesDetail.header || this.currentSalesDetail;
  }
  /** 获取所有 booking（含 root + children），按服务端原始顺序输出。 */
  getBookings() {
    var _a;
    return ((_a = this.currentSalesDetail) == null ? void 0 : _a.bookings) || [];
  }
  /** 获取根 booking（is_next === 0 / is_root === 1），多个时取第一个。 */
  getRootBooking() {
    if (!this.currentSalesDetail)
      return null;
    if (this.currentSalesDetail.rootBooking)
      return this.currentSalesDetail.rootBooking;
    const bookings = this.currentSalesDetail.bookings || [];
    return bookings.find((booking) => {
      const parentId = booking == null ? void 0 : booking.parent_id;
      return parentId === 0 || parentId === null || parentId === void 0;
    }) || null;
  }
  /** 按 product_uid 反查 booking 列表（用于商品行 ↔ booking 映射）。 */
  getChildBookingsByProductUid(productUid) {
    var _a;
    if (!this.currentSalesDetail || !productUid)
      return [];
    const indexed = (_a = this.currentSalesDetail.bookingsByProductUid) == null ? void 0 : _a[productUid];
    if (indexed)
      return indexed;
    return (this.currentSalesDetail.bookings || []).filter((booking) => {
      var _a2;
      const uid = (booking == null ? void 0 : booking.product_uid) || ((_a2 = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a2.product_uid);
      return String(uid || "") === String(productUid);
    });
  }
  /** 获取支付列表（已支付/退款等明细）。 */
  getPayments() {
    var _a;
    return ((_a = this.currentSalesDetail) == null ? void 0 : _a.payments) || [];
  }
  /** 获取附加费用（运费/服务费/税费等）。 */
  getSurcharges() {
    var _a;
    return ((_a = this.currentSalesDetail) == null ? void 0 : _a.surcharges) || [];
  }
  getTempOrder() {
    var _a;
    const result = ((_a = this.store.order) == null ? void 0 : _a.getTempOrder()) || null;
    return result;
  }
  async replaceTempOrder(tempOrder) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    const nextTempOrder = await this.store.order.replaceTempOrder(tempOrder);
    await this.effectsEmit("onTempOrderReplaced", { tempOrder: nextTempOrder });
    return nextTempOrder;
  }
  getOrderIdentity() {
    if (!this.store.order)
      return null;
    return this.store.order.getOrderIdentity();
  }
  getOrderSnapshot() {
    if (!this.store.order)
      return null;
    return this.store.order.getOrderSnapshot();
  }
  getOrderSyncState() {
    if (!this.store.order)
      return "local";
    return this.store.order.getOrderSyncState();
  }
  getOrderAmountSnapshot() {
    if (!this.store.order)
      return null;
    return this.store.order.getOrderAmountSnapshot();
  }
  getTempOrderNote() {
    if (!this.store.order)
      return "";
    return this.store.order.getTempOrderNote();
  }
  updateTempOrderNote(note, sync = false) {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const result = this.store.order.updateTempOrderNote(note, sync);
      return result;
    } catch (error) {
      throw error;
    }
  }
  updateRemoteOrderNote(orderId, note) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    this.store.order.syncTempOrderNoteToRemote(orderId, note);
  }
  updateTempOrderShopDiscount(amount) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    return this.store.order.updateTempOrderShopDiscount(amount);
  }
  updateTempOrderContactsInfo(contactsInfo) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    return this.store.order.updateTempOrderContactsInfo(contactsInfo);
  }
  /**
   * 运行时切换 tempOrder 是否写入 localStorage（委托 OrderModule）。
   * SalesSdk 等内存态场景可在挂载后设为 false，避免污染本地缓存。
   *
   * @example
   * bookingTicket.setEnableTempOrderPersist(false);
   * await bookingTicket.addProductToOrder(product);
   */
  setEnableTempOrderPersist(enabled) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    this.store.order.setEnableTempOrderPersist(enabled);
  }
  /**
   * 读取当前 tempOrder localStorage 持久化开关（委托 OrderModule）。
   *
   * @example
   * if (bookingTicket.isTempOrderPersistEnabled()) {
   *   bookingTicket.restoreOrder();
   * }
   */
  isTempOrderPersistEnabled() {
    if (!this.store.order)
      return true;
    return this.store.order.isTempOrderPersistEnabled();
  }
  ensureTempOrder() {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    return this.store.order.ensureTempOrder();
  }
  // 主动创建临时订单；若已存在则直接返回已有订单
  async addNewOrder() {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const tempOrder = await this.store.order.addNewOrder();
      if (this.syncAppDataToTempOrder(tempOrder)) {
        this.store.order.persistTempOrder();
        await this.store.order.saveDraft();
      }
      return tempOrder;
    } catch (error) {
      throw error;
    }
  }
  async saveDraft() {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    return this.store.order.saveDraft();
  }
  // 重置 tempOrder 与与上一单强相关的运行态（resource/entryPaxNumber/enabledReservationRuleProducts），
  // 适用于从支付页通过 react-router 跳回继续下单时清理残留数据
  async restoreOrder() {
    try {
      if (!this.store.order) {
        throw new Error("scanOrder 解决方案需要 order 模块支持");
      }
      const tempOrder = this.store.order.restoreOrder();
      this.currentSalesDetail = null;
      await this.effectsEmit("onTempOrderReplaced", { tempOrder });
      if (this.syncAppDataToTempOrder(tempOrder)) {
        this.store.order.persistTempOrder();
        await this.store.order.saveDraft();
      }
      return tempOrder;
    } catch (error) {
      throw error;
    }
  }
  /**
   * 仅清空 tempOrder 购物车行（products / bookings / discount_list）。
   * 同步清空内存中的 salesDetail 商品/预约视图，避免编辑态仍读到旧 bookings。
   */
  async clearOrderCartLines() {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const tempOrder = await this.store.order.clearOrderCartLines();
      if (this.currentSalesDetail) {
        this.currentSalesDetail = {
          ...this.currentSalesDetail,
          products: [],
          bookings: [],
          rootBooking: null,
          bookingsByProductUid: {},
          discount_list: []
        };
      }
      await this.effectsEmit("onTempOrderReplaced", { tempOrder });
      if (this.syncAppDataToTempOrder(tempOrder)) {
        this.store.order.persistTempOrder();
        await this.store.order.saveDraft();
      }
      return tempOrder;
    } catch (error) {
      throw error;
    }
  }
  getOrderProducts() {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    const products = this.store.order.getOrderProducts();
    return products;
  }
  async getSummary() {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const summary = await this.store.order.getOrderSummary();
      return summary;
    } catch (error) {
      throw error;
    }
  }
  getHistoricalProductDiscountList(products) {
    const historyDiscountList = [];
    products.forEach((item) => {
      if (!this.isPersistedOrderProduct(item))
        return;
      (item.discount_list || []).forEach((discount) => {
        var _a, _b, _c, _d, _e, _f;
        const discountId = ((_a = discount.discount) == null ? void 0 : _a.resource_id) || discount.id;
        if (!discountId || !["good_pass", "discount_card"].includes(discount.type))
          return;
        const quantity = item.quantity || item.num || item.product_quantity || 1;
        const savedAmount = new import_decimal.default(discount.amount || 0).times(quantity).plus(((_b = discount == null ? void 0 : discount.metadata) == null ? void 0 : _b.product_discount_difference) || 0);
        const index = historyDiscountList.findIndex((n) => n.id === discountId);
        if (index !== -1) {
          historyDiscountList[index] = {
            ...historyDiscountList[index],
            amount: new import_decimal.default(historyDiscountList[index].amount || 0).plus(discount.amount || 0).toNumber(),
            savedAmount: savedAmount.plus(historyDiscountList[index].savedAmount || 0).toNumber()
          };
          return;
        }
        historyDiscountList.push({
          ...discount,
          id: discountId,
          tag: discount.tag || discount.type,
          name: discount.name || ((_d = (_c = discount.discount) == null ? void 0 : _c.title) == null ? void 0 : _d.auto),
          format_title: ((_e = discount.discount) == null ? void 0 : _e.title) || discount.format_title,
          isEditMode: true,
          limited_relation_product_data: {},
          savedAmount: savedAmount.toNumber(),
          isAvailable: true,
          isDisabled: true,
          isSelected: true,
          product_id: ((_f = discount.discount) == null ? void 0 : _f.product_id) || discount.product_id
        });
      });
    });
    return historyDiscountList;
  }
  isPersistedOrderProduct(product) {
    const orderDetailId = product.order_detail_id ?? product.orderDetailId;
    if (orderDetailId !== void 0 && orderDetailId !== null && orderDetailId !== "") {
      return true;
    }
    const bookingId = product.booking_id ?? product.bookingId;
    return bookingId !== void 0 && bookingId !== null && bookingId !== "";
  }
  mergeHistoricalDiscountList(discountList, products) {
    const historyDiscountList = this.getHistoricalProductDiscountList(products);
    const historyIds = new Set(historyDiscountList.map((discount) => discount.id));
    return [
      ...historyDiscountList,
      ...(discountList || []).filter((discount) => !historyIds.has(discount.id))
    ];
  }
  mergeCurrentDiscountSelectionState(discountList, currentDiscountList) {
    if (!currentDiscountList.length)
      return discountList;
    const currentDiscountMap = new Map(
      currentDiscountList.map((discount) => [discount.id, discount])
    );
    return discountList.map((discount) => {
      const currentDiscount = currentDiscountMap.get(discount.id);
      if (!currentDiscount)
        return discount;
      if (currentDiscount.isManualSelect) {
        return {
          ...discount,
          isSelected: false,
          isManualSelect: true
        };
      }
      if (currentDiscount.isSelected) {
        return {
          ...discount,
          isSelected: true,
          isManualSelect: false
        };
      }
      return discount;
    });
  }
  async loadDiscountConfig(params) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    const tempOrder = this.store.order.ensureTempOrder();
    const orderStore = this.store.order.store || {};
    const discountModule = orderStore.discount;
    const rulesModule = orderStore.rules;
    const orderId = tempOrder.order_id || ((_b = (_a = this.getOrderIdentity) == null ? void 0 : _a.call(this)) == null ? void 0 : _b.orderId);
    const customerId = Number(
      (params == null ? void 0 : params.customerId) || tempOrder.customer_id || ((_c = tempOrder.customer) == null ? void 0 : _c.id) || ((_e = (_d = tempOrder._extend) == null ? void 0 : _d.customerSnapshot) == null ? void 0 : _e.id) || ((_g = (_f = tempOrder._extend) == null ? void 0 : _f.customerSnapshot) == null ? void 0 : _g.customer_id) || 0
    );
    const currentDiscountList = ((_h = discountModule == null ? void 0 : discountModule.getDiscountList) == null ? void 0 : _h.call(discountModule)) || [];
    let preparedDiscountList = [];
    if (customerId && customerId !== 1) {
      preparedDiscountList = await this.store.order.loadDiscountConfig({
        customerId,
        action: (params == null ? void 0 : params.action) || (orderId ? "edit" : "create"),
        orderId: Number(orderId) || void 0,
        apply: false
      });
      await ((_i = discountModule == null ? void 0 : discountModule.setOriginalDiscountList) == null ? void 0 : _i.call(discountModule, preparedDiscountList));
    }
    let nextDiscountList = this.mergeHistoricalDiscountList(
      preparedDiscountList || ((_j = discountModule == null ? void 0 : discountModule.getDiscountList) == null ? void 0 : _j.call(discountModule)) || [],
      tempOrder.products || []
    );
    nextDiscountList = this.mergeCurrentDiscountSelectionState(
      nextDiscountList,
      currentDiscountList
    );
    await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
    if (rulesModule) {
      const holders = ((_k = tempOrder.holder) == null ? void 0 : _k.form_record_id) ? [{ form_record_id: tempOrder.holder.form_record_id }] : [];
      const result = rulesModule.calcDiscount({
        productList: tempOrder.products,
        discountList: nextDiscountList,
        holders,
        isFormSubject: !!((_l = tempOrder.holder) == null ? void 0 : _l.type) && tempOrder.holder.type === "form",
        orderTotalAmount: Number(((_m = orderStore.summary) == null ? void 0 : _m.total_amount) || 0)
      }) || { productList: tempOrder.products, discountList: nextDiscountList };
      if (result.productList) {
        tempOrder.products = result.productList;
      }
      if (result.discountList) {
        nextDiscountList = this.mergeHistoricalDiscountList(
          result.discountList,
          tempOrder.products || []
        );
        import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
        await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
        tempOrder.discount_list = nextDiscountList.filter((discount) => discount.isSelected);
      }
    }
    this.store.order.persistTempOrder();
    await this.effectsEmit("onDiscountApplied", {
      productList: tempOrder.products || [],
      discountList: nextDiscountList,
      selectedDiscountList: tempOrder.discount_list || [],
      tempOrder
    });
    return {
      productList: tempOrder.products || [],
      discountList: nextDiscountList
    };
  }
  async bestDiscount(cb) {
    var _a, _b, _c, _d;
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    const tempOrder = this.store.order.ensureTempOrder();
    const orderStore = this.store.order.store || {};
    const discountModule = orderStore.discount;
    const rulesModule = orderStore.rules;
    const originalDiscountList = ((_a = discountModule == null ? void 0 : discountModule.getOriginalDiscountList) == null ? void 0 : _a.call(discountModule)) || this.getDiscountList();
    let nextDiscountList = this.mergeHistoricalDiscountList(
      originalDiscountList || [],
      tempOrder.products || []
    );
    let result = {
      productList: tempOrder.products || [],
      discountList: nextDiscountList
    };
    await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
    if (rulesModule) {
      const holders = ((_b = tempOrder.holder) == null ? void 0 : _b.form_record_id) ? [{ form_record_id: tempOrder.holder.form_record_id }] : [];
      result = rulesModule.calcDiscount({
        productList: tempOrder.products,
        discountList: nextDiscountList,
        holders,
        isFormSubject: !!((_c = tempOrder.holder) == null ? void 0 : _c.type) && tempOrder.holder.type === "form",
        orderTotalAmount: Number(((_d = orderStore.summary) == null ? void 0 : _d.total_amount) || 0)
      }) || result;
      if (result.productList) {
        tempOrder.products = result.productList;
      }
      if (result.discountList) {
        nextDiscountList = this.mergeHistoricalDiscountList(
          result.discountList,
          tempOrder.products || []
        );
        import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
        await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
        tempOrder.discount_list = nextDiscountList.filter((discount) => discount.isSelected);
        result = {
          productList: tempOrder.products,
          discountList: nextDiscountList
        };
      }
    }
    await this.store.order.recalculateSummary({ createIfMissing: true });
    this.store.order.persistTempOrder();
    cb == null ? void 0 : cb(result);
    return result;
  }
  getDiscountList() {
    if (!this.store.order)
      return [];
    return this.store.order.getDiscountList();
  }
  async scanPromotionCode(code, customerId) {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const raw = await this.store.order.scanCode(code, customerId);
      if (raw.isAvailable) {
        await this.store.order.recalculateSummary({ createIfMissing: true });
        this.store.order.persistTempOrder();
      }
      return {
        isAvailable: raw.isAvailable,
        type: raw.type,
        unavailableReason: raw.unavailableReason
      };
    } catch (error) {
      throw error;
    }
  }
  // TODO 需要优化，这段逻辑太长了，里面应该有些历史遗留问题
  async setDiscountSelected(params) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i;
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const list = this.store.order.getDiscountList();
      const updated = list.map(
        (d) => d.id === params.discountId ? {
          ...d,
          isSelected: params.isSelected,
          isManualSelect: !params.isSelected
        } : d
      );
      const tempOrder = this.store.order.ensureTempOrder();
      const orderStore = this.store.order.store || {};
      const discountModule = orderStore.discount;
      const rulesModule = orderStore.rules;
      const holders = ((_a = tempOrder.holder) == null ? void 0 : _a.form_record_id) ? [{ form_record_id: tempOrder.holder.form_record_id }] : [];
      let nextDiscountList = updated;
      await (discountModule == null ? void 0 : discountModule.setDiscountList(updated));
      if (rulesModule) {
        const result = rulesModule.calcDiscount(
          {
            productList: tempOrder.products,
            discountList: updated,
            holders,
            isFormSubject: !!((_b = tempOrder.holder) == null ? void 0 : _b.type) && tempOrder.holder.type === "form"
          },
          {
            discountId: params.discountId,
            isSelected: params.isSelected
          }
        ) || { productList: tempOrder.products, discountList: updated };
        if (result == null ? void 0 : result.productList) {
          tempOrder.products = result.productList;
        }
        if (result == null ? void 0 : result.discountList) {
          nextDiscountList = result.discountList;
          if (!params.isSelected) {
            const beforeSelectedIds = new Set(
              updated.filter((d) => d.isSelected).map((d) => d.id)
            );
            for (const d of nextDiscountList) {
              if (d.isSelected && !beforeSelectedIds.has(d.id)) {
                d.isSelected = false;
              }
            }
          }
        }
      }
      const selectedResourceIds = new Set(
        nextDiscountList.filter((d) => d.isSelected).map((d) => d.id)
      );
      for (const product of tempOrder.products) {
        const productUid = (_c = product.metadata) == null ? void 0 : _c.unique_identification_number;
        const runtimeOrigin = productUid ? (_f = (_e = (_d = tempOrder._extend) == null ? void 0 : _d.productsByUid) == null ? void 0 : _e[productUid]) == null ? void 0 : _f.origin : void 0;
        if ((runtimeOrigin == null ? void 0 : runtimeOrigin.isManualDiscount) || ((_g = product.metadata) == null ? void 0 : _g.is_manual_discount))
          continue;
        product.discount_list = (product.discount_list || []).filter((pd) => {
          var _a2;
          const rid = ((_a2 = pd.discount) == null ? void 0 : _a2.resource_id) ?? pd.id;
          return rid != null && selectedResourceIds.has(rid);
        });
        const totalPerUnitDiscount = (product.discount_list || []).reduce(
          (sum, pd) => sum + (pd.amount || 0),
          0
        );
        const optionSum = (0, import_utils.sumOptionUnitPrice)(product.product_option_item);
        const sourcePrice = ((_h = product.metadata) == null ? void 0 : _h.source_product_price) ?? (((_i = product.metadata) == null ? void 0 : _i.main_product_original_price) != null ? new import_decimal.default(Number(product.metadata.main_product_original_price) || 0).minus(optionSum).toFixed(2) : product.original_price ?? "0");
        const newSourceSellingPrice = new import_decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
        const newMainSellingPrice = new import_decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
        if (product.metadata) {
          product.metadata.main_product_selling_price = newMainSellingPrice;
          product.metadata.price_schema_version = 2;
        }
        product.selling_price = (0, import_utils.composeLinePrice)({
          mainPrice: newMainSellingPrice,
          bundle: product.product_bundle
        });
      }
      import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
      await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
      tempOrder.discount_list = (nextDiscountList || []).filter((d) => d.isSelected);
      await this.store.order.recalculateSummary({ createIfMissing: true });
      this.store.order.persistTempOrder();
      this.effectsEmit("onDiscountApplied", {
        productList: tempOrder.products,
        discountList: nextDiscountList,
        selectedDiscountList: tempOrder.discount_list,
        tempOrder
      });
    } catch (error) {
      throw error;
    }
  }
  async applyDiscountCalculationResult(result) {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      if (!result)
        return;
      const tempOrder = this.store.order.ensureTempOrder();
      const orderStore = this.store.order.store || {};
      const discountModule = orderStore.discount;
      if (result.productList) {
        tempOrder.products = result.productList;
      }
      if (result.discountList) {
        import_Order.OrderModule.populateSavedAmounts(
          tempOrder.products,
          result.discountList
        );
        await (discountModule == null ? void 0 : discountModule.setDiscountList(result.discountList));
        tempOrder.discount_list = result.discountList.filter(
          (discount) => discount.isSelected
        );
      }
      await this.store.order.recalculateSummary({ createIfMissing: true });
      this.store.order.persistTempOrder();
    } catch (error) {
      throw error;
    }
  }
  async submitScanOrder(params) {
    return this.submitSalesOrder(params);
  }
  /**
   * 提交当前 Sales 订单。
   *
   * PaymentModal 场景通过 smallTicketDataFlag=1 请求 B 端小票数据；
   * payments 会交给 OrderModule 统一映射为 Sales 协议支付项。
   */
  async submitSalesOrder(params) {
    var _a, _b, _c;
    if (!this.store.order) {
      throw new Error("BaseSales 解决方案需要 order 模块支持");
    }
    this.store.order.persistTempOrder();
    const submitParams = {
      cacheId: this.cacheId,
      platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
      businessCode: (_b = this.otherParams) == null ? void 0 : _b.businessCode,
      channel: this.getSubmitOrderSalesChannel(),
      type: (_c = this.otherParams) == null ? void 0 : _c.type,
      ...(params == null ? void 0 : params.payments) !== void 0 ? { payments: params.payments } : {},
      ...(params == null ? void 0 : params.paymentStatus) !== void 0 ? { paymentStatus: params.paymentStatus } : {},
      ...(params == null ? void 0 : params.smallTicketDataFlag) !== void 0 ? { smallTicketDataFlag: params.smallTicketDataFlag } : {},
      ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
    };
    console.log(submitParams, "submitParams123");
    return this.store.order.submitTempOrder(submitParams);
  }
  async syncPaymentsToOrder(params) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    const channel = params.channel ?? this.getSubmitOrderSalesChannel();
    const syncParams = {
      ...params,
      ...channel !== void 0 ? { channel } : {}
    };
    const syncState = this.store.order.getOrderSyncState();
    if (params.submitWhenPaid && syncState === "submitting") {
      return this.store.order.syncPaymentsToOrder(syncParams);
    }
    const payments = params.payments || [];
    await this.effectsEmit(import_types.BaseSalesHookNames.onPaymentSyncStart, {
      payments,
      params: syncParams,
      amountSnapshot: this.store.order.getOrderAmountSnapshot(),
      orderSnapshot: this.store.order.getOrderSnapshot()
    });
    try {
      const syncResult = await this.store.order.syncPaymentsToOrder(syncParams);
      await this.effectsEmit(import_types.BaseSalesHookNames.onPaymentSyncEnd, {
        ok: true,
        syncResult,
        payments: this.store.order.getOrderPayments(),
        params: syncParams,
        amountSnapshot: this.store.order.getOrderAmountSnapshot(),
        orderSnapshot: this.store.order.getOrderSnapshot()
      });
      return syncResult;
    } catch (error) {
      await this.effectsEmit(import_types.BaseSalesHookNames.onPaymentSyncEnd, {
        ok: false,
        error,
        payments: this.store.order.getOrderPayments(),
        params: syncParams,
        amountSnapshot: this.store.order.getOrderAmountSnapshot(),
        orderSnapshot: this.store.order.getOrderSnapshot()
      });
      throw error;
    }
  }
  /** 读取当前 BaseSales 订单上下文中的 Sales 协议支付项。 */
  getOrderPayments() {
    if (!this.store.order)
      return [];
    return this.store.order.getOrderPayments();
  }
  /** 覆盖当前订单支付项，内部由 OrderModule 清洗为 Sales 协议字段。 */
  setOrderPayments(payments) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    return this.store.order.setOrderPayments(payments);
  }
  /** 追加单个支付项到当前订单。 */
  addOrderPayment(payment) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    const payments = this.store.order.addOrderPayment(payment);
    const amountSnapshot = this.store.order.getOrderAmountSnapshot();
    const syncState = this.store.order.getOrderSyncState();
    if (amountSnapshot && syncState !== "submitting") {
      const paymentStatus = Number(amountSnapshot.amountGap || 0) <= 0 ? "paid" : "partially_paid";
      void this.syncPaymentsToOrder({
        payments,
        paymentStatus,
        submitWhenPaid: true,
        smallTicketDataFlag: 1
      }).catch((error) => {
        this.logError("auto sync payments failed", {
          error: error instanceof Error ? error.message : String(error)
        });
      });
    }
    return payments;
  }
  /** 更新当前订单中的指定支付项。 */
  updateOrderPayment(paymentIdentity, updates) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    return this.store.order.updateOrderPayment(paymentIdentity, updates);
  }
  /** 删除当前订单中的指定支付项。 */
  deleteOrderPayment(paymentIdentity) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    return this.store.order.deleteOrderPayment(paymentIdentity);
  }
  /** 覆盖 wallet pass 支付项，同时保留普通支付项。 */
  updateVoucherOrderPayments(payments) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    return this.store.order.updateVoucherOrderPayments(payments);
  }
  getWalletProductList() {
    var _a, _b;
    const tempOrder = (_a = this.store.order) == null ? void 0 : _a.getTempOrder();
    if (!((_b = tempOrder == null ? void 0 : tempOrder.products) == null ? void 0 : _b.length))
      return [];
    return tempOrder.products.map((product) => {
      const metadata = product.metadata || {};
      return {
        product_id: product.product_id,
        product_variant_id: String(product.product_variant_id ?? ""),
        quantity: product.num || 1,
        is_price_include_tax: tempOrder.is_price_include_tax,
        is_charge_tax: product.is_charge_tax ?? 0,
        tax_fee: product.tax_fee,
        selling_price: Number(product.selling_price || 0),
        discount_list: product.discount_list || [],
        holder_id: product.holder_id ?? metadata.holder_id,
        original_price: product.original_price,
        main_product_original_price: metadata.main_product_original_price ?? product.original_price,
        main_product_selling_price: metadata.main_product_selling_price ?? product.selling_price,
        metadata: {
          main_product_attached_bundle_tax_fee: metadata.main_product_attached_bundle_tax_fee,
          main_product_attached_bundle_surcharge_fee: metadata.main_product_attached_bundle_surcharge_fee,
          surcharge_rounding_remainder: metadata.surcharge_rounding_remainder
        },
        product_bundle: (product.product_bundle || []).map((bundle) => {
          const bundleMetadata = bundle.metadata || {};
          return {
            is_price_include_tax: tempOrder.is_price_include_tax,
            // 套餐子项在 tempOrder 上常为 id（如 1718），prepare/deduction 协议要求 bundle_id
            bundle_id: bundle.bundle_id ?? bundle.id,
            bundle_product_id: bundle.bundle_product_id ?? bundle._bundle_product_id,
            bundle_group_id: bundle.bundle_group_id ?? bundle.group_id,
            bundle_variant_id: bundle.bundle_variant_id,
            price_type: bundle.price_type,
            price_type_ext: bundle.price_type_ext,
            bundle_sum_price: bundle.bundle_sum_price,
            bundle_selling_price: bundle.bundle_selling_price,
            num: bundle.num,
            is_charge_tax: bundle.is_charge_tax,
            tax_fee: bundle.tax_fee,
            metadata: {
              surcharge_fee: bundleMetadata.surcharge_fee,
              surcharge_rounding_remainder: bundleMetadata.surcharge_rounding_remainder
            }
          };
        })
      };
    });
  }
  async initWalletData(params) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    if (!this.store.payment)
      throw new Error("payment 模块未初始化");
    const snapshot = this.store.order.getOrderSnapshot();
    const tempOrder = snapshot == null ? void 0 : snapshot.tempOrder;
    const amount = snapshot == null ? void 0 : snapshot.amount;
    if (!tempOrder || !amount) {
      return {
        walletRecommendList: [],
        userIdentificationCodes: [],
        transformList: [],
        noApplicableVoucher: [],
        products: []
      };
    }
    const walletBusinessData = {
      customer_id: tempOrder.customer_id ? Number(tempOrder.customer_id) : void 0,
      holder: tempOrder.holder,
      amountInfo: {
        totalAmount: amount.totalAmount,
        subTotal: amount.summary.product_amount || amount.summary.product_expect_amount || amount.totalAmount,
        depositAmount: amount.depositAmount,
        isDeposit: tempOrder.is_deposit
      },
      products: this.getWalletProductList(),
      order_wait_pay_amount: (params == null ? void 0 : params.order_wait_pay_amount) ?? Number(amount.amountGap || 0),
      is_price_include_tax: tempOrder.is_price_include_tax ?? this.otherParams.is_price_include_tax ?? 1,
      ...snapshot.identity.orderId ? { payment_order_id: String(snapshot.identity.orderId) } : {}
    };
    const result = await this.store.payment.wallet.initializeWalletDataFromBusinessAsync(
      walletBusinessData
    );
    await this.core.effects.emit(`${this.name}:onWalletDataInitialized`, {
      orderId: snapshot.identity.orderId,
      customerId: walletBusinessData.customer_id,
      walletBusinessData: {
        customer_id: walletBusinessData.customer_id,
        amountInfo: walletBusinessData.amountInfo,
        order_wait_pay_amount: walletBusinessData.order_wait_pay_amount
      },
      timestamp: Date.now()
    });
    return result;
  }
  /**
   * 更新当前订单客户字段。
   *
   * 这是 PaymentModal 客户切换的订单事实入口；外部客户模块同步应由
   * 调用方通过 onCustomerChange 回调完成。
   */
  updateOrderCustomer(customer) {
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    const result = this.store.order.updateTempOrderCustomer(customer);
    this.store.order.recalculateSummary({ createIfMissing: true });
    this.store.order.persistTempOrder();
    return result;
  }
  /** 获取可用支付方式列表，供 PaymentModal 渲染支付选项。 */
  async getPaymentMethodsAsync() {
    if (this.store.payment) {
      return this.store.payment.getPayMethodListAsync();
    }
    const response = await this.request.get("/pay/custom-payment/all");
    return (response == null ? void 0 : response.data) || [];
  }
  /** 轻量舍入能力，供现金支付 UI 计算 rounding_amount。 */
  roundAmount(params) {
    const amount = new import_decimal.default(params.amount || 0);
    const interval = new import_decimal.default(params.interval || 0.05);
    const rule = params.rule || "standard_rounding";
    const quotient = amount.div(interval);
    let roundedQuotient;
    if (rule === "always_up") {
      roundedQuotient = quotient.ceil();
    } else if (rule === "always_down") {
      roundedQuotient = quotient.floor();
    } else if (rule === "standard_down") {
      roundedQuotient = quotient.toDecimalPlaces(0, import_decimal.default.ROUND_HALF_DOWN);
    } else {
      roundedQuotient = quotient.toDecimalPlaces(0, import_decimal.default.ROUND_HALF_UP);
    }
    const roundedAmount = roundedQuotient.times(interval).toDecimalPlaces(2);
    return {
      originalAmount: amount.toFixed(2),
      roundedAmount: roundedAmount.toFixed(2),
      roundingDifference: roundedAmount.minus(amount).toFixed(2)
    };
  }
  /**
   * 发送支付链接。
   *
   * 如果没有 orderIds 或显式 submitBeforeSend，会先提交当前本地订单到云端；
   * 只有成功拿到远端 order_id 后才调用 OrderModule 发送邮件。
   */
  async sendCustomerPayLink(params) {
    var _a, _b;
    if (!this.store.order)
      throw new Error("order 模块未初始化");
    let orderIds = params.order_ids || params.orderIds || [];
    if (!orderIds.length || params.submitBeforeSend) {
      const submitResult = await this.submitSalesOrder({
        smallTicketDataFlag: 1
      });
      const orderId = ((_a = submitResult == null ? void 0 : submitResult.data) == null ? void 0 : _a.order_id) ?? (submitResult == null ? void 0 : submitResult.order_id) ?? ((_b = submitResult == null ? void 0 : submitResult.data) == null ? void 0 : _b.id) ?? (submitResult == null ? void 0 : submitResult.id);
      if (!orderId) {
        throw new Error("本地订单提交云端失败，无法发送支付链接");
      }
      orderIds = [orderId];
    }
    return this.store.order.sendCustomerPayLink({
      emails: params.emails,
      notify_action: params.notify_action,
      order_ids: orderIds
    });
  }
  transformBaseProductToOrderProduct(params) {
    return (0, import_transformBaseProductToOrderProduct.transformBaseProductToOrderProduct)(params);
  }
  async calculateProductBookingPrice(params) {
    const quotation = this.store.quotation;
    const customerId = params.customer_id ?? this.getCurrentOrderCustomerId();
    await this.loadQuotationForPriceQuery({
      quotation,
      customer_id: customerId,
      channel: params.channel
    });
    return (0, import_quotationPrice.calculateBaseSalesProductBookingPrice)({
      ...params,
      customer_id: customerId,
      quotation
    });
  }
  async addProductToOrder(product, booking) {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const products = await this.store.order.addProductToOrder(product, booking);
      return products;
    } catch (error) {
      throw error;
    }
  }
  async updateOrderProduct(params) {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const products = await this.store.order.updateOrderProduct(params);
      return products;
    } catch (error) {
      throw error;
    }
  }
  async updateOrderProductQuantity(params) {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const products = await this.store.order.updateOrderProductQuantity(params);
      return products;
    } catch (error) {
      throw error;
    }
  }
  updateOrderBooking(params) {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      return this.store.order.updateOrderBooking(params);
    } catch (error) {
      throw error;
    }
  }
  /**
   * 设置单行商品备注（与整单 `updateTempOrderNote` 区分）。
   * 多行同 SKU 时必须传入与删除/更新一致的 unique_identification_number。
   */
  async setOrderProductLineNote(identity, note) {
    try {
      const params = {
        product_id: identity.product_id,
        product_variant_id: identity.product_variant_id,
        updates: { note: String(note || "") }
      };
      if (identity.unique_identification_number !== void 0) {
        params.unique_identification_number = identity.unique_identification_number;
      }
      if (identity.product_option_item !== void 0) {
        params.product_option_item = identity.product_option_item;
      }
      if (identity.product_bundle !== void 0)
        params.product_bundle = identity.product_bundle;
      const products = await this.updateOrderProduct(params);
      return products;
    } catch (error) {
      throw error;
    }
  }
  async removeProductFromOrder(identity) {
    try {
      if (!this.store.order)
        throw new Error("order 模块未初始化");
      const products = await this.store.order.removeProductFromOrder(identity);
      return products;
    } catch (error) {
      throw error;
    }
  }
  // 获取商品列表
  // TODO 需要跟 webpos 内的对齐一下
  async getProductList() {
    var _a, _b, _c;
    const menu_list_ids = ((_b = (_a = this.otherParams) == null ? void 0 : _a.dineInConfig) == null ? void 0 : _b["menu.associated_menus"].map((n) => Number(n.value))) || [];
    try {
      const res = await ((_c = this.store.products) == null ? void 0 : _c.loadProducts({
        menu_list_ids,
        cacheId: this.cacheId,
        schedule_date: (0, import_dayjs.default)().format("YYYY-MM-DD"),
        schedule_datetime: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
      }));
      return res;
    } catch (error) {
      throw error;
    }
  }
  getOtherParams() {
    return this.otherParams;
  }
  async setOtherParams(params, { cover = false } = {}) {
    if (cover) {
      this.otherParams = params;
    } else {
      this.otherParams = { ...this.otherParams, ...params };
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BaseSalesImpl,
  ...require("./types")
});
