function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
import { useEffect } from 'react';
import { formatAmount, locales } from '@pisell/utils';
import useEngineContext from "../../../hooks/useEngineContext";
import { getLineProductOptions, normalizeOptionForDisplay } from "../../../plus/salesSdk/utils/productSkuOptions";
import { formatBigSaleBookingTime } from "../utils/formatTime";
var EMPTY_CART_UPDATE = {
  total: '0',
  products: [],
  fees: []
};
var UNIT_LABEL = {
  KILOGRAMS: 'kg',
  GRAMS: 'g',
  POUNDS: 'lb',
  OUNCES: 'oz'
};
var toArray = function toArray(value) {
  return Array.isArray(value) ? value : [];
};
var getLocale = function getLocale(utils) {
  var _app$locales, _utils$storage;
  var getApp = utils === null || utils === void 0 ? void 0 : utils.getApp;
  var app = typeof getApp === 'function' ? getApp() : undefined;
  var getLocale = app === null || app === void 0 || (_app$locales = app.locales) === null || _app$locales === void 0 ? void 0 : _app$locales.getLocale;
  var storageGet = utils === null || utils === void 0 || (_utils$storage = utils.storage) === null || _utils$storage === void 0 ? void 0 : _utils$storage.get;
  return (typeof getLocale === 'function' ? getLocale() : undefined) || (typeof storageGet === 'function' ? storageGet('umi_locale') : undefined) || 'en-US';
};
var getCurrencySymbol = function getCurrencySymbol(utils) {
  var getSymbolic = utils === null || utils === void 0 ? void 0 : utils.getSymbolic;
  return typeof getSymbolic === 'function' ? getSymbolic() : '';
};
var toFiniteNumber = function toFiniteNumber(value) {
  var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
};
var callLocaleText = function callLocaleText(key) {
  var text = locales.getText(key);
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }
  return typeof text === 'function' ? text.apply(void 0, args) : text;
};
var postCartUpdateToCds = function postCartUpdateToCds(utils, data) {
  var _utils$interaction;
  var postMessageToApp = utils === null || utils === void 0 || (_utils$interaction = utils.interaction) === null || _utils$interaction === void 0 || (_utils$interaction = _utils$interaction.utils) === null || _utils$interaction === void 0 ? void 0 : _utils$interaction.postMessageToApp;
  if (typeof postMessageToApp !== 'function') return;
  console.log('postCartUpdateToCds data', data);
  try {
    postMessageToApp({
      module: 'cds',
      key: 'cartUpdate',
      data: data
    });
  } catch (error) {
    console.warn('[BigSale] post cart update to CDS failed', error);
  }
};

/**
 * 过滤赠品行：CDS 商品列表展示主购物车行，赠品由主商品促销数据承载。
 */
var isGiftProduct = function isGiftProduct(product) {
  var _product$metadata;
  return Boolean((product === null || product === void 0 ? void 0 : product.gift_card) || (product === null || product === void 0 ? void 0 : product.isGift) || (product === null || product === void 0 ? void 0 : product._isGiftPromotion) || (product === null || product === void 0 || (_product$metadata = product.metadata) === null || _product$metadata === void 0 ? void 0 : _product$metadata._giftInfo) || (product === null || product === void 0 ? void 0 : product._giftInfo));
};

/**
 * 将 SalesSdk 的两种购物车来源统一成 CDS 可消费的商品行。
 *
 * - booking：真实商品在 `booking._extend.product`
 * - item：商品行自身就是 product
 */
