import 'package:flutter/widgets.dart';
import '/models/entities/PagedResult.dart';

class LoadMore extends StatefulWidget {
  LoadMore({
    Key? key,
    required this.builder,
    required this.fetch,
    this.onError,
  }) : super(key: key);

  Future Function(Map param) fetch;
  Function? onError;

  Widget Function({
    required BuildContext context,
    required ScrollController scrollController,
    required PagedResult data,
    required bool haveMore,
  }) builder;

  @override
  State<StatefulWidget> createState() => _LoadMoreState();
}

class _LoadMoreState extends State<LoadMore> {
  final _controller = ScrollController();
  // 是否还有更多
  bool haveMore = true;

  PagedResult result = PagedResult(total: 0, size: 0, pages: 0, current: 0);
  List<dynamic> listData = [];

  @override
  initState() {
    super.initState();

    // 添加滚动监听
    _controller.addListener(() {
      //当滚动到最底部的时候，加载新的数据
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        //当还有更多数据的时候才会进行加载新数据
        if (haveMore) {
          fetchData();
        }
      }
    });

    fetchData();
  }

  Future fetchData() {
    final pageNum = result.current + 1;
    final pageSize = result.size == 0 ? 10 : result.size;
    Map<String, dynamic> params = {"pageNum": pageNum, "pageSize": pageSize};
    return Future.value(widget.fetch(params).then((res) {
      setState(() {
        result = PagedResult.fromJson(res);
        // 如果当前页小于总页数
        haveMore = result.current < result.pages;
      });
    }).catchError((err) {
      print(err);
      if (null != widget.onError) {
        widget.onError!(err);
      }
    }));
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(
      context: context,
      scrollController: _controller,
      data: result,
      haveMore: haveMore,
    );
  }
}
