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 _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; }
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); }
import Decimal from 'decimal.js';

/** 解析商品行数量（checkout 协议 product_num 语义 = 当前行 num） */
export function resolveSafeProductNum(num) {
  var parsed = Number(num);
  if (!Number.isFinite(parsed) || parsed <= 0) return 1;
  return Math.floor(parsed);
}

/**
 * 将 discount_list 中 type=product 项的 product_num 同步为当前商品数量。
 *
 * @example
 * syncManualProductDiscountProductNum(line.discount_list, line.num);
 */
export function syncManualProductDiscountProductNum(discountList, productNum) {
  var quantity = resolveSafeProductNum(productNum);
  return (discountList || []).map(function (item) {
    if ((item === null || item === void 0 ? void 0 : item.type) !== 'product') return item;
    return _objectSpread(_objectSpread({}, item), {}, {
      discount: _objectSpread(_objectSpread({}, item.discount || {}), {}, {
        product_num: quantity
      })
    });
  });
}

/** 从多源解析改价前行总价（与 cacheItem._extend.origin_total 语义一致） */
export function resolveManualDiscountOriginTotal(sources) {
  var _sources$quantity;
  var candidates = [sources.originTotal, sources.extendOriginTotal, sources.originExtendOriginTotal, sources.sourceExtendOriginTotal];
  for (var _i = 0, _candidates = candidates; _i < _candidates.length; _i++) {
    var candidate = _candidates[_i];
    if (candidate === undefined || candidate === null || candidate === '') continue;
    var parsed = Number(candidate);
    if (Number.isFinite(parsed)) return parsed;
  }
  var unit = Number(sources.catalogUnitPrice);
  var quantity = (_sources$quantity = sources.quantity) !== null && _sources$quantity !== void 0 ? _sources$quantity : 1;
  if (Number.isFinite(unit) && unit > 0) {
    return new Decimal(unit).mul(quantity).toNumber();
  }
  return NaN;
}

/** 从 payload / extend / origin 解析手动折扣原因 */
export function resolveManualDiscountReasonFromSources(sources) {
  for (var _i2 = 0, _arr = [sources.discountReason, sources.extendDiscountReason, sources.originExtendDiscountReason]; _i2 < _arr.length; _i2++) {
    var candidate = _arr[_i2];
    if (candidate != null && String(candidate).trim() !== '') {
      return String(candidate);
    }
  }
  return '';
}

/** 是否带手动改价标记（price_override / is_manual_discount） */
export function hasManualProductDiscountFlag(metadata) {
  if (!metadata) return false;
  var override = metadata.price_override;
  if (override !== undefined && override !== null && override !== '') {
    return true;
  }
  return metadata.is_manual_discount === 1 || metadata.is_manual_discount === true;
}

/**
 * normalize 兜底：手动改价但 discount_list 缺 type=product 时，按行级原价/折后价补写。
 *
 * @example
 * ensureManualProductDiscountList({
 *   discountList: [],
 *   metadata: { price_override: '5', is_manual_discount: 1 },
 *   originalPrice: '11.00',
 *   sellingPrice: '5.00',
 *   quantity: 1,
 * });
 */
export function ensureManualProductDiscountList(params) {
  var _metadata$origin, _metadata$origin2, _metadata$origin3, _metadata$origin4;
  var list = params.discountList || [];
  var quantity = resolveSafeProductNum(params.quantity);
  if (findManualProductDiscountItem(list)) {
    return syncManualProductDiscountProductNum(list, quantity);
  }
  var metadata = params.metadata || {};
  var originalNum = Number(params.originalPrice);
  var sellingNum = Number(params.sellingPrice);
  var shouldBuild = hasManualProductDiscountFlag(metadata) || shouldBuildManualProductDiscount({
    originTotal: originalNum,
    sellingTotal: sellingNum
  });
  if (!shouldBuild) {
    return list;
  }
  if (!Number.isFinite(originalNum) || !Number.isFinite(sellingNum) || originalNum === sellingNum) {
    return list;
  }
  var message = resolveManualDiscountMessage(list, resolveManualDiscountReasonFromSources({
    extendDiscountReason: (_metadata$origin = metadata.origin) === null || _metadata$origin === void 0 || (_metadata$origin = _metadata$origin._extend) === null || _metadata$origin === void 0 ? void 0 : _metadata$origin.discount_reason,
    originExtendDiscountReason: (_metadata$origin2 = metadata.origin) === null || _metadata$origin2 === void 0 || (_metadata$origin2 = _metadata$origin2._extend) === null || _metadata$origin2 === void 0 ? void 0 : _metadata$origin2.discount_reason
  }));
  return mergeManualProductDiscountIntoList(list, buildManualProductDiscountItem({
    originTotal: originalNum,
    sellingTotal: sellingNum,
    quantity: quantity,
    message: message,
    discountway: (_metadata$origin3 = metadata.origin) === null || _metadata$origin3 === void 0 || (_metadata$origin3 = _metadata$origin3._extend) === null || _metadata$origin3 === void 0 ? void 0 : _metadata$origin3.discountway,
    discount_per: (_metadata$origin4 = metadata.origin) === null || _metadata$origin4 === void 0 || (_metadata$origin4 = _metadata$origin4._extend) === null || _metadata$origin4 === void 0 ? void 0 : _metadata$origin4.discount_per
  }));
}

