function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 _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 _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); }
import Decimal from 'decimal.js';
import { formatAmount, locales } from '@pisell/utils';

/**
 * “本次支付”快照 —— 显式、与具体接口字段解耦的中间结构。
 *
 * 注意（data-field-semantics）：从原始收款记录（如 getOrderPayments 返回项）
 * 映射到本快照的逻辑，字段含义需业务确认后再补充（见 buildPaymentSnapshotFromPayments）。
 * 本文件的 buildSessionLines 仅依赖本结构，是可独立验证的纯函数。
 */

var EPS = 0.0001;
function toNumber(value) {
  var n = Number(value);
  return Number.isFinite(n) ? n : 0;
}
function fmt(value, symbol) {
  return String(formatAmount(new Decimal(value).toString(), 2, symbol));
}

/** 取末四位（容错任意分隔符）。 */
function lastFour(id) {
  var digits = String(id || '').replace(/\D/g, '');
  return digits.slice(-4);
}

/**
 * 由快照构建“本次支付”明细行（纯函数，逻辑对齐 demo 的 session lines）。
 */
export function buildSessionLines(snapshot) {
  var _snapshot$cardPayment, _snapshot$vouchers;
  var symbol = snapshot.currencySymbol;
  var lines = [];
  if (toNumber(snapshot.cashTendered) > EPS) {
    lines.push({
      id: 'session_cash_tender',
      label: String(locales.getText('payment.result.cashReceived')),
      amount: fmt(toNumber(snapshot.cashTendered), symbol)
    });
  }
  if (toNumber(snapshot.changeDue) > EPS) {
    lines.push({
      id: 'session_cash_change',
      label: String(locales.getText('payment.result.changeDue')),
      amount: fmt(toNumber(snapshot.changeDue), symbol),
      tone: 'change'
    });
  }
  ((_snapshot$cardPayment = snapshot.cardPayments) !== null && _snapshot$cardPayment !== void 0 ? _snapshot$cardPayment : []).forEach(function (card, index) {
    var _card$id;
    var total = toNumber(card.amount);
    if (total <= EPS) return;
    var tail = lastFour(card.last4);
    var cardName = card.label || String(locales.getText('payment.result.card'));
    var paidWord = String(locales.getText('payment.result.paidSuffix'));
    var label = [cardName, tail, paidWord].filter(Boolean).join(' ');
    lines.push({
      id: "session_card_".concat((_card$id = card.id) !== null && _card$id !== void 0 ? _card$id : index),
      label: label,
      amount: fmt(total, symbol)
    });
    var surcharge = toNumber(card.surcharge);
    if (surcharge > EPS) {
      var _card$id2, _card$id3;
      var applied = Math.max(0, Math.round((total - surcharge) * 100) / 100);
      lines.push({
        id: "session_card_applied_".concat((_card$id2 = card.id) !== null && _card$id2 !== void 0 ? _card$id2 : index),
        label: String(locales.getText('payment.result.applied')),
        amount: fmt(applied, symbol),
        nested: true
      });
      lines.push({
        id: "session_card_surcharge_".concat((_card$id3 = card.id) !== null && _card$id3 !== void 0 ? _card$id3 : index),
        label: String(locales.getText('payment.result.paymentSurcharge')),
        amount: fmt(surcharge, symbol),
        nested: true
      });
    }
  });
  ((_snapshot$vouchers = snapshot.vouchers) !== null && _snapshot$vouchers !== void 0 ? _snapshot$vouchers : []).forEach(function (voucher, index) {
    var _voucher$id;
    var amount = toNumber(voucher.amount);
    if (amount <= EPS) return;
    var tail = lastFour(voucher.id);
    var voucherName = voucher.label || String(locales.getText('payment.result.voucher'));
    lines.push({
      id: "session_voucher_".concat((_voucher$id = voucher.id) !== null && _voucher$id !== void 0 ? _voucher$id : index),
      label: [voucherName, tail].filter(Boolean).join(' '),
      amount: fmt(amount, symbol)
    });
    var balance = toNumber(voucher.balanceRemaining);
    if (balance > EPS) {
      var _voucher$id2;
      lines.push({
        id: "session_voucher_balance_".concat((_voucher$id2 = voucher.id) !== null && _voucher$id2 !== void 0 ? _voucher$id2 : index),
        label: String(locales.getText('payment.result.balance')),
        amount: fmt(balance, symbol),
        nested: true,
        tone: 'balance'
      });
    }
  });
  return lines;
}

/** 把原始收款记录映射为快照的额外选项。 */

