import 'package:flutter/material.dart';
import 'package:get/get.dart';

typedef GetJson = Widget Function(BuildContext context, List<dynamic> jsonData);

class MoreList extends StatefulWidget {
  final Future Function(Map params)? serves;
  final Map? params;
  final GetJson? getJson;
  final Widget? child;

  const MoreList(
      {Key? key,
      required this.serves,
      required this.getJson,
      this.child,
      required this.params})
      : super(key: key);

  @override
  _MoreList createState() => _MoreList(serves, params);
}

//传一个serves进来传一个json出去
class _MoreList extends State<MoreList> {
  final Future Function(Map params)? serves;
  final Map? params;
  final jsonData = Rx<List<dynamic>>([]);
  _MoreList(this.serves, this.params);

  final ScrollController _scrollController = ScrollController();
  final _page = Rx<int>(1);
  bool isLoading = false;
  final hasMore = Rx<bool>(false);

  @override
  void initState() {
    super.initState();
    getList();
    addEvent();
  }
  void addEvent(){
    _scrollController.addListener(() {
      if (!hasMore.value) {
        print('暂无更多');
        return;
      }
      if (!isLoading &&
          _scrollController.position.pixels >=
              _scrollController.position.maxScrollExtent) {
        _page.value++;
        params!['pageNum'] = _page.value;
        getList();
      }
    });
  }

  void getList() {
    if (serves != null) {
      isLoading = true;
      serves!(params!).then((res) {
        var list = [];
        list = [...jsonData.value, ...res['records']];
        jsonData.value = list;
        if (res['total'] > jsonData.value.length) {
          hasMore.value = true;
        }else {
          hasMore.value = false;
        }
        isLoading=false;
      });
    }
  }

  Future onRefresh() {
    return Future.delayed(Duration(seconds: 1), () {
      _page.value = 1;
      jsonData.value = [];
      params!['pageNum'] = _page.value;
      getList();
    });
  }

  @override
  Widget build(BuildContext context) {
    if (serves == null)
      return ListView(
        children: [widget.child!],
      );
    return RefreshIndicator(
        onRefresh: onRefresh,
        child: ListView.builder(
            controller: _scrollController,
            itemCount: 1,
            itemBuilder: (BuildContext context, int position) {
              return Obx(() => widget.getJson!(context, jsonData.value));
            }));
  }
}
