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/venueBooking/components/Addons/index.tsx
var Addons_exports = {};
__export(Addons_exports, {
  default: () => Addons
});
module.exports = __toCommonJS(Addons_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_productSelect = __toESM(require("../../../../plus/productSelect"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_context = require("../../context");
var import_transformProductDetail = require("../../utils/transformProductDetail");
var import_index = require("./index.less");
function Addons() {
  var _a;
  const context = (0, import_useEngineContext.default)();
  const { utils } = context.appHelper || {};
  const {
    runModuleAction,
    refreshViewModel,
    viewModel,
    goToStep
  } = (0, import_context.useVenueBookingContext)();
  const productList = viewModel.addonProductList || [];
  const scrollRef = (0, import_react.useRef)(null);
  const isMobileView = (0, import_utils.isMobile)();
  const maxHeight = window.innerHeight - 100;
  (0, import_react.useEffect)(() => {
    if (productList.length > 0) return;
    const fetchProductList = async () => {
      try {
        const res = await runModuleAction("getAddonProducts");
        if (Array.isArray(res)) {
          refreshViewModel({ addonProductList: res });
        } else {
          import_antd.Modal.confirm({
            title: (res == null ? void 0 : res.message) || String(import_utils.locales.getText("pisell2.venue.error.load.products") || "商品加载失败"),
            okText: String(import_utils.locales.getText("pisell2.event.confirm") || "确认"),
            cancelButtonProps: { style: { display: "none" } },
            maskClosable: false,
            onOk: () => {
              location.replace("/");
            }
          });
        }
      } catch (error) {
        console.error("[venueBooking] getProductList failed", error);
      }
    };
    fetchProductList();
  }, []);
  const addOrderProduct = async (params) => {
    const { orderProduct, sourceData } = params;
    try {
      await runModuleAction("addProductToOrder", orderProduct);
      await refreshViewModel();
    } catch (error) {
      console.error("[venueBooking] addProductToOrder failed", {
        error,
        sourceData,
        mappedData: orderProduct
      });
    }
  };
  const removeOrderProduct = async (params) => {
    const { product_id, product_variant_id, identity_key, sourceData } = params;
    try {
      await runModuleAction("removeProductFromOrder", {
        product_id,
        product_variant_id,
        ...identity_key ? { identity_key } : {}
      });
      await refreshViewModel();
    } catch (error) {
      console.error("[venueBooking] removeProductFromOrder failed", {
        error,
        sourceData,
        product_id,
        product_variant_id,
        identity_key
      });
    }
  };
  const updateOrderProduct = async (params) => {
    const { product_id, product_variant_id, identity_key, updates, sourceData } = params;
    try {
      await runModuleAction("updateProductInOrder", {
        product_id,
        product_variant_id,
        ...identity_key ? { identity_key } : {},
        updates
      });
      await refreshViewModel();
    } catch (error) {
      console.error("[venueBooking] updateProductInOrder failed", {
        error,
        sourceData,
        product_id,
        product_variant_id,
        identity_key,
        updates
      });
    }
  };
  const handleSelectProduct = async (item, clickType, meta) => {
    const sourceItem = (meta == null ? void 0 : meta.product) || item;
    if ((meta == null ? void 0 : meta.intent) === "quantity") {
      const quantityData = {
        ...item,
        quantity: item == null ? void 0 : item.num,
        option: (item == null ? void 0 : item.option) ?? (item == null ? void 0 : item.product_option_item),
        bundle: (item == null ? void 0 : item.bundle) ?? (item == null ? void 0 : item.product_bundle),
        origin: sourceItem,
        price: (item == null ? void 0 : item.price) ?? (item == null ? void 0 : item.selling_price)
      };
      const orderProduct = (0, import_transformProductDetail.transformProductDetailToOrderProduct)({
        payload: quantityData,
        fallbackProductId: (item == null ? void 0 : item.product_id) ?? (item == null ? void 0 : item.id),
        sourceItem
      });
      if (!orderProduct) {
        console.warn("[venueBooking] quantity add missing product_id", quantityData);
        return;
      }
      const nextQuantity = Number((meta == null ? void 0 : meta.quantity) ?? (quantityData == null ? void 0 : quantityData.quantity) ?? 0);
      const productVariantId = Number((orderProduct == null ? void 0 : orderProduct.product_variant_id) ?? 0);
      if (Number.isNaN(productVariantId)) {
        console.warn("[venueBooking] quantity action missing product_variant_id", {
          quantityData,
          orderProduct
        });
        return;
      }
      const normalizedQuantity = Number.isNaN(nextQuantity) ? 0 : Math.max(0, Math.floor(nextQuantity));
      const cartItems = Array.isArray(viewModel == null ? void 0 : viewModel.cartItems) ? viewModel.cartItems : [];
      const existedCartItem = cartItems.find((cartItem) => {
        return String((cartItem == null ? void 0 : cartItem.product_id) ?? null) === String((orderProduct == null ? void 0 : orderProduct.product_id) ?? null) && Number((cartItem == null ? void 0 : cartItem.product_variant_id) ?? 0) === productVariantId;
      });
      const existedIdentityKey = typeof (existedCartItem == null ? void 0 : existedCartItem.identity_key) === "string" && existedCartItem.identity_key.length > 0 ? existedCartItem.identity_key : void 0;
      if (normalizedQuantity <= 0) {
        await removeOrderProduct({
          product_id: (orderProduct == null ? void 0 : orderProduct.product_id) ?? null,
          product_variant_id: productVariantId,
          identity_key: existedIdentityKey,
          sourceData: quantityData
        });
        return;
      }
      if (!existedCartItem) {
        await addOrderProduct({
          orderProduct: { ...orderProduct, num: normalizedQuantity },
          sourceData: quantityData
        });
        return;
      }
      await updateOrderProduct({
        product_id: (orderProduct == null ? void 0 : orderProduct.product_id) ?? null,
        product_variant_id: productVariantId,
        identity_key: existedIdentityKey,
        updates: {
          num: normalizedQuantity,
          _origin: orderProduct == null ? void 0 : orderProduct._origin
        },
        sourceData: quantityData
      });
    } else {
      utils == null ? void 0 : utils.action({
        type: "pisell1.productDetail",
        data: {
          detail: { ...sourceItem, open_deposit: 1 },
          setting: { can_input: true, item_max_length: 1, is_detail_open: true }
        },
        callback: async (data) => {
          if (data == null ? void 0 : data.isCancel) return;
          const orderProduct = (0, import_transformProductDetail.transformProductDetailToOrderProduct)({
            payload: data,
            fallbackProductId: (item == null ? void 0 : item.product_id) ?? (item == null ? void 0 : item.id),
            sourceItem
          });
          if (!orderProduct) {
            console.warn("[venueBooking] productDetail callback missing product_id", data);
            return;
          }
          await addOrderProduct({ orderProduct, sourceData: data });
        }
      });
    }
  };
  const productSelectNode = /* @__PURE__ */ import_react.default.createElement(
    import_productSelect.default,
    {
      dataSource: productList,
      onChange: handleSelectProduct,
      loading: false,
      emptyDescription: import_utils.locales.getText("pisell2.venue.addons.empty"),
      token: {
        colorPrimary: "var(--theme-color)",
        containerBg: "#FFFFFF",
        tabItemBg: "#F2F4F7",
        tabItemHoverBg: "#F2F4F7",
        tabItemActiveBg: "var(--theme-color)",
        categoryTextColor: "#1B1B1B",
        cardSelectedBg: "var(--theme-color)"
      },
      customScrollParent: ((_a = scrollRef.current) == null ? void 0 : _a.getScrollContainer()) || "",
      hideCategoryWhenOne: true,
      version: "v2",
      value: (viewModel == null ? void 0 : viewModel.cartItems) || [],
      productListSetting: {
        imgWidth: 80,
        imgHeight: 80
      },
      cartElementId: "#venue-booking-cart-btn"
    }
  );
  if (isMobileView) {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-addons pisell-venue-booking-addons--mobile" }, productSelectNode);
  }
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-addons" }, /* @__PURE__ */ import_react.default.createElement(import_materials.PisellScrollView, { maxHeight, overflow: "y", ref: scrollRef }, productSelectNode));
}
