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/components/checkout/PaymentModal.tsx
var PaymentModal_exports = {};
__export(PaymentModal_exports, {
  default: () => PaymentModal_default
});
module.exports = __toCommonJS(PaymentModal_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_locales = require("../../utils/locales");
var import_ahooks = require("ahooks");
var import_react_dom = require("react-dom");
var import_locales2 = __toESM(require("./locales"));
var import_materials = require("@pisell/materials");
var import_materials2 = require("@pisell/materials");
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_noteModal = __toESM(require("../../plus/noteModal"));
var import_SendPaymentLinkModal = __toESM(require("./components/SendPaymentLinkModal"));
var import_AmountSummary = __toESM(require("./components/AmountSummary/index"));
var import_SavePayLaterHandler = __toESM(require("./components/SavePayLaterHandler"));
var import_WalletPassModule = __toESM(require("./components/WalletPassModule"));
var import_PaymentOptionsModule = __toESM(require("./components/PaymentOptionsModule"));
var import_CashPaymentModule = __toESM(require("./components/CashPaymentModule"));
var import_AdditionalModule = __toESM(require("./components/AdditionalModule"));
var import_amount = require("../booking/components/footer/amount");
var import_PaymentResultToast = require("./components/PaymentResultToast");
var import_PaymentResultToastUtils = require("./utils/PaymentResultToastUtils");
var import_icon = require("@pisell/icon");
var import_styles = require("./styles");
var import_paymentMethods = __toESM(require("../pay/toB/paymentMethods"));
var import_components = require("../../pro/comprehensiveSearch/components");
var import_SearchAndClientModule = __toESM(require("./components/SearchAndClientModule"));
var import_useToast = __toESM(require("../../hooks/useToast"));
var import_index = require("./index.less");
var import_constants = require("./constants");
var import_lodash = require("lodash");
var import_utils2 = require("./utils");
var import_usePaymentLogger = __toESM(require("./hooks/usePaymentLogger"));
var import_antd = require("antd");
var CheckoutHooks = {
  OnStateAmountChanged: "checkout:onStateAmountChanged",
  OnBalanceDueAmountChanged: "checkout:onBalanceDueAmountChanged",
  OnOrderSubmitStart: "checkout:onOrderSubmitStart",
  OnOrderSubmitEnd: "checkout:onOrderSubmitEnd",
  OnOrderSyncFailed: "checkout:onOrderSyncFailed",
  OnOrderPaymentAdded: "checkout:onPaymentItemAdded"
};
var PaymentContent = (0, import_react.forwardRef)(
  ({
    cartData,
    orderInfo,
    isModalOpen,
    onPaymentComplete,
    onPaymentCancel,
    onStatusChange,
    dispatch,
    state,
    showingCashToastRef,
    onToastClose,
    orderNote,
    setOrderNote,
    setNoteModalSource,
    setNoteModalOpen,
    totalAmount = 0,
    moduleConfig: parentModuleConfig,
    onShowCashPaymentChange,
    showSuccessToast,
    dynamicMaxHeight = "600px",
    onOrderSyncFailed,
    generateActionButtons,
    paymentResultToastConfig
  }, ref) => {
    var _a, _b, _c;
    const context = (0, import_useEngineContext.default)();
    const utils = context.appHelper.utils || {};
    const { pisellos, getData, pisellosAllModule, interaction } = utils;
    const Toast = (0, import_useToast.default)();
    const checkoutRef = (0, import_react.useRef)(null);
    const savePayLaterHandlerRef = (0, import_react.useRef)(null);
    const [customAmount, setCustomAmount] = (0, import_react.useState)("");
    const [balanceDueAmount, setBalanceDueAmount] = (0, import_react.useState)("");
    const [recommendAmounts, setRecommendAmounts] = (0, import_react.useState)([]);
    const paymentMethodsRef = (0, import_react.useRef)(null);
    const [paymentMethods, setPaymentMethods] = (0, import_react.useState)([]);
    const [showCashPayment, setShowCashPayment] = (0, import_react.useState)(false);
    const [paymentOptionsTitle, setPaymentOptionsTitle] = (0, import_react.useState)(
      import_utils.locales.getText("cards.and.digitals") || "Cards & Digitals"
    );
    const clientChangedRef = (0, import_react.useRef)(false);
    const walletPassRef = (0, import_react.useRef)(null);
    const [paymentItems, setPaymentItems] = (0, import_react.useState)([]);
    const [walletPassData, setWalletPassData] = (0, import_react.useState)({});
    const isOrderFree = (0, import_react.useMemo)(() => {
      if (!customAmount) return false;
      const amount = parseFloat(customAmount);
      return amount <= 0;
    }, [customAmount]);
    const [paymentLinkModalOpen, setPaymentLinkModalOpen] = (0, import_react.useState)(false);
    const [showPriceAdjustModal, setShowPriceAdjustModal] = (0, import_react.useState)(false);
    const logger = (0, import_usePaymentLogger.default)();
    const currency = getData("shop_currency_code") || "USD";
    const open_deposit = getData("bookingv2_deposit") || 0;
    const checkoutModule = pisellos == null ? void 0 : pisellos.getModule("checkout");
    const walletPassDetail = (0, import_react.useMemo)(() => {
      const map = paymentMethods.reduce((acc, item) => {
        if (import_constants.WALLET_PASS_CODE_ARRAY.includes(item.code)) {
          acc[item.code] = item;
        }
        return acc;
      }, {});
      return {
        map,
        isShow: true
      };
    }, [paymentMethods]);
    const handleAddCashPayment = async (result) => {
      const cashPaymentMethod = paymentMethods.find(
        (method) => {
          var _a2;
          return method.code === "CASHMANUAL" || method.type === "CASHMANUAL" || ((_a2 = method.name) == null ? void 0 : _a2.toLowerCase().includes("cash"));
        }
      );
      await (checkoutModule == null ? void 0 : checkoutModule.addPaymentItemAsync({
        amount: result.amount,
        /** 支付类型，跟支付列表上对应的支付方式保持一致 */
        code: cashPaymentMethod == null ? void 0 : cashPaymentMethod.code,
        /** 支付类型id，跟支付列表上对应的支付方式保持一致 */
        id: cashPaymentMethod == null ? void 0 : cashPaymentMethod.id,
        /** 支付类型名称，跟支付列表上对应的支付方式保持一致 */
        name: cashPaymentMethod == null ? void 0 : cashPaymentMethod.name,
        /** 支付类型type，跟支付列表上对应的支付方式保持一致 */
        type: cashPaymentMethod == null ? void 0 : cashPaymentMethod.type,
        /** 代金券、充值卡、积分卡等wallet pass id */
        voucher_id: 0,
        rounding_amount: result.roundingAmount
      }));
    };
    const processSurcharge = (surcharge) => {
      if (typeof surcharge === "string") {
        return surcharge.replace(/^[$¥€£]+/, "");
      }
      if (typeof surcharge === "number") {
        return String(surcharge);
      }
      return surcharge;
    };
    const onPaymentOptionClick = async (method) => {
      var _a2;
      const { id, code, name, type } = method || {};
      const eftposCodes = [
        "EFTPOS_LINKLY",
        "EFTPOS_PAYO",
        "EFTPOS_WINDCAVE",
        "EFTPOS_TYRO"
      ];
      const mx51Code = "EFTPOS";
      let payType = "";
      if (eftposCodes.includes((method == null ? void 0 : method.code) || "")) {
        payType = "eftpos";
      } else if ((method == null ? void 0 : method.code) === mx51Code) {
        payType = "mx51";
      }
      if (payType) {
        let data;
        const isSynced = await checkoutModule.isCurrentOrderSynced();
        if (!isSynced) {
          data = await checkoutModule.manualSyncOrderAsync();
        } else {
          const orderId = await checkoutModule.getCurrentOrderId();
          data = {
            orderId
          };
        }
        (_a2 = paymentMethodsRef.current) == null ? void 0 : _a2.onPay(payType, {
          source: "normal",
          data: {
            payMethod: { id, code, name, type },
            params: {
              orderId: data.orderId,
              symbol: getData("shop_symbol"),
              amount: customAmount,
              surcharge: processSurcharge(method.surcharge)
            },
            mode: "pay"
          },
          callback: ({ status, data: data2, msg }) => {
            console.log("eftpos_pay_result>>>>>>", status, data2, msg);
            if (status === "success") {
              const payResultParams = {
                amount: Number(data2 == null ? void 0 : data2.amount),
                // 支付金额
                code,
                // 支付类型code
                id,
                // 支付类型id
                name,
                // 支付类型name
                type,
                // 支付类型type
                voucher_id: "",
                service_charge: {},
                metadata: {
                  unique_payment_number: data2 == null ? void 0 : data2.uniquePaymentNumber
                }
              };
              if (payType === "eftpos") {
                payResultParams.service_charge = {
                  percentage: data2 == null ? void 0 : data2.surPercentRate,
                  amount: data2 == null ? void 0 : data2.surMoney
                };
              } else if (payType === "mx51") {
                if (Number((data2 == null ? void 0 : data2.surcharge) || 0) !== Number((method == null ? void 0 : method.surcharge) || 0)) {
                  payResultParams.service_charge = {
                    amount: (data2 == null ? void 0 : data2.surcharge) || "0",
                    percentage: "0"
                  };
                } else {
                  payResultParams.service_charge = {
                    amount: (method == null ? void 0 : method.fixed) || "0",
                    percentage: (method == null ? void 0 : method.percentage) || "0"
                  };
                }
              }
              checkoutModule == null ? void 0 : checkoutModule.addPaymentItemAsync(payResultParams);
            }
          }
        });
      } else {
        let service_charge = null;
        if ((method == null ? void 0 : method.fixed) || (method == null ? void 0 : method.percentage)) {
          service_charge = {
            amount: (method == null ? void 0 : method.fixed) || "0",
            percentage: (method == null ? void 0 : method.percentage) || "0"
          };
        }
        await (checkoutModule == null ? void 0 : checkoutModule.addPaymentItemAsync({
          amount: customAmount,
          /** 支付类型，跟支付列表上对应的支付方式保持一致 */
          code: method.code,
          /** 支付类型id，跟支付列表上对应的支付方式保持一致 */
          id: method.id,
          /** 支付类型名称，跟支付列表上对应的支付方式保持一致 */
          name: method.name,
          /** 支付类型type，跟支付列表上对应的支付方式保持一致 */
          type: method.type,
          /** 代金券、充值卡、积分卡等wallet pass id */
          voucher_id: 0,
          /** 支付手续费 */
          service_charge
        }));
      }
    };
    (0, import_react.useEffect)(() => {
      var _a2;
      if (checkoutModule && orderInfo && isModalOpen) {
        try {
          const currentAmount = checkoutModule.getStateAmount();
          if (currentAmount) {
            setCustomAmount(currentAmount);
            setBalanceDueAmount(currentAmount);
            const currentNote = checkoutModule.getOrderNote();
            if (currentNote) {
              setOrderNote(currentNote);
            } else if ((_a2 = cartData == null ? void 0 : cartData.order_info) == null ? void 0 : _a2.order_note) {
              setOrderNote(cartData.order_info.order_note);
            }
          }
        } catch (error) {
          console.warn("Failed to get initial custom amount:", error);
        }
      } else {
      }
      if (checkoutModule && isModalOpen) {
        checkoutModule.getPaymentMethodsAsync().then(async (paymentMethods2) => {
          const reorderedPaymentMethods = await (0, import_utils2.reorderPaymentMethodList)(paymentMethods2, interaction);
          setPaymentMethods(reorderedPaymentMethods);
          const isShowCashPayment = paymentMethods2.some(
            (item) => item.code === "CASHMANUAL"
          );
          setShowCashPayment(isShowCashPayment);
          onShowCashPaymentChange == null ? void 0 : onShowCashPaymentChange(isShowCashPayment);
          if (!isShowCashPayment) {
            setPaymentOptionsTitle(
              import_utils.locales.getText("pisell2.checkout.payment.select-payment") || "Select Payment"
            );
          }
        });
      }
    }, [checkoutModule, orderInfo]);
    (0, import_react.useEffect)(() => {
      if (customAmount && checkoutModule && currency && orderInfo && isModalOpen) {
        try {
          setRecommendAmounts(
            checkoutModule.payment.cash.getRecommendedAmount(
              customAmount,
              currency
            )
          );
        } catch (error) {
          console.warn("Failed to get recommended amounts:", error);
        }
      }
    }, [customAmount, checkoutModule, currency, orderInfo]);
    (0, import_react.useEffect)(() => {
      if (checkoutModule && checkoutModule.core && isModalOpen) {
        try {
          const core = checkoutModule.core;
          if (core.effects && typeof core.effects.on === "function") {
            const unsubscribe = core.effects.on(
              CheckoutHooks.OnStateAmountChanged,
              async (data) => {
                var _a2, _b2;
                console.log(
                  `Amount changed from ${data.oldAmount} to ${data.newAmount}`
                );
                if (clientChangedRef.current) {
                  clientChangedRef.current = false;
                  if (data.newAmount !== data.oldAmount) {
                    (_a2 = Toast == null ? void 0 : Toast.success) == null ? void 0 : _a2.call(
                      Toast,
                      import_utils.locales.getText(
                        "pisell2.checkout.client-card.tip.wallet-updated"
                      )
                    );
                  } else {
                    (_b2 = Toast == null ? void 0 : Toast.success) == null ? void 0 : _b2.call(
                      Toast,
                      import_utils.locales.getText(
                        "pisell2.checkout.client-card.tip.client-changed"
                      )
                    );
                  }
                }
                setCustomAmount(data.newAmount);
                const items = await checkoutModule.getCurrentOrderPaymentItemsAsync();
                setPaymentItems(items);
              }
            );
            const amountChangedUnsubscribe = core.effects.on(
              CheckoutHooks.OnBalanceDueAmountChanged,
              (data) => {
                setBalanceDueAmount(data.newAmount);
              }
            );
            const orderSubmitStartUnsubscribe = core.effects.on(
              CheckoutHooks.OnOrderSubmitStart,
              () => {
                var _a2;
                (_a2 = Toast == null ? void 0 : Toast.loading) == null ? void 0 : _a2.call(Toast);
              }
            );
            const orderSubmitEndUnsubscribe = core.effects.on(
              CheckoutHooks.OnOrderSubmitEnd,
              (res) => {
                var _a2, _b2;
                if (res.success) {
                  (_a2 = Toast == null ? void 0 : Toast.hide) == null ? void 0 : _a2.call(Toast);
                } else {
                  (_b2 = Toast == null ? void 0 : Toast.hide) == null ? void 0 : _b2.call(Toast);
                  if (onOrderSyncFailed) {
                    onOrderSyncFailed();
                  } else {
                    Toast == null ? void 0 : Toast.fail(
                      import_utils.locales.getText("pisell2.checkout.order-sync-failed") || "Order sync failed"
                    );
                  }
                }
              }
            );
            const orderPaymentAddedUnsubscribe = core.effects.on(
              CheckoutHooks.OnOrderPaymentAdded,
              (data) => {
                var _a2, _b2;
                console.log("orderPaymentAddedUnsubscribe>>>>", data);
                const balanceDueAmount2 = checkoutModule.getBalanceDueAmount();
                if (Number(balanceDueAmount2) > 0) {
                  const autoCloseConfig = (0, import_PaymentResultToastUtils.calculateAutoCloseConfig)(
                    "partially_paid",
                    false
                  );
                  const orderInfo2 = checkoutModule.getCurrentOrderInfo();
                  (0, import_PaymentResultToastUtils.displayPaymentResultToast)(
                    {
                      paymentStatus: "partially_paid",
                      orderTotalAmount: orderInfo2.totalAmount,
                      gapAmount: balanceDueAmount2,
                      failureReason: "",
                      autoCloseConfig,
                      actionButtons: generateActionButtons == null ? void 0 : generateActionButtons("partially_paid")
                    },
                    {
                      ...paymentResultToastConfig,
                      onToastClose: () => {
                        (0, import_PaymentResultToast.closePaymentResultToast)();
                      },
                      onCountdownComplete: () => {
                        (0, import_PaymentResultToast.closePaymentResultToast)();
                      }
                    }
                  );
                }
                const paymentMethodName = data.paymentMethodName || data.name || "";
                const isCashPayment = data.paymentMethodCode === "CASHMANUAL" || /现金|現金/i.test(paymentMethodName) || /cash/i.test(paymentMethodName);
                if (isCashPayment) {
                  logger == null ? void 0 : logger.addLog({
                    type: "info",
                    title: "open_till",
                    metadata: {}
                  });
                  (_b2 = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b2.call(_a2, {
                    module: "till",
                    key: "open_till"
                  });
                }
              }
            );
            return () => {
              if (unsubscribe && typeof unsubscribe === "function") {
                unsubscribe();
              }
              if (orderSubmitStartUnsubscribe && typeof orderSubmitStartUnsubscribe === "function") {
                orderSubmitStartUnsubscribe();
              }
              if (orderSubmitEndUnsubscribe && typeof orderSubmitEndUnsubscribe === "function") {
                orderSubmitEndUnsubscribe();
              }
              if (amountChangedUnsubscribe && typeof amountChangedUnsubscribe === "function") {
                amountChangedUnsubscribe();
              }
              if (orderPaymentAddedUnsubscribe && typeof orderPaymentAddedUnsubscribe === "function") {
                orderPaymentAddedUnsubscribe();
              }
            };
          }
        } catch (error) {
          console.warn("Failed to subscribe to amount change events:", error);
        }
      }
    }, [checkoutModule]);
    const handleAmountChange = (0, import_react.useCallback)(
      async (newAmount) => {
        if (checkoutModule) {
          try {
            await checkoutModule.setStateAmountAsync(newAmount);
            setCustomAmount(newAmount);
          } catch (error) {
            console.error("Failed to set custom amount:", error);
          }
        }
      },
      [checkoutModule]
    );
    const handleDepositStatusChange = (0, import_react.useCallback)(
      async (isDeposit) => {
        if (checkoutModule) {
          try {
            const depositStatus = isDeposit ? 1 : 0;
            await checkoutModule.updateOrderDepositStatusAsync(depositStatus);
            console.log(
              `Deposit status updated to: ${depositStatus} (${isDeposit ? "deposit" : "regular"})`
            );
          } catch (error) {
            console.error("Failed to update deposit status:", error);
          }
        }
      },
      [checkoutModule]
    );
    const handleWalletPassConfirmPay = async (action) => {
      var _a2, _b2;
      if (action === "save-without-deduct") {
        await checkoutModule.updateVoucherPaymentItemsAsync([]);
      } else if (action === "cancel") {
        return;
      }
      const result = await checkoutModule.manualSyncOrderAsync();
      showSuccessToast == null ? void 0 : showSuccessToast(result);
      if (result.success) {
        const responseData = (_a2 = result.response) == null ? void 0 : _a2.data;
        console.log("print_order_onOrderSynced>>>>", result);
        try {
          const params = {
            type: "99",
            // 打印订单全部信息
            data: {
              order_id: responseData.order_id,
              machine_code_print_info: responseData == null ? void 0 : responseData.machine_code_print_info,
              small_ticket_data: (_b2 = responseData == null ? void 0 : responseData.payment_info) == null ? void 0 : _b2.small_ticket_data
            }
          };
          console.log("print_order_onOrderSynced_params>>>>", params);
          (0, import_utils.webPrint)(params, (res) => {
            console.log("print_order_onOrderSynced_res>>>>", res);
          });
        } catch (error) {
          console.error("print_order_onOrderSynced_error>>>>", error);
        }
      }
    };
    const handleSavePayLater = (0, import_react.useCallback)(
      async (action) => {
        if (action === "apply-deduct-now") {
          console.log("立即应用并扣除钱包余额，然后保存稍后付款");
        } else if (action === "save-without-deduct") {
          console.log("保存但不扣除钱包余额，稍后付款");
          await checkoutModule.updateVoucherPaymentItemsAsync([]);
        } else if (action === "cancel") {
          console.log("取消保存稍后付款");
          return;
        }
        if (checkoutModule) {
          const res = await checkoutModule.saveForLaterPaymentAsync();
          if (res.success) {
            onPaymentCancel(true);
            (0, import_PaymentResultToast.closePaymentResultToast)();
          }
        }
      },
      [checkoutModule, onPaymentCancel]
    );
    const moduleConfig = {
      showWalletPass: walletPassDetail.isShow,
      showCashPayment: (parentModuleConfig == null ? void 0 : parentModuleConfig.showCashPayment) ?? true,
      showAdditionalModule: true,
      showPaymentOptions: true
    };
    const handleSearch = (0, import_react.useCallback)((keyword) => {
      if (walletPassRef.current) {
        return walletPassRef.current.handleSearchIdentificationCode(keyword);
      }
    }, []);
    const getDataFromHost = () => {
      try {
        const is_price_include_tax = getData("is_price_include_tax");
        const tax_rate = getData("tax_rate") || "10";
        const tax_title = getData("tax_title") || "GST";
        const surcharge_list = getData("surcharge_list");
        const schedule_list = getData("schedule_list");
        let scheduleById = {};
        if (Array.isArray(schedule_list)) {
          for (let item of schedule_list) {
            scheduleById[item.id] = item;
          }
        }
        return {
          is_price_include_tax,
          tax_rate,
          tax_title,
          surcharge_list,
          schedule_list,
          scheduleById
        };
      } catch (error) {
        console.error(error);
        return {};
      }
    };
    const currentTotalPrice = (0, import_react.useMemo)(() => {
      if (!showPriceAdjustModal) return 0;
      const { ScheduleModule } = pisellosAllModule;
      try {
        const { productAmount } = (0, import_amount.getSumTotal)(state, {
          isEdit: true,
          ScheduleModule,
          ...getDataFromHost()
        });
        return productAmount;
      } catch (error) {
        console.error("计算总价失败:", error);
        return 0;
      }
    }, [state, showPriceAdjustModal]);
    const handleSelectWalletChange = (0, import_ahooks.useMemoizedFn)(
      async (select) => {
        if (walletPassDetail.isShow) {
          const voucherItems = [];
          select.forEach((item) => {
            var _a2, _b2, _c2, _d;
            const mapCode = item.code ? import_constants.WALLET_PASS_CODE_MAP[item.code] : null;
            if (mapCode) {
              voucherItems.push({
                /** 支付金额 */
                amount: item.amount,
                /** 支付类型，跟支付列表上对应的支付方式保持一致 */
                code: (_a2 = walletPassDetail.map[mapCode]) == null ? void 0 : _a2.code,
                /** 支付类型id，跟支付列表上对应的支付方式保持一致 */
                id: Number((_b2 = walletPassDetail.map[mapCode]) == null ? void 0 : _b2.id) || 0,
                /** 支付类型名称，跟支付列表上对应的支付方式保持一致 */
                name: (_c2 = walletPassDetail.map[mapCode]) == null ? void 0 : _c2.name,
                /** 支付类型type，跟支付列表上对应的支付方式保持一致 */
                type: (_d = walletPassDetail.map[mapCode]) == null ? void 0 : _d.type,
                /** 代金券、充值卡、积分卡等wallet pass id */
                voucher_id: item.voucher_id
              });
            }
          });
          logger == null ? void 0 : logger.addLog({
            type: "info",
            title: "handleSelectWalletChange checkoutModule updateVoucherPaymentItemsAsync",
            metadata: {}
          });
          await checkoutModule.updateVoucherPaymentItemsAsync(voucherItems);
          if (walletPassRef.current) {
            const data = walletPassRef.current.getWalletPassData(select);
            setWalletPassData(data);
          }
        }
      }
    );
    const handlePriceAdjustConfirm = async (newPrice) => {
      try {
        if (checkoutModule && (orderInfo == null ? void 0 : orderInfo.totalAmount)) {
          if (dispatch) {
            const { ScheduleModule } = pisellosAllModule;
            const { productAmount } = (0, import_amount.getSumTotal)(state, {
              isEdit: true,
              ScheduleModule
            });
            const discountAmount = Math.max(0, productAmount - newPrice);
            dispatch({
              type: "setState",
              payload: {
                shop_discount: discountAmount
              }
            });
          }
        }
      } catch (error) {
        console.error("Failed to adjust price:", error);
      }
      setShowPriceAdjustModal(false);
    };
    const handleButtonClick = async (key) => {
      var _a2;
      console.log("handleButtonClick", key);
      switch (key) {
        case "order-note":
          setNoteModalOpen(true);
          break;
        case "send-link":
          setPaymentLinkModalOpen(true);
          break;
        case "print-receipt":
          let data;
          const isSynced = await checkoutModule.isCurrentOrderSynced();
          if (!isSynced) {
            data = await checkoutModule.manualSyncOrderAsync();
          } else {
            const orderId = await checkoutModule.getCurrentOrderId();
            data = {
              orderId
            };
          }
          console.log("handleButtonClick_print-receipt_data>>>>", data);
          if (data.orderId) {
            const params = {
              type: "0",
              data: { order_id: data.orderId }
            };
            try {
              (0, import_utils.webPrint)(params, (res) => {
                console.log("handleButtonClick_print-receipt_res>>>>", res);
                if (!(res == null ? void 0 : res.result)) {
                  Toast == null ? void 0 : Toast.error((res == null ? void 0 : res.msg) || "");
                }
              });
            } catch (error) {
              console.error("handleButtonClick_print-receipt_error>>>>", error);
            }
          }
          break;
        case "manual-discount":
          if (!(orderInfo == null ? void 0 : orderInfo.totalAmount)) {
            Toast == null ? void 0 : Toast.fail(
              import_utils.locales.getText("pisell2.checkout.manual-discount.no-amount")
            );
            return;
          }
          const paymentItems2 = await checkoutModule.getCurrentOrderPaymentItemsAsync();
          if (paymentItems2 == null ? void 0 : paymentItems2.length) {
            Toast == null ? void 0 : Toast.fail(
              import_utils.locales.getText(
                "pisell2.checkout.manual-discount.has-payment-items"
              )
            );
            return;
          }
          if (Number(customAmount) <= 0 && Number(orderInfo == null ? void 0 : orderInfo.totalAmount) >= 0) {
            Toast == null ? void 0 : Toast.fail(
              import_utils.locales.getText("pisell2.checkout.manual-discount.no-amount")
            );
            return;
          }
          setShowPriceAdjustModal(true);
          break;
        case "save-pay-later":
          (_a2 = savePayLaterHandlerRef.current) == null ? void 0 : _a2.handleSavePayLaterClick();
          break;
      }
    };
    (0, import_react.useImperativeHandle)(ref, () => ({
      handleButtonClick
    }));
    const getCustomerInfo = () => {
      var _a2, _b2;
      const client = (_a2 = state == null ? void 0 : state.client) == null ? void 0 : _a2.value;
      const getValidName = (value) => {
        return value !== void 0 && value !== null && String(value).trim() !== "" ? String(value).trim() : null;
      };
      const displayName = getValidName(client == null ? void 0 : client.display_name) || getValidName(client == null ? void 0 : client.name) || import_utils.locales.getText("pisell2.checkout.customer.default-name") || "Customer";
      console.log("🔍 PaymentModal final displayName:", displayName);
      return {
        id: client == null ? void 0 : client.id,
        nickname: (client == null ? void 0 : client.nickname) || import_utils.locales.getText("pisell2.checkout.customer.default-name"),
        display_name: displayName,
        email: (client == null ? void 0 : client.email) || ((_b2 = client == null ? void 0 : client.contacts) == null ? void 0 : _b2.email) || ""
      };
    };
    const handleSendCustomerPaymentLink = async (data) => {
      const order = checkoutModule.getCurrentOrderInfo();
      if (order.isDeposit) {
        const stateAmount = checkoutModule.getStateAmount();
        await checkoutModule.setDepositAmountAsync(stateAmount);
      }
      const isCurrentOrderSynced = checkoutModule.isCurrentOrderSynced();
      if (!isCurrentOrderSynced) {
        await checkoutModule.manualSyncOrderAsync();
      }
      const res = await checkoutModule.sendCustomerPayLinkAsync({
        emails: data.emails,
        order_ids: [checkoutModule.getCurrentOrderId()]
      });
      if (res.success) {
        Toast == null ? void 0 : Toast.success(
          import_utils.locales.getText("pisell2.checkout.send-payment-link.success")
        );
        onPaymentCancel == null ? void 0 : onPaymentCancel(true);
      } else {
        Toast == null ? void 0 : Toast.error(
          res.message || import_utils.locales.getText("pisell2.checkout.send-payment-link.error")
        );
      }
    };
    const searchAndClientProps = (0, import_react.useMemo)(() => {
      if ((paymentItems == null ? void 0 : paymentItems.length) > 0) {
        return {
          disabledSwitch: true
        };
      }
      return {};
    }, [paymentItems]);
    const roundingFunction = async (amount) => {
      const res = await checkoutModule.roundAmountAsync(amount);
      return res;
    };
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        ref: checkoutRef,
        style: {
          ...import_styles.checkoutStyles.container,
          maxHeight: dynamicMaxHeight
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_SearchAndClientModule.default,
        {
          onClientChange: () => {
            clientChangedRef.current = true;
          },
          onSearch: handleSearch,
          ...searchAndClientProps
        }
      ),
      moduleConfig.showWalletPass && /* @__PURE__ */ import_react.default.createElement(
        import_WalletPassModule.default,
        {
          clientId: (_b = (_a = state == null ? void 0 : state.client) == null ? void 0 : _a.value) == null ? void 0 : _b.id,
          customAmount,
          orderInfo: orderInfo || void 0,
          ref: walletPassRef,
          paymentItems,
          onSelectChange: handleSelectWalletChange
        }
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_AmountSummary.default,
        {
          amountSymbol: state.amountSymbol,
          orderInfo: orderInfo || void 0,
          cartData,
          open_deposit,
          customAmount,
          balanceDueAmount,
          paymentItems,
          walletPassData,
          clientInfo: (_c = state == null ? void 0 : state.client) == null ? void 0 : _c.value,
          onAmountChange: handleAmountChange,
          onDepositStatusChange: handleDepositStatusChange,
          onConfirm: handleWalletPassConfirmPay,
          totalAmount
        }
      ),
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: showCashPayment ? "payment-grid-layout" : "payment-flex-layout"
        },
        showCashPayment && /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            style: showCashPayment ? {
              gridColumn: "1",
              gridRow: "1"
            } : {}
          },
          /* @__PURE__ */ import_react.default.createElement(
            import_CashPaymentModule.default,
            {
              isModalOpen,
              amountSymbol: state.amountSymbol,
              orderInfo: orderInfo || void 0,
              onPaymentComplete: handleAddCashPayment,
              amountButtons: recommendAmounts,
              customAmount,
              roundingFunction,
              balanceDueAmount
            }
          )
        ),
        moduleConfig.showPaymentOptions && /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: showCashPayment ? "" : "payment-options-module-container",
            style: showCashPayment ? {
              gridColumn: "2",
              gridRow: "1 / 3"
            } : {}
          },
          /* @__PURE__ */ import_react.default.createElement(
            import_PaymentOptionsModule.default,
            {
              amountSymbol: state.amountSymbol,
              orderInfo: orderInfo || void 0,
              onClick: onPaymentOptionClick,
              paymentMethods,
              customAmount,
              title: paymentOptionsTitle,
              disabled: isOrderFree
            }
          )
        ),
        moduleConfig.showAdditionalModule && /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: showCashPayment ? "" : "additional-module-container",
            style: showCashPayment ? {
              gridColumn: "1",
              gridRow: "2"
            } : {}
          },
          /* @__PURE__ */ import_react.default.createElement(
            import_AdditionalModule.default,
            {
              orderInfo: orderInfo || void 0,
              customAmount,
              handleButtonClick,
              hasOrderNote: !!orderNote && orderNote.trim().length > 0,
              disabled: isOrderFree,
              showCashPayment
            }
          )
        )
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_paymentMethods.default,
        {
          ref: paymentMethodsRef,
          dynamicMaxHeight,
          isWebPos: true
        }
      ),
      paymentLinkModalOpen && /* @__PURE__ */ import_react.default.createElement(
        import_SendPaymentLinkModal.default,
        {
          balanceAmount: customAmount,
          customerEmail: getCustomerInfo().email,
          customerName: getCustomerInfo().display_name || getCustomerInfo().nickname,
          customerId: getCustomerInfo().id,
          onClose: () => setPaymentLinkModalOpen(false),
          sendPaymentLink: handleSendCustomerPaymentLink
        }
      ),
      showPriceAdjustModal && (0, import_react_dom.createPortal)(
        /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-price-adjust-overlay" }, /* @__PURE__ */ import_react.default.createElement(
          "button",
          {
            className: "pisell-price-adjust-backdrop",
            style: {
              cursor: "pointer",
              border: "none",
              background: "transparent",
              width: "100%",
              height: "100%",
              position: "absolute",
              top: 0,
              left: 0
            },
            onClick: () => setShowPriceAdjustModal(false),
            "aria-label": import_utils.locales.getText(
              "pisell2.checkout.modal.close-price-adjustment"
            ) || "Close price adjustment modal"
          }
        ), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-price-adjust-container" }, /* @__PURE__ */ import_react.default.createElement(
          import_materials2.PisellAdjustPrice,
          {
            selectType: "dark",
            originValue: currentTotalPrice,
            value: currentTotalPrice,
            onChange: handlePriceAdjustConfirm,
            resetText: import_utils.locales.getText(
              "pisell2.checkout.modal.reset-price-adjustment"
            ),
            doneText: import_utils.locales.getText(
              "pisell2.checkout.modal.done-price-adjustment"
            )
          }
        ))),
        document.body
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_SavePayLaterHandler.default,
        {
          ref: savePayLaterHandlerRef,
          amountSymbol: state.amountSymbol,
          walletPassData,
          onSavePayLater: handleSavePayLater
        }
      )
    );
  }
);
var PaymentModal = ({
  open,
  data,
  callback,
  onClose,
  dispatch,
  state
}) => {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  const context = (0, import_useEngineContext.default)();
  import_utils.locales.init(
    import_locales2.default,
    ((_e = (_d = (_c = (_b = (_a = context.appHelper.utils) == null ? void 0 : _a.getApp) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.locales) == null ? void 0 : _d.getLocale) == null ? void 0 : _e.call(_d)) || ((_g = (_f = context.appHelper.utils) == null ? void 0 : _f.storage) == null ? void 0 : _g.get("umi_locale")) || "en"
  );
  const { pisellos, getData, interaction } = ((_h = context == null ? void 0 : context.appHelper) == null ? void 0 : _h.utils) || {};
  const [orderInfo, setOrderInfo] = (0, import_react.useState)(null);
  const [totalAmount, setTotalAmount] = (0, import_react.useState)(0);
  const [actualShowCashPayment, setActualShowCashPayment] = (0, import_react.useState)(true);
  const [windowHeight, setWindowHeight] = (0, import_react.useState)(0);
  const [showRetryModal, setShowRetryModal] = (0, import_react.useState)(false);
  const Toast = (0, import_useToast.default)();
  const handleRetry = async () => {
    const checkoutModule = pisellos == null ? void 0 : pisellos.getModule("checkout");
    const res = await (checkoutModule == null ? void 0 : checkoutModule.manualSyncOrderAsync());
    console.log(res);
    if (res.success) {
      setShowRetryModal(false);
      showSuccessToast == null ? void 0 : showSuccessToast(res);
    }
  };
  (0, import_react.useEffect)(() => {
    const updateHeight = () => {
      if (typeof window !== "undefined") {
        setWindowHeight(window.innerHeight);
      }
    };
    updateHeight();
    window.addEventListener("resize", updateHeight);
    window.addEventListener("orientationchange", updateHeight);
    return () => {
      window.removeEventListener("resize", updateHeight);
      window.removeEventListener("orientationchange", updateHeight);
    };
  }, []);
  const dynamicMaxHeight = (0, import_react.useMemo)(() => {
    if (windowHeight === 0) return "600px";
    const bodyTransform = getComputedStyle(document.body).transform;
    let scaleY = 1;
    if (bodyTransform !== "none") {
      const matrix = new DOMMatrix(bodyTransform);
      scaleY = matrix.d;
    }
    return `${Math.floor((windowHeight * 0.9 - 72) / scaleY)}px`;
  }, [windowHeight]);
  const moduleConfig = {
    showCashPayment: true
    // 控制是否显示现金支付模块
  };
  const handleShowCashPaymentChange = (0, import_react.useCallback)((show) => {
    setActualShowCashPayment(show);
  }, []);
  const [noteModalOpen, setNoteModalOpen] = (0, import_react.useState)(false);
  const [orderNote, setOrderNote] = (0, import_react.useState)("");
  const [noteModalSource, setNoteModalSource] = (0, import_react.useState)("payment-content");
  const handleNoteConfirm = async (noteValue) => {
    var _a2, _b2;
    if (noteModalSource === "payment-result-toast") {
      const checkoutModule = pisellos == null ? void 0 : pisellos.getModule("checkout");
      const orderId = checkoutModule == null ? void 0 : checkoutModule.getCurrentOrderId();
      if (checkoutModule) {
        (_a2 = checkoutModule.editOrderNoteByOrderIdAsync) == null ? void 0 : _a2.call(checkoutModule, orderId, noteValue);
        setOrderNote(noteValue);
        Toast == null ? void 0 : Toast.success(
          import_utils.locales.getText("pisell2.checkout.order-note.updated-successfully")
        );
      }
      setNoteModalOpen(false);
      return;
    }
    try {
      const checkoutModule = pisellos == null ? void 0 : pisellos.getModule("checkout");
      if (checkoutModule) {
        await ((_b2 = checkoutModule.updateOrderNoteAsync) == null ? void 0 : _b2.call(checkoutModule, noteValue));
        setOrderNote(noteValue);
        Toast == null ? void 0 : Toast.success(
          import_utils.locales.getText("pisell2.checkout.order-note.updated-successfully")
        );
      }
      if (dispatch) {
        dispatch({
          type: "setNotes",
          payload: {
            orderNote: noteValue,
            edit: true
          }
        });
      }
      if (noteModalSource === "payment-result-toast") {
        console.log("Note added from payment result toast");
      } else if (noteModalSource === "payment-content") {
        console.log("Note added from payment content");
      }
    } catch (error) {
      console.error("Failed to update order note:", error);
      Toast == null ? void 0 : Toast.error(
        import_utils.locales.getText("pisell2.checkout.order-note.update-failed")
      );
    }
    setNoteModalOpen(false);
  };
  const handleNoteDelete = async () => {
    var _a2;
    try {
      const checkoutModule = pisellos == null ? void 0 : pisellos.getModule("checkout");
      if (checkoutModule) {
        await ((_a2 = checkoutModule.updateOrderNoteAsync) == null ? void 0 : _a2.call(checkoutModule, ""));
        setOrderNote("");
        Toast == null ? void 0 : Toast.success(
          import_utils.locales.getText("pisell2.checkout.order-note.deleted-successfully")
        );
      }
      if (dispatch) {
        dispatch({
          type: "setNotes",
          payload: {
            orderNote: "",
            edit: true
          }
        });
      }
    } catch (error) {
      console.error("Failed to delete order note:", error);
      Toast == null ? void 0 : Toast.error(
        import_utils.locales.getText("pisell2.checkout.order-note.delete-failed")
      );
    }
    setNoteModalOpen(false);
  };
  const handleNoteCancel = () => {
    setNoteModalOpen(false);
  };
  const showingCashToastRef = (0, import_react.useRef)(false);
  const currentPaymentResultRef = import_react.default.useRef(null);
  const paymentContentRef = import_react.default.useRef(null);
  const handleOrderNoteClickFromToast = () => {
    setNoteModalSource("payment-result-toast");
    setNoteModalOpen(true);
  };
  const translation = (key, fallback) => {
    const umiLocale = (0, import_locales.getLocale)();
    const currentLang = import_utils.locales.formatLocale(umiLocale);
    try {
      const langPack = import_locales2.default[currentLang];
      const checkoutText = langPack == null ? void 0 : langPack[key];
      if (checkoutText) {
        return checkoutText;
      }
    } catch (error) {
      console.error("本地语言包访问错误:", error);
    }
    const globalResult = import_utils.locales.getText(key) || fallback;
    console.log("全局语言包结果:", globalResult);
    return globalResult;
  };
  const handlePaymentComplete = (result) => {
    currentPaymentResultRef.current = result;
  };
  const handleToastClose = () => {
    console.log(
      "PaymentModal - Toast closed, executing callbacks and closing modal"
    );
    if (currentPaymentResultRef.current) {
      callback == null ? void 0 : callback(currentPaymentResultRef.current);
    }
    onClose == null ? void 0 : onClose(true);
  };
  const handlePaymentCancel = (reset) => {
    console.log("Payment cancelled");
    callback == null ? void 0 : callback({ status: "cancelled" });
    const checkout = pisellos.getModule("checkout");
    checkout.cancelCurrentOrderAsync();
    onClose == null ? void 0 : onClose(reset || false);
  };
  const CustomHeader = () => /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      style: {
        display: "flex",
        alignItems: "center",
        width: "100%",
        position: "relative"
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          display: "flex",
          alignItems: "center",
          gap: "12px",
          flex: "0 0 auto"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(import_components.DeviceIconGroup, null)
    ),
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          position: "absolute",
          left: "50%",
          transform: "translateX(-50%)",
          fontWeight: "500"
        }
      },
      translation("order.total"),
      "：",
      (0, import_PaymentResultToastUtils.formatCurrency)(totalAmount, state == null ? void 0 : state.amountSymbol)
    )
  );
  (0, import_react.useEffect)(() => {
    var _a2;
    if ((_a2 = data == null ? void 0 : data.order_info) == null ? void 0 : _a2.order_note) {
      setOrderNote(data.order_info.order_note);
    }
  }, [data]);
  const logger = (0, import_usePaymentLogger.default)();
  const isLocalOrderCreated = (0, import_react.useRef)(void 0);
  const unsubscribeRef = (0, import_react.useRef)(void 0);
  (0, import_react.useEffect)(() => {
    const initCheckoutData = async () => {
      var _a2, _b2;
      try {
        const checkout = pisellos == null ? void 0 : pisellos.getModule("checkout");
        if (checkout && data && !isLocalOrderCreated.current) {
          isLocalOrderCreated.current = true;
          const shop_wallet_pass_id = await (0, import_utils2.getShopWalletPassId)(interaction);
          checkout.setOtherParams({
            is_price_include_tax: getData("is_price_include_tax"),
            tax_rate: getData("tax_rate") || "10",
            surcharge_list: getData("surcharge_list"),
            currency_format: getData("currency_format"),
            tax_title: getData("tax_title") || "GST",
            tax_country_code: getData("tax_country_code"),
            currency_code: getData("shop_currency_code"),
            currency_symbol: getData("shop_symbol"),
            order_rounding_setting: getData("order_rounding_setting"),
            shop_wallet_pass_id
          });
          console.time("initCheckoutData");
          const newData = (0, import_lodash.cloneDeep)(data);
          await checkout.createLocalOrderAsync({
            orderData: newData.order_info,
            cartSummary: (_a2 = newData.subtotal_info) == null ? void 0 : _a2.subTotalList,
            autoPayment: true,
            totalInfo: newData.subtotal_info
          });
          console.timeEnd("initCheckoutData");
          const orderInfo2 = checkout.getCurrentOrderInfo();
          if (orderInfo2 && orderInfo2.totalAmount) {
            setTotalAmount(orderInfo2.totalAmount);
          }
          setOrderInfo(orderInfo2);
          if (unsubscribeRef.current) {
            logger == null ? void 0 : logger.addLog({
              type: "info",
              title: "有重复的checkout:onOrderSynced，清空",
              metadata: {}
            });
            unsubscribeRef.current();
            unsubscribeRef.current = void 0;
          }
          unsubscribeRef.current = checkout.core.effects.on(
            "checkout:onOrderSynced",
            (data2) => {
              var _a3, _b3, _c2;
              const responseData = (_a3 = data2.response) == null ? void 0 : _a3.data;
              const paymentStatus = responseData == null ? void 0 : responseData.payment_status;
              if (data2.isManual) return;
              handlePaymentComplete(data2);
              if (showingCashToastRef.current) {
                return;
              }
              const orderTotalAmount = Number((responseData == null ? void 0 : responseData.total_amount) || 0);
              const gapAmount = Number((responseData == null ? void 0 : responseData.amount_gap) || 0);
              const currentChangeGivenAmount = Number(
                ((_b3 = responseData == null ? void 0 : responseData.payment_info) == null ? void 0 : _b3.current_change_given_amount) || 0
              );
              const failureReason = responseData == null ? void 0 : responseData.failure_reason;
              if (paymentStatus) {
                console.log("print_order_onOrderSynced>>>>", responseData);
                logger == null ? void 0 : logger.addLog({
                  type: "info",
                  title: "print_order_onOrderSynced",
                  metadata: {
                    responseData
                  }
                });
                try {
                  const params = {
                    type: "99",
                    // 打印订单全部信息
                    data: {
                      order_id: responseData.order_id,
                      machine_code_print_info: responseData == null ? void 0 : responseData.machine_code_print_info,
                      small_ticket_data: (_c2 = responseData == null ? void 0 : responseData.payment_info) == null ? void 0 : _c2.small_ticket_data
                    }
                  };
                  console.log("print_order_onOrderSynced_params>>>>", params);
                  logger == null ? void 0 : logger.addLog({
                    type: "info",
                    title: "print_order_onOrderSynced_params",
                    metadata: {
                      params
                    }
                  });
                  (0, import_utils.webPrint)(params, (res) => {
                    console.log("print_order_onOrderSynced_res>>>>", res);
                    logger == null ? void 0 : logger.addLog({
                      type: "info",
                      title: "print_order_onOrderSynced_res",
                      metadata: {
                        res
                      }
                    });
                  });
                } catch (error) {
                  console.error("print_order_onOrderSynced_error>>>>", error);
                  logger == null ? void 0 : logger.addLog({
                    type: "info",
                    title: "print_order_onOrderSynced_error",
                    metadata: {
                      error
                    }
                  });
                }
                const statusClassName = (0, import_PaymentResultToastUtils.calculateStatusClassName)(paymentStatus);
                const autoCloseConfig = (0, import_PaymentResultToastUtils.calculateAutoCloseConfig)(
                  paymentStatus,
                  !!currentChangeGivenAmount
                );
                (0, import_PaymentResultToastUtils.displayPaymentResultToast)(
                  {
                    paymentStatus,
                    orderTotalAmount,
                    gapAmount: paymentStatus === "partially_paid" ? gapAmount : currentChangeGivenAmount,
                    failureReason,
                    autoCloseConfig,
                    actionButtons: generateActionButtons(paymentStatus)
                  },
                  paymentResultToastConfig
                );
                const paymentResult = {
                  ...data2,
                  toastInfo: {
                    status: paymentStatus,
                    amount: orderTotalAmount,
                    gapAmount: currentChangeGivenAmount,
                    failureReason
                  }
                };
                handlePaymentComplete(paymentResult);
              } else {
                handlePaymentComplete(data2);
              }
            }
          );
        } else if (isLocalOrderCreated.current) {
          console.log(
            "🔄 PaymentModal: data changed, updating checkout data..."
          );
          isLocalOrderCreated.current = false;
          await checkout.cancelCurrentOrderAsync();
          await checkout.createLocalOrderAsync({
            orderData: data == null ? void 0 : data.order_info,
            cartSummary: (_b2 = data == null ? void 0 : data.subtotal_info) == null ? void 0 : _b2.subTotalList,
            autoPayment: true,
            totalInfo: data == null ? void 0 : data.subtotal_info
          });
          const orderInfo2 = checkout.getCurrentOrderInfo();
          if (orderInfo2 && orderInfo2.totalAmount) {
            setTotalAmount(orderInfo2.totalAmount);
          }
          setOrderInfo(orderInfo2);
          isLocalOrderCreated.current = true;
        }
      } catch (error) {
        console.error("Failed to initialize checkout data:", error);
        logger == null ? void 0 : logger.addLog({
          type: "error",
          title: "Failed to initialize checkout data",
          metadata: {
            error
          }
        });
      }
    };
    if (data) {
      initCheckoutData();
    }
  }, [data]);
  (0, import_react.useEffect)(() => {
    return () => {
      var _a2;
      if (typeof unsubscribeRef.current === "function") {
        (_a2 = unsubscribeRef.current) == null ? void 0 : _a2.call(unsubscribeRef);
        unsubscribeRef.current = void 0;
      }
    };
  }, []);
  const paymentResultToastConfig = {
    context,
    pisellos,
    getData,
    interaction,
    Toast,
    state,
    onToastClose: handleToastClose
  };
  const generateActionButtons = (paymentStatus) => {
    const getClassName = (suffix) => `payment-result-toast-${suffix}`;
    const handleDetailsClick = async () => {
      var _a2;
      setTimeout(() => {
        (0, import_PaymentResultToast.closePaymentResultToast)();
        handleToastClose();
      }, 0);
      const { isTerminal, isWebPos } = (_a2 = context.appHelper) == null ? void 0 : _a2.utils;
      if (isTerminal == null ? void 0 : isTerminal()) {
        const checkout = pisellos.getModule("checkout");
        const orderId = await checkout.getCurrentOrderId();
        return interaction.utils.postMessageToApp({
          module: "booking",
          key: "view_order",
          data: {
            order_id: orderId
          },
          origin: "/booking"
        });
      }
    };
    const handlePrintReceiptClick = async () => {
      const checkoutModule = pisellos == null ? void 0 : pisellos.getModule("checkout");
      if (!checkoutModule) return;
      let data2;
      const isSynced = await checkoutModule.isCurrentOrderSynced();
      if (!isSynced) {
        data2 = await checkoutModule.manualSyncOrderAsync();
      } else {
        const orderId = await checkoutModule.getCurrentOrderId();
        data2 = {
          orderId
        };
      }
      if (data2.orderId) {
        const params = {
          type: "0",
          data: { order_id: data2.orderId }
        };
        try {
          (0, import_utils.webPrint)(params, (res) => {
            console.log("handleButtonClick_print-receipt_res>>>>", res);
            if (!(res == null ? void 0 : res.result)) {
              Toast == null ? void 0 : Toast.error((res == null ? void 0 : res.msg) || "");
            }
          });
        } catch (error) {
          console.error("handleButtonClick_print-receipt_error>>>>", error);
        }
      }
    };
    const handleRetryClick = () => {
      console.log(import_utils.locales.getText("payment.result.actions.retryClicked"));
    };
    const handleChangePaymentClick = () => {
      console.log(
        import_utils.locales.getText("payment.result.actions.changePaymentClicked")
      );
    };
    const handleSaveAsPartialPaidClick = () => {
      var _a2;
      (_a2 = paymentContentRef.current) == null ? void 0 : _a2.handleButtonClick("save-pay-later");
    };
    const handleContinuePaymentClick = () => {
      console.log(
        import_utils.locales.getText("payment.result.actions.continuePaymentClicked")
      );
      (0, import_PaymentResultToast.closePaymentResultToast)();
    };
    const handleOrderNoteClick = () => {
      console.log(import_utils.locales.getText("payment.result.actions.orderNoteClicked"));
      if (handleOrderNoteClickFromToast) {
        handleOrderNoteClickFromToast();
      }
    };
    const handleRefundClick = () => {
      console.log(import_utils.locales.getText("payment.result.actions.refundClicked"));
    };
    switch (paymentStatus) {
      case "paid":
        return [
          [
            {
              id: "details",
              buttonProps: {
                className: getClassName("action-button"),
                onClick: handleDetailsClick,
                icon: /* @__PURE__ */ import_react.default.createElement(import_icon.FileCheck02, { className: getClassName("action-icon") }),
                children: import_utils.locales.getText("payment.result.details")
              }
            },
            {
              id: "print",
              buttonProps: {
                className: getClassName("action-button"),
                onClick: handlePrintReceiptClick,
                icon: /* @__PURE__ */ import_react.default.createElement(import_icon.Printer, { className: getClassName("action-icon") }),
                children: import_utils.locales.getText("payment.result.printReceipt")
              }
            },
            {
              id: "more",
              isMore: true,
              menuData: [
                {
                  key: "orderNote",
                  label: import_utils.locales.getText("payment.result.orderNote"),
                  icon: /* @__PURE__ */ import_react.default.createElement(
                    import_icon.MessageTextSquare02,
                    {
                      className: getClassName("menu-icon")
                    }
                  ),
                  onClick: handleOrderNoteClick
                }
              ],
              buttonProps: {
                className: getClassName("action-button"),
                icon: /* @__PURE__ */ import_react.default.createElement(import_icon.DotsVertical, { className: getClassName("action-icon") })
              }
            }
          ]
        ];
      case "partially_paid":
        return [
          [
            {
              id: "saveAsPartialPaid",
              buttonProps: {
                className: getClassName("action-button"),
                onClick: handleSaveAsPartialPaidClick,
                children: import_utils.locales.getText("payment.result.saveAsPartialPaid")
              }
            },
            {
              id: "continuePayment",
              buttonProps: {
                className: getClassName("action-button"),
                onClick: () => {
                  (0, import_PaymentResultToast.closePaymentResultToast)();
                },
                children: import_utils.locales.getText("payment.result.continuePayment")
              }
            },
            {
              id: "more",
              isMore: true,
              menuData: [
                {
                  key: "orderNote",
                  label: import_utils.locales.getText("payment.result.orderNote"),
                  icon: /* @__PURE__ */ import_react.default.createElement(
                    import_icon.MessageTextSquare02,
                    {
                      className: getClassName("menu-icon")
                    }
                  ),
                  onClick: handleOrderNoteClick
                }
              ],
              buttonProps: {
                className: getClassName("action-button"),
                icon: /* @__PURE__ */ import_react.default.createElement(import_icon.DotsVertical, { className: getClassName("action-icon") })
              }
            }
          ]
        ];
      case "failed":
        return [
          [
            {
              id: "retry",
              buttonProps: {
                className: getClassName("action-button retry-button"),
                onClick: handleRetryClick,
                icon: /* @__PURE__ */ import_react.default.createElement(import_icon.RefreshCw05, { className: getClassName("action-icon") }),
                children: import_utils.locales.getText("payment.result.retry")
              }
            },
            {
              id: "changePayment",
              buttonProps: {
                className: getClassName("action-button change-payment-button"),
                onClick: handleChangePaymentClick,
                icon: /* @__PURE__ */ import_react.default.createElement(import_icon.CreditCard02, { className: getClassName("action-icon") }),
                children: import_utils.locales.getText("payment.result.changePayment")
              }
            },
            {
              id: "more",
              isMore: true,
              menuData: [
                {
                  key: "orderNote",
                  label: import_utils.locales.getText("payment.result.orderNote"),
                  icon: /* @__PURE__ */ import_react.default.createElement(
                    import_icon.MessageTextSquare02,
                    {
                      className: getClassName("menu-icon")
                    }
                  ),
                  onClick: handleOrderNoteClick
                },
                {
                  key: "refund",
                  label: import_utils.locales.getText("payment.result.refund"),
                  icon: /* @__PURE__ */ import_react.default.createElement(import_icon.ArrowLeft, { className: getClassName("menu-icon") }),
                  onClick: handleRefundClick
                }
              ],
              buttonProps: {
                className: getClassName("action-button"),
                icon: /* @__PURE__ */ import_react.default.createElement(import_icon.DotsVertical, { className: getClassName("action-icon") })
              }
            }
          ]
        ];
      case "wallet-pass-failed":
        return [
          [
            {
              id: "savePartial",
              buttonProps: {
                className: getClassName("action-button primary-button"),
                onClick: handleSaveAsPartialPaidClick,
                children: import_utils.locales.getText("payment.result.saveAsPartialPaid")
              }
            },
            {
              id: "continuePayment",
              buttonProps: {
                className: getClassName("action-button primary-button"),
                onClick: handleContinuePaymentClick,
                children: import_utils.locales.getText("payment.result.continuePayment")
              }
            },
            {
              id: "more",
              isMore: true,
              menuData: [
                {
                  key: "details",
                  label: import_utils.locales.getText("payment.result.details"),
                  icon: /* @__PURE__ */ import_react.default.createElement(import_icon.FileCheck02, { className: getClassName("menu-icon") }),
                  onClick: handleDetailsClick
                },
                {
                  key: "print",
                  label: import_utils.locales.getText("payment.result.printReceipt"),
                  icon: /* @__PURE__ */ import_react.default.createElement(import_icon.Printer, { className: getClassName("menu-icon") }),
                  onClick: handlePrintReceiptClick
                },
                {
                  key: "orderNote",
                  label: import_utils.locales.getText("payment.result.orderNote"),
                  icon: /* @__PURE__ */ import_react.default.createElement(
                    import_icon.MessageTextSquare02,
                    {
                      className: getClassName("menu-icon")
                    }
                  ),
                  onClick: handleOrderNoteClick
                },
                {
                  key: "refund",
                  label: import_utils.locales.getText("payment.result.refund"),
                  icon: /* @__PURE__ */ import_react.default.createElement(import_icon.ArrowLeft, { className: getClassName("menu-icon") }),
                  onClick: handleRefundClick
                }
              ],
              buttonProps: {
                className: getClassName("action-button"),
                icon: /* @__PURE__ */ import_react.default.createElement(import_icon.DotsVertical, { className: getClassName("action-icon") })
              }
            }
          ]
        ];
      default:
        return [];
    }
  };
  const showSuccessToast = (0, import_PaymentResultToastUtils.createShowSuccessToast)(
    paymentResultToastConfig,
    generateActionButtons
  );
  return /* @__PURE__ */ import_react.default.createElement(import_PaymentResultToast.PaymentResultToastProvider, null, /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellContainer,
    {
      renderType: "modal",
      props: {
        open,
        onCancel: () => {
          handlePaymentCancel(false);
        },
        title: /* @__PURE__ */ import_react.default.createElement(CustomHeader, null),
        width: 880,
        destroyOnClose: false,
        maskClosable: false,
        footer: null,
        closeIcon: null,
        wrapClassName: `payment-modal-wrapper ${!actualShowCashPayment ? "no-cash-payment" : ""}`,
        size: "large",
        headerDivider: false,
        style: {
          height: "auto"
        },
        bodyStyle: {
          maxHeight: "100%",
          // 使用100%基于父元素，而不是视口的90%
          overflowY: "auto",
          padding: 0,
          display: "flex",
          flexDirection: "column"
        }
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      PaymentContent,
      {
        ref: paymentContentRef,
        isModalOpen: open,
        cartData: (0, import_lodash.cloneDeep)(data),
        orderInfo,
        onPaymentComplete: handlePaymentComplete,
        onPaymentCancel: handlePaymentCancel,
        dispatch,
        state,
        showingCashToastRef,
        onToastClose: handleToastClose,
        orderNote,
        setOrderNote,
        setNoteModalSource,
        setNoteModalOpen,
        totalAmount,
        moduleConfig,
        onShowCashPaymentChange: handleShowCashPaymentChange,
        showSuccessToast,
        dynamicMaxHeight,
        onOrderSyncFailed: () => setShowRetryModal(true),
        generateActionButtons,
        paymentResultToastConfig
      }
    )
  ), noteModalOpen && (0, import_react_dom.createPortal)(
    /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement(
      import_noteModal.default,
      {
        open: noteModalOpen,
        title: import_utils.locales.getText("pisell2.text.add-order-notes"),
        value: orderNote,
        onConfirm: handleNoteConfirm,
        onDelete: handleNoteDelete,
        onCancel: handleNoteCancel
      }
    )),
    document.body
  ), /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellContainer,
    {
      renderType: "modal",
      props: {
        open: showRetryModal,
        title: import_utils.locales.getText("pisell2.checkout.tips"),
        footer: null,
        closable: false,
        maskClosable: false,
        keyboard: false,
        onCancel: () => {
        }
        // 禁用关闭
      }
    },
    /* @__PURE__ */ import_react.default.createElement("div", { style: { textAlign: "center", padding: "20px" } }, /* @__PURE__ */ import_react.default.createElement("div", { style: { marginBottom: "16px", fontSize: "16px" } }, import_utils.locales.getText("pisell2.checkout.sync-retry-hint") || "请点击重试按钮重新同步订单"), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        type: "primary",
        size: "large",
        onClick: handleRetry,
        style: { width: "100%", marginTop: "80px" }
      },
      import_utils.locales.getText("retry") || "重试"
    ))
  ));
};
var PaymentModal_default = PaymentModal;
