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/bigSale/hooks/useSyncBigSaleCartToCds.ts
var useSyncBigSaleCartToCds_exports = {};
__export(useSyncBigSaleCartToCds_exports, {
  useSyncBigSaleCartToCds: () => useSyncBigSaleCartToCds
});
module.exports = __toCommonJS(useSyncBigSaleCartToCds_exports);
var import_react = require("react");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_productSkuOptions = require("../../../plus/salesSdk/utils/productSkuOptions");
var import_formatTime = require("../utils/formatTime");
var EMPTY_CART_UPDATE = {
  total: "0",
  products: [],
  fees: []
};
var UNIT_LABEL = {
  KILOGRAMS: "kg",
  GRAMS: "g",
  POUNDS: "lb",
  OUNCES: "oz"
};
var toArray = (value) => {
  return Array.isArray(value) ? value : [];
};
var getLocale = (utils) => {
  var _a, _b;
  const getApp = utils == null ? void 0 : utils.getApp;
  const app = typeof getApp === "function" ? getApp() : void 0;
  const getLocale2 = (_a = app == null ? void 0 : app.locales) == null ? void 0 : _a.getLocale;
  const storageGet = (_b = utils == null ? void 0 : utils.storage) == null ? void 0 : _b.get;
  return (typeof getLocale2 === "function" ? getLocale2() : void 0) || (typeof storageGet === "function" ? storageGet("umi_locale") : void 0) || "en-US";
};
var getCurrencySymbol = (utils) => {
  const getSymbolic = utils == null ? void 0 : utils.getSymbolic;
  return typeof getSymbolic === "function" ? getSymbolic() : "";
};
var toFiniteNumber = (value, fallback = 0) => {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
};
var callLocaleText = (key, ...args) => {
  const text = import_utils.locales.getText(key);
  return typeof text === "function" ? text(...args) : text;
};
var postCartUpdateToCds = (utils, data) => {
  var _a, _b;
  const postMessageToApp = (_b = (_a = utils == null ? void 0 : utils.interaction) == null ? void 0 : _a.utils) == null ? void 0 : _b.postMessageToApp;
  if (typeof postMessageToApp !== "function") return;
  console.log("postCartUpdateToCds data", data);
  try {
    postMessageToApp({
      module: "cds",
      key: "cartUpdate",
      data
    });
  } catch (error) {
    console.warn("[BigSale] post cart update to CDS failed", error);
  }
};
var isGiftProduct = (product) => {
  var _a;
  return Boolean(
    (product == null ? void 0 : product.gift_card) || (product == null ? void 0 : product.isGift) || (product == null ? void 0 : product._isGiftPromotion) || ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a._giftInfo) || (product == null ? void 0 : product._giftInfo)
  );
};
var getCartProductLines = (cart) => {
  const bookingLines = toArray(
    cart == null ? void 0 : cart.bookings
  ).reduce(
    (lines, booking) => {
      var _a;
      const product = (_a = booking == null ? void 0 : booking._extend) == null ? void 0 : _a.product;
      if (!product) return lines;
      lines.push({
        type: "booking",
        line: booking,
        product
      });
      return lines;
    },
    []
  );
  const productLines = toArray(cart == null ? void 0 : cart.items).reduce((lines, item) => {
    if (!item) return lines;
    lines.push({
      type: "product",
      line: item,
      product: item
    });
    return lines;
  }, []);
  return [...bookingLines, ...productLines].filter(
    ({ product }) => !isGiftProduct(product)
  );
};
var formatWeightValue = (value) => {
  return toFiniteNumber(value).toFixed(3);
};
var getWeighingInfo = (product) => {
  var _a, _b, _c, _d, _e;
  return ((_b = (_a = product == null ? void 0 : product._origin) == null ? void 0 : _a._extend) == null ? void 0 : _b.weighing) ?? ((_e = (_d = (_c = product == null ? void 0 : product.metadata) == null ? void 0 : _c.origin) == null ? void 0 : _d._extend) == null ? void 0 : _e.weighing);
};
var normalizeHolderIds = (value) => {
  if (value === void 0 || value === null || value === "") return [];
  return Array.isArray(value) ? value : [value];
};
var getBookingResourceMessage = (booking) => {
  const resources = toArray(booking == null ? void 0 : booking.resources);
  const labels = resources.map((resource) => {
    var _a;
    return (_a = resource == null ? void 0 : resource.metadata) == null ? void 0 : _a.resource_name;
  }).filter(Boolean);
  return labels.join(" · ");
};
var getBookingHolderMessage = (booking) => {
  var _a;
  const holderIds = normalizeHolderIds(
    (booking == null ? void 0 : booking.holder_id) ?? ((_a = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a.holder_id)
  );
  const holders = toArray((booking == null ? void 0 : booking.holderOptions) ?? (booking == null ? void 0 : booking.holders));
  return holderIds.map((id) => {
    const holder = holders.find(
      (item) => String(item.id) === String(id)
    );
    return (holder == null ? void 0 : holder.label) ?? String(id);
  }).filter(Boolean).join(" · ");
};
var appendWeighingMessage = (lines, product, currencySymbol) => {
  const weighing = getWeighingInfo(product);
  if (!weighing) return;
  const { mode, unit_price, unit, weight, tare, net_weight } = weighing;
  const unitLabel = UNIT_LABEL[unit] || unit;
  const tareValue = toFiniteNumber(tare == null ? void 0 : tare.value);
  const manualPrefix = mode === "manual" ? "(M) " : "";
  const unitPriceText = `${currencySymbol || ""}${unit_price ?? "0.00"}`;
  if (tareValue > 0) {
    lines.push(
      `${manualPrefix}${import_utils.locales.getText(
        "pisell2.big-sale.weighing.gross"
      )}: ${formatWeightValue(weight)} ${unitLabel}`
    );
    lines.push(
      `${import_utils.locales.getText(
        "pisell2.big-sale.weighing.tare"
      )}: ${formatWeightValue(tare == null ? void 0 : tare.value)} ${UNIT_LABEL[tare == null ? void 0 : tare.unit] || (tare == null ? void 0 : tare.unit) || unitLabel}`
    );
  }
  lines.push(
    `${tareValue > 0 ? "" : manualPrefix}${formatWeightValue(
      net_weight
    )} ${unitLabel} ${import_utils.locales.getText(
      "pisell2.big-sale.weighing.net"
    )} @ ${unitPriceText}/${unitLabel}`
  );
};
var appendOptionItemMessages = (lines, product, currencySymbol) => {
  const optionItems = (0, import_productSkuOptions.getLineProductOptions)(product);
  if (!optionItems.length) return;
  optionItems.forEach((option) => {
    const normalized = (0, import_productSkuOptions.normalizeOptionForDisplay)(option);
    const title = normalized == null ? void 0 : normalized.name;
    if (!title) return;
    lines.push(
      `${title}  ${(0, import_utils.formatAmount)((normalized == null ? void 0 : normalized.price) ?? 0, 2, currencySymbol)} x ${(normalized == null ? void 0 : normalized.num) ?? 1}`
    );
  });
};
var appendBundleMessages = (lines, product, currencySymbol) => {
  const bundles = toArray(product == null ? void 0 : product.product_bundle);
  if (!bundles.length) return;
  bundles.forEach((bundle) => {
    const title = (bundle == null ? void 0 : bundle.bundle_title) || (bundle == null ? void 0 : bundle.title) || "";
    const price = (bundle == null ? void 0 : bundle.price) ?? 0;
    lines.push(
      `${title}  ${(0, import_utils.formatAmount)(price, 2, currencySymbol)} x ${(bundle == null ? void 0 : bundle.num) ?? 1}`
    );
    const options = toArray((bundle == null ? void 0 : bundle.option) || (bundle == null ? void 0 : bundle.options));
    if (!options.length) return;
    options.forEach((option) => {
      const optionName = (option == null ? void 0 : option.name) || "";
      lines.push(
        `  ${optionName}  ${(0, import_utils.formatAmount)(
          (option == null ? void 0 : option.price) ?? 0,
          2,
          currencySymbol
        )} x ${(option == null ? void 0 : option.num) ?? 1}`
      );
    });
  });
};
var getProductFormatMessage = (cartLine, params) => {
  const { currencySymbol, locale } = params;
  const { type, line, product } = cartLine;
  const lines = [];
  if (type === "booking") {
    const booking = line;
    const resourceMessage = getBookingResourceMessage(booking);
    const timeMessage = (0, import_formatTime.formatBigSaleBookingTime)(booking, locale);
    const holderMessage = getBookingHolderMessage(booking);
    if (resourceMessage) lines.push(resourceMessage);
    if (timeMessage) lines.push(timeMessage);
    if (holderMessage) lines.push(holderMessage);
  }
  appendWeighingMessage(lines, product, currencySymbol);
  if (product == null ? void 0 : product.product_option_string) {
    lines.push(product.product_option_string);
  }
  appendOptionItemMessages(lines, product, currencySymbol);
  appendBundleMessages(lines, product, currencySymbol);
  return lines.length ? `${lines.join("\n")}
` : "";
};
var collectDiscountFees = (product) => {
  const discountList = toArray(product == null ? void 0 : product.discount_list);
  if (!discountList.length) return [];
  return discountList.map((discount) => {
    var _a;
    return {
      isReduce: (discount == null ? void 0 : discount.type) === "good_pass",
      title: ((_a = discount == null ? void 0 : discount.discount) == null ? void 0 : _a.title) || "",
      price: discount == null ? void 0 : discount.amount,
      type: discount == null ? void 0 : discount.type
    };
  });
};
var buildCdsProductPayload = (cartLine, params) => {
  const { line, product } = cartLine;
  const productFormatMessage = getProductFormatMessage(cartLine, params);
  const payload = {
    productID: product == null ? void 0 : product.product_id,
    title: (product == null ? void 0 : product.title) || "",
    cover: product == null ? void 0 : product.cover,
    price: Number((product == null ? void 0 : product.selling_price) ?? 0),
    buyCount: (product == null ? void 0 : product.num) ?? 0,
    productFormatMessage,
    note: (line == null ? void 0 : line.note) ?? (product == null ? void 0 : product.note),
    isWeightProduct: getWeighingInfo(product) ? 1 : 0
  };
  if (Number(product == null ? void 0 : product.original_price) !== Number(product == null ? void 0 : product.selling_price)) {
    payload.modifyPrice = Number((product == null ? void 0 : product.original_price) ?? 0);
  }
  return payload;
};
var buildCartUpdatePayload = (context, params) => {
  var _a;
  const cartLines = getCartProductLines(context == null ? void 0 : context.cart);
  if (!cartLines.length) {
    return {
      currency_symbol: params.currencySymbol,
      ...EMPTY_CART_UPDATE
    };
  }
  const fees = [];
  const products = cartLines.map((cartLine) => {
    fees.push(...collectDiscountFees(cartLine.product));
    return buildCdsProductPayload(cartLine, params);
  });
  const summary = (_a = context.summary) == null ? void 0 : _a.summary;
  fees.unshift({
    title: import_utils.locales.getText("pisell2.big-sale.subtotal"),
    price: (summary == null ? void 0 : summary.product_expect_amount) ?? "0",
    type: "subtotal",
    message: callLocaleText("pisell2.big-sale.cart-items", products.length)
  });
  return {
    currency_symbol: params.currencySymbol,
    total: (summary == null ? void 0 : summary.expect_amount) ?? "0",
    products,
    fees
  };
};
function useSyncBigSaleCartToCds(context, options = {}) {
  var _a, _b, _c, _d, _e;
  const engineContext = (0, import_useEngineContext.default)();
  const { enabled = true } = options;
  (0, import_react.useEffect)(() => {
    var _a2;
    if (!enabled) return;
    const utils = ((_a2 = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a2.utils) || {};
    const locale = getLocale(utils);
    const currencySymbol = getCurrencySymbol(utils);
    const data = buildCartUpdatePayload(context, {
      currencySymbol,
      locale
    });
    postCartUpdateToCds(utils, data);
  }, [
    (_a = context == null ? void 0 : context.cart) == null ? void 0 : _a.bookings,
    (_b = context == null ? void 0 : context.cart) == null ? void 0 : _b.items,
    (_c = context == null ? void 0 : context.summary) == null ? void 0 : _c.summary,
    (_d = context == null ? void 0 : context.sales) == null ? void 0 : _d.tempOrder,
    (_e = context == null ? void 0 : context.sales) == null ? void 0 : _e.bookingTicket,
    engineContext,
    enabled
  ]);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useSyncBigSaleCartToCds
});