function asRecords(value) {
  return Array.isArray(value) ? value.filter(function (item) {
    return !!item && _typeof(item) === 'object';
  }) : [];
}
function firstDefined(record, keys) {
  var _iterator = _createForOfIteratorHelper(keys),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var key = _step.value;
      var value = record[key];
      if (value !== undefined && value !== null && value !== '') return value;
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return undefined;
}

// —— 以下字段读取与 pisellSaleSummaryDetail / SummaryFinancialSections 保持一致 ——
function getPaymentAmount(record) {
  return toNumber(firstDefined(record, ['origin_amount', 'amount']));
}
function getServiceFee(record) {
  return toNumber(record.service_fee);
}
function isVoucherRecord(record) {
  return !!record.voucher_id;
}
function isRefundRecord(record) {
  var rawType = String(record.type || record.status || '').toLowerCase();
  return rawType.includes('refund') || getPaymentAmount(record) < 0;
}
function isCashRecord(record) {
  var code = String(record.code || record.type || '').toLowerCase();
  return code.includes('cash');
}
function getCardLast4(record) {
  var _firstDefined;
  return String((_firstDefined = firstDefined(record, ['card_last_four', 'card_last4', 'last4', 'last_digits'])) !== null && _firstDefined !== void 0 ? _firstDefined : '').replace(/\D/g, '');
}
function resolveMethodName(record, map) {
  var code = String(record.code || record.payment_method || '').trim();
  var name = String(record.name || '').trim();
  if (code && map[code]) return map[code];
  return name || code;
}
function toDisplayText(value, translationOriginal) {
  if (!value) return '';
  if (typeof value === 'string') return value;
  var translated = translationOriginal === null || translationOriginal === void 0 ? void 0 : translationOriginal(value);
  if (translated) return translated;
  var fallbackKeys = ['original', 'auto', 'en-US', 'en', 'zh-CN', 'zh-HK'];
  for (var _i = 0, _fallbackKeys = fallbackKeys; _i < _fallbackKeys.length; _i++) {
    var key = _fallbackKeys[_i];
    var _text = value[key];
    if (typeof _text === 'string' && _text) return _text;
  }
  return '';
}

/**
 * 把这次支付的收款记录（currentBaseSales.getOrderPayments() 同源）映射为快照。
 * 字段映射沿用 sale detail 既有规范；现金实收取 metadata.actual_paid_amount，
 * 找零取 metadata.change_given_amount。
 */
export function buildPaymentSnapshotFromPayments(payments, currencySymbol) {
  var _options$paymentMetho;
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var records = asRecords(payments);
  var map = (_options$paymentMetho = options.paymentMethodNameMap) !== null && _options$paymentMetho !== void 0 ? _options$paymentMetho : {};
  var cardPayments = [];
  var vouchers = [];
  // 现金实收/找零取自 metadata（与 TEMP_ORDER 字段映射一致）：
  // actual_paid_amount = 实际收款，change_given_amount = 找零；
  // amount/origin_amount 是计入订单净额，不能当实收。
  var cashReceived = 0;
  var cashChange = 0;
  records.forEach(function (record, index) {
    if (isRefundRecord(record)) return; // 本次支付只展示正向收款

    if (isCashRecord(record)) {
      var meta = record.metadata || {};
      var received = firstDefined(meta, ['actual_paid_amount']);
      cashReceived += received !== undefined ? toNumber(received) : getPaymentAmount(record);
      cashChange += toNumber(meta.change_given_amount);
      return;
    }
    var amount = getPaymentAmount(record);
    if (amount <= EPS) return;
    if (isVoucherRecord(record)) {
      var fundRecord = record.fund_record || {};
      vouchers.push({
        id: String(fundRecord.encoded || fundRecord.code || record.voucher_id || index),
        label: toDisplayText(fundRecord.wallet_pass_name, options.translationOriginal) || undefined,
        amount: amount,
        balanceRemaining: toNumber(fundRecord.using_after_value)
      });
      return;
    }
    cardPayments.push({
      id: String(record.order_payment_id || record.id || index),
      label: resolveMethodName(record, map) || undefined,
      last4: getCardLast4(record),
      amount: amount,
      surcharge: getServiceFee(record)
    });
  });
  var snapshot = {
    currencySymbol: currencySymbol,
    cardPayments: cardPayments,
    vouchers: vouchers
  };

  // 现金：实收取 actual_paid_amount 汇总；找零优先取记录 metadata，缺失时回退入参
  var changeDue = cashChange > EPS ? cashChange : toNumber(options.changeGivenAmount);
  if (cashReceived > EPS || changeDue > EPS) {
    snapshot.cashTendered = cashReceived;
    snapshot.changeDue = changeDue;
  }
  return snapshot;
}