import 'package:zhiying_base_widget/widgets/team/fans_list/model/team_fans_list_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class TeamListFansRepository {
  final int _max = 20;
  final String _baseUrl = '/api/v1/user/fans/';
  final String _pageKey = 'page';
  final String _sizeKey = 'size';

  final String type;

  int _currentPage = 1;
  bool _hasMoreData = true;
  List<TeamFansListItemModel> _oldData = [];
  Map<String, String> _reqArgs = {};

  TeamListFansRepository({this.type = 'all'});

  /// 初始化方法
  Future<TeamFansListModel> fetchInitData() async {
    _currentPage = 1;
    _hasMoreData = true;
    _oldData.clear();
    return _fetchBase();
  }

  /// 上拉更多
  Future<TeamFansListModel> fetchOnLoad() async {
    if (_hasMoreData) {
      return _fetchBase();
    }
    return null;
  }

  /// 下拉刷新
  Future<TeamFansListModel> fetchOnRefresh() async {
    return fetchInitData();
  }

  /// 排序方法
  Future<TeamFansListModel> fetchSort(String key, String value) async {
    if (EmptyUtil.isEmpty(key)) return null;
    if (EmptyUtil.isEmpty(value)) {
      _reqArgs[key] = '';
    } else {
      _reqArgs[key] = value;
    }
    return fetchInitData();
  }

  /// 基础请求
  Future<TeamFansListModel> _fetchBase() async {
    try {
      /// 构建URL
      String url = _buildReqUrl();
      var result = await NetUtil.post(url, method: NetMethod.GET);
      if (!EmptyUtil.isEmpty(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
        TeamFansListModel model = TeamFansListModel.fromJson(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
        if (EmptyUtil.isEmpty(model)) {
          _hasMoreData = false;
          return null;
        }
        if (!EmptyUtil.isEmpty(model.fans) && model.fans.length >= _max) {
          ++_currentPage;
          _hasMoreData = true;
          model.fans.insertAll(0, _oldData);
        } else {
          model.fans.insertAll(0, _oldData);
          _hasMoreData = false;
        }
        _oldData = model.fans;
        return model;
      }
    } catch (e, s) {
      Logger.error('e = ${e.toString()}, s = ${s.toString()}');
    }
    return null;
  }

  /// 构建url
  String _buildReqUrl() {
    StringBuffer sb = StringBuffer();
    sb.write(_baseUrl);
    sb.write(type);
    sb.write('?');
    _reqArgs[_pageKey] = _currentPage.toString();
    _reqArgs[_sizeKey] = _max.toString();

    // sb.write('${_pageKey}=${_currentPage.toString()}&');
    // sb.write('${_sizeKey}=${_MAX.toString()}&');

    if (!EmptyUtil.isEmpty(_reqArgs)) {
      _reqArgs.forEach((key, value) {
        sb.write(key);
        sb.write('=');
        sb.write(value);
        sb.write('&');
      });
    }

    String tempUrl = sb.toString();
    if (tempUrl.endsWith('&')) {
      return tempUrl.substring(0, tempUrl.length - 1);
    } else {
      return tempUrl;
    }
  }
}
