import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'YSNetWork.dart';
import 'YSTools.dart';

GlobalKey<YSRefreshLoadState> refreshKey = GlobalKey();
GlobalKey<YSRefreshLoadState> refreshKey2 = GlobalKey();
GlobalKey<YSRefreshLoadState> refreshKey3 = GlobalKey();
GlobalKey<YSRefreshLoadState> refreshKey4 = GlobalKey();
class YSRefreshLoad extends StatefulWidget {
  final Widget child;
  final ValueSetter postData;
  final String url;
  final Map request;
  const YSRefreshLoad({Key? key, required this.url, required this.request, required this.child, required this.postData,}) : super(key: key);
  @override
  YSRefreshLoadState createState() => YSRefreshLoadState();
}

class YSRefreshLoadState extends State<YSRefreshLoad> {
  int _page = 1;
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  List _dataArray = [];
  int _totalNum = 0;
  bool _isNull = true;
  Map _searchRequest = {};
  @override
  void initState() {
    Future.delayed(const Duration(seconds: 0)).then((value){
      _refreshData();
    });
    super.initState();
  }

  refresh({Map? request}){
    if(request!=null){
      _searchRequest = request;
    }
    _refreshData();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _isNull==true?Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset('images/tzh_null.png',height: hsp(102),width: hsp(175),),
          Text('\n暂无内容\n\n\n\n\n\n\n\n',style: TextStyle(fontSize: zsp(14),color: Color(0xFFC8C9CC)),)
        ],
      ),
    ):SmartRefresher(
        onRefresh: _refreshData,
        onLoading: _loadMore,
        enablePullUp: _dataArray.length<_totalNum,
        controller: _refreshController,
        header: const ClassicHeader(
          height: 45.0,
          releaseText: '松开手刷新',
          refreshingText: '刷新中',
          completeText: '刷新完成',
          failedText: '刷新失败',
          idleText: '下拉刷新',
        ),
        footer: const ClassicFooter(
          height: 45.0,
          canLoadingText: '没有更多数据了',
          noDataText: ' 无数据',
          loadingText: '加载中 ',
          failedText: '加载失败',
          idleText: '上拉加载',
        ),
        child: NotificationListener<CustomNotification>(
          onNotification: (value){
            _refreshData();
            return true;
          },
          child: _dataArray.isEmpty?Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset('images/tzh_null.png',height: hsp(102),width: hsp(175),),
                Text('\n暂无内容\n\n\n\n\n\n\n\n',style: TextStyle(fontSize: zsp(14),color: const Color(0xFFC8C9CC)),)
              ],
            ),
          ):widget.child,
        )
    );
  }

  Future<void> _refreshData() async{
    _page = 1;
    Map request = {'current':_page,'size':'10'};
    request.addAll(widget.request);
    if(_searchRequest.isNotEmpty)request.addAll(_searchRequest);
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: widget.url, parameter: request, successSetter: (dict){
      _isNull = false;
      Map data = dict['data']?? {};
      _totalNum = data['total']??0;
      _dataArray = data['records']??[];
      _refreshController.refreshCompleted();
      widget.postData(_dataArray);
    },isLoading: true);
  }

  Future<void> _loadMore() async{
    _page++;
    Map request = {'current':_page,'size':'10'};
    request.addAll(widget.request);
    if(_searchRequest.isNotEmpty)request.addAll(_searchRequest);
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: widget.url, parameter: request, successSetter: (dict){
      Map data = dict['data']?? {};
      _dataArray.addAll(data['records']??[]);
      _refreshController.loadComplete();
      widget.postData(_dataArray);
    },isLoading: true);
  }
}


class CustomNotification extends Notification {
  CustomNotification(this.value);
  final String value;
}
