import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:sport/services/api/resp.dart';

import 'view_state_list_model.dart';

/// 基于
abstract class ViewStateRefreshListModel<T> extends ViewStateListModel<T> {
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 分页条目数量
  int pageSize = 20;
  int pageTotal = 0;

  EasyRefreshController _refreshController = EasyRefreshController();

  EasyRefreshController get refreshController => _refreshController;

  /// 当前页码
  int _currentPageNum = pageNumFirst;

  bool hasMore = false;

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List<T>> refresh({bool init = false}) async {
    try {
      list.clear();
      _currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      refreshController.finishRefresh();
      if (data.isEmpty) {
        refreshController.finishLoad(success: true, noMore: true);
        setEmpty();
      } else {
        onCompleted(data);
        list.addAll(data);

        if (pageTotal > 0) {
          hasMore = _currentPageNum < pageTotal;
        } else {
          if (data.length < pageSize) {
            hasMore = false;
          } else {
            hasMore = true;
          }
        }

        setIdle();

        SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) {
          // 小于分页的数量,禁止上拉加载更多
          if (data.length < pageSize) {
            refreshController.finishLoad(success: true, noMore: !hasMore);
            setIdle();
          } else {
            //防止上次上拉加载更多失败,需要重置状态
            refreshController.finishLoad();
          }
        });
      }
      return data;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.finishRefresh(success: false);
      // setError(e, s);
      setEmpty();
      return null;
    }
  }

  /// 上拉加载更多
  Future<List<T>> loadMore() async {
    try {
      var data = await loadData(pageNum: ++_currentPageNum);
      if (data.isEmpty) {
        _currentPageNum--;
        refreshController.finishLoad(noMore: true);
      } else {
        onCompleted(data);
        list.addAll(data);
        if (data.length < pageSize) {
          refreshController.finishLoad(noMore: true);
        } else {
          refreshController.finishLoad();
        }
        notifyListeners();
      }
      return data;
    } catch (e, s) {
      _currentPageNum--;
      refreshController.finishLoad(success: false);
      debugPrint('error--->\n' + e.toString());
      debugPrint('statck--->\n' + s.toString());
      return null;
    }
  }

  // 加载数据
  Future<List<T>> loadData({int pageNum});

  List<T> handlePage(RespPage page) {
    var pageResult = page.pageResult;
    if (pageResult.page != null) {
      pageSize = pageResult.page.limit;
      pageTotal = pageResult.page.totalPage;
    }
    return pageResult.results;
  }

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