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/scanOrder/components/Menu/index.tsx
var Menu_exports = {};
__export(Menu_exports, {
  default: () => Menu
});
module.exports = __toCommonJS(Menu_exports);
var import_react = __toESM(require("react"));
var import_productSelect = __toESM(require("../../../../plus/productSelect"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_context = require("../../context");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_transformProductDetail = require("../../utils/transformProductDetail");
function Menu(props) {
  var _a;
  const { onCheckout, productList, isProductListLoading, onEnsureProductList } = props;
  const context = (0, import_useEngineContext.default)();
  const { utils } = context.appHelper || {};
  const {
    runModuleAction,
    refreshViewModel,
    viewModel
  } = (0, import_context.useScanOrderContext)();
  const [dineInConfig, setDineInConfig] = (0, import_react.useState)(null);
  const getConfig = (0, import_react.useCallback)(async () => {
    const otherParams = await runModuleAction("getOtherParams");
    console.log("otherParams >>>>> ", otherParams);
    const dineInConfig2 = (otherParams == null ? void 0 : otherParams.dineInConfig) ?? {};
    setDineInConfig(dineInConfig2);
  }, [runModuleAction]);
  (0, import_react.useEffect)(() => {
    getConfig();
  }, []);
  (0, import_react.useEffect)(() => {
    void onEnsureProductList();
  }, [onEnsureProductList]);
  const scrollRef = (0, import_react.useRef)(null);
  const isMobileView = (0, import_utils.isMobile)();
  const height = window.innerHeight - 100;
  const addOrderProduct = async (params) => {
    const { orderProduct, sourceData } = params;
    try {
      await runModuleAction("addProductToOrder", orderProduct);
      await refreshViewModel();
    } catch (error) {
      console.error("[scanOrder] 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("[scanOrder] 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("[scanOrder] updateProductInOrder failed", {
        error,
        sourceData,
        product_id,
        product_variant_id,
        identity_key,
        updates
      });
    }
  };
  const handleSelectProduct = async (item, clickType, meta) => {
    console.log(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("[scanOrder] 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("[scanOrder] 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: false }
        },
        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("[scanOrder] 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: isProductListLoading,
      emptyDescription: import_utils.locales.getText(
        "pisell2.scan.order.empty.product"
      ),
      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: "#scan-order-v2-cart-btn"
    }
  );
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-menu" }, /* @__PURE__ */ import_react.default.createElement(import_materials.PisellScrollView, { height, overflow: "y", ref: scrollRef }, productSelectNode));
}