var getCartProductLines = function getCartProductLines(cart) {
  var bookingLines = toArray(cart === null || cart === void 0 ? void 0 : cart.bookings).reduce(function (lines, booking) {
    var _booking$_extend;
    var product = booking === null || booking === void 0 || (_booking$_extend = booking._extend) === null || _booking$_extend === void 0 ? void 0 : _booking$_extend.product;
    if (!product) return lines;
    lines.push({
      type: 'booking',
      line: booking,
      product: product
    });
    return lines;
  }, []);
  var productLines = toArray(cart === null || cart === void 0 ? void 0 : cart.items).reduce(function (lines, item) {
    if (!item) return lines;
    lines.push({
      type: 'product',
      line: item,
      product: item
    });
    return lines;
  }, []);
  return [].concat(_toConsumableArray(bookingLines), _toConsumableArray(productLines)).filter(function (_ref) {
    var product = _ref.product;
    return !isGiftProduct(product);
  });
};
var formatWeightValue = function formatWeightValue(value) {
  return toFiniteNumber(value).toFixed(3);
};
var getWeighingInfo = function getWeighingInfo(product) {
  var _product$_origin$_ext, _product$_origin, _product$metadata2;
  return (_product$_origin$_ext = product === null || product === void 0 || (_product$_origin = product._origin) === null || _product$_origin === void 0 || (_product$_origin = _product$_origin._extend) === null || _product$_origin === void 0 ? void 0 : _product$_origin.weighing) !== null && _product$_origin$_ext !== void 0 ? _product$_origin$_ext : product === null || product === void 0 || (_product$metadata2 = product.metadata) === null || _product$metadata2 === void 0 || (_product$metadata2 = _product$metadata2.origin) === null || _product$metadata2 === void 0 || (_product$metadata2 = _product$metadata2._extend) === null || _product$metadata2 === void 0 ? void 0 : _product$metadata2.weighing;
};
var normalizeHolderIds = function normalizeHolderIds(value) {
  if (value === undefined || value === null || value === '') return [];
  return Array.isArray(value) ? value : [value];
};
var getBookingResourceMessage = function getBookingResourceMessage(booking) {
  var resources = toArray(booking === null || booking === void 0 ? void 0 : booking.resources);
  var labels = resources.map(function (resource) {
    var _resource$metadata;
    return resource === null || resource === void 0 || (_resource$metadata = resource.metadata) === null || _resource$metadata === void 0 ? void 0 : _resource$metadata.resource_name;
  }).filter(Boolean);
  return labels.join(' · ');
};
var getBookingHolderMessage = function getBookingHolderMessage(booking) {
  var _booking$holder_id, _booking$metadata, _booking$holderOption;
  var holderIds = normalizeHolderIds((_booking$holder_id = booking === null || booking === void 0 ? void 0 : booking.holder_id) !== null && _booking$holder_id !== void 0 ? _booking$holder_id : booking === null || booking === void 0 || (_booking$metadata = booking.metadata) === null || _booking$metadata === void 0 ? void 0 : _booking$metadata.holder_id);
  var holders = toArray((_booking$holderOption = booking === null || booking === void 0 ? void 0 : booking.holderOptions) !== null && _booking$holderOption !== void 0 ? _booking$holderOption : booking === null || booking === void 0 ? void 0 : booking.holders);
  return holderIds.map(function (id) {
    var _holder$label;
    var holder = holders.find(function (item) {
      return String(item.id) === String(id);
    });
    return (_holder$label = holder === null || holder === void 0 ? void 0 : holder.label) !== null && _holder$label !== void 0 ? _holder$label : String(id);
  }).filter(Boolean).join(' · ');
};
var appendWeighingMessage = function appendWeighingMessage(lines, product, currencySymbol) {
  var weighing = getWeighingInfo(product);
  if (!weighing) return;
  var mode = weighing.mode,
    unit_price = weighing.unit_price,
    unit = weighing.unit,
    weight = weighing.weight,
    tare = weighing.tare,
    net_weight = weighing.net_weight;
  var unitLabel = UNIT_LABEL[unit] || unit;
  var tareValue = toFiniteNumber(tare === null || tare === void 0 ? void 0 : tare.value);
  var manualPrefix = mode === 'manual' ? '(M) ' : '';
  var unitPriceText = "".concat(currencySymbol || '').concat(unit_price !== null && unit_price !== void 0 ? unit_price : '0.00');
  if (tareValue > 0) {
    lines.push("".concat(manualPrefix).concat(locales.getText('pisell2.big-sale.weighing.gross'), ": ").concat(formatWeightValue(weight), " ").concat(unitLabel));
    lines.push("".concat(locales.getText('pisell2.big-sale.weighing.tare'), ": ").concat(formatWeightValue(tare === null || tare === void 0 ? void 0 : tare.value), " ").concat(UNIT_LABEL[tare === null || tare === void 0 ? void 0 : tare.unit] || (tare === null || tare === void 0 ? void 0 : tare.unit) || unitLabel));
  }
  lines.push("".concat(tareValue > 0 ? '' : manualPrefix).concat(formatWeightValue(net_weight), " ").concat(unitLabel, " ").concat(locales.getText('pisell2.big-sale.weighing.net'), " @ ").concat(unitPriceText, "/").concat(unitLabel));
};
var appendOptionItemMessages = function appendOptionItemMessages(lines, product, currencySymbol) {
  var optionItems = getLineProductOptions(product);
  if (!optionItems.length) return;
  optionItems.forEach(function (option) {
    var _normalized$price, _normalized$num;
    var normalized = normalizeOptionForDisplay(option);
    var title = normalized === null || normalized === void 0 ? void 0 : normalized.name;
    if (!title) return;
    lines.push("".concat(title, "  ").concat(formatAmount((_normalized$price = normalized === null || normalized === void 0 ? void 0 : normalized.price) !== null && _normalized$price !== void 0 ? _normalized$price : 0, 2, currencySymbol), " x ").concat((_normalized$num = normalized === null || normalized === void 0 ? void 0 : normalized.num) !== null && _normalized$num !== void 0 ? _normalized$num : 1));
  });
};
var appendBundleMessages = function appendBundleMessages(lines, product, currencySymbol) {
  var bundles = toArray(product === null || product === void 0 ? void 0 : product.product_bundle);
  if (!bundles.length) return;
  bundles.forEach(function (bundle) {
    var _bundle$price, _bundle$num;
    var title = (bundle === null || bundle === void 0 ? void 0 : bundle.bundle_title) || (bundle === null || bundle === void 0 ? void 0 : bundle.title) || '';
    var price = (_bundle$price = bundle === null || bundle === void 0 ? void 0 : bundle.price) !== null && _bundle$price !== void 0 ? _bundle$price : 0;
    lines.push("".concat(title, "  ").concat(formatAmount(price, 2, currencySymbol), " x ").concat((_bundle$num = bundle === null || bundle === void 0 ? void 0 : bundle.num) !== null && _bundle$num !== void 0 ? _bundle$num : 1));
    var options = toArray((bundle === null || bundle === void 0 ? void 0 : bundle.option) || (bundle === null || bundle === void 0 ? void 0 : bundle.options));
    if (!options.length) return;
    options.forEach(function (option) {
      var _option$price, _option$num;
      var optionName = (option === null || option === void 0 ? void 0 : option.name) || '';
      lines.push("  ".concat(optionName, "  ").concat(formatAmount((_option$price = option === null || option === void 0 ? void 0 : option.price) !== null && _option$price !== void 0 ? _option$price : 0, 2, currencySymbol), " x ").concat((_option$num = option === null || option === void 0 ? void 0 : option.num) !== null && _option$num !== void 0 ? _option$num : 1));
    });
  });
};
var getProductFormatMessage = function getProductFormatMessage(cartLine, params) {
  var currencySymbol = params.currencySymbol,
    locale = params.locale;
  var type = cartLine.type,
    line = cartLine.line,
    product = cartLine.product;
  var lines = [];
  if (type === 'booking') {
    var booking = line;
    var resourceMessage = getBookingResourceMessage(booking);
    var timeMessage = formatBigSaleBookingTime(booking, locale);
    var 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 && product !== void 0 && product.product_option_string) {
    lines.push(product.product_option_string);
  }
  appendOptionItemMessages(lines, product, currencySymbol);
  appendBundleMessages(lines, product, currencySymbol);
  return lines.length ? "".concat(lines.join('\n'), "\n") : '';
};
var collectDiscountFees = function collectDiscountFees(product) {
  var discountList = toArray(product === null || product === void 0 ? void 0 : product.discount_list);
  if (!discountList.length) return [];
  return discountList.map(function (discount) {
    var _discount$discount;
    return {
      isReduce: (discount === null || discount === void 0 ? void 0 : discount.type) === 'good_pass',
      title: (discount === null || discount === void 0 || (_discount$discount = discount.discount) === null || _discount$discount === void 0 ? void 0 : _discount$discount.title) || '',
      price: discount === null || discount === void 0 ? void 0 : discount.amount,
      type: discount === null || discount === void 0 ? void 0 : discount.type
    };
  });
};
var buildCdsProductPayload = function buildCdsProductPayload(cartLine, params) {
  var _product$selling_pric, _product$num, _note;
  var line = cartLine.line,
    product = cartLine.product;
  var productFormatMessage = getProductFormatMessage(cartLine, params);
  var payload = {
    productID: product === null || product === void 0 ? void 0 : product.product_id,
    title: (product === null || product === void 0 ? void 0 : product.title) || '',
    cover: product === null || product === void 0 ? void 0 : product.cover,
    price: Number((_product$selling_pric = product === null || product === void 0 ? void 0 : product.selling_price) !== null && _product$selling_pric !== void 0 ? _product$selling_pric : 0),
    buyCount: (_product$num = product === null || product === void 0 ? void 0 : product.num) !== null && _product$num !== void 0 ? _product$num : 0,
    productFormatMessage: productFormatMessage,
    note: (_note = line === null || line === void 0 ? void 0 : line.note) !== null && _note !== void 0 ? _note : product === null || product === void 0 ? void 0 : product.note,
    isWeightProduct: getWeighingInfo(product) ? 1 : 0
  };
  if (Number(product === null || product === void 0 ? void 0 : product.original_price) !== Number(product === null || product === void 0 ? void 0 : product.selling_price)) {
    var _product$original_pri;
    payload.modifyPrice = Number((_product$original_pri = product === null || product === void 0 ? void 0 : product.original_price) !== null && _product$original_pri !== void 0 ? _product$original_pri : 0); //原价, 注意字段名反了
  }
  return payload;
};
var buildCartUpdatePayload = function buildCartUpdatePayload(context, params) {
  var _context$summary, _summary$product_expe, _summary$expect_amoun;
  var cartLines = getCartProductLines(context === null || context === void 0 ? void 0 : context.cart);
  if (!cartLines.length) {
    return _objectSpread({
      currency_symbol: params.currencySymbol
    }, EMPTY_CART_UPDATE);
  }
  var fees = [];
  var products = cartLines.map(function (cartLine) {
    fees.push.apply(fees, _toConsumableArray(collectDiscountFees(cartLine.product)));
    return buildCdsProductPayload(cartLine, params);
  });
  var summary = (_context$summary = context.summary) === null || _context$summary === void 0 ? void 0 : _context$summary.summary;
  fees.unshift({
    title: locales.getText('pisell2.big-sale.subtotal'),
    price: (_summary$product_expe = summary === null || summary === void 0 ? void 0 : summary.product_expect_amount) !== null && _summary$product_expe !== void 0 ? _summary$product_expe : '0',
    type: 'subtotal',
    message: callLocaleText('pisell2.big-sale.cart-items', products.length)
  });
  return {
    currency_symbol: params.currencySymbol,
    total: (_summary$expect_amoun = summary === null || summary === void 0 ? void 0 : summary.expect_amount) !== null && _summary$expect_amoun !== void 0 ? _summary$expect_amoun : '0',
    products: products,
    fees: fees
  };
};

