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 _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 React, { memo, useMemo } from 'react';
import classNames from 'classnames';
import Decimal from 'decimal.js';
// @ts-ignore
import { isEqual } from 'lodash';
import { Iconfont } from '@pisell/materials';
import { formatAmount, locales } from '@pisell/utils';
import useEngineContext from "../../../../hooks/useEngineContext";
import { useSalesSdk, useSalesSdkCart, useSalesSdkSummary } from "../../../salesSdk";
import { resolvePaymentMethodName, usePaymentMethodNameMap } from "../../../pisellSalesManagement/hooks/usePaymentMethodNameMap";
import "./index.less";
var PREFIX = 'pisell-sale-detail-summary-financial';
function toDecimal(value) {
  try {
    if (value instanceof Decimal) return value;
    if (value === undefined || value === null || value === '') {
      return new Decimal(0);
    }
    return new Decimal(value);
  } catch (_unused) {
    return new Decimal(0);
  }
}
function isNonZeroAmount(value) {
  return !toDecimal(value).isZero();
}
function formatMoney(value, symbol) {
  return formatAmount(toDecimal(value).toString(), 2, symbol);
}
function formatPlainNumber(value) {
  return toDecimal(value).toFixed(2).replace(/\.?0+$/, '');
}
function formatDeduction(value, symbol) {
  var amount = toDecimal(value).abs().negated();
  return formatMoney(amount, symbol);
}
function asRecords(value) {
  return Array.isArray(value) ? value.filter(function (item) {
    return !!item && _typeof(item) === 'object';
  }) : [];
}
function firstDefined(record, keys) {
  if (!record) return undefined;
  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;
}
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;
  }
  var firstText = Object.values(value).find(function (item) {
    return typeof item === 'string' && !!item;
  });
  return firstText || '';
}
function getPaymentAmount(record) {
  return firstDefined(record, ['origin_amount', 'amount']);
}
function getPaymentSurchargeAmount(record) {
  return record.service_fee;
}
function isRefundPaymentRecord(record) {
  var rawType = String(record.type || record.status || '').toLowerCase();
  return rawType.includes('refund') || toDecimal(getPaymentAmount(record)).lt(0);
}
function isVoucherPaymentRecord(record) {
  return !!record.voucher_id;
}
function isPointCardPaymentRecord(record) {
  return String(record.code || '').toUpperCase() === 'POINTCARD';
}
function isPointCardAdjustmentEntry(entry) {
  return String(entry.tag || entry.code || '').toUpperCase() === 'POINTCARD';
}
function buildPaymentDetailEntry(record, fallbackKey, paymentMethodNameMap) {
  var isRefund = isRefundPaymentRecord(record);
  var amount = getPaymentAmount(record);
  var surchargeAmount = getPaymentSurchargeAmount(record);
  return {
    key: String(record.order_payment_id || record.id || fallbackKey),
    title: resolvePaymentMethodName(record, paymentMethodNameMap),
    amount: isRefund ? toDecimal(amount).abs().negated() : amount,
    isRefund: isRefund,
    surchargeAmount: isNonZeroAmount(surchargeAmount) ? isRefund ? toDecimal(surchargeAmount).abs().negated() : surchargeAmount : undefined
  };
}
function buildDiscountAdjustmentEntry(record, translationOriginal) {
  var amount = record.savedAmount || record.amount;
  if (!isNonZeroAmount(amount)) return null;
  return {
    key: record.id,
    code: record.code,
    title: toDisplayText(record.format_title, translationOriginal),
    tag: record.tag ? String(record.tag) : undefined,
    amount: toDecimal(amount).abs().negated(),
    balance: record.balance,
    tone: 'deduction'
  };
}
function buildVoucherPaymentAdjustmentEntry(record, translationOriginal) {
  var amount = record.amount;
  if (!isNonZeroAmount(amount)) return null;
  var fundRecord = record.fund_record || {};
  var title = toDisplayText(fundRecord.wallet_pass_name, translationOriginal) || String(record.code || locales.getText('pisell2.sale-detail.item'));
  var code = fundRecord.encoded || fundRecord.code;
  var isPointCard = isPointCardPaymentRecord(record);
  var pointUsage = isPointCard ? toDecimal(fundRecord.using_before_value).minus(toDecimal(fundRecord.using_after_value)).abs() : null;
  return {
    key: String(record.order_payment_id),
    title: title,
    code: code ? String(code) : undefined,
    tag: record.code ? String(record.code) : undefined,
    amount: toDecimal(amount).abs().negated(),
    balance: fundRecord.using_after_value,
    pointUsage: pointUsage && !pointUsage.isZero() ? pointUsage : undefined,
    tone: 'deduction'
  };
}
var SectionCard = /*#__PURE__*/memo(function SectionCard(_ref) {
  var children = _ref.children,
    iconType = _ref.iconType,
    title = _ref.title,
    tone = _ref.tone;
  return /*#__PURE__*/React.createElement("section", {
    className: classNames("".concat(PREFIX, "__card"), _defineProperty(_defineProperty({}, "".concat(PREFIX, "__card--payment"), tone === 'payment'), "".concat(PREFIX, "__card--promotion"), tone === 'promotion'))
  }, /*#__PURE__*/React.createElement("header", {
    className: "".concat(PREFIX, "__card-header")
  }, /*#__PURE__*/React.createElement(Iconfont, {
    type: iconType
  }), /*#__PURE__*/React.createElement("span", null, title)), children);
});
var AmountRows = /*#__PURE__*/memo(function AmountRows(_ref2) {
  var rows = _ref2.rows,
    symbol = _ref2.symbol;
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__rows")
  }, rows.map(function (row) {
    return /*#__PURE__*/React.createElement("div", {
      className: classNames("".concat(PREFIX, "__row"), _defineProperty(_defineProperty({}, "".concat(PREFIX, "__row--deduction"), row.tone === 'deduction'), "".concat(PREFIX, "__row--highlight"), row.tone === 'highlight')),
      key: row.key
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__row-label")
    }, row.label), /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__row-value")
    }, row.tone === 'deduction' ? formatDeduction(row.value, symbol) : formatMoney(row.value, symbol)));
  }));
});
var PaymentDetailsContent = /*#__PURE__*/memo(function PaymentDetailsContent(_ref3) {
  var symbol = _ref3.symbol,
    toPayAmount = _ref3.toPayAmount,
    payments = _ref3.payments,
    summary = _ref3.summary;
  var currentLocale = locales.getLocale();
  var paymentMethodNameMap = usePaymentMethodNameMap();
  var entries = useMemo(function () {
    var nonVoucherPayments = payments.filter(function (payment) {
      return !isVoucherPaymentRecord(payment);
    });
    var nextEntries = nonVoucherPayments.map(function (payment, index) {
      return buildPaymentDetailEntry(payment, "payment-".concat(index), paymentMethodNameMap);
    });
    if (!payments.length) {
      if (isNonZeroAmount(summary.order_paid_amount)) {
        nextEntries.push({
          key: 'paid-summary',
          title: locales.getText('pisell2.sale-detail.pay.payment'),
          amount: summary.order_paid_amount,
          isRefund: false
        });
      }
      if (isNonZeroAmount(summary.total_refund_amount)) {
        nextEntries.push({
          key: 'refund-summary',
          title: locales.getText('pisell2.sale-detail.refund'),
          amount: toDecimal(summary.total_refund_amount).abs().negated(),
          isRefund: true
        });
      }
    }
    return nextEntries;
  }, [currentLocale, paymentMethodNameMap, payments, summary.order_paid_amount, summary.total_refund_amount]);
  var summaryRows = [{
    key: 'toPay',
    label: locales.getText('pisell2.sale-detail.to-pay'),
    value: toPayAmount,
    tone: 'highlight'
  }];
  return /*#__PURE__*/React.createElement(React.Fragment, null, entries.length ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__payment-list")
  }, entries.map(function (entry) {
    return /*#__PURE__*/React.createElement("article", {
      className: classNames("".concat(PREFIX, "__payment"), _defineProperty({}, "".concat(PREFIX, "__payment--refund"), entry.isRefund)),
      key: entry.key
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__payment-content")
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__payment-title")
    }, entry.title), /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__payment-amount")
    }, formatMoney(entry.amount, symbol))), entry.surchargeAmount !== undefined ? /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__payment-sub-content")
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__payment-sub-title")
    }, locales.getText('pisell2.sale-detail.payment-surcharge')), /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__payment-sub-amount")
    }, formatMoney(entry.surchargeAmount, symbol))) : null);
  })) : null, /*#__PURE__*/React.createElement(AmountRows, {
    rows: summaryRows,
    symbol: symbol
  }));
});
var AmountBreakdownSectionView = /*#__PURE__*/memo(function AmountBreakdownSectionView(_ref4) {
  var symbol = _ref4.symbol,
    summary = _ref4.summary,
    taxTitle = _ref4.taxTitle;
  var currentLocale = locales.getLocale();
  var amountRows = useMemo(function () {
    if (!summary) return [];
    return [{
      key: 'subtotal',
      label: locales.getText('pisell2.sale-detail.subtotal'),
      value: summary.product_amount
    }, {
      key: 'surcharge',
      label: locales.getText('pisell2.sale-detail.surcharge'),
      value: summary.surcharge_fee
    }, {
      key: 'discount',
      label: locales.getText('pisell2.sale-detail.discount'),
      value: summary.discount_amount,
      tone: isNonZeroAmount(summary.discount_amount) ? 'deduction' : undefined
    }, {
      key: 'tax',
      label: summary.tax_title || taxTitle || locales.getText('pisell2.sale-detail.tax'),
      value: summary.tax_fee
    }, {
      key: 'total',
      label: locales.getText('pisell2.sale-detail.total-amount'),
      value: summary.expect_amount,
      tone: 'highlight'
    }];
  }, [currentLocale, summary, taxTitle]);
  if (!amountRows.length) return null;
  return /*#__PURE__*/React.createElement(SectionCard, {
    iconType: "pisell2-file-05",
    title: locales.getText('pisell2.sale-detail.amount-breakdown')
  }, /*#__PURE__*/React.createElement(AmountRows, {
    rows: amountRows,
    symbol: symbol
  }));
}, isEqual);
var AmountBreakdownSection = /*#__PURE__*/memo(function AmountBreakdownSection() {
  var engineContext = useEngineContext();
  var sales = useSalesSdk();
  var summaryState = useSalesSdkSummary();
  var tempOrder = sales.tempOrder;
  var symbol = (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.currency_symbol) || engineContext.appHelper.utils.getSymbolic();
  return /*#__PURE__*/React.createElement(AmountBreakdownSectionView, {
    symbol: symbol,
    summary: summaryState.summary,
    taxTitle: tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.tax_title
  });
});
var PaymentDetailsSectionView = /*#__PURE__*/memo(function PaymentDetailsSectionView(_ref5) {
  var rawPayments = _ref5.payments,
    symbol = _ref5.symbol,
    summary = _ref5.summary;
  var payments = useMemo(function () {
    return asRecords(rawPayments);
  }, [rawPayments]);
  var hasSummary = !!summary;
  var orderPaidAmount = summary === null || summary === void 0 ? void 0 : summary.order_paid_amount;
  var totalRefundAmount = summary === null || summary === void 0 ? void 0 : summary.total_refund_amount;
  var showPaymentDetails = useMemo(function () {
    if (!hasSummary) return false;
    var hasNonVoucherPayment = payments.some(function (payment) {
      return !isVoucherPaymentRecord(payment);
    });
    return hasNonVoucherPayment || !payments.length && (isNonZeroAmount(orderPaidAmount) || isNonZeroAmount(totalRefundAmount));
  }, [hasSummary, orderPaidAmount, payments, totalRefundAmount]);
  if (!showPaymentDetails || !summary) return null;
  return /*#__PURE__*/React.createElement(SectionCard, {
    iconType: "pisell2-credit-card-02",
    title: locales.getText('pisell2.sale-detail.payment-details'),
    tone: "payment"
  }, /*#__PURE__*/React.createElement(PaymentDetailsContent, {
    payments: payments,
    summary: summary,
    symbol: symbol,
    toPayAmount: summary.amount_gap
  }));
}, isEqual);
var PaymentDetailsSection = /*#__PURE__*/memo(function PaymentDetailsSection() {
  var engineContext = useEngineContext();
  var sales = useSalesSdk();
  var summaryState = useSalesSdkSummary();
  var tempOrder = sales.tempOrder;
  var symbol = (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.currency_symbol) || engineContext.appHelper.utils.getSymbolic();
  return /*#__PURE__*/React.createElement(PaymentDetailsSectionView, {
    payments: tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payments,
    symbol: symbol,
    summary: summaryState.summary
  });
});
var AdjustmentSectionView = /*#__PURE__*/memo(function AdjustmentSectionView(_ref6) {
  var discountList = _ref6.discountList,
    rawPayments = _ref6.payments,
    shopDiscount = _ref6.shopDiscount,
    symbol = _ref6.symbol,
    translationOriginal = _ref6.translationOriginal;
  var payments = useMemo(function () {
    return asRecords(rawPayments);
  }, [rawPayments]);
  var currentLocale = locales.getLocale();
  var adjustmentEntries = useMemo(function () {
    var entries = [];
    asRecords(discountList).filter(function (record) {
      return record.isSelected;
    }).forEach(function (record) {
      var entry = buildDiscountAdjustmentEntry(record, translationOriginal);
      if (entry) entries.push(entry);
    });
    payments.filter(isVoucherPaymentRecord).forEach(function (record) {
      var entry = buildVoucherPaymentAdjustmentEntry(record, translationOriginal);
      if (entry) entries.push(entry);
    });
    if (isNonZeroAmount(shopDiscount)) {
      entries.push({
        key: 'manual-order-discount',
        title: locales.getText('pisell2.sale-detail.manual-order-adjustment'),
        amount: toDecimal(shopDiscount).abs().negated(),
        tone: 'deduction'
      });
    }
    return entries;
  }, [currentLocale, discountList, payments, shopDiscount, translationOriginal]);
  if (!adjustmentEntries.length) return null;
  return /*#__PURE__*/React.createElement(SectionCard, {
    iconType: "pisell2-a-wallet-021",
    title: locales.getText('pisell2.sale-detail.passes-vouchers'),
    tone: "promotion"
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__adjustment-list")
  }, adjustmentEntries.map(function (entry) {
    var isPointCard = isPointCardAdjustmentEntry(entry);
    return /*#__PURE__*/React.createElement("article", {
      className: "".concat(PREFIX, "__adjustment"),
      key: entry.key
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__adjustment-main")
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__adjustment-title")
    }, entry.title), /*#__PURE__*/React.createElement("span", {
      className: classNames("".concat(PREFIX, "__adjustment-amount"), _defineProperty({}, "".concat(PREFIX, "__adjustment-amount--addition"), entry.tone === 'addition'))
    }, formatMoney(entry.amount, symbol), isPointCard && isNonZeroAmount(entry.pointUsage) ? " (".concat(formatPlainNumber(toDecimal(entry.pointUsage).abs().negated()), ")") : null)), entry.code || entry.subtitle || entry.tag || entry.balance !== undefined ? /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__adjustment-meta")
    }, entry.code || entry.subtitle || entry.tag ? /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__adjustment-subtitle")
    }, [entry.code || entry.subtitle, entry.tag].filter(Boolean).join(' · ')) : null, entry.balance !== undefined ? /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__adjustment-balance")
    }, /*#__PURE__*/React.createElement("span", null, locales.getText('pisell2.sale-detail.balance')), /*#__PURE__*/React.createElement("span", null, isPointCard ? formatPlainNumber(entry.balance) : formatMoney(entry.balance, symbol))) : null) : null);
  })));
}, isEqual);
var AdjustmentSection = /*#__PURE__*/memo(function AdjustmentSection() {
  var engineContext = useEngineContext();
  var sales = useSalesSdk();
  var cart = useSalesSdkCart();
  var tempOrder = sales.tempOrder;
  var symbol = (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.currency_symbol) || engineContext.appHelper.utils.getSymbolic();
  var translationOriginal = engineContext.appHelper.utils.translationOriginal;
  return /*#__PURE__*/React.createElement(AdjustmentSectionView, {
    discountList: cart.discountList,
    payments: tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payments,
    shopDiscount: tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.shop_discount,
    symbol: symbol,
    translationOriginal: translationOriginal
  });
});
export var SummaryFinancialSections = /*#__PURE__*/memo(function SummaryFinancialSections(_ref7) {
  var className = _ref7.className;
  return /*#__PURE__*/React.createElement("div", {
    className: classNames(PREFIX, className)
  }, /*#__PURE__*/React.createElement(PaymentDetailsSection, null), /*#__PURE__*/React.createElement(AdjustmentSection, null));
});