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/plus/saleDetail/components/PromotionAlert/index.tsx
var PromotionAlert_exports = {};
__export(PromotionAlert_exports, {
  PROMOTION_ALERT_ACTION_TYPE: () => PROMOTION_ALERT_ACTION_TYPE,
  PromotionAlert: () => PromotionAlert,
  default: () => PromotionAlert_default,
  hasVisiblePromotionAlert: () => hasVisiblePromotionAlert
});
module.exports = __toCommonJS(PromotionAlert_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_locales = __toESM(require("../../../../components/shoppingCart/locales"));
var import_usePromotionModal = require("../../../../components/shoppingCart/hooks/usePromotionModal");
var import_utils2 = require("../../../../components/shoppingCart/utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_useTranslationOriginal = __toESM(require("../../../../hooks/useTranslationOriginal"));
var import_SalesSdkContext = require("../../../salesSdk/context/SalesSdkContext");
var import_SalesSdkHostBridgesContext = require("../../../salesSdk/context/SalesSdkHostBridgesContext");
var import_SalesSdkUIHostsContext = require("../../../salesSdk/context/SalesSdkUIHostsContext");
var import_useSalesSdkCustomer = require("../../../salesSdk/hooks/useSalesSdkCustomer");
var import_buildBookingEditDrawerState = require("../../../salesSdk/bookingEditService/buildBookingEditDrawerState");
var import_openGiftSkuDetail = require("../../../salesSdk/giftSelect/openGiftSkuDetail");
var import_bookingDate = require("../../../salesSdk/utils/bookingDate");
var import_resolveLocalizedText = require("../../../salesSdk/utils/resolveLocalizedText");
var import_index = require("./index.less");
var PREFIX = "pisell-sale-detail-promotion-alert";
var PROMOTION_ALERT_ACTION_TYPE = "X_ITEMS_FOR_Y_PRICE";
function hasVisiblePromotionAlert(cart) {
  return ((cart == null ? void 0 : cart.unfulfilledPromotions) ?? []).some(
    (item) => (item == null ? void 0 : item.actionType) === PROMOTION_ALERT_ACTION_TYPE
  );
}
function resolveAlertMessage(promotion, translationOriginal) {
  const strategyName = (0, import_resolveLocalizedText.resolveLocalizedText)(promotion.strategyName, translationOriginal);
  const alertFn = import_utils.locales.getText("pisell2.text.shopping-cart.marketing.alert");
  if (typeof alertFn === "function") {
    return alertFn(promotion.needQuantity, strategyName);
  }
  if (typeof alertFn === "string") {
    return alertFn.replace("{strategy}", strategyName).replace("{name}", strategyName).replace("{count}", String(promotion.needQuantity)).replace("{need}", String(promotion.needQuantity));
  }
  return `${strategyName}：还差 ${promotion.needQuantity} 件可享受优惠`;
}
function resolveBrowseProductOptions(promotion, catalogProducts = []) {
  if (Array.isArray(promotion.eligibleProducts) && promotion.eligibleProducts.length > 0) {
    return promotion.eligibleProducts;
  }
  const strategyId = promotion.strategyId;
  if (!strategyId) return [];
  return (catalogProducts || []).filter((item) => {
    var _a;
    const tags = (item == null ? void 0 : item._promotionTags) || ((_a = item == null ? void 0 : item.metadata) == null ? void 0 : _a._promotionTags) || [];
    return tags.some((tag) => String(tag == null ? void 0 : tag.strategyId) === String(strategyId));
  }).map((item) => ({
    product_id: Number((item == null ? void 0 : item.id) ?? (item == null ? void 0 : item.product_id)) || 0,
    product_variant_id: Number(item == null ? void 0 : item.product_variant_id) || 0
  })).filter((item) => item.product_id > 0);
}
function mapUnfulfilledPromotionToLegacyItem(promotion, options) {
  const eligibleProducts = resolveBrowseProductOptions(
    promotion,
    options == null ? void 0 : options.catalogProducts
  );
  const scheduleDate = options == null ? void 0 : options.scheduleDate;
  return {
    ...promotion,
    eligibleProducts,
    products: (0, import_utils2.formatProductsByVariant)(eligibleProducts),
    isMultiple: true,
    isGift: false,
    selected: [],
    selectedProducts: [],
    promotionInfo: promotion,
    state: {
      amountSymbol: (options == null ? void 0 : options.amountSymbol) || "$",
      ...scheduleDate && (0, import_dayjs.default)(scheduleDate).isValid() ? { date: { value: (0, import_dayjs.default)(scheduleDate) } } : {}
    }
  };
}
var PromotionAlert = ({ context, className }) => {
  var _a, _b, _c, _d, _e, _f;
  const salesFromContext = context == null ? void 0 : context.sales;
  const salesFromProvider = (0, import_react.useContext)(import_SalesSdkContext.SalesSdkContext);
  const sales = salesFromContext ?? salesFromProvider;
  const customer = (0, import_useSalesSdkCustomer.useSalesSdkCustomer)();
  const uiHosts = (0, import_SalesSdkUIHostsContext.useSalesSdkUIHosts)();
  const hostBridges = (0, import_SalesSdkHostBridgesContext.useSalesSdkHostBridges)();
  const translationOriginal = (0, import_useTranslationOriginal.default)();
  const engineContext = (0, import_useEngineContext.default)();
  const locale = ((_e = (_d = (_c = (_b = (_a = engineContext.appHelper.utils) == null ? void 0 : _a.getApp) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.locales) == null ? void 0 : _d.getLocale) == null ? void 0 : _e.call(_d)) || "en";
  const promotions = (0, import_react.useMemo)(() => {
    var _a2;
    if (!hasVisiblePromotionAlert(context == null ? void 0 : context.cart)) return [];
    return (((_a2 = context == null ? void 0 : context.cart) == null ? void 0 : _a2.unfulfilledPromotions) ?? []).filter(
      (item) => (item == null ? void 0 : item.actionType) === PROMOTION_ALERT_ACTION_TYPE
    );
  }, [(_f = context == null ? void 0 : context.cart) == null ? void 0 : _f.unfulfilledPromotions]);
  (0, import_react.useEffect)(() => {
    import_utils.locales.init(import_locales.default, locale);
  }, [locale]);
  const handlePromotionBrowseConfirm = (0, import_ahooks.useMemoizedFn)(
    async ({ selectedProducts }) => {
      var _a2;
      const addProductWithFlow = (_a2 = context == null ? void 0 : context.cart) == null ? void 0 : _a2.addProductWithFlow;
      if (!addProductWithFlow || !(selectedProducts == null ? void 0 : selectedProducts.length)) return;
      for (const product of selectedProducts) {
        await addProductWithFlow(product, { type: "select" });
      }
    }
  );
  const openPromotionSkuDetailHost = (0, import_ahooks.useMemoizedFn)(
    async ({ product, selected, currentItem, onComplete }) => {
      var _a2, _b2, _c2, _d2, _e2, _f2, _g, _h;
      const flowDate = (0, import_bookingDate.formatBookingDateTime)(((_b2 = (_a2 = sales == null ? void 0 : sales.bookingTicket) == null ? void 0 : _a2.getBookingDate) == null ? void 0 : _b2.call(_a2)) ?? null);
      const customerId = (0, import_buildBookingEditDrawerState.resolveAddFlowCustomerId)(
        (sales == null ? void 0 : sales.tempOrder) ?? null,
        (_c2 = customer.selected) == null ? void 0 : _c2.id,
        (_f2 = (_e2 = (_d2 = sales == null ? void 0 : sales.bookingTicket) == null ? void 0 : _d2.getOrderCustomerSnapshot) == null ? void 0 : _e2.call(_d2)) == null ? void 0 : _f2.id
      );
      await (0, import_openGiftSkuDetail.openGiftSkuDetail)({
        product,
        selected,
        currentItem,
        bookingTicket: (sales == null ? void 0 : sales.bookingTicket) ?? null,
        uiHosts,
        normalProductDetailBridge: hostBridges.normalProductDetail,
        customerId,
        date: flowDate,
        bookingConfig: ((_h = (_g = sales == null ? void 0 : sales.bookingTicket) == null ? void 0 : _g.getBookingConfig) == null ? void 0 : _h.call(_g)) ?? null,
        tempOrder: (sales == null ? void 0 : sales.tempOrder) ?? null,
        onComplete
      });
    }
  );
  const { openModal, MarketingModal } = (0, import_usePromotionModal.usePromotionModal)({
    onConfirm: handlePromotionBrowseConfirm,
    openGiftSkuDetail: openPromotionSkuDetailHost
  });
  const handleBrowseItems = (0, import_ahooks.useMemoizedFn)((promotion) => {
    var _a2, _b2, _c2, _d2, _e2, _f2;
    const catalogProducts = ((_c2 = (_b2 = (_a2 = sales == null ? void 0 : sales.bookingTicket) == null ? void 0 : _a2.getProductCatalog) == null ? void 0 : _b2.call(_a2)) == null ? void 0 : _c2.products) ?? [];
    const scheduleDate = (0, import_bookingDate.formatBookingDateTime)(((_e2 = (_d2 = sales == null ? void 0 : sales.bookingTicket) == null ? void 0 : _d2.getBookingDate) == null ? void 0 : _e2.call(_d2)) ?? null);
    const amountSymbol = ((_f2 = sales == null ? void 0 : sales.tempOrder) == null ? void 0 : _f2.currency_symbol) || "$";
    openModal(
      mapUnfulfilledPromotionToLegacyItem(promotion, {
        catalogProducts,
        scheduleDate,
        amountSymbol
      })
    );
  });
  const items = (0, import_react.useMemo)(
    () => promotions.map((promotion) => ({
      key: promotion.strategyId,
      promotion,
      message: resolveAlertMessage(promotion, translationOriginal)
    })),
    [promotions, translationOriginal]
  );
  if (items.length === 0) return null;
  const AlertView = import_materials.PisellAlert;
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: [PREFIX, className].filter(Boolean).join(" ") }, /* @__PURE__ */ import_react.default.createElement("div", null, items.map((item) => /* @__PURE__ */ import_react.default.createElement(
    AlertView,
    {
      key: item.key,
      type: "error",
      description: item.message,
      action: /* @__PURE__ */ import_react.default.createElement(
        "button",
        {
          type: "button",
          className: `${PREFIX}__browse-button`,
          onClick: () => handleBrowseItems(item.promotion)
        },
        /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell2.text.shopping-cart.marketing.browse.items")),
        /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-arrow-right" })
      )
    }
  )))), MarketingModal);
};
var PromotionAlert_default = PromotionAlert;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PROMOTION_ALERT_ACTION_TYPE,
  PromotionAlert,
  hasVisiblePromotionAlert
});
