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 _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 _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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useMemo, useState } from 'react';
import classNames from 'classnames';
import { formatAmount, locales } from '@pisell/utils';
import useEngineContext from "../../../../hooks/useEngineContext";
import { SubTotal } from "../../../../index";
import "./index.less";
var PREFIX = 'pisell-sale-detail-summary';
var PAYMENT_STATUS_COLOR_MAP = {
  unpaid: '#B2DDFF',
  payment_processing: '#FEDF89',
  payment_pending: '#FEDF89',
  authorized: '#ABEFC6',
  paid: '#ABEFC6',
  refunded: '#FECDCA',
  partially_refunded: '#FCCEEE',
  voided: '#D0D5DD'
};
var PAYMENT_STATUS_TEXT_KEY_MAP = {
  authorized: 'pisell2.sale-detail.paymentStatus.authorized',
  paid: 'pisell2.sale-detail.paymentStatus.paid',
  partially_paid: 'pisell2.sale-detail.paymentStatus.partially_paid',
  partially_refunded: 'pisell2.sale-detail.paymentStatus.partially_refunded',
  payment_pending: 'pisell2.sale-detail.paymentStatus.payment_pending',
  refunded: 'pisell2.sale-detail.paymentStatus.refunded',
  unpaid: 'pisell2.sale-detail.paymentStatus.unpaid',
  voided: 'pisell2.sale-detail.paymentStatus.voided',
  payment_processing: 'pisell2.sale-detail.paymentStatus.payment_processing'
};
var EMPTY_SUMMARY_VIEW = {
  amountLabel: '',
  amountText: '',
  paidText: '',
  statusText: '',
  statusStyle: {},
  totalText: '',
  itemCount: 0,
  isRefundAmount: false,
  subTotalList: [],
  orderTotalList: [],
  hasOrderTotal: false
};
function normalizeStatusText(status) {
  var key = status === null || status === void 0 ? void 0 : status.toLowerCase();
  var textKey = key && PAYMENT_STATUS_TEXT_KEY_MAP[key];
  return textKey ? locales.getText(textKey) : status || '';
}
function hexToRgba(hex, alpha) {
  var normalized = hex.replace('#', '');
  var value = normalized.length === 3 ? normalized.split('').map(function (char) {
    return char + char;
  }).join('') : normalized;
  var red = parseInt(value.slice(0, 2), 16);
  var green = parseInt(value.slice(2, 4), 16);
  var blue = parseInt(value.slice(4, 6), 16);
  return "rgba(".concat(red, ", ").concat(green, ", ").concat(blue, ", ").concat(alpha, ")");
}
function getPaymentStatusStyle(status) {
  var key = status === null || status === void 0 ? void 0 : status.toLowerCase();
  var color = key && PAYMENT_STATUS_COLOR_MAP[key] || '#D0D5DD';
  return {
    '--pisell-sale-detail-summary-status-color': color,
    '--pisell-sale-detail-summary-status-bg': hexToRgba(color, 0.16),
    '--pisell-sale-detail-summary-status-border': hexToRgba(color, 0.46),
    '--pisell-sale-detail-summary-status-glow': hexToRgba(color, 0.14)
  };
}
function getItemCountText(count) {
  var formatItemCount = locales.getText('pisell2.sale-detail.item-count');
  return typeof formatItemCount === 'function' ? formatItemCount(count) : "".concat(count, " ").concat(count === 1 ? 'item' : 'items');
}
export function Summary(_ref) {
  var _engineContext$appHel2, _summaryContext$sales4, _summaryContext$sales5, _summaryContext$summa;
  var className = _ref.className,
    _ref$defaultExpanded = _ref.defaultExpanded,
    defaultExpanded = _ref$defaultExpanded === void 0 ? false : _ref$defaultExpanded,
    summaryContext = _ref.context;
  var engineContext = useEngineContext();
  var _engineContext$appHel = (_engineContext$appHel2 = engineContext.appHelper) === null || _engineContext$appHel2 === void 0 ? void 0 : _engineContext$appHel2.utils,
    getData = _engineContext$appHel.getData;
  var _useState = useState(defaultExpanded),
    _useState2 = _slicedToArray(_useState, 2),
    showDetail = _useState2[0],
    setShowDetail = _useState2[1];
  var currentLocale = locales.getLocale();
  var summaryView = useMemo(function () {
    var _ref2, _summaryContext$sales, _summaryContext$sales2, _summaryContext$sales3, _ref3, _ref4, _tempOrder$payment_st, _tempOrder$payments$l, _tempOrder$payments, _getData, _summary$order_paid_a, _summary$total_amount;
    /** React 快照可能滞后于 OS；优先读顶层 tempOrder，否则回退 live getTempOrder。 */
    var tempOrder = (_ref2 = (_summaryContext$sales = summaryContext.sales.tempOrder) !== null && _summaryContext$sales !== void 0 ? _summaryContext$sales : (_summaryContext$sales2 = summaryContext.sales.bookingTicket) === null || _summaryContext$sales2 === void 0 || (_summaryContext$sales3 = _summaryContext$sales2.getTempOrder) === null || _summaryContext$sales3 === void 0 ? void 0 : _summaryContext$sales3.call(_summaryContext$sales2)) !== null && _ref2 !== void 0 ? _ref2 : null;
    var summary = (_ref3 = (_ref4 = summaryContext.summary.summary) !== null && _ref4 !== void 0 ? _ref4 : tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.summary) !== null && _ref3 !== void 0 ? _ref3 : null;
    if (!summary) {
      return EMPTY_SUMMARY_VIEW;
    }
    var symbol = (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.currency_symbol) || engineContext.appHelper.utils.getSymbolic();
    var translationOriginal = engineContext.appHelper.utils.translationOriginal;
    var paymentStatus = String((_tempOrder$payment_st = tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payment_status) !== null && _tempOrder$payment_st !== void 0 ? _tempOrder$payment_st : '').toLowerCase();
    var hasPayment = ((_tempOrder$payments$l = tempOrder === null || tempOrder === void 0 || (_tempOrder$payments = tempOrder.payments) === null || _tempOrder$payments === void 0 ? void 0 : _tempOrder$payments.length) !== null && _tempOrder$payments$l !== void 0 ? _tempOrder$payments$l : 0) > 0;
    var hasOrderPaidAmount = Number(summary.order_paid_amount) > 0;
    var isFullyPaid = paymentStatus === 'paid';
    var isRefundAmount = Number(summary.amount_gap) < 0;
    var isRefunded = paymentStatus === 'refunded' && Number(summary.total_refund_amount) >= 0;
    var isPartiallyRefunded = paymentStatus === 'partially_refunded' && Number(summary.total_refund_amount) >= 0;
    var amountLabelKey = '';
    var displayAmount = summary.amount_gap;
    if (isRefunded) {
      amountLabelKey = 'pisell2.sale-detail.refunded';
      displayAmount = summary.total_refund_amount;
    } else if (isPartiallyRefunded) {
      amountLabelKey = 'pisell2.sale-detail.partially-refunded';
      displayAmount = summary.total_refund_amount;
    } else {
      amountLabelKey = isRefundAmount ? 'pisell2.sale-detail.refund' : isFullyPaid ? 'pisell2.sale-detail.fully-paid' : 'pisell2.sale-detail.to-pay';
      if (!isFullyPaid && !hasOrderPaidAmount && !Number(summary.amount_gap)) {
        displayAmount = summary.total_amount;
      }
    }
    var amountLabel = locales.getText(amountLabelKey);
    var parsedTaxRate = Number((_getData = getData('tax_rate')) !== null && _getData !== void 0 ? _getData : 10);
    var surcharges = summary.surcharges ? summary.surcharges : [];
    var surchargeList = surcharges.filter(function (surcharge) {
      return surcharge.name;
    }).map(function (surcharge) {
      return {
        key: "custom_surcharge_".concat(surcharge.surcharge_id),
        value: surcharge.amount,
        label: translationOriginal(surcharge.name)
      };
    });
    var subTotalList = [{
      key: 'sub_total',
      value: summary.product_expect_amount
    }].concat(_toConsumableArray(surchargeList), [{
      key: 'tax',
      value: summary.tax_fee,
      tax: {
        is_price_include_tax: getData('is_price_include_tax'),
        rate: Number.isNaN(parsedTaxRate) ? 0.1 : parsedTaxRate / 100,
        title: getData('tax_title') || 'GST'
      }
    }, {
      key: 'discount',
      value: summary.discount_amount
    }, {
      key: 'expect_amount',
      value: summary.expect_amount,
      label: locales.getText('pisell2.sale-detail.total')
    }, {
      hidden: !Number(summary.rounding_amount),
      key: 'custom_roundingAmount',
      value: summary.rounding_amount,
      label: locales.getText('pisell2.sale-detail.rounding')
    }]);
    var orderTotalList = [{
      hidden: !hasPayment || !Number(summary.pay_service_charge_amount),
      key: 'custom_payServiceChargeAmount',
      value: summary.pay_service_charge_amount,
      label: locales.getText('pisell2.text.payment-service-charge')
    }, {
      hidden: !hasPayment,
      key: 'custom_orderPaidAmount',
      value: summary.order_paid_amount,
      label: locales.getText('pisell2.text.amount-paid-on-order')
    }, {
      hidden: !hasPayment,
      key: 'custom_actualPaidAmount',
      value: summary.customer_paid_amount,
      label: locales.getText('pisell2.text.amount-actually-paid-by-the-customer')
    }, {
      hidden: !hasPayment || !Number(summary.total_refund_amount),
      key: 'custom_totalRefundAmount',
      value: summary.total_refund_amount,
      label: locales.getText('pisell2.text.refunded-amount')
    }];
    return {
      amountLabel: amountLabel,
      amountText: formatAmount(displayAmount, 2, symbol),
      paidText: formatAmount((_summary$order_paid_a = summary.order_paid_amount) !== null && _summary$order_paid_a !== void 0 ? _summary$order_paid_a : 0, 2, symbol),
      statusText: normalizeStatusText(tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payment_status),
      statusStyle: getPaymentStatusStyle(tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payment_status),
      totalText: formatAmount((_summary$total_amount = summary.total_amount) !== null && _summary$total_amount !== void 0 ? _summary$total_amount : 0, 2, symbol),
      itemCount: Number(summary.product_quantity) || 0,
      isRefundAmount: isRefundAmount,
      subTotalList: subTotalList,
      orderTotalList: orderTotalList,
      hasOrderTotal: hasPayment
    };
  }, [engineContext, currentLocale, getData, (_summaryContext$sales4 = summaryContext.sales) === null || _summaryContext$sales4 === void 0 ? void 0 : _summaryContext$sales4.tempOrder, (_summaryContext$sales5 = summaryContext.sales) === null || _summaryContext$sales5 === void 0 ? void 0 : _summaryContext$sales5.bookingTicket, (_summaryContext$summa = summaryContext.summary) === null || _summaryContext$summa === void 0 ? void 0 : _summaryContext$summa.summary]);
  if (!summaryView.amountLabel) {
    return null;
  }
  return /*#__PURE__*/React.createElement("section", {
    className: classNames(PREFIX, _defineProperty({}, "".concat(PREFIX, "--open"), showDetail), className)
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__bar")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__left")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__headline")
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__label")
  }, summaryView.amountLabel), summaryView.statusText ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__status"),
    style: summaryView.statusStyle
  }, summaryView.statusText) : null), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__meta")
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__item-count")
  }, getItemCountText(summaryView.itemCount)), /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__dot")
  }), /*#__PURE__*/React.createElement("span", null, locales.getText('pisell2.sale-detail.total'), ' ', summaryView.totalText), /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__dot")
  }), /*#__PURE__*/React.createElement("span", null, locales.getText('pisell2.sale-detail.pay.paid'), ' ', summaryView.paidText))), /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: "".concat(PREFIX, "__detail-trigger"),
    onClick: function onClick() {
      return setShowDetail(function (visible) {
        return !visible;
      });
    }
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__detail-text")
  }, locales.getText('pisell2.sale-detail.details')), /*#__PURE__*/React.createElement("span", {
    className: classNames("".concat(PREFIX, "__amount"), _defineProperty({}, "".concat(PREFIX, "__amount--refund"), summaryView.isRefundAmount))
  }, summaryView.amountText))), /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(PREFIX, "__details"), _defineProperty({}, "".concat(PREFIX, "__details--open"), showDetail))
  }, /*#__PURE__*/React.createElement(SubTotal, {
    mode: "column1",
    list: summaryView.subTotalList
  }), summaryView.hasOrderTotal ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__divider")
  }) : null, summaryView.hasOrderTotal ? /*#__PURE__*/React.createElement(SubTotal, {
    mode: "column1",
    list: summaryView.orderTotalList,
    style: {
      padding: '0 0 10px'
    }
  }) : null));
}