import 'package:flutter/widgets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class PullToRefresh extends StatelessWidget {
  /// 刷新加载包装的内容体
  final Widget child;

  final Widget? header;

  final Widget? footer;

  /// 刷新加载状态控制器
  final PullToRefreshController controller;

  /// 是否支持下拉刷新
  final bool enableRefresh;

  /// 是否支持上拉加载
  final bool enableLoadMore;

  /// 刷新回调
  final VoidCallback? onRefresh;

  /// 加载更多回调
  final VoidCallback? onLoadMore;

  const PullToRefresh({
    super.key,
    required this.controller,
    required this.child,
    this.header,
    this.footer,
    this.enableRefresh = false,
    this.enableLoadMore = false,
    this.onRefresh,
    this.onLoadMore,
  });

  @override
  Widget build(BuildContext context) {
    VoidCallback refreshCallback = onRefresh ??
        () => {
              // 默认1s之后重置刷新
              Future.delayed(const Duration(milliseconds: 1000), () {
                controller.refreshCompleted();
              })
            };
    VoidCallback loadMoreCallback = onLoadMore ??
        () => {
              // 默认1s之后结束加载更多
              Future.delayed(const Duration(milliseconds: 1000), () {
                controller.loadMoreComplete();
              })
            };

    return SmartRefresher(
      controller: controller._refreshController,
      enablePullDown: enableRefresh,
      enablePullUp: enableLoadMore,
      header: header,
      footer: footer,
      onRefresh: refreshCallback,
      onLoading: loadMoreCallback,
      child: child,
    );
  }
}

class PullToRefreshController {
  RefreshController? _rController;

  RefreshController get _refreshController {
    _rController ??= RefreshController(initialRefresh: false);
    return _rController!;
  }

  /// 请求刷新
  void requestRefresh() {
    _refreshController.requestRefresh();
  }

  /// 完成刷新
  void refreshCompleted() {
    _refreshController.refreshCompleted(resetFooterState: true);
  }

  /// 加载更多完成
  void loadMoreComplete({bool success = true}) {
    success
        ? _refreshController.loadComplete()
        : _refreshController.loadFailed();
  }

  /// 加载更多完成并没有更多数据
  void loadMoreCompleteWithNoData() {
    _refreshController.loadNoData();
  }

  /// 重置加载更多
  void resetLoadMoreData() {
    _refreshController.resetNoData();
  }

  /// 是否正在刷新
  bool get isRefresh => _refreshController.isRefresh;

  /// 是否正在加载
  bool get isLoading => _refreshController.isLoading;
}
