import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { useEffect, useRef, useState } from 'react';
import "./index.scss";
/**
 * 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 = useState(false),
    isLoading = _useState[0],
    setIsLoading = _useState[1];
  var _useState2 = useState(false),
    isRefreshing = _useState2[0],
    setIsRefreshing = _useState2[1];
  // 下拉刷新的阈值
  var threshold = 50;
  // 最大下拉距离
  var maxPullDistance = 100;
  var _useState3 = useState(0),
    pullDistance = _useState3[0],
    setPullDistance = _useState3[1];
  var startYRef = useRef(0);
  var _useState4 = useState(false),
    isDragging = _useState4[0],
    setIsDragging = _useState4[1];
  var observerRef = useRef(null);
  // 防止初始加载直接请求下一页
  var hasInitialLoad = useRef(false);

  // 监听加载下一页数据
  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]);

  // 初始化加载标记
  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 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      return _regeneratorRuntime.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.createElement("div", {
    onTouchStart: handleTouchStart,
    onTouchMove: handleTouchMove,
    onTouchEnd: handleTouchEnd,
    onMouseDown: handleTouchStart,
    onMouseMove: handleTouchMove,
    onMouseUp: handleTouchEnd,
    className: "stream-list-container"
  }, /*#__PURE__*/React.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.createElement("span", null, refreshingText)), /*#__PURE__*/React.createElement("div", {
    style: {
      transform: "translateY(" + (isRefreshing ? threshold : pullDistance) + "px)",
      transition: 'transform 0.3s ease'
    }
  }, children), !isRefreshing && !isLastPage && (isLoading ? /*#__PURE__*/React.createElement("div", {
    className: "loading-text"
  }, loadingText) : /*#__PURE__*/React.createElement("div", {
    className: "spin"
  }, loadMoreText)));
};
StreamList.displayName = 'StreamList';
export default StreamList;