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/actionButtons/index.tsx
var actionButtons_exports = {};
__export(actionButtons_exports, {
  default: () => actionButtons_default
});
module.exports = __toCommonJS(actionButtons_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_decimal = __toESM(require("decimal.js"));
var import_icon = require("@pisell/icon");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_dayjs = __toESM(require("dayjs"));
var import_clearCartModal = __toESM(require("../clearCartModal"));
var import_customiseItemModal = __toESM(require("../customiseItemModal"));
var import_voucherModal = __toESM(require("../voucherModal"));
var import_amount = require("../footer/amount");
var import_index = require("./index.less");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_useScanManager = __toESM(require("../../../ticketBooking/hooks/pisellos/useScanManager"));
var import_priceKeyboard = require("../../../../pro/priceKeyboard");
var import_pisellos = require("../../../ticketBooking/hooks/pisellos");
var import_useShopDiscountModule = require("../../../ticketBooking/hooks/pisellos/useShopDiscountModule");
var import_useLogger = __toESM(require("../../../../hooks/useLogger"));
var import_useCartChangeEffect = __toESM(require("../../../ticketBooking/hooks/pisellos/useCartChangeEffect"));
var createToastContent = (text) => /* @__PURE__ */ import_react.default.createElement("div", { className: "action-buttons-toast-content" }, text);
var ActionButtons = ({
  state,
  dispatch,
  disabled = false,
  source
}) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
  const [showClearModal, setShowClearModal] = (0, import_react.useState)(false);
  const [showPriceAdjustModal, setShowPriceAdjustModal] = (0, import_react.useState)(false);
  const [showCustomiseModal, setShowCustomiseModal] = (0, import_react.useState)(false);
  const [showVoucherModal, setShowVoucherModal] = (0, import_react.useState)(false);
  const { onCartChange } = (0, import_useCartChangeEffect.default)();
  const { executeIfActive } = (0, import_pisellos.useActiveExecute)();
  const context = (0, import_useEngineContext.default)();
  const { getData, pisellosAllModule } = (_a = context.appHelper) == null ? void 0 : _a.utils;
  const Toast = (0, import_materials.useToast)();
  const pisellOS = (0, import_useEngineContext.usePisellOS)();
  const bookingTicket = (0, import_pisellos.useBookingTicket)();
  const { ScheduleModule } = pisellosAllModule;
  const shopDiscount = (0, import_useShopDiscountModule.useShopDiscountModule)();
  const logger = (0, import_useLogger.default)();
  const { clearAllScanListenersTaskQueue } = (0, import_useScanManager.default)();
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const handleCustomerSelected = () => {
      dispatch({
        type: "setState",
        payload: {
          shop_discount: "0"
        }
      });
    };
    const wrappedHandleCustomerSelected = executeIfActive(handleCustomerSelected);
    bookingTicket.effectsOn(
      "onCustomerSelected",
      wrappedHandleCustomerSelected
    );
    return () => {
      bookingTicket.effectsOff(
        "onCustomerSelected",
        wrappedHandleCustomerSelected
      );
    };
  }, [dispatch, bookingTicket]);
  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 hasCartItems = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2;
    return (((_b2 = (_a2 = state == null ? void 0 : state.service) == null ? void 0 : _a2.value) == null ? void 0 : _b2.length) || 0) + (((_d2 = (_c2 = state == null ? void 0 : state.addons) == null ? void 0 : _c2.value) == null ? void 0 : _d2.length) || 0) > 0;
  }, [(_b = state == null ? void 0 : state.service) == null ? void 0 : _b.value, (_c = state == null ? void 0 : state.addons) == null ? void 0 : _c.value]);
  const isDisabledEdit = (0, import_react.useMemo)(() => {
    return disabled || (state == null ? void 0 : state.disabledEdit) || (state == null ? void 0 : state.channelDisabledEdit);
  }, [disabled, state == null ? void 0 : state.disabledEdit, state == null ? void 0 : state.channelDisabledEdit]);
  const currentTotalPrice = (0, import_react.useMemo)(() => {
    if (!hasCartItems) return 0;
    try {
      const { productAmount } = (0, import_amount.getSumTotal)(state, {
        isEdit: true,
        ScheduleModule,
        ...getDataFromHost()
      });
      return productAmount;
    } catch (error) {
      console.error("计算总价失败:", error);
      return 0;
    }
  }, [state, hasCartItems]);
  const currentTotalPriceAfterDiscount = (0, import_react.useMemo)(() => {
    return new import_decimal.default(currentTotalPrice).minus(state.shop_discount || 0).toNumber();
  }, [state.shop_discount, currentTotalPrice]);
  const [discountList, setDiscountList] = (0, import_react.useState)([]);
  const usedVouchersCount = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    try {
      if (!((_b2 = (_a2 = state.service) == null ? void 0 : _a2.value) == null ? void 0 : _b2.length)) {
        return 0;
      }
      return discountList.filter((discount) => discount.isSelected).length;
    } catch (error) {
      console.error("计算已使用券数量失败:", error);
      return 0;
    }
  }, [discountList, (_d = state.service) == null ? void 0 : _d.value]);
  const shouldShowWarning = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    try {
      return ((_b2 = (_a2 = state.service) == null ? void 0 : _a2.value) == null ? void 0 : _b2.length) > 0 && discountList.length > 0 && !discountList.some((discount) => discount.isSelected) && discountList.some((discount) => discount.isManualSelect);
    } catch (error) {
      console.error("判断警告状态失败:", error);
      return false;
    }
  }, [discountList, (_e = state.service) == null ? void 0 : _e.value]);
  (0, import_react.useEffect)(() => {
    var _a2;
    const { pisellos } = ((_a2 = context.appHelper) == null ? void 0 : _a2.utils) || {};
    if (!pisellos || !shopDiscount) return;
    const onDiscountListChange = (discount) => {
      setDiscountList(discount);
    };
    const wrappedHandler = executeIfActive(onDiscountListChange);
    shopDiscount.effectsOn(
      "onDiscountListChange",
      wrappedHandler
    );
    return () => {
      shopDiscount.effectsOff(
        "onDiscountListChange",
        wrappedHandler
      );
    };
  }, [(_f = context.appHelper) == null ? void 0 : _f.utils]);
  const handleClear = () => {
    setShowClearModal(true);
  };
  const handleClearItemsOnly = () => {
    logger.addLog({
      title: "ActionButtons: handleClearItemsOnly 调用",
      metadata: {}
    });
    clearAllScanListenersTaskQueue();
    if (!hasCartItems) {
      Toast == null ? void 0 : Toast.info(
        createToastContent(
          import_utils.locales.getText("pisell2.clear-cart-modal.empty-cart-tip")
        )
      );
      return;
    }
    dispatch({
      type: "setService",
      payload: {
        value: []
      }
    });
    onCartChange("clearAll", []);
    dispatch({
      type: "setAddons",
      payload: {
        value: []
      }
    });
    dispatch({
      type: "setState",
      payload: {
        shop_discount: "0"
      }
    });
    dispatch({
      type: "setPaymentPaid",
      payload: {
        value: {}
      }
    });
    setShowClearModal(false);
    Toast == null ? void 0 : Toast.success(
      createToastContent(
        import_utils.locales.getText("pisell2.action-buttons.clear-success")
      )
    );
  };
  const handleClearAllAndReset = () => {
    var _a2, _b2;
    logger.addLog({
      title: "ActionButtons: handleClearAllAndReset 调用",
      metadata: {}
    });
    clearAllScanListenersTaskQueue();
    (_b2 = (_a2 = window == null ? void 0 : window.shopApi) == null ? void 0 : _a2.bookingTicket) == null ? void 0 : _b2.clearAllCart();
    onCartChange("clearAll", []);
    setShowClearModal(false);
    Toast == null ? void 0 : Toast.success(
      createToastContent(
        import_utils.locales.getText("pisell2.action-buttons.clear-success")
      )
    );
  };
  const handleManuelOrder = () => {
    if (!hasCartItems) {
      Toast == null ? void 0 : Toast.info(
        createToastContent(
          import_utils.locales.getText("pisell2.action-buttons.no-items-to-adjust")
        )
      );
      return;
    }
    setShowPriceAdjustModal(true);
  };
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2;
    if (((_b2 = (_a2 = state.service) == null ? void 0 : _a2.value) == null ? void 0 : _b2.length) === 0 && ((_d2 = (_c2 = state.addons) == null ? void 0 : _c2.value) == null ? void 0 : _d2.length) === 0) {
      dispatch({
        type: "setState",
        payload: {
          shop_discount: 0
        }
      });
    }
  }, [(_g = state.service) == null ? void 0 : _g.value, (_h = state.addons) == null ? void 0 : _h.value]);
  const handlePriceAdjustConfirm = (discountAmount) => {
    const normalizedDiscountAmount = new import_decimal.default(discountAmount || 0).toDecimalPlaces(2, import_decimal.default.ROUND_DOWN).toString();
    dispatch({
      type: "setState",
      payload: {
        shop_discount: normalizedDiscountAmount
      }
    });
    setShowPriceAdjustModal(false);
    Toast == null ? void 0 : Toast.success(
      createToastContent(
        import_utils.locales.getText("pisell2.action-buttons.price-adjusted-success")
      )
    );
  };
  const handleCustomiseItem = () => {
    setShowCustomiseModal(true);
  };
  const handleGoodPassClick = () => {
    setShowVoucherModal(true);
  };
  const handleCustomiseItemSave = (data) => {
    var _a2;
    console.log("保存自定义商品:", data);
    const customItem = {
      // 基础商品信息（按照 service2/utils.ts 693-730 行格式，但简化）
      id: `custom_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      // 前端使用 UUID，避免 React diff key 重复
      _id: `custom_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      // 生成唯一ID
      title: data.productName,
      name: data.productName,
      price: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1),
      total: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1),
      num: data.quantity,
      is_bundle: 0,
      // 自定义商品特殊标识
      isCustomItem: true,
      vouchersApplicable: data.vouchersApplicable,
      // 是否适用优惠券/折扣
      // 后端需要的完整格式存储在 _extend 中
      _extend: {
        num: data.quantity,
        price: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1),
        product_id: 0,
        discount_amount: 0,
        product_discount_reason: "",
        name: data.productName,
        note: "",
        discountway: "num",
        discount_type: data.priceType === "deduction" ? "discount" : "normal",
        order_detail_id: 0,
        startDate: (0, import_dayjs.default)(),
        endDate: (0, import_dayjs.default)(),
        // 保留一些必要的购物车字段
        quantity: data.quantity,
        total: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1),
        origin_total: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1)
      },
      new: 1
    };
    const currentServices = ((_a2 = state == null ? void 0 : state.service) == null ? void 0 : _a2.value) || [];
    const updatedServices = [customItem, ...currentServices];
    dispatch({
      type: "setService",
      payload: {
        value: updatedServices,
        changeService: false
      }
    });
    setShowCustomiseModal(false);
    Toast == null ? void 0 : Toast.success(
      createToastContent(import_utils.locales.getText("pisell2.customise-item.save-success"))
    );
  };
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__action-buttons" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      className: "action-button clear-button",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icon.Trash01, { size: 22 }),
      onClick: handleClear,
      type: "text",
      disabled: isDisabledEdit
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      className: "action-button customise-button",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icon.PlusCircle, { size: 22 }),
      onClick: handleCustomiseItem,
      type: "text",
      disabled: isDisabledEdit
    },
    import_utils.locales.getText("pisell2.action-buttons.customise-item")
  ), /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      className: "action-button manuel-button",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icon.Calculator, { size: 22 }),
      onClick: handleManuelOrder,
      type: "text",
      disabled: isDisabledEdit
    },
    import_utils.locales.getText("pisell2.action-buttons.manuel-order")
  ), /* @__PURE__ */ import_react.default.createElement("div", { className: "action-button-wrapper" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      className: "action-button goodpass-button",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icon.Sale03, { size: 22 }),
      onClick: handleGoodPassClick,
      type: "text"
    },
    import_utils.locales.getText("pisell2.text.goodpass")
  ), usedVouchersCount > 0 && /* @__PURE__ */ import_react.default.createElement("div", { className: "voucher-badge" }, usedVouchersCount), shouldShowWarning && /* @__PURE__ */ import_react.default.createElement("div", { className: "voucher-warning-icon" }, "!"))), /* @__PURE__ */ import_react.default.createElement(
    import_clearCartModal.default,
    {
      visible: showClearModal,
      onCancel: () => setShowClearModal(false),
      onClearItemsOnly: handleClearItemsOnly,
      onClearAllAndReset: handleClearAllAndReset
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_priceKeyboard.DiscountKeyboard,
    {
      containerProps: {
        renderType: "modal",
        open: showPriceAdjustModal,
        onCancel: () => setShowPriceAdjustModal(false)
      },
      selectType: "dark",
      originalValue: currentTotalPrice,
      defaultValue: currentTotalPriceAfterDiscount,
      onEnter: handlePriceAdjustConfirm
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_customiseItemModal.default,
    {
      visible: showCustomiseModal,
      onClose: () => setShowCustomiseModal(false),
      onSave: handleCustomiseItemSave,
      currencySymbol: ((_k = (_j = (_i = context.appHelper) == null ? void 0 : _i.utils) == null ? void 0 : _j.getSymbolic) == null ? void 0 : _k.call(_j)) || "$",
      disabled: isDisabledEdit
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_voucherModal.default,
    {
      visible: showVoucherModal,
      onClose: () => setShowVoucherModal(false),
      state,
      dispatch,
      source
    }
  ));
};
var actionButtons_default = ActionButtons;