/**
 * Standard 大促模板购物车变更时，向 Native CDS 同步购物车快照。
 */
export function useSyncBigSaleCartToCds(context) {
  var _context$cart, _context$cart2, _context$summary2, _context$sales, _context$sales2;
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var engineContext = useEngineContext();
  var _options$enabled = options.enabled,
    enabled = _options$enabled === void 0 ? true : _options$enabled;
  useEffect(function () {
    var _engineContext$appHel;
    if (!enabled) return;
    var utils = (engineContext === null || engineContext === void 0 || (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.utils) || {};
    var locale = getLocale(utils);
    var currencySymbol = getCurrencySymbol(utils);
    var data = buildCartUpdatePayload(context, {
      currencySymbol: currencySymbol,
      locale: locale
    });
    postCartUpdateToCds(utils, data);
  }, [context === null || context === void 0 || (_context$cart = context.cart) === null || _context$cart === void 0 ? void 0 : _context$cart.bookings, context === null || context === void 0 || (_context$cart2 = context.cart) === null || _context$cart2 === void 0 ? void 0 : _context$cart2.items, context === null || context === void 0 || (_context$summary2 = context.summary) === null || _context$summary2 === void 0 ? void 0 : _context$summary2.summary, context === null || context === void 0 || (_context$sales = context.sales) === null || _context$sales === void 0 ? void 0 : _context$sales.tempOrder, context === null || context === void 0 || (_context$sales2 = context.sales) === null || _context$sales2 === void 0 ? void 0 : _context$sales2.bookingTicket, engineContext, enabled]);
}