"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _react = _interopRequireWildcard(require("react"));
require("./index.scss");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
/**
 * StreamList 组件
 */
var StreamList = function StreamList(_ref) {
  var children = _ref.children,
    onNextPage = _ref.onNextPage,
    onRefreshPage = _ref.onRefreshPage,
    _ref$refreshingText = _ref.refreshingText,
    refreshingText = _ref$refreshingText === void 0 ? '正在刷新中...' : _ref$refreshingText,
    _ref$loadingText = _ref.loadingText,
    loadingText = _ref$loadingText === void 0 ? '加载中...' : _ref$loadingText,
    _ref$loadMoreText = _ref.loadMoreText,
    loadMoreText = _ref$loadMoreText === void 0 ? '加载更多' : _ref$loadMoreText,
    _ref$isLastPage = _ref.isLastPage,
    isLastPage = _ref$isLastPage === void 0 ? false : _ref$isLastPage,
    _ref$nowPage = _ref.nowPage,
    nowPage = _ref$nowPage === void 0 ? 1 : _ref$nowPage;
  var _useState = (0, _react.useState)(false),
    isLoading = _useState[0],
    setIsLoading = _useState[1];
  var _useState2 = (0, _react.useState)(false),
    isRefreshing = _useState2[0],
    setIsRefreshing = _useState2[1];
  // 下拉刷新的阈值
  var threshold = 50;
  // 最大下拉距离
  var maxPullDistance = 100;
  var _useState3 = (0, _react.useState)(0),
    pullDistance = _useState3[0],
    setPullDistance = _useState3[1];
  var startYRef = (0, _react.useRef)(0);
  var _useState4 = (0, _react.useState)(false),
    isDragging = _useState4[0],
    setIsDragging = _useState4[1];
  var observerRef = (0, _react.useRef)(null);
  // 防止初始加载直接请求下一页
  var hasInitialLoad = (0, _react.useRef)(false);

  // 监听加载下一页数据
  (0, _react.useEffect)(function () {
    if (isRefreshing || isLastPage) {
      // @ts-ignore
      return;
    }
    var spinElement = document.querySelector('.spin');
    if (spinElement && !observerRef.current) {
      // 创建 IntersectionObserver 观察器
      observerRef.current = new IntersectionObserver(function (entries) {
        var entry = entries[0];
        if (entry.isIntersecting && !isLoading) {
          setIsLoading(true);
          var nextPage = nowPage + 1;
          onNextPage({
            page: nextPage
          }).then(function (res) {})["catch"](function (err) {
            console.error('加载下一页失败:', err);
          })["finally"](function () {
            return setIsLoading(false);
          });
        }
      }, {
        threshold: 0.4
      });
      // 观察加载更多元素
      observerRef.current.observe(spinElement);
    }
    return function () {
      if (observerRef.current) {
        // 清除观察者
        observerRef.current.disconnect();
        observerRef.current = null;
      }
    };
  }, [nowPage, isLoading, isRefreshing, isLastPage]);

  // 初始化加载标记
  (0, _react.useEffect)(function () {
    hasInitialLoad.current = true;
  }, []);

  // 处理触摸和鼠标事件
  var handleTouchStart = function handleTouchStart(e) {
    startYRef.current = 'touches' in e ? e.touches[0].clientY : e.clientY;
    setIsDragging(true);
  };
  var handleTouchMove = function handleTouchMove(e) {
    if (isRefreshing || !isDragging && !('touches' in e)) return;
    var clientY = 'touches' in e ? e.touches[0].clientY : e.clientY;
    var distance = clientY - startYRef.current;

    // 更新下拉距离
    if (distance > 0 && distance <= maxPullDistance) {
      setPullDistance(distance);
    } else if (distance > maxPullDistance) {
      setPullDistance(maxPullDistance);
    }
  };
  var handleTouchEnd = /*#__PURE__*/function () {
    var _ref2 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee() {
      return _regenerator["default"].wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            setIsDragging(false);
            if (pullDistance > threshold) {
              setIsRefreshing(true);
              setPullDistance(0);
              onRefreshPage().then(function (res) {})["catch"](function (err) {
                console.error('刷新失败:', err);
              })["finally"](function () {
                setIsRefreshing(false);
              });
            } else {
              setPullDistance(0); // 重置下拉距离
            }
          case 1:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function handleTouchEnd() {
      return _ref2.apply(this, arguments);
    };
  }();
  return /*#__PURE__*/_react["default"].createElement("div", {
    onTouchStart: handleTouchStart,
    onTouchMove: handleTouchMove,
    onTouchEnd: handleTouchEnd,
    onMouseDown: handleTouchStart,
    onMouseMove: handleTouchMove,
    onMouseUp: handleTouchEnd,
    className: "stream-list-container"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "refresh-indicator",
    style: {
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      transform: "translateY(" + (isRefreshing ? threshold : pullDistance) + "px)",
      transition: isRefreshing || pullDistance === 0 ? 'transform 0.3s ease' : 'none'
    }
  }, isRefreshing && /*#__PURE__*/_react["default"].createElement("span", null, refreshingText)), /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      transform: "translateY(" + (isRefreshing ? threshold : pullDistance) + "px)",
      transition: 'transform 0.3s ease'
    }
  }, children), !isRefreshing && !isLastPage && (isLoading ? /*#__PURE__*/_react["default"].createElement("div", {
    className: "loading-text"
  }, loadingText) : /*#__PURE__*/_react["default"].createElement("div", {
    className: "spin"
  }, loadMoreText)));
};
StreamList.displayName = 'StreamList';
var _default = exports["default"] = StreamList;