import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/widgets/favorites/goods_list/model/favorites_goods_list_model.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/models/home_goods_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class FavoritesGoodsListRepository {
  String type;

  final int _MAX = 5;
  int _currentPage = 1;
  bool _hasMoreData = true;

  FavoritesGoodsListDataModel _oldData = new FavoritesGoodsListDataModel();
  Map<int, int> _selectIndex = {};

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

  String keyword;

  /// 返回选中的商品长度
  int getSelectLength() {
    return _selectIndex.length;
  }

  /// 右滑动删除当个商品
  Future<FavoritesGoodsListDataModel> slideDeleteData(int index) async{
    _selectIndex.clear();
    _oldData.lists.forEach((element) {
      element.isSelect = false;
    });
    _oldData.isAllSelect = false;
    _selectIndex[index] = index;
    return delete();
  }

  /// 选中所有
  Future<FavoritesGoodsListDataModel> selectAllData() async {
    try {
      _selectIndex.clear();
      int index = 0;
      _oldData.lists.forEach((element) {
        element.isSelect = true;
        _selectIndex[index] = index;
        ++index;
      });
      _oldData.isAllSelect = true;
      return _oldData;
    }catch(e, s){
      Logger.error(e,s);
    }
    return null;
  }

  /// 单个选中状态
  Future<FavoritesGoodsListDataModel> signSelectData(final int selectIndex) async {
    _oldData.lists[selectIndex].isSelect = !_oldData.lists[selectIndex].isSelect;

    if (_oldData.lists[selectIndex].isSelect) {
      // 新增
      _selectIndex[selectIndex] = selectIndex;
    } else {
      // 移除
      _selectIndex.remove(selectIndex);
    }
    _oldData.isAllSelect = false;
    if (_selectIndex.length == _oldData.lists.length) {
      _oldData.isAllSelect = true;
    }
    return _oldData;
  }

  /// 取消选中所有 or 重置选中状态
  Future<FavoritesGoodsListDataModel> cancelSelectAllData() async {
    _selectIndex.clear();
    _oldData.lists.forEach((element) {
      element.isSelect = false;
    });
    _oldData.isAllSelect = false;
    return _oldData;
  }

  /// 关键字搜索
  Future<FavoritesGoodsListDataModel> search(String keyword) async {
    try {
      _selectIndex.clear();
      _oldData.lists.clear();
      _currentPage = 1;
      _hasMoreData = true;

      this.keyword = keyword;
      return _baseRequest();
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 删除数据
  Future<FavoritesGoodsListDataModel> delete() async {
    try {
      // Logger.log('select Index length = ${_selectIndex.length}');
      if (_selectIndex.length > 0) {
        List<String> gids = [];
        _selectIndex.forEach((key, value) {
          gids.add(_oldData.lists[value].goodId);
        });
        var result = await NetUtil.post('/api/v1/user/myfav/delete', params: {'gids': gids}, method: NetMethod.POST);
        if (NetUtil.isSuccess(result)) {
          List<FavoritesGoodsListItemModel> tempList = [];
          // TODO 这里有问题：移除删除
          for (int i = 0; i < _oldData.lists.length; i++) {
            if (!_selectIndex.containsKey(i)) {
              tempList.add(_oldData.lists[i]);
            }
          }
          _oldData.lists.clear();
          _selectIndex.clear();
          _oldData.isAllSelect = false;
          _oldData.lists = tempList;
          return _oldData;
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 初始化请求
  Future<FavoritesGoodsListDataModel> fetchInit() async {
    _currentPage = 1;
    _hasMoreData = true;
    _oldData?.lists?.clear();
    _selectIndex.clear();
    _oldData.isAllSelect = false;
    return _baseRequest();
  }

  /// 下拉刷新
  Future<FavoritesGoodsListDataModel> fetchRefresh() async {
    return fetchInit();
  }

  /// 上拉更多
  Future<FavoritesGoodsListDataModel> fetchLoad() async {
    if (_hasMoreData) {
      return _baseRequest();
    }
    return null;
  }

  /// 基础请求
  Future<FavoritesGoodsListDataModel> _baseRequest() async {
    try {
      var result;
      if(EmptyUtil.isEmpty(keyword)) {
        result = await NetUtil.post('/api/v1/user/myfav/$type?page=${_currentPage.toString()}', params: {}, method: NetMethod.GET);
      }else{
        result = await NetUtil.post('/api/v1/user/myfav/s', params: {'keyword': keyword}, method: NetMethod.POST);
      }
      if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
        List data = result[GlobalConfig.HTTP_RESPONSE_KEY_DATA];
        data.forEach((element) {
          _oldData.lists.add(FavoritesGoodsListItemModel.fromJson(element));
        });
        ++_currentPage;
        _hasMoreData = true;
        // _hasMoreData = data.length >= _MAX ? true : false;
        return _oldData;
      }
      _hasMoreData = false;
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }
}
