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/booking/components/footer/index.tsx
var footer_exports = {};
__export(footer_exports, {
  default: () => footer_default
});
module.exports = __toCommonJS(footer_exports);
var import_icons = require("@ant-design/icons");
var import_ChevronDown = __toESM(require("@pisell/icon/es/ChevronDown"));
var import_utils = require("@pisell/utils");
var import_antd = require("antd");
var import_classnames = __toESM(require("classnames"));
var import_react = __toESM(require("react"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_PaymentModal = __toESM(require("../../../checkout/PaymentModal"));
var import_PaymentResultToast = require("../../../checkout/components/PaymentResultToast");
var import_addons = require("../../addons");
var import_utils2 = require("../../info/service2/utils");
var import_serve = require("../../info2/serve");
var import_AppointmentProductModal = __toESM(require("./AppointmentProductModal"));
var import_FooterMenus = __toESM(require("./FooterMenus"));
var import_amount = require("./amount");
var import_index = require("./index.less");
var import_serve2 = require("./serve");
var import_utils3 = require("./utils");
var import_noteModal = __toESM(require("../../../../plus/noteModal"));
var import_confirmHolderModal = require("../../utils/confirmHolderModal");
var import__ = require("../../../../index");
var import_useIsBooking4Shop = require("../../hooks/useIsBooking4Shop");
var import_utils4 = require("@pisell/utils");
var import_dayjs = __toESM(require("dayjs"));
var import_useScanManager = __toESM(require("../../../ticketBooking/hooks/pisellos/useScanManager"));
var import_materials = require("@pisell/materials");
var import_useCustomer = require("../../../ticketBooking/hooks/pisellos/useCustomer");
var import_ahooks = require("ahooks");
var import_lodash = require("lodash");
var import_useShopDiscountModule = require("../../../ticketBooking/hooks/pisellos/useShopDiscountModule");
var import_utils5 = require("../../utils");
var import_useLogger = __toESM(require("../../../../hooks/useLogger"));
var import_useActiveExecute = require("../../../ticketBooking/hooks/pisellos/useActiveExecute");
var import_printer = __toESM(require("../../../../hooks/printer"));
var import_PaymentResultToastUtils = require("../../../checkout/utils/PaymentResultToastUtils");
var import_materials2 = require("@pisell/materials");
var import_icon = require("@pisell/icon");
var import_IsActiveContext = require("../../../ticketBooking/context/IsActiveContext");
var import_serve3 = require("../../editBookingModal/serve");
var import_ticketBooking = require("../../../ticketBooking/components/ticketBooking");
var import_decimal = __toESM(require("decimal.js"));
var import_useRuntime = require("../../../ticketBooking/hooks/useRuntime");
var import_compensatedPisellContainer = __toESM(require("../../../../pro/compensatedPisellContainer"));
var import_responsive = require("../../../../responsive");
var Footer = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
  const { state, buttons, dispatch, source, variant } = props;
  const isPhoneVariant = variant === "phone";
  const [showDetail, setShowDetail] = (0, import_react.useState)(false);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [checkoutLoading, setCheckoutLoading] = (0, import_react.useState)(false);
  const [noteModalOpen, setNoteModalOpen] = (0, import_react.useState)(false);
  const [isPaymentModalOpen, setIsPaymentModalOpen] = (0, import_react.useState)(false);
  const [paymentModalData, setPaymentModalData] = (0, import_react.useState)(null);
  const [paymentCallback, setPaymentCallback] = (0, import_react.useState)(null);
  const [terminalWarningOpen, setTerminalWarningOpen] = (0, import_react.useState)(false);
  const logger = (0, import_useLogger.default)();
  const [editOrderId, setEditOrderId] = (0, import_react.useState)(0);
  const [isShowPaymentLink, setIsShowPaymentLink] = (0, import_react.useState)(false);
  const isBooking4Shop = (0, import_useIsBooking4Shop.useIsBooking4Shop)(state);
  const appointmentProductRef = (0, import_react.useRef)(null);
  const context = (0, import_useEngineContext.default)();
  const {
    isTerminal,
    isWebPos,
    interaction,
    store,
    storage,
    pisellosAllModule,
    getData,
    pisellos
  } = (_a = context.appHelper) == null ? void 0 : _a.utils;
  const { disableAllScanListeners } = (0, import_useScanManager.default)();
  const { ScheduleModule } = pisellosAllModule;
  const { isSecondaryScreen } = ((_b = import_useRuntime.useRuntime) == null ? void 0 : _b()) || { isSecondaryScreen: false };
  (0, import_react.useEffect)(() => {
    store == null ? void 0 : store.dispatch({
      type: "global/_getMetadataMap",
      callback: (data) => {
        console.log(data, "data");
        setIsShowPaymentLink(!!data["payment_collection_link_config_switch"]);
      }
    });
    const paymentCollectionLinkConfigSwitch = getData("payment_collection_link_config_switch");
    if (paymentCollectionLinkConfigSwitch !== void 0) {
      setIsShowPaymentLink(!!paymentCollectionLinkConfigSwitch);
    }
  }, []);
  (0, import_react.useEffect)(() => {
    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;
        }
      }
      dispatch({
        type: "setState",
        payload: {
          is_price_include_tax,
          tax_rate,
          tax_title,
          surcharge_list,
          schedule_list,
          scheduleById
        }
      });
    } catch (error) {
      console.error(error);
    }
  }, []);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2, _e2;
    if ((((_b2 = (_a2 = state.service) == null ? void 0 : _a2.value) == null ? void 0 : _b2.length) === 0 || !((_c2 = state.service) == null ? void 0 : _c2.value)) && !((_e2 = (_d2 = state.paymentPaid) == null ? void 0 : _d2.value) == null ? void 0 : _e2.paidAmount)) {
      setEditOrderId(0);
    }
  }, [state.service.value, (_c = state.paymentPaid) == null ? void 0 : _c.value]);
  const { executeIfActive } = (0, import_useActiveExecute.useActiveExecute)();
  const { nativePrint } = (0, import_printer.default)();
  const Toast = (0, import_materials2.useToast)();
  const paymentResultToastConfig = {
    context,
    pisellos,
    getData,
    interaction,
    Toast,
    onToastClose: () => {
    }
  };
  const generateActionButtons = (paymentStatus, enabledAutoPrint = false, orderId = "") => {
    const getClassName = (suffix) => `payment-result-toast-${suffix}`;
    const handleDetailsClick = async () => {
      var _a2;
      setTimeout(() => {
        (0, import_PaymentResultToast.closeAllPaymentResultToasts)();
      }, 0);
      const { isTerminal: isTerminal2, isWebPos: isWebPos2, NativePage } = (_a2 = context.appHelper) == null ? void 0 : _a2.utils;
      if (isWebPos2) {
        const nativePage = NativePage == null ? void 0 : NativePage();
        nativePage.open({ page: "/native/order/detail", params: { order_id: orderId } });
        return;
      }
      if (isTerminal2 == null ? void 0 : isTerminal2()) {
        return interaction.utils.postMessageToApp({
          module: "booking",
          key: "view_order",
          data: {
            order_id: orderId
          },
          origin: "/booking"
        });
      }
    };
    const handlePrintReceiptClick = async () => {
      setTimeout(() => {
        (0, import_PaymentResultToast.closeAllPaymentResultToasts)();
      }, 0);
      let data = {
        orderId
      };
      if (data.orderId) {
        const params2 = {
          type: "0",
          data: { order_id: data.orderId }
        };
        try {
          nativePrint(params2, (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);
        }
      }
    };
    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")
          }
        }
      ]
    ];
  };
  let isCurrentOrderSynceFromCart = (0, import_react.useRef)(false);
  (0, import_react.useEffect)(() => {
    const orderSubmitStartUnsubscribe = pisellos.effects.on(
      "checkout:onOrderSubmitStart",
      executeIfActive(() => {
        var _a2;
        if (isPaymentModalOpen || window.isPaymentModalPluginOpen) return;
        isCurrentOrderSynceFromCart.current = true;
        (_a2 = Toast == null ? void 0 : Toast.loading) == null ? void 0 : _a2.call(Toast, "", 0);
      })
    );
    const orderSubmitEndUnsubscribe = pisellos.effects.on(
      "checkout:onOrderSubmitEnd",
      executeIfActive(() => {
        var _a2;
        if (isPaymentModalOpen || window.isPaymentModalPluginOpen) return;
        (_a2 = Toast == null ? void 0 : Toast.hide) == null ? void 0 : _a2.call(Toast);
      })
    );
    const orderSyncedUnsubscribe = pisellos.effects.on(
      "checkout:onOrderSynced",
      executeIfActive(async (data) => {
        var _a2, _b2, _c2, _d2, _e2, _f2;
        if (!isCurrentOrderSynceFromCart.current) return;
        isCurrentOrderSynceFromCart.current = false;
        if (isPaymentModalOpen || window.isPaymentModalPluginOpen) return;
        const responseData = (_a2 = data.response) == null ? void 0 : _a2.data;
        const paymentStatus = responseData == null ? void 0 : responseData.payment_status;
        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(
          (_b2 = responseData == null ? void 0 : responseData.payment_info) == null ? void 0 : _b2.current_change_given_amount
        );
        const failureReason = responseData == null ? void 0 : responseData.failure_reason;
        if (paymentStatus) {
          console.log("footer_print_order_onOrderSynced>>>>", responseData);
          logger == null ? void 0 : logger.addLog({
            type: "info",
            title: "footer_print_order_onOrderSynced",
            metadata: {
              responseData
            }
          });
          try {
            const params2 = {
              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,
                machine_code_print_info_v2: responseData == null ? void 0 : responseData.machine_code_print_info_v2
              }
            };
            console.log("footer_print_order_onOrderSynced_params>>>>", params2);
            logger == null ? void 0 : logger.addLog({
              type: "info",
              title: "footer_print_order_onOrderSynced_params",
              metadata: {
                params: params2
              }
            });
            nativePrint(params2, (res) => {
              console.log("footer_print_order_onOrderSynced_res>>>>", res);
              logger == null ? void 0 : logger.addLog({
                type: "info",
                title: "footer_print_order_onOrderSynced_res",
                metadata: {
                  res
                }
              });
            });
          } catch (error) {
            console.error("footer_print_order_onOrderSynced_error>>>>", error);
            logger == null ? void 0 : logger.addLog({
              type: "info",
              title: "footer_print_order_onOrderSynced_error",
              metadata: {
                error
              }
            });
          }
          const autoCloseConfig = (0, import_PaymentResultToastUtils.calculateAutoCloseConfig)(
            paymentStatus,
            !!currentChangeGivenAmount
          );
          let enabledAutoPrint = false;
          if (isWebPos) {
            enabledAutoPrint = false;
          } else {
            enabledAutoPrint = await ((_e2 = (_d2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _d2.asyncDataManager) == null ? void 0 : _e2.call(_d2, {
              module: "get",
              key: "auto_print_receipt"
            }));
          }
          autoCloseConfig.autoClose = false;
          autoCloseConfig.autoCloseDelay = 0;
          autoCloseConfig.maskClosable = false;
          console.log("displayPaymentResultToast__footer", autoCloseConfig);
          (0, import_PaymentResultToastUtils.displayPaymentResultToast)(
            {
              paymentStatus,
              orderTotalAmount: (_f2 = data.response.data) == null ? void 0 : _f2.total_amount,
              gapAmount: paymentStatus === "partially_paid" ? gapAmount : currentChangeGivenAmount,
              failureReason,
              autoCloseConfig,
              actionButtons: generateActionButtons(paymentStatus, enabledAutoPrint, responseData == null ? void 0 : responseData.order_id)
            },
            paymentResultToastConfig
          );
        }
        handleClearAll();
      })
    );
    return () => {
      orderSubmitStartUnsubscribe();
      orderSubmitEndUnsubscribe();
      orderSyncedUnsubscribe();
    };
  }, [isPaymentModalOpen]);
  (0, import_react.useEffect)(() => {
    window._setEditOrderMode = async (order_id2) => {
      let bookingOrigin = await (0, import_serve3._getBookingDetail)(order_id2);
      let booking = (0, import_ticketBooking._formatBookingDetail)(bookingOrigin, {});
      changeCustomerToGlobalState(booking.client.value);
      dispatch({
        type: "setService",
        payload: {
          value: booking.service.value
        }
      });
      setEditOrderId(order_id2);
      const paidAmount = bookingOrigin.payments.reduce((total2, item) => {
        return total2 + Number(item.amount);
      }, 0);
      const paidAmountWithoutSurcharge = bookingOrigin.payments.reduce((total2, item) => {
        var _a2;
        return total2 + Number(item.amount) - Number(((_a2 = item.service_charge) == null ? void 0 : _a2.amount) || 0);
      }, 0);
      dispatch({
        type: "setPaymentPaid",
        payload: {
          value: {
            paidAmount,
            paidAmountWithoutSurcharge
          }
        }
      });
      shopDiscount.loadPrepareConfig({
        customerId: booking.client.value.id,
        action: "create",
        with_good_pass: 1,
        with_discount_card: 1
      });
    };
  }, []);
  const { setActiveTab } = state;
  const isTeam = (0, import_react.useMemo)(() => {
    return storage.get("channel") === "android_team_portal" || storage.get("channel") === "ios_team_portal";
  }, []);
  const actionMap = {
    sale: {
      label: import_utils.locales.getText("pisell2.text.addons"),
      key: "sale"
    },
    paymentLink: {
      label: import_utils.locales.getText("pisell2.text.payment-link"),
      key: "payment",
      children: [
        {
          label: import_utils.locales.getText("pisell2.text.send-mail"),
          key: "sendMail"
        },
        {
          label: import_utils.locales.getText("pisell2.text.copy-to-clipboard"),
          key: "copy"
        }
      ]
    },
    print: {
      label: "Print",
      key: "print"
    },
    orderDetail: {
      label: import_utils.locales.getText("pisell2.text.deposit-order-detail"),
      key: "orderDetail"
    },
    refund: {
      label: import_utils.locales.getText("pisell2.text.refund"),
      key: "refund"
    },
    rebook: {
      label: import_utils.locales.getText("pisell2.text.rebook"),
      key: "rebook"
    },
    cancelOrder: {
      label: "Cancel order",
      key: "cancelOrder"
    }
  };
  (0, import_react.useEffect)(() => {
    if (state.bookingDetail) {
      state.action({
        type: "pisell1.registerPlugin",
        data: {
          pluginList: ["RefundPlugin"]
        }
      });
    }
  }, [state.bookingDetail]);
  const params = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    return ((_c2 = (_b2 = (_a2 = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.basic) == null ? void 0 : _c2.appointment_subject) || {};
  }, [(_f = (_e = (_d = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _d.config) == null ? void 0 : _e.basic) == null ? void 0 : _f.appointment_subject]);
  const transaction_habit_selection = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    return ((_c2 = (_b2 = (_a2 = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.information_tab) == null ? void 0 : _c2.transaction_habit_selection) || {
      type: "service_now_pay_later",
      button_rows: 1
    };
  }, [(_h = (_g = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _g.config) == null ? void 0 : _h.information_tab]);
  const addonsEdit = (0, import_react.useMemo)(() => {
    var _a2;
    if ((_a2 = state.addons) == null ? void 0 : _a2.edit) {
      return true;
    }
    return false;
  }, [(_i = state.addons) == null ? void 0 : _i.edit]);
  const infoEdit = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
    if (!state.bookingId) {
      return true;
    }
    if ((_a2 = state.client) == null ? void 0 : _a2.edit) {
      return true;
    }
    if ((_b2 = state.date) == null ? void 0 : _b2.edit) {
      return true;
    }
    if ((_c2 = state.pet) == null ? void 0 : _c2.edit) {
      return true;
    }
    if ((_d2 = state.service) == null ? void 0 : _d2.edit) {
      return true;
    }
    if ((_e2 = state.notes) == null ? void 0 : _e2.edit) {
      return true;
    }
    if ((_f2 = state.contacts) == null ? void 0 : _f2.edit) {
      return true;
    }
    if ((_g2 = state.contacts_info) == null ? void 0 : _g2.edit) {
      return true;
    }
    return false;
  }, [state]);
  const isEdit = (0, import_react.useMemo)(() => {
    return infoEdit || addonsEdit;
  }, [infoEdit, addonsEdit]);
  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 total = (0, import_react.useMemo)(() => {
    return (0, import_amount.getSumTotal)(state, {
      isEdit,
      ScheduleModule,
      ...getDataFromHost()
    });
  }, [state, isEdit]);
  (0, import_react.useEffect)(() => {
    window.dispatchEvent(
      new CustomEvent("onOriginExpectAmountWithoutDiscountChange", {
        detail: {
          originExpectAmountWithoutDiscount: total == null ? void 0 : total.originExpectAmountWithoutDiscount
        }
      })
    );
  }, [total == null ? void 0 : total.originExpectAmountWithoutDiscount]);
  const orderTotalList = (0, import_react.useMemo)(() => {
    return [
      // 订单已付金额
      {
        hidden: !state.bookingId,
        key: "custom_orderPaidAmount",
        value: total.orderPaidAmount,
        label: import_utils.locales.getText("pisell2.text.amount-paid-on-order")
      },
      // 支付手续费
      {
        hidden: !state.bookingId,
        key: "custom_paySurchargeFee",
        value: total.paySurchargeFee,
        label: import_utils.locales.getText("pisell1.text.payment-fee")
      },
      // 客户实付金额
      {
        hidden: !state.bookingId,
        key: "custom_actualPaidAmount",
        value: total.actualPaidAmount,
        label: import_utils.locales.getText(
          "pisell2.text.amount-actually-paid-by-the-customer"
        )
      },
      // 退款金额
      {
        hidden: !state.bookingId || !total.totalRefundAmount,
        key: "custom_totalRefundAmount",
        value: total.totalRefundAmount,
        label: import_utils.locales.getText("pisell2.text.refunded-amount")
      }
    ];
  }, [total, (_j = state.bookingDetail) == null ? void 0 : _j.surcharge, state.bookingId]);
  const subTotalList = (0, import_react.useMemo)(() => {
    return [
      // 小计
      {
        key: "sub_total",
        value: total.productAmount
      },
      // 自定义手续费
      ...total.surcharge || [],
      // 税费
      {
        key: "tax",
        value: total.tax,
        tax: total.taxInfo
      },
      // 订单折扣（优惠券等）
      {
        key: "discount",
        value: total.shopDiscount
      },
      // 手动折扣
      // {
      //   key: 'shop_discount',
      //   value: Number(state.shop_discount) || 0,
      //   label: locales.getText('pisell2.text.manual-price-adjustment'),
      // },
      // 总计
      {
        key: "expect_amount",
        value: total.expectAmount,
        label: import_utils.locales.getText("pisell2.subtotal.total")
      },
      // 舍入金额
      {
        hidden: !total.roundingAmount,
        key: "custom_roundingAmount",
        value: total.roundingAmount,
        label: import_utils.locales.getText("pisell1.text.rounding")
      }
    ];
  }, [total, (_k = state.bookingDetail) == null ? void 0 : _k.surcharge, state.bookingId]);
  const isDisabled = (0, import_react.useMemo)(() => {
    var _a2;
    const isClient = state.client.value;
    if (!isClient) {
      return true;
    }
    const isService = (_a2 = state.service.value) == null ? void 0 : _a2.length;
    if (!isService) {
      return true;
    }
    const isDate = state.date.value;
    if (!isDate) {
      return true;
    }
    return false;
  }, [state, params]);
  const isDisabledCheckOutForNegativeOrder = (0, import_react.useMemo)(() => {
    return total.expectAmount < 0 && state.isBookingTicket2;
  }, [total, state.isBookingTicket2]);
  const isDisabledCheckOutForEditTicketMode = (0, import_react.useMemo)(() => {
    console.log("isDisabledCheckOutForEditTicketMode", total);
    return total.notPaidAmount <= 0 && state.isEditTicketMode;
  }, [total, state.isEditTicketMode]);
  const goCheckout = async (order_id2, isNewOrder, totalAmount) => {
    var _a2, _b2;
    if (!order_id2) return;
    if (isWebPos) {
      state.action({
        type: "pisell1.handleOpenPayment",
        data: { order: { id: order_id2 } },
        callback: (res) => {
          var _a3;
          if ((_a3 = res == null ? void 0 : res.data) == null ? void 0 : _a3.isCallbackFromToast) return;
          state == null ? void 0 : state.callback({}, "save");
        }
      });
      return;
    }
    if (isTerminal == null ? void 0 : isTerminal()) {
      disableAllScanListeners();
      return (_b2 = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b2.call(_a2, {
        module: "booking",
        key: "booking_checkout",
        data: {
          order_id: order_id2,
          callbackType: "pisell2",
          // 是新创建订单传递newOrder terminal内会执行弃单逻辑 编辑订单时不走弃单逻辑
          newOrder: isNewOrder
        }
      });
    }
    state.action({
      type: "pisell1.handlePayment",
      data: {
        orderId: order_id2
      },
      callback: () => {
        state == null ? void 0 : state.callback();
      }
    });
  };
  const goCheckout2 = async (res) => {
    state.action({
      type: "pisell1.handleOpenPayment",
      data: {
        order_info: res,
        subtotal_info: {
          subTotalList,
          orderTotalList,
          total,
          showDetail
        }
      },
      callback: (res2) => {
        var _a2, _b2, _c2, _d2;
        console.log("webpos_pay_result", res2);
        if ((res2 == null ? void 0 : res2.status) === "success") {
          (_b2 = (_a2 = window == null ? void 0 : window.shopApi) == null ? void 0 : _a2.bookingTicket) == null ? void 0 : _b2.clearAllCart();
        } else if ((res2 == null ? void 0 : res2.status) === "cancel") {
          (_d2 = (_c2 = window == null ? void 0 : window.shopApi) == null ? void 0 : _c2.booking) == null ? void 0 : _d2.voidBooking(order_id);
        } else {
        }
      }
    });
  };
  (0, import_ahooks.useDebounceEffect)(() => {
    (async () => {
      try {
        logger.addLog({
          title: "Footer: OrderTotalList/Total changed, updating PaymentModal data..."
        });
        if (isPaymentModalOpen) {
          const res = await handleSave({
            type: "checkout",
            messageShow: !(isTerminal == null ? void 0 : isTerminal()),
            noSubmit: true
          });
          if (!res) return;
          setCheckoutLoading(false);
          const modalData = {
            order_info: res,
            subtotal_info: {
              subTotalList,
              orderTotalList,
              total,
              showDetail
            },
            existPayment
          };
          if (JSON.stringify(modalData) === JSON.stringify(paymentModalData)) {
            return;
          }
          logger.addLog({
            title: "Footer: 检测到 PaymentModalData 和 modalData 不一致，更新 PaymentModalData",
            metadata: {
              paymentModalData,
              modalData
            }
          });
          setPaymentModalData(modalData);
        }
      } catch (error) {
      }
    })();
  }, [
    JSON.stringify(total),
    JSON.stringify(orderTotalList),
    JSON.stringify(subTotalList),
    (_m = (_l = state.client) == null ? void 0 : _l.value) == null ? void 0 : _m.id
  ]);
  const handleCheckoutInternal = async () => {
    var _a2, _b2, _c2;
    const isToastMode = ((_c2 = (_b2 = (_a2 = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.payment_setting) == null ? void 0 : _c2.payment_result_display_mode) !== "modal";
    if (isToastMode) {
      (0, import_PaymentResultToast.closeAllPaymentResultToasts)();
    }
    logger.addLog({
      title: "Footer: handleCheckoutInternal 调用",
      metadata: { isToastMode }
    });
    const isNewOrder = !state.bookingId;
    if (isEdit) {
      if ((0, import_utils2.isDayBooking)(state)) {
        const isHasDayProducts = handleDaySubmit();
        if (isHasDayProducts) return;
      }
      if (state.isBookingTicket2) {
        const res = await handleSave({
          type: "checkout",
          messageShow: !(isTerminal == null ? void 0 : isTerminal()),
          noSubmit: true
        });
        if (!res) return;
        const modalData = {
          order_info: res,
          subtotal_info: {
            subTotalList: (0, import_lodash.cloneDeep)(subTotalList),
            orderTotalList: (0, import_lodash.cloneDeep)(orderTotalList),
            total: (0, import_lodash.cloneDeep)(total),
            showDetail
          },
          existPayment
        };
        setPaymentModalData(modalData);
        setIsPaymentModalOpen(true);
        window.isPaymentModalPluginOpen = true;
        setCheckoutLoading(false);
        setPaymentCallback(() => (paymentResult) => {
          var _a3, _b3, _c3, _d2;
          console.log("Payment result:", paymentResult);
          setIsPaymentModalOpen(false);
          window.isPaymentModalPluginOpen = false;
          if ((paymentResult == null ? void 0 : paymentResult.status) === "success" || ((_b3 = (_a3 = paymentResult == null ? void 0 : paymentResult.response) == null ? void 0 : _a3.data) == null ? void 0 : _b3.payment_status) === "paid") {
            console.log("Payment completed successfully");
            setPaymentModalData(null);
            setPaymentCallback(null);
          } else if ((paymentResult == null ? void 0 : paymentResult.status) === "cancelled") {
            console.log("Payment cancelled");
            if (res == null ? void 0 : res.order_id) {
              (_d2 = (_c3 = window == null ? void 0 : window.shopApi) == null ? void 0 : _c3.booking) == null ? void 0 : _d2.voidBooking(res.order_id);
            }
            setPaymentModalData(null);
            setPaymentCallback(null);
          } else {
            console.log("Payment status:", paymentResult == null ? void 0 : paymentResult.status);
            setPaymentModalData(null);
            setPaymentCallback(null);
          }
        });
      } else {
        const res = await handleSave({
          type: "checkout",
          messageShow: !(isTerminal == null ? void 0 : isTerminal())
        });
        console.log(res);
        goCheckout((res == null ? void 0 : res.order_id) || state.bookingId, isNewOrder);
      }
      return;
    }
    return goCheckout(state.bookingId, isNewOrder);
  };
  const { run: handleCheckout } = (0, import_ahooks.useDebounceFn)(handleCheckoutInternal, {
    wait: 500,
    leading: true,
    trailing: false
  });
  const handleSaveAddons = async () => {
    try {
      let _list = [...state.addons.value];
      await state.apis.saveAddonsByOrderId({
        products: (0, import_addons.formatProducts)(_list),
        shop_discount: state.bookingDetail.shop_discount,
        shop_discount_reason: state.bookingDetail.shop_discount_reason
      });
      import_antd.message.success(
        import_utils.locales.getText("pisell2.text.addons") + import_utils.locales.getText("pisell2.text.updated")
      );
    } catch (err) {
      console.log("state.bookingId && state.addons.edit", err);
    }
  };
  const getApis = () => {
    if (isBooking4Shop || state.renderType === "dayBooking") {
      return {
        editBooking: import_serve.editBookings,
        createBooking: import_serve.createBookings
      };
    }
    return {
      editBooking: state.apis.editBooking,
      createBooking: state.apis.createBooking
    };
  };
  const handleDaySubmit = () => {
    var _a2;
    const _isHasDayProducts = (0, import_utils2.isHasDayAppointmentProduct)(state);
    if (_isHasDayProducts) {
      (_a2 = appointmentProductRef == null ? void 0 : appointmentProductRef.current) == null ? void 0 : _a2.open();
    }
    return _isHasDayProducts;
  };
  const isOnlyDeposit = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2;
    if (((_a2 = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _a2.deposit_payment_time) && ((_d2 = (_c2 = (_b2 = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _b2.payment_types) == null ? void 0 : _c2.every) == null ? void 0 : _d2.call(
      _c2,
      (item) => item === "deposit"
    ))) {
      return true;
    }
    return false;
  }, [state == null ? void 0 : state.bookingDetail]);
  const arrearsText = (0, import_react.useMemo)(() => {
    let str = "";
    if (isOnlyDeposit) {
      return str;
    }
    if (total.dueAmount < 0) {
      str = `${import_utils.locales.getText("pisell1.text.refund-customer")}: ${(0, import_utils.formatAmount)(
        total.dueAmount,
        2,
        (state == null ? void 0 : state.amountSymbol) || "$"
      )}`;
    }
    return str;
  }, [state, total, isOnlyDeposit]);
  const mainApp = (_p = (_o = (_n = context == null ? void 0 : context.appHelper) == null ? void 0 : _n.utils) == null ? void 0 : _o.getApp) == null ? void 0 : _p.call(_o);
  const handleSave = async ({
    type,
    messageShow = true,
    noSubmit = false
  }) => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2;
    logger.addLog({
      title: "Footer: handleSave 调用",
      metadata: {
        type,
        noSubmit
      }
    });
    if (state.isEditTicketMode) {
      window.isPaymentModalPluginOpen = true;
    } else {
      window.isPaymentModalPluginOpen = false;
    }
    const isToastMode = ((_c2 = (_b2 = (_a2 = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.payment_setting) == null ? void 0 : _c2.payment_result_display_mode) !== "modal";
    if (isToastMode) {
      (0, import_PaymentResultToast.closeAllPaymentResultToasts)();
    }
    if ((0, import_utils2.isDayBooking)(state)) {
      const isHasDayProducts = handleDaySubmit();
      if (isHasDayProducts) return;
    }
    const products = (_d2 = state.service.value) == null ? void 0 : _d2.filter((item) => !(item == null ? void 0 : item._giftInfo));
    const hasUnspecifiedHolderProduct = products == null ? void 0 : products.some((item) => {
      var _a3, _b3, _c3;
      return (!((_a3 = item._extend) == null ? void 0 : _a3.holder_id) || ((_c3 = (_b3 = item._extend) == null ? void 0 : _b3.holder_id) == null ? void 0 : _c3.length) === 0) && !(0, import_utils2.isNormalProductByDurationSchedule)(item);
    });
    if (!(0, import_utils5.isWalkIn)((_f2 = (_e2 = state.client) == null ? void 0 : _e2.value) == null ? void 0 : _f2.id) && (0, import_utils2.getIsSubjectRequire)(state) && hasUnspecifiedHolderProduct) {
      await (0, import_confirmHolderModal.showConfirmHolderModal)(state, dispatch);
    }
    if (isBooking4Shop && (0, import_utils2.getIsSubjectRequire)(state) && (0, import_utils3.checkHolderIsError)(state)) {
      return;
    }
    let _setLoading = type === "checkout" ? setCheckoutLoading : setLoading;
    _setLoading(true);
    const loadingTimer = setTimeout(() => {
      _setLoading(false);
    }, 2e4);
    const { createBooking, editBooking } = getApis();
    const editApi = state.renderType === "eventBooking" ? import_serve2.editEventBooking : editBooking;
    const createApi = state.renderType === "eventBooking" ? import_serve2.createEventBooking : createBooking;
    let saveOtherValue = {};
    if (type === "save") {
      saveOtherValue = await ((_g2 = state == null ? void 0 : state.onSave) == null ? void 0 : _g2.call(state, state.client)) || {};
    }
    try {
      let callbackData = (state == null ? void 0 : state.bookingId) ? { order_id: state == null ? void 0 : state.bookingId } : null;
      const mergedForFormat = { ...state, ...saveOtherValue };
      if (state.order_type) {
        mergedForFormat.order_type = state.order_type;
      }
      let values = (0, import_utils3.formatValues)(mergedForFormat);
      values.product_tax_fee = total.tax || 0;
      if (noSubmit) {
        return values;
      }
      const checkout = pisellos.getModule("checkout");
      if (editOrderId) {
        const subtotal_info = {
          subTotalList: (0, import_lodash.cloneDeep)(subTotalList),
          orderTotalList: (0, import_lodash.cloneDeep)(orderTotalList),
          total: (0, import_lodash.cloneDeep)(total),
          showDetail
        };
        await checkout.updateLocalOrderAsync({
          orderId: editOrderId,
          orderData: values,
          cartSummary: subtotal_info.subTotalList,
          autoPayment: true,
          totalInfo: subtotal_info
        });
        const res = await checkout.manualSyncOrderAsync();
        if (res.success) {
          state == null ? void 0 : state.callback(res, type);
          _setLoading(false);
        }
        if (state.isEditTicketMode) {
          (_h2 = state == null ? void 0 : state.dialogCallback) == null ? void 0 : _h2.call(state, { type: "save", data: callbackData || values });
        }
        setEditOrderId(0);
        return;
      }
      if (type === "save" && !state.bookingId) {
        const isNeedDeposit = checkout.checkIsNeedDepositAsync(values.bookings, values.relation_products);
        if (isNeedDeposit == null ? void 0 : isNeedDeposit.hasDeposit) {
          values.is_deposit = 1;
          values.deposit_amount = isNeedDeposit == null ? void 0 : isNeedDeposit.total;
        }
      }
      let api = state.bookingId ? editApi : createApi;
      (0, import_utils4.sendWarningLog)({
        title: "saveBooking",
        content: [
          { key: "下单前数据", value: JSON.stringify(values) },
          { key: "日期", value: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm") },
          {
            key: "店铺id",
            value: (_l2 = (_k2 = (_j2 = (_i2 = store == null ? void 0 : store.getState) == null ? void 0 : _i2.call(store)) == null ? void 0 : _j2.global) == null ? void 0 : _k2.globalConfig) == null ? void 0 : _l2.id
          },
          {
            key: "shopApi",
            value: JSON.stringify(window == null ? void 0 : window.shopApi, (key, value) => {
              if (typeof value === "function") {
                return "function";
              }
              return value;
            })
          }
        ]
      });
      if (addonsEdit) {
        await handleSaveAddons();
      }
      console.log("mainApp>>>>>", mainApp);
      const autoPrintReceiptPrinters = mainApp.storage.getStorage("autoPrintAfterSave");
      logger == null ? void 0 : logger.addLog({
        type: "info",
        title: "handleSave_autoPrintReceiptPrinters",
        metadata: {
          autoPrintReceiptPrinters
        }
      });
      if (autoPrintReceiptPrinters) {
        values.small_ticket_data_flag = 1;
      }
      if (infoEdit) {
        callbackData = await api(values, state.bookingId || editOrderId);
        callbackData = { order_id: state.bookingId || editOrderId, ...callbackData || {} };
        if (messageShow) {
          import_antd.message.success(
            import_utils.locales.getText(
              state.bookingId ? "pisell2.text.appointment-updated" : "pisell2.text.created-successfully"
            )
          );
        }
      }
      if (!state.bookingId && type === "save" && autoPrintReceiptPrinters && callbackData) {
        logger == null ? void 0 : logger.addLog({
          type: "info",
          title: "检测到保存订单需要自动打印小票",
          metadata: {}
        });
        const params2 = {
          type: "99",
          // 打印订单全部信息
          data: {
            order_id: callbackData.order_id,
            machine_code_print_info: (callbackData == null ? void 0 : callbackData.machine_code_print_info) || {},
            small_ticket_data: (callbackData == null ? void 0 : callbackData.small_ticket_data) || {},
            machine_code_print_info_v2: (callbackData == null ? void 0 : callbackData.machine_code_print_info_v2) || {}
          }
        };
        nativePrint(params2, (res) => {
          console.log("handleSave_autoPrintReceipt_res>>>>", res);
          logger == null ? void 0 : logger.addLog({
            type: "info",
            title: "handleSave_autoPrintReceipt_res",
            metadata: {
              res
            }
          });
        });
      }
      state == null ? void 0 : state.callback(callbackData, type);
      clearTimeout(loadingTimer);
      _setLoading(false);
      return callbackData || values;
    } catch (err) {
      console.log(err);
      if ((err == null ? void 0 : err.code) === 70101) {
        import_antd.message.error(err == null ? void 0 : err.message);
      }
      clearTimeout(loadingTimer);
      _setLoading(false);
    }
  };
  const onSelect = async (e) => {
    const status = "completed";
    dispatch({
      type: "setStatus",
      payload: status
    });
    const data = await state.apis.editBookingStatus({
      appointment_status: status
    });
    import_antd.message.success(import_utils.locales.getText("pisell1.text.edit-status-success"));
    state == null ? void 0 : state.callback({ order_id: state.bookingId });
  };
  const handleRefund = () => {
    var _a2, _b2;
    if (isTerminal == null ? void 0 : isTerminal()) {
      return (_b2 = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b2.call(_a2, {
        module: "booking",
        key: "booking_refund",
        data: {
          order_id: state.bookingId
        },
        origin: "/booking"
      });
    }
    state.action({
      type: "pisell1.handleRefund",
      data: {
        orderId: state.bookingId
      },
      callback: () => {
        state == null ? void 0 : state.callback({ order_id: state.bookingId });
      }
    });
  };
  const paymentRefundedStatus = (0, import_react.useMemo)(() => {
    var _a2;
    return ["partially_refunded", "refunded"].includes(
      (_a2 = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _a2.payment_status
    );
  }, [state == null ? void 0 : state.bookingDetail]);
  const checkoutButton = (0, import_react.useMemo)(() => {
    let buttonType = "primary";
    if (transaction_habit_selection.type === "service_now_pay_later") {
      buttonType = "default";
    }
    if (source === "payment") {
      buttonType = "primary";
    }
    if (!isEdit) {
      buttonType = "primary";
    }
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.ConfigProvider,
      {
        theme: {
          token: {
            colorPrimary: buttonType === "primary" ? "#7F56DA" : "#F79009"
          }
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          className: (0, import_classnames.default)("pisell-lowcode__booking-footer-buttons-item", {
            ["pisell-lowcode__booking-footer-buttons-item-primary"]: buttonType === "primary"
          }),
          type: "primary",
          loading: checkoutLoading,
          onClick: () => {
            handleCheckout();
          },
          disabled: isDisabled || isDisabledCheckOutForNegativeOrder || isDisabledCheckOutForEditTicketMode || arrearsText !== ""
        },
        import_utils.locales.getText("pisell2.text.checkout")
      )
    );
  }, [isEdit, checkoutLoading, isDisabled, state, source, arrearsText]);
  const handleMenuClick = async (e) => {
    var _a2, _b2;
    let id = state.bookingId;
    let customer = state.bookingDetail.customer;
    if (isEdit) {
      const res = await handleSave({ type: "checkout", messageShow: false });
      id = (res == null ? void 0 : res.order_id) || state.bookingId;
      customer = (res == null ? void 0 : res.customer_id) ? { id: res == null ? void 0 : res.customer_id } : state.bookingDetail.customer;
    }
    if (e.key === "sendMail") {
      console.log(e);
      state.action({
        type: "pisell1.sendPayLinkEmail",
        data: {
          id,
          is_deposit: state.bookingDetail.is_deposit || Number((_a2 = state.bookingDetail) == null ? void 0 : _a2.deposit_amount),
          deposit_payment_time: state.bookingDetail.deposit_payment_time,
          customer,
          contacts: (_b2 = state.bookingDetail) == null ? void 0 : _b2.contacts
        },
        callback: () => {
        }
      });
    }
    if (e.key === "copy") {
      state.action({
        type: "pisell1.genClientPayLink",
        data: {
          id
        },
        callback: () => {
        }
      });
    }
  };
  const handleRebook = () => {
    var _a2;
    (_a2 = state.onRebook) == null ? void 0 : _a2.call(state);
  };
  const handleSale = () => {
    var _a2, _b2;
    if (isWebPos) {
      return state.action({
        type: "pisell1.handleOpenEditBooking",
        data: { order_id: state.bookingId },
        callback: (res) => {
          var _a3, _b3;
          (_b3 = (_a3 = window == null ? void 0 : window.shopApi) == null ? void 0 : _a3.booking) == null ? void 0 : _b3.refreshBookingDetail();
        }
      });
    }
    if (isTerminal == null ? void 0 : isTerminal()) {
      return (_b2 = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b2.call(_a2, {
        module: "booking",
        key: "edit_order",
        data: {
          order_id: state.bookingId
        }
      });
    }
    if (state.channelDisabledEdit) {
      setTerminalWarningOpen(true);
      return;
    }
    setActiveTab == null ? void 0 : setActiveTab("addons");
  };
  const handlePrint = () => {
  };
  const handleOrderDetail = () => {
    if (isWebPos) {
      return state.action({
        type: "pisell1.handleOpenEditBooking",
        data: { order_id: state.bookingId },
        callback: (res) => {
          var _a2, _b2;
          (_b2 = (_a2 = window == null ? void 0 : window.shopApi) == null ? void 0 : _a2.booking) == null ? void 0 : _b2.refreshBookingDetail();
        }
      });
    }
    if (isTerminal == null ? void 0 : isTerminal()) {
      return interaction.utils.postMessageToApp({
        module: "booking",
        key: "view_order",
        data: {
          order_id: state.bookingId
        },
        origin: "/booking"
      });
    }
    state.action({
      type: "pisell1.goOrderDetail",
      data: {
        orderId: state.bookingId
      },
      callback: () => {
        state == null ? void 0 : state.callback();
      }
    });
  };
  const handleCancel = () => {
  };
  const paymentLinkButton = (0, import_react.useMemo)(() => {
    const items = [
      { label: import_utils.locales.getText("pisell2.text.send-mail"), key: "sendMail" },
      { label: import_utils.locales.getText("pisell2.text.copy-to-clipboard"), key: "copy" }
    ];
    return /* @__PURE__ */ import_react.default.createElement(import_antd.Dropdown, { menu: { items, onClick: handleMenuClick } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { className: "pisell-lowcode__booking-footer-buttons-item" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Space, null, import_utils.locales.getText("pisell2.text.payment-link"), /* @__PURE__ */ import_react.default.createElement(import_icons.DownOutlined, null))));
  }, [handleMenuClick]);
  const saveButton = (0, import_react.useMemo)(() => {
    let buttonType = "default";
    if (transaction_habit_selection.type === "service_now_pay_later") {
      buttonType = "primary";
    }
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.ConfigProvider,
      {
        theme: {
          token: {
            colorPrimary: buttonType === "primary" ? "#7F56DA" : "#F79009"
          }
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          className: (0, import_classnames.default)("pisell-lowcode__booking-footer-buttons-item", {
            ["pisell-lowcode__booking-footer-buttons-item-primary"]: buttonType === "primary"
          }),
          type: "primary",
          onClick: () => {
            handleSave({ type: "save" });
          },
          disabled: isDisabled || !isEdit,
          loading
        },
        import_utils.locales.getText("pisell2.text.save")
      )
    );
  }, [loading, isDisabled, isEdit, infoEdit, addonsEdit, state]);
  const handleNote = () => {
    setNoteModalOpen(true);
  };
  const handleNoteConfirm = (noteValue) => {
    dispatch({
      type: "setNotes",
      payload: {
        orderNote: noteValue,
        edit: true
      }
    });
    setNoteModalOpen(false);
  };
  const handleNoteDelete = () => {
    dispatch({
      type: "setNotes",
      payload: {
        orderNote: "",
        edit: true
      }
    });
    setNoteModalOpen(false);
  };
  const handleNoteCancel = () => {
    setNoteModalOpen(false);
  };
  const completeButton = (0, import_react.useMemo)(() => {
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        className: "pisell-lowcode__booking-footer-buttons-item",
        type: "primary",
        onClick: onSelect,
        disabled: state.appointment_status === "completed"
      },
      import_utils.locales.getText("pisell2.text.status.completed")
    );
  }, [state.appointment_status]);
  const rebookButton = (0, import_react.useMemo)(() => {
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        className: "pisell-lowcode__booking-footer-buttons-item",
        onClick: handleRebook
      },
      import_utils.locales.getText("pisell2.text.rebook")
    );
  }, [state == null ? void 0 : state.onRebook]);
  const refundButton = (0, import_react.useMemo)(() => {
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        className: "pisell-lowcode__booking-footer-buttons-item",
        type: "default",
        onClick: handleRefund
      },
      import_utils.locales.getText("pisell2.text.refund")
    );
  }, []);
  const handleClearAll = () => {
    var _a2;
    (_a2 = state == null ? void 0 : state.clearAllValue) == null ? void 0 : _a2.call(state);
  };
  const clearAllButton = (0, import_react.useMemo)(() => {
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.ConfigProvider,
      {
        theme: {
          token: {
            colorPrimary: "#f04438"
          }
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          className: "pisell-lowcode__booking-footer-buttons-item",
          type: "primary",
          onClick: handleClearAll
        },
        import_utils.locales.getText("pisell2.booking.info.text.clear-all")
      )
    );
  }, []);
  const hasOrderNote = (0, import_react.useMemo)(() => {
    var _a2;
    const note = ((_a2 = state == null ? void 0 : state.notes) == null ? void 0 : _a2.orderNote) || "";
    return note.trim().length > 0;
  }, [(_q = state == null ? void 0 : state.notes) == null ? void 0 : _q.orderNote]);
  const noteButton = (0, import_react.useMemo)(() => {
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.ConfigProvider,
      {
        theme: {
          token: {
            colorPrimary: "#0d7fa9"
          }
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          className: "pisell-lowcode__booking-footer-buttons-item note-button",
          type: "primary",
          onClick: handleNote
        },
        import_utils.locales.getText("pisell2.ticket-booking.note"),
        hasOrderNote && /* @__PURE__ */ import_react.default.createElement("span", { className: "note-indicator" }, /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-info-circle2" }))
      )
    );
  }, [hasOrderNote]);
  let buttonMap = {
    checkout: checkoutButton,
    save: saveButton,
    complete: completeButton,
    refund: refundButton,
    paymentLink: paymentLinkButton,
    rebook: rebookButton,
    clearAll: clearAllButton,
    note: noteButton
  };
  const isShowClearAll = (0, import_react.useMemo)(() => {
    if (!state.bookingId) {
      return true;
    }
  }, [state.bookingId]);
  const isCheckout = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2;
    let list = ["unfulfilled", "unpaid", "payment_processing"];
    if (!state.bookingId || ((_b2 = (_a2 = state.bookingDetail) == null ? void 0 : _a2.bookings) == null ? void 0 : _b2.appointment_status) !== "cancelled" && list.includes(
      ((_c2 = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _c2.payment_status) === "partially_paid" ? "unpaid" : (_d2 = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _d2.payment_status
    ) && !state.disabledEdit) {
      return true;
    } else {
      if (total.notPaidAmount > 0) {
        return true;
      }
      return false;
    }
  }, [state.bookingDetail, total.notPaidAmount]);
  const _buttons = (0, import_react.useMemo)(() => {
    const isEvent = (0, import_utils2.isEventBooking)(state);
    if (state.appointment_status === "cancelled") {
      return [buttonMap.rebook];
    }
    if (paymentRefundedStatus) {
      if (isEvent) {
        return [""];
      }
      return [buttonMap.rebook];
    }
    if (source === "addons") {
      let arr = [];
      arr = [...buttons];
      if (isEdit) {
        arr.push(buttonMap.save);
      }
      return arr;
    }
    if (source === "payment") {
      let arr = [];
      if (state.bookingId && isShowPaymentLink) {
        arr.push(buttonMap.paymentLink);
      }
      if (!isTeam) {
        if (total.paidAmount > 0) {
          arr.push(buttonMap.refund);
        }
        if (isCheckout) {
          arr.push(buttonMap.checkout);
        }
      }
      return arr;
    }
    if (source === "info") {
      let arr = [];
      if (state.isBookingTicket2) {
        arr.push(buttonMap.note);
      }
      if (isCheckout) {
        if (!isTeam) {
          arr.push(buttonMap.checkout);
        }
      } else {
        if (!isEdit) {
          arr.push(buttonMap.complete);
        }
      }
      if (isEdit) {
        arr.push(buttonMap.save);
      }
      return arr;
    }
    if (source === "addTime") {
      let arr = [];
      arr = [...buttons];
      return arr;
    }
    return [];
  }, [
    buttons,
    total,
    isEdit,
    checkoutLoading,
    isDisabled,
    source,
    buttonMap,
    loading,
    isCheckout,
    state,
    isTeam,
    isShowClearAll
  ]);
  const moreButton = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    let arr = [];
    if (!state.bookingId) {
      return [];
    }
    if (source !== "info") {
      return [];
    }
    if (state.renderType === "eventBooking") {
      return [];
    }
    if (((_a2 = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _a2.payment_status) === "refunded") {
      return [];
    }
    if (_buttons.length !== 0) {
      if (state.bookingId && isShowPaymentLink && ((_b2 = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _b2.payment_status) !== "partially_refunded") {
        arr.push(actionMap.paymentLink);
      }
    }
    if (transaction_habit_selection.button_rows == 1) {
      if (state.appointment_status !== "cancelled") {
        if (!state.disabledEdit && !state.isBookingCreatePage && !(0, import_utils2.isDayBooking)(state)) {
          arr.push(actionMap.sale);
        }
      }
    }
    if (!isTeam) {
      if (transaction_habit_selection.button_rows == 1) {
        arr.push(actionMap.orderDetail);
      }
      if (total.paidAmount > 0) {
        arr.push(actionMap.refund);
      }
    }
    if (state.appointment_status !== "cancelled") {
      arr.push(actionMap.rebook);
    }
    return arr;
  }, [
    state,
    total,
    isShowPaymentLink,
    source,
    _buttons.length,
    (_r = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _r.payment_status
  ]);
  const totalText = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2;
    let str = "";
    if (total.totalRefundAmount > 0) {
      return `${import_utils.locales.getText(
        "pisell2.text.refunded-amount"
      )}: ${(0, import_utils.formatAmount)(
        total.totalRefundAmount,
        2,
        (state == null ? void 0 : state.amountSymbol) || "$"
      )}`;
    }
    if (isOnlyDeposit) {
      return `${import_utils.locales.getText("pisell2.text.deposit-paid")} ${(0, import_utils.formatAmount)(
        (_a2 = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _a2.deposit_paid_amount,
        2,
        (state == null ? void 0 : state.amountSymbol) || "$"
      )} ${total.duration ? `(${total.duration})` : ""}`;
    }
    if (total.notPaidAmount <= 0 && (state.bookingId || ((_b2 = state.bookingDetail) == null ? void 0 : _b2.id))) {
      str = `${import_utils.locales.getText("pisell1.text.fully-paid")}: ${(0, import_utils.formatAmount)(
        total.sumTotalAmount,
        2,
        (state == null ? void 0 : state.amountSymbol) || "$"
      )}`;
    }
    if (total.notPaidAmount > 0 || !state.bookingId && !((_c2 = state.bookingDetail) == null ? void 0 : _c2.id)) {
      if (total.dueAmount < 0 && ((_d2 = state.bookingDetail) == null ? void 0 : _d2.id)) {
        str = `${import_utils.locales.getText("pisell1.text.fully-paid")}: ${(0, import_utils.formatAmount)(
          total.sumTotalAmount,
          2,
          (state == null ? void 0 : state.amountSymbol) || "$"
        )}`;
      } else {
        str = `${import_utils.locales.getText("pisell2.text.to-pay")}: ${(0, import_utils.formatAmount)(
          total.notPaidAmount,
          2,
          (state == null ? void 0 : state.amountSymbol) || "$"
        )}`;
      }
    }
    if (total.duration) {
      str = str + ` (${total.duration})`;
    }
    return str;
  }, [state, total, state.bookingId, isOnlyDeposit, (_s = state.bookingDetail) == null ? void 0 : _s.id]);
  const showFooter = (0, import_react.useMemo)(() => {
    var _a2;
    if (state.bookingId) {
      if (!state.bookingDetail) {
        return true;
      }
      if (!((_a2 = state.addons) == null ? void 0 : _a2.load) && state.renderType !== "eventBooking" && !state.isBookingCreatePage) {
        return true;
      }
    }
    return false;
  }, [
    state.bookingId,
    state.bookingDetail,
    (_t = state.addons) == null ? void 0 : _t.load,
    state.renderType
  ]);
  const menuChange = (e) => {
    console.log("e.key", e.key);
    switch (e.key) {
      case "sendMail":
        handleMenuClick(e);
        break;
      case "copy":
        handleMenuClick(e);
        break;
      case "rebook":
        handleRebook();
        break;
      case "sale":
        handleSale();
        break;
      case "print":
        handlePrint();
        break;
      case "orderDetail":
        handleOrderDetail();
        break;
      case "refund":
        handleRefund();
        break;
      case "cancelOrder":
        handleCancel();
        break;
      default:
        break;
    }
  };
  const changeCustomerToGlobalState = (0, import_ahooks.useMemoizedFn)((value, options) => {
    var _a2, _b2, _c2;
    debugger;
    const beforeValue = (_a2 = state == null ? void 0 : state.client) == null ? void 0 : _a2.value;
    dispatch({
      type: "setClient",
      payload: {
        value,
        edit: true
      }
    });
    if ((beforeValue == null ? void 0 : beforeValue.id) === (value == null ? void 0 : value.id)) return;
    if (((_c2 = (_b2 = state == null ? void 0 : state.service) == null ? void 0 : _b2.value) == null ? void 0 : _c2.length) && !(options == null ? void 0 : options.reset)) {
      dispatch({
        type: "setService",
        payload: {
          value: state.service.value.map((item) => ({ ...item, _extend: { ...item._extend, holder_id: [] } }))
        }
      });
    }
  });
  const { selectCustomer } = (0, import_useCustomer.useCustomer)({
    changeCustomerToGlobalState
  });
  const shopDiscount = (0, import_useShopDiscountModule.useShopDiscountModule)();
  const { clearAllScanListenersTaskQueue } = (0, import_useScanManager.default)();
  const handleClearAllAndReset = () => {
    var _a2, _b2;
    logger.addLog({
      title: "Footer: PaymentOnClose reset 清空所有内容并重置购物车",
      metadata: {}
    });
    clearAllScanListenersTaskQueue();
    (_b2 = (_a2 = window == null ? void 0 : window.shopApi) == null ? void 0 : _a2.bookingTicket) == null ? void 0 : _b2.clearAllCart();
  };
  const setEditCartMode = (order_id2, payData, closeModal = false) => {
    setEditOrderId(order_id2);
    if (closeModal) {
      setIsPaymentModalOpen(false);
    }
    dispatch({
      type: "setService",
      payload: {
        value: state.service.value.map((item) => {
          var _a2;
          return { ...item, edit: true, booking_id: (item == null ? void 0 : item.booking_id) || "0", discount_list: ((_a2 = item.discount_list) == null ? void 0 : _a2.map((d) => ({ ...d, id: d.discount.resource_id }))) || [] };
        })
      }
    });
    dispatch({
      type: "setPaymentPaid",
      payload: {
        value: {
          paidAmount: payData.paidAmount,
          paidAmountWithoutSurcharge: payData.paidAmountWithoutSurcharge
        }
      }
    });
    shopDiscount.loadPrepareConfig({
      customerId: state.client.value.id,
      action: "create",
      with_good_pass: 1,
      with_discount_card: 1
    });
  };
  const [existPayment, setExistPayment] = (0, import_react.useState)([]);
  (0, import_react.useEffect)(() => {
    async function loadEditModePayments() {
      var _a2, _b2, _c2;
      if (!state.isEditTicketMode) return;
      if (!((_a2 = state.bookingDetail) == null ? void 0 : _a2.id)) return;
      setEditOrderId(state.bookingDetail.id);
      const checkoutModule = await pisellos.getModule("checkout");
      const paymentMethodList = await checkoutModule.getPaymentMethodsAsync();
      const onlineStorePaymentCodeList = ["WXPAY", "WECHAT", "ALIPAY", "APPLE_PAY", "CREDIT_CARD_3DS", "CREDIT_CARD_TOKEN", "GOOGLE_PAY", "GOOGLE_PAY_3DS", "CREDIT_CARD"];
      const existPayment2 = (_c2 = (_b2 = state.bookingDetail.payments) == null ? void 0 : _b2.filter((item) => item.status === "paid")) == null ? void 0 : _c2.map((item) => {
        var _a3;
        let paymentMethod = paymentMethodList.find((method) => method.code === item.payment_method);
        if (!paymentMethod && onlineStorePaymentCodeList.includes(item.payment_method)) {
          paymentMethod = {
            id: "",
            name: item.payment_method,
            code: item.payment_method,
            type: item.payment_method
          };
        }
        return {
          uuid: ((_a3 = item == null ? void 0 : item.metadata) == null ? void 0 : _a3.unique_payment_number) || item.pay_number,
          custom_payment_id: paymentMethod.id,
          order_payment_id: item.id,
          name: paymentMethod == null ? void 0 : paymentMethod.name,
          code: item.payment_method,
          type: paymentMethod == null ? void 0 : paymentMethod.type,
          amount: item.origin_amount,
          rounding_amount: item.rounding_amount,
          status: "active",
          order_payment_type: item.type,
          metadata: item.metadata,
          voucher_id: item.voucher_id,
          service_charge: item.service_charge && typeof item.service_charge === "object" && !Array.isArray(item.service_charge) ? item.service_charge : {},
          created_at: item.created_at,
          updated_at: item.updated_at,
          service_fee: item.service_fee
        };
      });
      setExistPayment(existPayment2);
    }
    loadEditModePayments();
  }, [state.isEditTicketMode, (_u = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _u.id]);
  const isActive = (0, import_IsActiveContext.useIsActive)();
  return /* @__PURE__ */ import_react.default.createElement(import_antd.Skeleton, { title: false, round: true, loading: showFooter, active: true }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-footer-total" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-footer-left" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-footer-left-total" }, totalText), /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-footer-left-arrears" }, arrearsText)), /* @__PURE__ */ import_react.default.createElement(
    "span",
    {
      className: "pisell-lowcode__booking-footer-right",
      onClick: () => {
        setShowDetail(!showDetail);
      }
    },
    import_utils.locales.getText("pisell2.text.details"),
    " ",
    /* @__PURE__ */ import_react.default.createElement(
      import_ChevronDown.default,
      {
        className: (0, import_classnames.default)("pisell-lowcode__booking-footer-right-icon", {
          "pisell-lowcode__booking-footer-right-icon-show": showDetail || isSecondaryScreen
        })
      }
    )
  )), /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)("pisell-lowcode__booking-footer-total-detail", {
        "pisell-lowcode__booking-footer-total-detail-show": showDetail || isSecondaryScreen
      })
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "order-total-item-border" }),
    /* @__PURE__ */ import_react.default.createElement(import__.SubTotal, { mode: "column1", list: subTotalList, style: { padding: `0` } }),
    /* @__PURE__ */ import_react.default.createElement("div", { className: state.bookingId ? "order-total-item-border" : "" }),
    !!state.bookingId && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
      import__.SubTotal,
      {
        mode: "column1",
        list: orderTotalList,
        style: { padding: ` 0 0 16px` }
      }
    ))
  ), !isSecondaryScreen && !(state == null ? void 0 : state.disableEventBookingEdit) && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-footer-buttons" }, /* @__PURE__ */ import_react.default.createElement(
    import_FooterMenus.default,
    {
      items: moreButton,
      state,
      dispatch,
      source,
      menuChange
    }
  ), _buttons.length ? _buttons : state.bookingId && isShowPaymentLink ? paymentLinkButton : null), !isSecondaryScreen && source === "info" && state.bookingId && !state.disabledEdit && (transaction_habit_selection == null ? void 0 : transaction_habit_selection.button_rows) == 2 ? /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "pisell-lowcode__booking-footer-buttons",
      style: { marginTop: 12 }
    },
    state.appointment_status !== "cancelled" && !state.isBookingCreatePage && !(0, import_utils2.isDayBooking)(state) ? /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        onClick: () => handleSale(),
        size: "large",
        className: "pisell-lowcode__booking-footer-buttons-item"
      },
      actionMap.sale.label
    ) : null,
    isTeam ? null : /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        onClick: () => handleOrderDetail(),
        size: "large",
        className: "pisell-lowcode__booking-footer-buttons-item"
      },
      actionMap.orderDetail.label
    )
  ) : null, /* @__PURE__ */ import_react.default.createElement(
    import_compensatedPisellContainer.default,
    {
      renderType: isPhoneVariant ? "drawer" : "modal",
      props: isPhoneVariant ? {
        open: terminalWarningOpen,
        placement: "bottom",
        width: "100%",
        height: "auto",
        title: null,
        onClose: () => setTerminalWarningOpen(false),
        footer: /* @__PURE__ */ import_react.default.createElement(
          import_antd.Button,
          {
            block: true,
            type: "primary",
            onClick: () => setTerminalWarningOpen(false)
          },
          import_utils.locales.getText("pisell2.text.ok")
        )
      } : {
        open: terminalWarningOpen,
        title: null,
        onCancel: () => setTerminalWarningOpen(false),
        footer: /* @__PURE__ */ import_react.default.createElement("div", { style: { display: "flex", justifyContent: "flex-end" } }, /* @__PURE__ */ import_react.default.createElement(
          import_antd.Button,
          {
            type: "primary",
            onClick: () => setTerminalWarningOpen(false)
          },
          import_utils.locales.getText("pisell2.text.ok")
        ))
      }
    },
    import_utils.locales.getText("pisell2.text.terminal-edit-message")
  ), /* @__PURE__ */ import_react.default.createElement(import_AppointmentProductModal.default, { ref: appointmentProductRef }), noteModalOpen && /* @__PURE__ */ import_react.default.createElement(
    import_noteModal.default,
    {
      open: noteModalOpen,
      title: import_utils.locales.getText("pisell2.text.add-order-notes"),
      value: ((_v = state.notes) == null ? void 0 : _v.orderNote) || "",
      onConfirm: handleNoteConfirm,
      onDelete: handleNoteDelete,
      onCancel: handleNoteCancel
    }
  ), isPaymentModalOpen && /* @__PURE__ */ import_react.default.createElement(
    import_PaymentModal.default,
    {
      open: true,
      editOrderId,
      variant,
      data: paymentModalData,
      config: {
        showHeaderCenter: true,
        showHeaderRightButton: !state.isEditTicketMode
      },
      callback: paymentCallback || void 0,
      setEditCartMode,
      paymentResultDisplayMode: (_y = (_x = (_w = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _w.config) == null ? void 0 : _x.payment_setting) == null ? void 0 : _y.payment_result_display_mode,
      shopDiscount: state.shop_discount,
      client: (_z = state.client) == null ? void 0 : _z.value,
      currentTotalPrice: total.productAmount,
      onChangeShopDiscount: (discount) => {
        const normalizedDiscountAmount = new import_decimal.default(discount || 0).toDecimalPlaces(2, import_decimal.default.ROUND_DOWN).toString();
        dispatch({
          type: "setState",
          payload: {
            shop_discount: normalizedDiscountAmount
          }
        });
      },
      onChangeOrderNote: handleNoteConfirm,
      onDeleteOrderNote: handleNoteDelete,
      onClose: (reset, options) => {
        var _a2;
        console.log("🔄 Footer: Closing PaymentModal", reset);
        setIsPaymentModalOpen(false);
        window.isPaymentModalPluginOpen = false;
        setPaymentModalData(null);
        setPaymentCallback(null);
        if (reset) {
          handleClearAllAndReset();
        }
        (_a2 = state == null ? void 0 : state.dialogCallback) == null ? void 0 : _a2.call(state, {
          type: "paymentClose",
          reset,
          data: {
            order_id: options == null ? void 0 : options.order_id
          }
        });
        setEditOrderId(0);
      },
      onSetLocalOrderId: (e) => {
        setEditOrderId(e);
      }
    }
  ), isActive && /* @__PURE__ */ import_react.default.createElement(import_confirmHolderModal.ConfirmHolderModal, null));
};
Footer.displayName = "BookingFooter";
var footer_default = (0, import_responsive.withResponsive)(Footer);
