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 _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, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Popover } from 'antd';
import classNames from 'classnames';
import Decimal from 'decimal.js';
import { Iconfont } from '@pisell/materials';
import { formatAmount, locales } from '@pisell/utils';
import { getElementScaleX, getElementScaleY, useElementScale } from "../../../../hooks/useElementScale";
import useEngineContext from "../../../../hooks/useEngineContext";
import PisellSaleSummaryDetail from "../../../pisellSaleSummaryDetail";
import { usePaymentMethodNameMap } from "../../../pisellSalesManagement/hooks/usePaymentMethodNameMap";
import "./index.less";
var PREFIX = 'pisell-sale-detail-summary';
var POPOVER_WIDTH_RATIO = 0.85;
var POPOVER_VIEWPORT_MARGIN = 24;
var POPOVER_MIN_HEIGHT = 160;
var PAYMENT_STATUS_COLOR_MAP = {
  unpaid: '#B2DDFF',
  payment_processing: '#FEDF89',
  payment_pending: '#FEDF89',
  authorized: '#ABEFC6',
  paid: '#ABEFC6',
  refunded: '#FECDCA',
  partially_refunded: '#FCCEEE',
  partially_paid: '#FDB022',
  voided: '#D0D5DD'
};
var EMPTY_SUMMARY_VIEW = {
  amountLabel: '',
  amountText: '',
  savedText: '',
  hasSavedAmount: false,
  statusStyle: {},
  isRefundAmount: false
};
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 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');
  if (typeof formatItemCount === 'function') {
    return formatItemCount(count);
  }
  var itemLabel = locales.getText('pisell2.sale-detail.item');
  return itemLabel === 'pisell2.sale-detail.item' ? "".concat(count) : "".concat(count, " ").concat(itemLabel);
}
export function Summary(_ref) {
  var _engineContext$appHel, _summaryContext$sales4, _summaryContext$sales5, _summaryContext$summa, _summary$expect_amoun, _summary$order_paid_a;
  var className = _ref.className,
    _ref$defaultExpanded = _ref.defaultExpanded,
    defaultExpanded = _ref$defaultExpanded === void 0 ? false : _ref$defaultExpanded,
    summaryContext = _ref.context;
  var engineContext = useEngineContext();
  var appUtils = (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.utils;
  var getData = appUtils === null || appUtils === void 0 ? void 0 : appUtils.getData;
  var paymentMethodNameMap = usePaymentMethodNameMap();
  var _useState = useState(defaultExpanded),
    _useState2 = _slicedToArray(_useState, 2),
    showDetail = _useState2[0],
    setShowDetail = _useState2[1];
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    popoverWidth = _useState4[0],
    setPopoverWidth = _useState4[1];
  var _useState5 = useState(),
    _useState6 = _slicedToArray(_useState5, 2),
    popoverMaxHeight = _useState6[0],
    setPopoverMaxHeight = _useState6[1];
  var summaryRef = useRef(null);
  var bodyElement = typeof document === 'undefined' ? null : document.body;
  var bodyScale = useElementScale(bodyElement);
  var updatePopoverSize = useCallback(function () {
    var _viewport$offsetTop;
    var target = summaryRef.current;
    if (!target) return;
    var rect = target.getBoundingClientRect();
    var scaleX = getElementScaleX(bodyElement) || 1;
    var scaleY = getElementScaleY(bodyElement) || 1;
    var viewport = window.visualViewport;
    var viewportTop = (_viewport$offsetTop = viewport === null || viewport === void 0 ? void 0 : viewport.offsetTop) !== null && _viewport$offsetTop !== void 0 ? _viewport$offsetTop : 0;
    var availableHeight = (rect.top - viewportTop - POPOVER_VIEWPORT_MARGIN) / scaleY;
    setPopoverWidth(rect.width / scaleX * POPOVER_WIDTH_RATIO);
    setPopoverMaxHeight(Math.max(POPOVER_MIN_HEIGHT, availableHeight));
  }, [bodyElement]);
  useEffect(function () {
    var _window$visualViewpor;
    if (!showDetail) return undefined;
    updatePopoverSize();
    window.addEventListener('resize', updatePopoverSize);
    (_window$visualViewpor = window.visualViewport) === null || _window$visualViewpor === void 0 || _window$visualViewpor.addEventListener('resize', updatePopoverSize);
    var summaryResizeObserver = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updatePopoverSize) : null;
    if (summaryRef.current) {
      summaryResizeObserver === null || summaryResizeObserver === void 0 || summaryResizeObserver.observe(summaryRef.current);
    }
    return function () {
      var _window$visualViewpor2;
      window.removeEventListener('resize', updatePopoverSize);
      (_window$visualViewpor2 = window.visualViewport) === null || _window$visualViewpor2 === void 0 || _window$visualViewpor2.removeEventListener('resize', updatePopoverSize);
      summaryResizeObserver === null || summaryResizeObserver === void 0 || summaryResizeObserver.disconnect();
    };
  }, [showDetail, updatePopoverSize]);
  useEffect(function () {
    if (showDetail) {
      updatePopoverSize();
    }
  }, [bodyScale.x, bodyScale.y, showDetail, updatePopoverSize]);
  var handleDetailOpenChange = useCallback(function (open) {
    if (open) {
      updatePopoverSize();
    }
    setShowDetail(open);
  }, [updatePopoverSize]);
  var handlePopoverOpenChange = useCallback(function (open) {
    if (!open) {
      handleDetailOpenChange(false);
    }
  }, [handleDetailOpenChange]);
  var handlePopoverAfterOpenChange = useCallback(function (open) {
    if (!open) {
      setPopoverWidth(undefined);
      setPopoverMaxHeight(undefined);
    }
  }, []);
  var orderSnapshot = useMemo(function () {
    var _ref2, _summaryContext$sales, _summaryContext$sales2, _summaryContext$sales3, _ref3, _ref4, _tempOrder$payment_st, _appUtils$getSymbolic;
    /** 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;
    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();
    return {
      tempOrder: tempOrder,
      summary: summary,
      symbol: (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.currency_symbol) || (appUtils === null || appUtils === void 0 || (_appUtils$getSymbolic = appUtils.getSymbolic) === null || _appUtils$getSymbolic === void 0 ? void 0 : _appUtils$getSymbolic.call(appUtils)) || '',
      paymentStatus: paymentStatus
    };
  }, [appUtils, (_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]);
  var detailDataSource = useMemo(function () {
    var summary = orderSnapshot.summary,
      tempOrder = orderSnapshot.tempOrder,
      symbol = orderSnapshot.symbol;
    if (!summary) return undefined;
    return {
      summary: summary,
      payments: tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payments,
      paymentStatus: tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payment_status,
      shopDiscount: tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.shop_discount,
      currencySymbol: symbol,
      taxTitle: (getData === null || getData === void 0 ? void 0 : getData('tax_title')) || summary.tax_title,
      paymentMethodNameMap: paymentMethodNameMap
    };
  }, [getData, orderSnapshot, paymentMethodNameMap]);
  var summaryView = useMemo(function () {
    var summary = orderSnapshot.summary,
      tempOrder = orderSnapshot.tempOrder,
      symbol = orderSnapshot.symbol,
      paymentStatus = orderSnapshot.paymentStatus;
    if (!summary) {
      return EMPTY_SUMMARY_VIEW;
    }
    var isFullyPaid = paymentStatus === 'paid';
    var balanceDueAmount = paymentStatus === 'payment_processing' ? summary.expect_amount : summary.amount_gap;
    var isRefundAmount = toDecimal(balanceDueAmount).lt(0);
    var isRefunded = paymentStatus === 'refunded' && Number(summary.total_refund_amount) > 0;
    var isPartiallyRefunded = paymentStatus === 'partially_refunded' && Number(summary.total_refund_amount) > 0;
    var amountLabelKey = '';
    if (isRefunded) {
      amountLabelKey = 'pisell2.sale-detail.refunded';
    } else if (isPartiallyRefunded) {
      amountLabelKey = 'pisell2.sale-detail.partially-refunded';
    } else {
      amountLabelKey = isRefundAmount ? 'pisell2.sale-detail.refund' : isFullyPaid ? 'pisell2.sale-detail.fully-paid' : 'pisell2.sale-detail.to-pay';
    }
    var amountLabel = locales.getText(amountLabelKey);
    return {
      amountLabel: amountLabel,
      amountText: formatAmount(balanceDueAmount, 2, symbol),
      savedText: formatAmount(toDecimal(summary.discount_amount).abs().toString(), 2, symbol),
      hasSavedAmount: isNonZeroAmount(summary.discount_amount),
      statusStyle: getPaymentStatusStyle(tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.payment_status),
      isRefundAmount: isRefundAmount
    };
  }, [orderSnapshot]);
  var summary = orderSnapshot.summary;
  var symbol = orderSnapshot.symbol;
  var itemCount = Number(summary === null || summary === void 0 ? void 0 : summary.product_quantity) || 0;
  var totalText = formatAmount((_summary$expect_amoun = summary === null || summary === void 0 ? void 0 : summary.expect_amount) !== null && _summary$expect_amoun !== void 0 ? _summary$expect_amoun : 0, 2, symbol);
  var paidText = formatAmount((_summary$order_paid_a = summary === null || summary === void 0 ? void 0 : summary.order_paid_amount) !== null && _summary$order_paid_a !== void 0 ? _summary$order_paid_a : 0, 2, symbol);
  var hasPaymentSurcharge = toDecimal(summary === null || summary === void 0 ? void 0 : summary.surcharge_fee).gt(0);
  if (!summaryView.amountLabel) {
    return null;
  }
  return /*#__PURE__*/React.createElement(Popover, {
    open: showDetail,
    trigger: "click",
    placement: "top",
    arrow: false,
    destroyTooltipOnHide: true,
    overlayClassName: "".concat(PREFIX, "__popover-overlay"),
    overlayInnerStyle: {
      padding: 0,
      overflow: 'hidden',
      border: '1px solid var(--theme-color)'
    },
    overlayStyle: {
      width: popoverWidth,
      maxWidth: 'calc(100vw - 32px)'
    },
    onOpenChange: handlePopoverOpenChange,
    afterOpenChange: handlePopoverAfterOpenChange,
    content: /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__popover-panel"),
      style: {
        maxHeight: popoverMaxHeight
      }
    }, /*#__PURE__*/React.createElement("button", {
      type: "button",
      className: "".concat(PREFIX, "__popover-header"),
      "aria-label": String(locales.getText('pisell2.sale-detail.customer-detail')),
      onClick: function onClick() {
        return handleDetailOpenChange(false);
      }
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__popover-handle")
    }, /*#__PURE__*/React.createElement(Iconfont, {
      type: "pisell2-chevron-down-double"
    }))), /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__popover-content")
    }, /*#__PURE__*/React.createElement(PisellSaleSummaryDetail, {
      dataSource: detailDataSource
    })))
  }, /*#__PURE__*/React.createElement("section", {
    ref: summaryRef,
    className: classNames(PREFIX, _defineProperty({}, "".concat(PREFIX, "--open"), showDetail), className)
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__bar")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__top")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__meta")
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__item-count")
  }, getItemCountText(itemCount)), /*#__PURE__*/React.createElement("span", null, locales.getText('pisell2.sale-detail.total'), " ", totalText), /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__dot")
  }), /*#__PURE__*/React.createElement("span", null, locales.getText('pisell2.sale-detail.pay.paid'), " ", paidText), summaryView.hasSavedAmount ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__saved")
  }, locales.getText('pisell2.sale-detail.saved'), ' ', summaryView.savedText) : null, hasPaymentSurcharge ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__payment-sc-note")
  }, locales.getText('pisell2.sale-detail.excl-payment-sc')) : null), /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: "".concat(PREFIX, "__detail-trigger"),
    "aria-expanded": showDetail,
    onClick: function onClick() {
      return handleDetailOpenChange(!showDetail);
    }
  }, /*#__PURE__*/React.createElement("span", {
    className: classNames("".concat(PREFIX, "__detail-icon"), _defineProperty({}, "".concat(PREFIX, "__detail-icon--open"), showDetail)),
    "aria-hidden": true
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__detail-chevron")
  })), /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__detail-text")
  }, locales.getText('pisell2.sale-detail.customer-detail')))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__bottom")
  }, summaryView.amountLabel ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__status"),
    style: summaryView.statusStyle
  }, String(summaryView.amountLabel).toUpperCase()) : null, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__balance")
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "__balance-label")
  }, locales.getText('pisell2.sale-detail.balance-due')), /*#__PURE__*/React.createElement("span", {
    className: classNames("".concat(PREFIX, "__amount"), _defineProperty({}, "".concat(PREFIX, "__amount--refund"), summaryView.isRefundAmount))
  }, summaryView.amountText))))));
}