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, useCallback } from 'react';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';
import timezonePlugin from 'dayjs/plugin/timezone';
import utcPlugin from 'dayjs/plugin/utc';
import { locales } from '@pisell/utils';
import { Timeline, Skeleton, PisellEmpty, usePisellConfig, PisellModal, PisellStatisticList, Button } from '@pisell/materials';
import { getAssetList, getActiveLogs } from "../../serve";
import "./index.less";
dayjs.extend(timezonePlugin);
dayjs.extend(utcPlugin);
var stateTimeUnix = 1723255863; // 2024.8.10 时间戳
var TimelineSection = function TimelineSection(props) {
  var code = props.code,
    tag = props.tag,
    timezone = props.timezone,
    apiPrefix = props.apiPrefix,
    isTerminalEnv = props.isTerminalEnv,
    interaction = props.interaction;
  var _usePisellConfig = usePisellConfig(),
    _usePisellConfig$symb = _usePisellConfig.symbol,
    symbol = _usePisellConfig$symb === void 0 ? '$' : _usePisellConfig$symb;
  var _React$useState = React.useState(false),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    isShowtimeLineDetail = _React$useState2[0],
    setIsShowtimeLineDetail = _React$useState2[1];
  var _React$useState3 = React.useState(true),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    isSpending = _React$useState4[0],
    setIsSpending = _React$useState4[1];
  var _React$useState5 = React.useState(null),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    timeLineDetail = _React$useState6[0],
    setTimeLineDetail = _React$useState6[1];
  var assetActionEnum = useMemo(function () {
    return {
      recharge: tag === 'point_card' ? locales.getText('wallet-pass-gallery.pointsEarned') : locales.getText('wallet-pass-gallery.recharge'),
      order_expend: tag === 'point_card' ? locales.getText('wallet-pass-gallery.pointsRedeemed') : locales.getText('wallet-pass-gallery.spending'),
      order_refund: locales.getText('wallet-pass-gallery.refund'),
      expire: locales.getText('wallet-pass-gallery.expire')
    };
  }, [tag]);
  var formatCurrencyAmount = useCallback(function () {
    var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
    var isNegative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    if (!amount) return '';
    if (tag === 'good_pass') return locales.getText('wallet-pass-gallery.goodPass.usedCredit')(parseInt(amount));
    var absAmount = amount.startsWith('-') ? amount.substring(1) : amount;
    var showSymbol = !['point_card', 'good_pass'].includes(tag);
    return isNegative ? "-".concat(showSymbol ? symbol : '').concat(absAmount) : "".concat(showSymbol ? symbol : '').concat(amount);
  }, [symbol, tag]);
  var timeTreeNode = useCallback(function (data) {
    var _data$action = data.action,
      action = _data$action === void 0 ? '' : _data$action,
      _data$created_at = data.created_at,
      created_at = _data$created_at === void 0 ? '' : _data$created_at,
      _data$amount = data.amount,
      amount = _data$amount === void 0 ? '' : _data$amount,
      _data$currency_symbol = data.currency_symbol,
      currency_symbol = _data$currency_symbol === void 0 ? '' : _data$currency_symbol;
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-wallet-pass-gallery_timeline-node"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-wallet-pass-gallery_timeline-node-left"
    }, /*#__PURE__*/React.createElement("p", {
      className: "pisell-wallet-pass-gallery_timeline-node-action"
    }, action ? assetActionEnum[action] : ''), created_at && /*#__PURE__*/React.createElement("p", {
      className: "pisell-wallet-pass-gallery_timeline-node-time"
    }, created_at, (action === 'recharge' || action === 'order_expend') && /*#__PURE__*/React.createElement("button", {
      type: "button",
      className: "pisell-wallet-pass-gallery_timeline-node-detail-link",
      onClick: function onClick() {
        setIsShowtimeLineDetail(true);
        setIsSpending(action === 'order_expend');
        setTimeLineDetail(data);
      },
      style: {
        background: 'transparent',
        border: 'none',
        padding: 0
      }
    }, locales.getText('wallet-pass-gallery.viewDetails')))), /*#__PURE__*/React.createElement("div", {
      className: "pisell-wallet-pass-gallery_timeline-node-amount".concat(action === 'recharge' ? ' pisell-wallet-pass-gallery_timeline-node-amount-positive' : '').concat(action === 'order_expend' ? ' pisell-wallet-pass-gallery_timeline-node-amount-negative' : '')
    }, amount && currency_symbol ? formatCurrencyAmount(amount, action === 'order_expend') : ''));
  }, [assetActionEnum, formatCurrencyAmount]);
  var assetListReq = useRequest(function () {
    if (apiPrefix === '/shop') {
      return getActiveLogs({
        filter_card_id: code
      });
    }
    return getAssetList({
      num: '99',
      skip: '1',
      card_id: code,
      sourceType: tag,
      tag: tag,
      business_object: 'customer'
    });
  }, {
    ready: !!code,
    refreshDeps: [code, tag]
  });
  var timelineItems = useMemo(function () {
    var _assetListReq$data;
    var list = ((_assetListReq$data = assetListReq.data) === null || _assetListReq$data === void 0 ? void 0 : _assetListReq$data.list) || [];
    if (!Array.isArray(list) || list.length === 0) return [];
    var filteredByAction = list.filter(function (item) {
      return !!assetActionEnum[item.action || ''];
    });
    var filteredByTime = filteredByAction.filter(function (item) {
      var itemUnix = dayjs.tz((item === null || item === void 0 ? void 0 : item.created_at) || '', timezone).unix();
      if ((item === null || item === void 0 ? void 0 : item.action) === 'order_expend' && itemUnix < stateTimeUnix) return false;
      if ((item === null || item === void 0 ? void 0 : item.tag) === 'point_card' && itemUnix < stateTimeUnix) return false;
      return true;
    });
    var nonZeroPoint = filteredByTime.filter(function (it) {
      return !(it.tag === 'point_card' && (it.amount === '0' || parseFloat(it.amount || '0') === 0));
    });
    return nonZeroPoint.map(function (item) {
      return {
        children: assetActionEnum[(item === null || item === void 0 ? void 0 : item.action) || ''] ? timeTreeNode(item) : null
      };
    });
  }, [assetListReq.data, assetActionEnum, timeTreeNode, timezone, stateTimeUnix]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_timeline-subtitle"
  }, locales.getText('wallet-pass-gallery.activelog')), assetListReq.loading ? /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_timeline-loading"
  }, /*#__PURE__*/React.createElement(Skeleton, {
    active: true,
    paragraph: {
      rows: 6
    },
    round: true
  })) : timelineItems.length > 0 ? /*#__PURE__*/React.createElement(Timeline, {
    items: timelineItems,
    className: "pisell-wallet-pass-gallery_timeline-list"
  }) : /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_timeline-empty"
  }, /*#__PURE__*/React.createElement(PisellEmpty, null)), /*#__PURE__*/React.createElement(PisellModal, {
    platform: 'pc',
    mobileModalHeight: "auto",
    cancelVisible: false,
    destroyOnClose: true,
    onCancel: function onCancel() {
      return setIsShowtimeLineDetail(false);
    },
    title: isSpending ? locales.getText('wallet-pass-gallery.spendingDetails') : locales.getText('wallet-pass-gallery.rechargeDetails'),
    open: isShowtimeLineDetail,
    footer: [/*#__PURE__*/React.createElement(Button, {
      type: "primary",
      block: true,
      size: "large",
      onClick: function onClick() {
        return setIsShowtimeLineDetail(false);
      }
    }, locales.getText('wallet-pass-gallery.done'))]
  }, /*#__PURE__*/React.createElement(PisellStatisticList, {
    data: [{
      label: locales.getText('wallet-pass-gallery.date'),
      value: (timeLineDetail === null || timeLineDetail === void 0 ? void 0 : timeLineDetail.created_at) || ''
    }, {
      label: isSpending ? locales.getText('wallet-pass-gallery.spending') : locales.getText('wallet-pass-gallery.recharge'),
      value: formatCurrencyAmount((timeLineDetail === null || timeLineDetail === void 0 ? void 0 : timeLineDetail.amount) || '', isSpending)
    }, {
      label: locales.getText('wallet-pass-gallery.viewOrder'),
      value: timeLineDetail && timeLineDetail !== null && timeLineDetail !== void 0 && timeLineDetail.resource_code ? "#".concat(timeLineDetail === null || timeLineDetail === void 0 ? void 0 : timeLineDetail.resource_code) : timeLineDetail !== null && timeLineDetail !== void 0 && timeLineDetail.transaction_id ? "#".concat(timeLineDetail === null || timeLineDetail === void 0 ? void 0 : timeLineDetail.transaction_id) : '',
      isLink: !!(timeLineDetail && timeLineDetail !== null && timeLineDetail !== void 0 && timeLineDetail.resource_id),
      onClick: function onClick() {
        if (isTerminalEnv) {
          var _interaction$utils, _interaction$utils$po;
          return interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$po = _interaction$utils.postMessageToApp) === null || _interaction$utils$po === void 0 ? void 0 : _interaction$utils$po.call(_interaction$utils, {
            module: 'booking',
            key: 'view_order',
            data: {
              order_id: timeLineDetail === null || timeLineDetail === void 0 ? void 0 : timeLineDetail.resource_id
            },
            origin: '/booking'
          });
        }
        var link = apiPrefix === '/shop' ? "/admin/order/orders/detail?id=".concat(timeLineDetail === null || timeLineDetail === void 0 ? void 0 : timeLineDetail.resource_id) : "/order/details?id=".concat(timeLineDetail === null || timeLineDetail === void 0 ? void 0 : timeLineDetail.resource_id);
        location.replace(link);
      },
      link: timeLineDetail && timeLineDetail !== null && timeLineDetail !== void 0 && timeLineDetail.resource_id ? true : undefined
    }],
    labelColor: "#101828",
    valueColor: "#101828",
    backgroundColors: ['#fff'],
    isHasBorder: false
  })));
};
export default TimelineSection;