import { Module, PisellCore, ModuleOptions } from '../../types';
import { BaseModule } from '../BaseModule';
import { OrderModuleAPI, CommitOrderParams, UpdateOrderBookingParams, UpdateOrderProductParams, UpdateOrderProductQuantityParams, CheckoutOrderParams, CancelOrderParams, ChangeBookingStatusParams } from './types';
import { CartItem } from '../Cart/types';
import { type SubmitPayloadEnhancer } from './utils';
import type { OrderAmountSnapshot, AddProductBookingInput, OrderIdentitySnapshot, OrderPaymentSource, OrderSnapshot, OrderSyncState, SyncPaymentsToOrderParams, SyncPaymentsToOrderResult, SubmitSalesOrderParams, OrderProduct, OrderProductIdentity, OrderSummary, OrderTempOrder, OrderPaymentData, SendCustomerPayLinkParams, UpdateTempOrderCustomerInput, OrderCustomerPatch, OrderCustomerView, ReplaceTempOrderOptions, OrderPromotionEvaluator, OrderGiftSelectResolver, OrderUnfulfilledPromotion, OrderLastGiftActions } from './types';
import type { ICustomer } from '../AccountList/types';
import type { Discount } from '../Discount/types';
import { UnavailableReason } from '../Rules/types';
export declare class OrderModule extends BaseModule implements Module, OrderModuleAPI {
    protected defaultName: string;
    protected defaultVersion: string;
    private store;
    private request;
    private logger;
    private window;
    private cacheId;
    private salesSummaryModuleName;
    private rulesHooksOverride?;
    private orderHooks?;
    private otherParams?;
    /** 评估器引用；由 SalesSdkProvider 注入，未注入时 applyPromotion 静默跳过 */
    private promotionEvaluator;
    /** 赠品选择 resolver；由 SDK host bridge 注入 */
    private giftSelectResolver;
    /** applyPromotion 递归保护 flag（写路径同步调 applyPromotion，禁止重入） */
    private isApplyingPromotion;
    /** 最近一次 applyPromotion 的未满足促销提示 */
    private lastUnfulfilledPromotions;
    /** 最近一次 applyPromotion 的赠品操作 diff（debug / SDK 读取使用） */
    private lastGiftActions;
    /**
     * 是否将 tempOrder 写入 IndexedDB 草稿（orders store）。
     * BigSale 弹窗等短生命周期场景通过 setEnableTempOrderPersist(false) 关闭。
     */
    private draftPersistEnabled;
    private collectHydratedEditDiscounts;
    /**
     * Populate `savedAmount` on each discount based on product-level discount details.
     * Only selected discounts get a non-zero value.
     */
    static populateSavedAmounts(productList: Array<Record<string, any>>, discountList: Array<Record<string, any>>): void;
    private applyProductDiscountPrices;
    constructor(name?: string, version?: string);
    initialize(core: PisellCore, options: ModuleOptions): Promise<void>;
    /**
     * 记录信息日志
     */
    private logInfo;
    /**
     * 记录警告日志
     */
    private logWarning;
    /**
     * 记录错误日志
     */
    private logError;
    private registerDiscountModules;
    private createDefaultRulesHooks;
    loadDiscountConfig(params: {
        customerId: number;
        action?: 'create' | 'edit';
        orderId?: number;
        apply?: boolean;
    }): Promise<Discount[]>;
    getDiscountList(): Discount[];
    private ensureEditDiscountConfigForProductChange;
    scanCode(code: string, customerId?: number): Promise<{
        isAvailable: boolean;
        discountList: Discount[];
        type: 'server' | 'clientCalc';
        unavailableReason?: UnavailableReason;
        unavailableReasonKey?: string | null;
        scannedDiscountList?: Discount[];
    }>;
    applyDiscount(): void;
    /**
     * 注入促销评估器。
     *
     * @example
     * order.setPromotionEvaluator(appHelper.utils.promotionEvaluator);
     */
    setPromotionEvaluator(evaluator: OrderPromotionEvaluator | null): void;
    /**
     * 注入赠品选择 resolver。OS 需要补赠品时会 await 调用 resolver；缺省时跳过新增并 console.warn。
     *
     * @example
     * order.setGiftSelectResolver(async (ctx) => {
     *   // SDK 内部决定弹窗 or 自动选第一项，返回完整 OrderProduct[]
     *   return giftSelectBridge.request(ctx);
     * });
     */
    setGiftSelectResolver(resolver: OrderGiftSelectResolver | null): void;
    /**
     * 为商品目录追加促销标签，供上层 Sales 门面复用。
     *
     * @example
     * const products = order.appendPromotionTags(catalogProducts);
     */
    appendPromotionTags<T extends Record<string, any>>(products: T[]): T[];
    /**
     * 应用购物车促销：计算 → 差异化赠品 → 写回 tempOrder.products → emit onPromotionApplied。
     *
     * 调用时机：写路径（add/update/remove/clear/setCustomer）末尾自动触发；外部一般无需手动调。
     *
     * 关键约束：
     * - 不调用任何公开 CRUD API（如 removeProductFromOrder），全部内部 mutate tempOrder.products，避免事件风暴；
     * - 用 `isApplyingPromotion` 防递归；
     * - 多选项赠品依赖 giftSelectResolver，未注入则跳过且 console.warn；
     * - 不主动调用 applyDiscount / recalculateSummary，调用方负责跟进。
     */
    applyPromotion(): Promise<void>;
    /** 最近一次 applyPromotion 输出的未满足促销列表 */
    getUnfulfilledPromotions(): OrderUnfulfilledPromotion[];
    /** 最近一次 applyPromotion 输出的赠品操作 diff */
    getLastGiftActions(): OrderLastGiftActions | null;
    initTempOrder(params: {
        cacheId?: string;
        salesSummaryModuleName?: string;
    }): void;
    /**
     * 控制 IndexedDB 草稿（saveDraft）是否写入。
     * localStorage 版 tempOrder 持久化已废弃，此方法仅影响 saveDraft。
     *
     * @example
     * order.setEnableTempOrderPersist(false); // BigSale 弹窗：跳过 ~1s 的 dbUpdate
     */
    setEnableTempOrderPersist(enabled: boolean): void;
    /** 是否允许 saveDraft 写入 IndexedDB 草稿。 */
    isTempOrderPersistEnabled(): boolean;
    /** @deprecated OrderModule 不再负责 tempOrder localStorage 持久化；草稿保存请使用 IndexedDB saveDraft。 */
    persistTempOrder(): void;
    private createDefaultTempOrderInstance;
    private createExternalSaleNumber;
    private ensureExternalSaleNumber;
    private ensureRequestUniqueIdempotencyToken;
    private buildPaymentSyncIdempotencyToken;
    saveDraft(): Promise<void>;
    private saveDraftInBackground;
    private hydrateTempOrderFromLocalRecord;
    private extractOrderIdFromSubmitResult;
    private calculatePaymentEffectiveAmount;
    private calculatePaymentTotal;
    private getDepositAmount;
    private isDepositOrder;
    private getOrderExpectedAmount;
    private isDepositCovered;
    private normalizePaymentSource;
    private updateTempOrderPaymentStatus;
    private shouldKeepPaymentStatusAfterAmountRecalc;
    private resolveWalletPassUseValue;
    private adjustVoucherFundRecord;
    private capVoucherPaymentsByRemainingAmount;
    private calculatePaidPaymentSummary;
    private calculatePaymentServiceFee;
    private calculatePaymentGapAmount;
    private calculatePaymentRoundingAmount;
    private formatSummaryMetadataMoney;
    private syncSummaryProductMetadata;
    private calculateSummaryAmountGap;
    private getSummaryRefundAmount;
    private calculatePaymentTargetAmount;
    private normalizeFingerprintMoney;
    private normalizeFingerprintValue;
    private buildProductFingerprintItem;
    private buildOrderProductsFingerprint;
    private buildProductStructuralFingerprintItem;
    private buildOrderProductsStructuralFingerprint;
    private getOriginalSalesSnapshot;
    private restoreOriginalSnapshotIfProductsUnchanged;
    private clearPersistedAmountFieldsForFullRecalc;
    private getPaymentTargetAmount;
    ensureTempOrder(): OrderTempOrder;
    restoreOrder(): OrderTempOrder;
    getTempOrder(): OrderTempOrder | null;
    replaceTempOrder(tempOrder: OrderTempOrder, options?: ReplaceTempOrderOptions): Promise<OrderTempOrder>;
    getOrderIdentity(): OrderIdentitySnapshot | null;
    getOrderSyncState(): OrderSyncState;
    getOrderAmountSnapshot(): OrderAmountSnapshot | null;
    getOrderSnapshot(): OrderSnapshot | null;
    addNewOrder(): Promise<OrderTempOrder>;
    getOrderProducts(): OrderProduct[];
    private getProductUid;
    private sanitizeOrderProductForTempOrder;
    private sanitizeTempOrderProducts;
    private ensureExtend;
    private captureProductRuntime;
    private createLinkedProductAndBooking;
    private getBookingUniqueIdentificationNumber;
    private findBookingIndexByUniqueIdentificationNumber;
    private removeLinkedBookingsForProduct;
    private getSalesSummary;
    recalculateSummary(options?: {
        createIfMissing?: boolean;
    }): Promise<OrderSummary | null>;
    getOrderSummary(): Promise<OrderSummary>;
    updateTempOrderNote(note: string): string;
    updateTempOrderNote(note: string, sync: true): Promise<string>;
    updateTempOrderNote(note: string, sync: boolean): string | Promise<string>;
    syncTempOrderNoteToRemote(orderId: number | string, note: string): Promise<string>;
    getTempOrderNote(): string;
    updateTempOrderShopDiscount(amount: string | number): string;
    updateTempOrderBuzzer(buzzer: string): string;
    updateTempOrderContactsInfo(contactsInfo: Record<string, any> | null): Record<string, any> | null;
    private buildTempOrderCustomer;
    private isCustomerBoundDiscount;
    private clearCustomerBoundDiscounts;
    /**
     * 更新当前 tempOrder 的客户协议字段。
     *
     * PaymentModal 只需要修改订单里的客户事实；如果外部还有客户模块需要同步，
     * 应由调用方通过回调处理，不能把外部 UI 状态写进 tempOrder。
     */
    updateTempOrderCustomer(customer: UpdateTempOrderCustomerInput): OrderSnapshot['customer'];
    setOrderCustomer(patch: OrderCustomerPatch | null, snapshot?: ICustomer | null): void;
    getOrderCustomer(): OrderCustomerView | null;
    getOrderCustomerSnapshot(): ICustomer | null;
    clearOrderCustomer(): void;
    private emitOrderCustomerChange;
    /**
     * 读取当前订单的 Sales 协议支付项。
     *
     * 这里返回的是 tempOrder.payments，而不是旧 PaymentModule 的本地
     * payment order / tender session。Sales checkout 以该数组为提交事实来源。
     */
    getOrderPayments(): OrderPaymentData[];
    /**
     * 用一组支付来源覆盖当前订单支付项。
     *
     * 入参允许来自 PaymentModule 的 PaymentItem，内部统一映射为 Sales 协议：
     * uuid -> metadata.unique_payment_number，id -> custom_payment_id，
     * isSynced 等运行态字段不会进入 tempOrder.payments。
     */
    setOrderPayments(payments: OrderPaymentSource[]): OrderPaymentData[];
    /** 追加单个支付项，并立即持久化当前 tempOrder。 */
    addOrderPayment(payment: OrderPaymentSource): OrderPaymentData[];
    /**
     * 按支付唯一号、后端支付 ID、自定义支付方式 ID 或旧 uuid 更新支付项。
     *
     * 该方法服务 PaymentModal 的 void / 编辑场景；更新 metadata 时会做浅合并，
     * 避免覆盖 unique_payment_number、现金实付/找零等已有元数据。
     */
    updateOrderPayment(paymentIdentity: string | number, updates: Partial<OrderPaymentData> & Record<string, any>): OrderPaymentData[];
    /** 从当前订单支付项中移除指定支付项。 */
    deleteOrderPayment(paymentIdentity: string | number): OrderPaymentData[];
    /**
     * 覆盖当前订单中的 wallet pass 支付项。
     *
     * 判断口径与 PaymentModal 保持一致：voucher_id 存在且不为 0 的支付项
     * 视为 wallet pass；其它支付项保持不变。
     */
    updateVoucherOrderPayments(payments: OrderPaymentSource[]): OrderPaymentData[];
    private shouldMergeProductToOrder;
    /**
     * 预约商品加车后的统一收尾：促销、折扣、summary 重算与持久化（批量拆行时只调用一次）。
     *
     * @example
     * await this.finalizeProductOrderMutation(tempOrder);
     */
    private finalizeProductOrderMutation;
    /**
     * 向 tempOrder 追加一条商品行（及可选 booking），不触发 summary 重算。
     * 带 booking 且 num>1 时由 `addProductToOrder` 拆成多次本方法调用（每次 num=1）。
     *
     * @example
     * await this.appendProductLineToTempOrder(tempOrder, { product_id: 1, num: 1 }, booking);
     */
    private appendProductLineToTempOrder;
    /**
     * 添加商品行。带 booking 时强制独立行；num>1 时拆成多条 num=1 的 product+booking（对齐 BookingByStep / ticketBooking addService）。
     *
     * @example
     * await order.addProductToOrder({ product_id: 1, num: 3 }, { start_time: '10:00' });
     * // → tempOrder.products 新增 3 行，每行 num=1，bookings 3 条
     */
    addProductToOrder(product: Partial<OrderProduct> & OrderProductIdentity, booking?: AddProductBookingInput): Promise<OrderProduct[]>;
    private hasGoodPassDiscount;
    private getBundleRuntimeIdentity;
    private preservePersistedBundlePriceFields;
    updateOrderProduct(params: UpdateOrderProductParams): Promise<OrderProduct[]>;
    updateOrderProductQuantity(params: UpdateOrderProductQuantityParams): Promise<OrderProduct[]>;
    updateOrderBooking(params: UpdateOrderBookingParams): any[];
    /**
     * 商品行写路径收尾：促销 → 折扣 → 清洗 → summary → 持久化。
     * 批量删除等多行变更场景只应调用一次，避免 N 次 applyPromotion。
     *
     * @example
     * await this.finalizeAfterProductsMutation(tempOrder);
     */
    private finalizeAfterProductsMutation;
    /**
     * 批量按 identity 删除购物车行，末尾仅一次促销重算。
     *
     * @example
     * await order.removeProductsFromOrder([identityA, identityB]);
     */
    removeProductsFromOrder(identities: OrderProductIdentity[]): Promise<OrderProduct[]>;
    removeProductFromOrder(identity: OrderProductIdentity): Promise<OrderProduct[]>;
    /**
     * 仅清空购物车行（products / bookings），不重置整单。
     * 用于「仅清空商品」；客户、备注、支付等协议字段保持不变。
     */
    clearOrderCartLines(): Promise<OrderTempOrder>;
    buildCurrentSubmitPayloadForLocalPrint(params?: {
        cacheId?: string;
        platform?: string;
        businessCode?: string;
        channel?: string;
        type?: string;
    }): import("./types").OrderSubmitPayload;
    applyLocalPrintOrderNumbers(order?: Record<string, any> | null): Promise<OrderTempOrder>;
    /**
     * 提交当前 Sales tempOrder。
     *
     * smallTicketDataFlag 用于 B 端 checkout 小票数据返回。PaymentModal 在支付提交时
     * 应传 1，确保 /shop/order/sales/checkout 返回打印所需数据。
     */
    submitTempOrder<T = any>(params?: {
        cacheId?: string;
        platform?: string;
        businessCode?: string;
        channel?: string;
        type?: string;
        payments?: OrderPaymentSource[];
        paymentStatus?: SubmitSalesOrderParams['query']['payment_status'];
        smallTicketDataFlag?: number;
        enhancePayload?: SubmitPayloadEnhancer;
    }): Promise<T>;
    private markLocalOrderSynced;
    private isSubmitResponseRejected;
    private isLocalPendingSubmitResult;
    private isSubmitErrorResponse;
    private extractSubmitErrorResponse;
    private logSubmitBackendRejected;
    syncPaymentsToOrder<T = any>(params: SyncPaymentsToOrderParams): Promise<SyncPaymentsToOrderResult<T>>;
    createOrder(params: CommitOrderParams['query']): {
        type: "appointment_booking" | "virtual";
        platform: string;
        sales_channel: string;
        order_sales_channel: string;
        bookings: any[];
        shop_note: string;
        schedule_date: string;
        is_deposit: number;
        relation_products: any[];
        relation_forms: any[];
    };
    checkBeforeSubmitOrder(params: {
        cartItems: CartItem[];
        type: 'holder' | 'account';
    }): boolean;
    submitOrder(order: CommitOrderParams): Promise<void>;
    cancelOrder(params: CancelOrderParams): Promise<any>;
    changeBookingStatus(params: ChangeBookingStatusParams): Promise<any>;
    /**
     * Checkout 专用：创建订单到后端
     *
     * 专门为 Checkout 模块设计的订单创建方法，
     * 通过 OS Server 调用 checkout 接口创建订单
     * 接收已经处理好的订单数据，无需再处理购物车
     *
     * @param params Checkout 订单参数（已处理的订单数据）
     * @returns 后端返回的订单数据（包含订单ID等）
     */
    createOrderByCheckout(params: CheckoutOrderParams): Promise<any>;
    submitSalesOrder<T = any>(params: SubmitSalesOrderParams): Promise<T>;
    /**
     * 发送支付链接邮件。
     *
     * 调用前必须已经有远端 order_id。BaseSales 会在需要时先提交本地订单，
     * OrderModule 只负责校验 order_ids 并调用 /order/batch-email。
     */
    sendCustomerPayLink<T = any>(params: SendCustomerPayLinkParams): Promise<T>;
    getSalesOrderByLookup(params: {
        lookup: number | string;
        forceRemote?: boolean;
    }): Promise<any>;
    /**
     * 把 sqlite / 后端返回的订单记录直接恢复为 tempOrder。
     *
     * 数据源应尽量返回 tempOrder 所需结构；这里仅做 SDK 运行必须字段兜底，
     * 例如数组字段、商品行唯一值、价格 metadata、summary 派生状态和 _extend。
     */
    hydrateTempOrderFromRecord(record: Record<string, any>, options?: {
        recalcOnHydrate?: boolean;
    }): Promise<OrderTempOrder>;
    private normalizeTempOrderForRuntime;
    private pickHydratedDisplayText;
    private formatHydratedNamePair;
    private buildHydratedProductOptionString;
    private normalizeHydratedProductOptionItem;
    private normalizeHydratedOrderProduct;
    getLastOrderInfo(): Record<string, any> | undefined;
    getOrderInfo(order_id: number): Promise<any>;
}
export type { UpdateOrderBookingParams, UpdateOrderProductParams, UpdateOrderProductQuantityParams, } from './types';
