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_react_dom = require("react-dom");
var import_antd = require("antd");
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_utils2 = require("@pisell/utils");
var import_index = require("./index.less");
var import_useCustomer = require("../../../ticketBooking/hooks/pisellos/useCustomer");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_useScanManager = __toESM(require("../../../ticketBooking/hooks/pisellos/useScanManager"));
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;
  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 context = (0, import_useEngineContext.default)();
  const Toast = (_b = (_a = context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.Toast;
  const pisellOS = (0, import_useEngineContext.usePisellOS)();
  const { selectCustomer } = (0, import_useCustomer.useCustomer)();
  const { clearAllScanListenersTaskQueue } = (0, import_useScanManager.default)();
  (0, import_react.useEffect)(() => {
    if (!pisellOS) return;
    const handleCustomerSelected = () => {
      dispatch({
        type: "setState",
        payload: {
          shop_discount: "0"
        }
      });
    };
    pisellOS.effects.on("bookingTicket:onCustomerSelected", handleCustomerSelected);
    return () => {
      pisellOS.effects.off("bookingTicket:onCustomerSelected", handleCustomerSelected);
    };
  }, [dispatch, pisellOS]);
  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;
  }, [(_c = state == null ? void 0 : state.service) == null ? void 0 : _c.value, (_d = state == null ? void 0 : state.addons) == null ? void 0 : _d.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 { expectAmount } = (0, import_amount.getSumTotal)(state, true);
      return expectAmount;
    } catch (error) {
      console.error("计算总价失败:", error);
      return 0;
    }
  }, [state, hasCartItems]);
  const currentOriginTotalPrice = (0, import_react.useMemo)(() => {
    if (!hasCartItems) return 0;
    const { originExpectAmount } = (0, import_amount.getSumTotal)(state, true);
    return originExpectAmount;
  }, [state, hasCartItems]);
  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, (_e = state.service) == null ? void 0 : _e.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, (_f = state.service) == null ? void 0 : _f.value]);
  (0, import_react.useEffect)(() => {
    var _a2;
    const { pisellos } = ((_a2 = context.appHelper) == null ? void 0 : _a2.utils) || {};
    if (!pisellos) return;
    const onDiscountListChange = (discount) => {
      setDiscountList(discount);
    };
    pisellos.effects.on("shopDiscount:onDiscountListChange", onDiscountListChange);
    return () => {
      pisellos.effects.off("shopDiscount:onDiscountListChange", onDiscountListChange);
    };
  }, [(_g = context.appHelper) == null ? void 0 : _g.utils]);
  const handleClear = () => {
    setShowClearModal(true);
  };
  const handleClearItemsOnly = () => {
    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: []
      }
    });
    dispatch({
      type: "setAddons",
      payload: {
        value: []
      }
    });
    dispatch({
      type: "setState",
      payload: {
        shop_discount: "0"
      }
    });
    setShowClearModal(false);
    Toast == null ? void 0 : Toast.success(createToastContent(import_utils.locales.getText("pisell2.action-buttons.clear-success")));
  };
  const handleClearAllAndReset = () => {
    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: ""
      }
    });
    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);
  };
  const handlePriceAdjustConfirm = (newPrice) => {
    const { productAmount } = (0, import_amount.getSumTotal)(state, true);
    const discountAmount = Math.max(0, productAmount - newPrice);
    const discountAmountStr = (0, import_utils2.formatAmount)(discountAmount, 2, "");
    dispatch({
      type: "setState",
      payload: {
        shop_discount: discountAmountStr
      }
    });
    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
    }
  ), showPriceAdjustModal && (0, import_react_dom.createPortal)(
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-price-adjust-overlay" }, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "pisell-price-adjust-backdrop",
        onMouseDown: (e) => {
          e.preventDefault();
          setShowPriceAdjustModal(false);
        }
      }
    ), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-price-adjust-container" }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellAdjustPrice,
      {
        selectType: "dark",
        originValue: currentOriginTotalPrice,
        value: currentTotalPrice,
        onChange: handlePriceAdjustConfirm
      }
    ))),
    document.body
  ), /* @__PURE__ */ import_react.default.createElement(
    import_customiseItemModal.default,
    {
      visible: showCustomiseModal,
      onClose: () => setShowCustomiseModal(false),
      onSave: handleCustomiseItemSave,
      currencySymbol: ((_j = (_i = (_h = context.appHelper) == null ? void 0 : _h.utils) == null ? void 0 : _i.getSymbolic) == null ? void 0 : _j.call(_i)) || "$",
      disabled: isDisabledEdit
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_voucherModal.default,
    {
      visible: showVoucherModal,
      onClose: () => setShowVoucherModal(false),
      state,
      dispatch,
      source
    }
  ));
};
var actionButtons_default = ActionButtons;