/** 商品手动折扣 discount_list 项（checkout 协议，type = product） */

/**
 * 从 discount_list 中取手动改价项（type = product）。
 *
 * @example
 * const manual = findManualProductDiscountItem(product.discount_list);
 * manual?.discount.message; // 折扣原因
 */
export function findManualProductDiscountItem(discountList) {
  return (discountList || []).find(function (item) {
    return (item === null || item === void 0 ? void 0 : item.type) === 'product';
  });
}

/**
 * 解析折扣原因：优先 discount_list[type=product].discount.message。
 *
 * @example
 * resolveManualDiscountMessage(line.discount_list, line.metadata?.legacy_reason);
 */
export function resolveManualDiscountMessage(discountList, fallback) {
  var _findManualProductDis;
  var message = (_findManualProductDis = findManualProductDiscountItem(discountList)) === null || _findManualProductDis === void 0 || (_findManualProductDis = _findManualProductDis.discount) === null || _findManualProductDis === void 0 ? void 0 : _findManualProductDis.message;
  if (message != null && String(message).trim() !== '') {
    return String(message);
  }
  return fallback !== null && fallback !== void 0 ? fallback : '';
}

/** 去掉 discount_list 中已有的手动改价项，避免重复叠加 */
export function stripManualProductDiscountItems(discountList) {
  return (discountList || []).filter(function (item) {
    return (item === null || item === void 0 ? void 0 : item.type) !== 'product';
  });
}

/**
 * 由改价前后行总价构建手动折扣项；amount = |originTotal - sellingTotal|（行级差额）。
 *
 * @example
 * buildManualProductDiscountItem({
 *   originTotal: 11,
 *   sellingTotal: 4,
 *   quantity: 1,
 *   message: 'VIP',
 * });
 */
export function buildManualProductDiscountItem(params) {
  var _params$message, _params$discountway, _params$discount_per;
  var origin = new Decimal(Number(params.originTotal) || 0);
  var selling = new Decimal(Number(params.sellingTotal) || 0);
  var diff = origin.minus(selling);
  var quantity = resolveSafeProductNum(params.quantity);
  return {
    amount: diff.abs().toDecimalPlaces(2).toNumber(),
    type: 'product',
    discount: {
      message: (_params$message = params.message) !== null && _params$message !== void 0 ? _params$message : '',
      discountway: (_params$discountway = params.discountway) !== null && _params$discountway !== void 0 ? _params$discountway : 'num',
      product_num: quantity,
      discount_per: (_params$discount_per = params.discount_per) !== null && _params$discount_per !== void 0 ? _params$discount_per : '',
      discount_type: diff.isNegative() ? 'change_price' : 'discount'
    }
  };
}

/**
 * 将手动改价项合并进 discount_list（替换已有 type=product 项）。
 *
 * @example
 * mergeManualProductDiscountIntoList(coupons, manualItem);
 */
export function mergeManualProductDiscountIntoList(discountList, manualItem) {
  var base = stripManualProductDiscountItems(discountList);
  if (!manualItem) return base;
  if (manualItem.amount === 0 && !manualItem.discount.message) return base;
  return [].concat(_toConsumableArray(base), [manualItem]);
}

/** 是否应写入手动改价 discount_list 项 */
export function shouldBuildManualProductDiscount(params) {
  if (params.hasPriceOverride) return true;
  var origin = Number(params.originTotal);
  var selling = Number(params.sellingTotal);
  if (!Number.isFinite(origin) || !Number.isFinite(selling)) return false;
  return origin !== selling;
}