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__ = 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_hooks = require("../../../appointmentBooking/hooks");
var Footer = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
  const { state, buttons, dispatch, source } = props;
  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 [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;
  (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"]);
      }
    });
  }, []);
  (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, (_b = state.paymentPaid) == null ? void 0 : _b.value]);
  const [modal, contextHolder] = import_antd.Modal.useModal();
  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) || {};
  }, [(_e = (_d = (_c = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _c.config) == null ? void 0 : _d.basic) == null ? void 0 : _e.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
    };
  }, [(_g = (_f = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _f.config) == null ? void 0 : _g.information_tab]);
  const addonsEdit = (0, import_react.useMemo)(() => {
    var _a2;
    if ((_a2 = state.addons) == null ? void 0 : _a2.edit) {
      return true;
    }
    return false;
  }, [(_h = state.addons) == null ? void 0 : _h.edit]);
  const infoEdit = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2, _e2, _f2;
    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;
    }
    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]);
  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, (_i = state.bookingDetail) == null ? void 0 : _i.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, (_j = state.bookingDetail) == null ? void 0 : _j.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 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, total_amount: totalAmount },
        callback: (res) => {
          var _a3, _b3, _c2, _d2;
          console.log("webpos_pay_result", res);
          if ((res == null ? void 0 : res.status) === "success") {
            (_b3 = (_a3 = window == null ? void 0 : window.shopApi) == null ? void 0 : _a3.bookingTicket) == null ? void 0 : _b3.clearAllCart();
          } else if ((res == null ? void 0 : res.status) === "cancel") {
            (_d2 = (_c2 = window == null ? void 0 : window.shopApi) == null ? void 0 : _c2.booking) == null ? void 0 : _d2.voidBooking(order_id2);
          } else {
          }
        }
      });
      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 {
        console.log(
          "🔄 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
            }
          };
          if (JSON.stringify(modalData) === JSON.stringify(paymentModalData)) {
            return;
          }
          setPaymentModalData(modalData);
        }
      } catch (error) {
      }
    })();
  }, [
    JSON.stringify(total),
    JSON.stringify(orderTotalList),
    JSON.stringify(subTotalList),
    (_l = (_k = state.client) == null ? void 0 : _k.value) == null ? void 0 : _l.id
  ]);
  const handleCheckout = async () => {
    (0, import_PaymentResultToast.closeAllPaymentResultToasts)();
    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
          }
        };
        setPaymentModalData(modalData);
        setIsPaymentModalOpen(true);
        setCheckoutLoading(false);
        setPaymentCallback(() => (paymentResult) => {
          var _a2, _b2, _c2, _d2;
          console.log("Payment result:", paymentResult);
          setIsPaymentModalOpen(false);
          if ((paymentResult == null ? void 0 : paymentResult.status) === "success") {
            console.log("Payment completed successfully");
            (_b2 = (_a2 = window == null ? void 0 : window.shopApi) == null ? void 0 : _a2.bookingTicket) == null ? void 0 : _b2.clearAllCart();
            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 = (_c2 = window == null ? void 0 : window.shopApi) == null ? void 0 : _c2.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 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 handleSave = async ({
    type,
    messageShow = true,
    noSubmit = false
  }) => {
    var _a2;
    (0, import_PaymentResultToast.closeAllPaymentResultToasts)();
    if ((0, import_utils2.isDayBooking)(state)) {
      const isHasDayProducts = handleDaySubmit();
      if (isHasDayProducts) return;
    }
    if (isBooking4Shop && (0, import_utils2.getIsSubjectRequire)(state) && (0, import_utils3.checkHolderIsError)(state)) {
      return;
    }
    let _setLoading = type === "checkout" ? setCheckoutLoading : setLoading;
    _setLoading(true);
    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 ((_a2 = state == null ? void 0 : state.onSave) == null ? void 0 : _a2.call(state, state.client)) || {};
    }
    try {
      let callbackData = null;
      let values = (0, import_utils3.formatValues)({ ...state, ...saveOtherValue });
      values.product_tax_fee = total.tax || 0;
      if (noSubmit) {
        return values;
      }
      if (editOrderId) {
        const checkout = pisellos.getModule("checkout");
        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);
        }
        return;
      }
      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") }
        ]
      });
      if (addonsEdit) {
        await handleSaveAddons();
      }
      if (infoEdit) {
        callbackData = await api(values, state.bookingId || editOrderId);
        if (messageShow) {
          import_antd.message.success(
            import_utils.locales.getText(
              state.bookingId ? "pisell2.text.appointment-updated" : "pisell2.text.created-successfully"
            )
          );
        }
      }
      state == null ? void 0 : state.callback(callbackData, type);
      _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);
      }
      _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 || 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 (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) {
      modal.warning({
        okText: import_utils.locales.getText("pisell2.text.ok"),
        content: import_utils.locales.getText("pisell2.text.terminal-edit-message")
      });
      return;
    }
    setActiveTab == null ? void 0 : setActiveTab("addons");
  };
  const handlePrint = () => {
  };
  const handleOrderDetail = () => {
    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;
  }, [(_m = state == null ? void 0 : state.notes) == null ? void 0 : _m.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;
    let list = [
      "unfulfilled",
      "partially_paid",
      "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) && !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,
    (_n = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _n.payment_status
  ]);
  const totalText = (0, import_react.useMemo)(() => {
    var _a2;
    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) {
      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) {
      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]);
  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,
    (_o = state.addons) == null ? void 0 : _o.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) => {
    dispatch({
      type: "setClient",
      payload: {
        value,
        edit: true
      }
    });
  });
  const { selectCustomer } = (0, import_useCustomer.useCustomer)({
    changeCustomerToGlobalState
  });
  const shopDiscount = (0, import_hooks.useShopDiscount)();
  const { clearAllScanListenersTaskQueue } = (0, import_useScanManager.default)();
  const handleClearAllAndReset = () => {
    var _a2;
    clearAllScanListenersTaskQueue();
    dispatch({
      type: "setService",
      payload: {
        value: []
      }
    });
    dispatch({
      type: "setAddons",
      payload: {
        value: []
      }
    });
    selectCustomer(null);
    dispatch({
      type: "setDate",
      payload: {
        value: (0, import_dayjs.default)(),
        // 当前时间
        end_date: (0, import_dayjs.default)().add(1, "days")
        // 明天
      }
    });
    dispatch({
      type: "setPet",
      payload: {
        holders: [],
        value: {}
      }
    });
    dispatch({
      type: "setNotes",
      payload: {
        value: "",
        orderNote: ""
      }
    });
    (_a2 = shopDiscount == null ? void 0 : shopDiscount.clear) == null ? void 0 : _a2.call(shopDiscount);
    setEditOrderId(0);
  };
  const setEditCartMode = (order_id2, payData, closeModal = false) => {
    setEditOrderId(order_id2);
    if (closeModal) {
      setIsPaymentModalOpen(false);
    }
    dispatch({
      type: "setService",
      payload: {
        value: state.service.value.map((item) => ({ ...item, edit: true, booking_id: "checkout_edit", discount_list: item.discount_list.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
    });
  };
  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
        })
      }
    )
  )), /* @__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
      })
    },
    /* @__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` }
      }
    ))
  ), !(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), 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, contextHolder, /* @__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: ((_p = state.notes) == null ? void 0 : _p.orderNote) || "",
      onConfirm: handleNoteConfirm,
      onDelete: handleNoteDelete,
      onCancel: handleNoteCancel
    }
  ), isPaymentModalOpen && /* @__PURE__ */ import_react.default.createElement(
    import_PaymentModal.default,
    {
      open: true,
      editOrderId,
      data: paymentModalData,
      callback: paymentCallback || void 0,
      setEditCartMode,
      state,
      dispatch,
      onClose: (reset) => {
        setIsPaymentModalOpen(false);
        setPaymentModalData(null);
        setPaymentCallback(null);
        setEditOrderId(0);
        dispatch({
          type: "setPaymentPaid",
          payload: {
            value: {}
          }
        });
        if (reset) {
          setTimeout(() => {
            handleClearAllAndReset();
          }, 0);
        }
      }
    }
  ));
};
var footer_default = Footer;
