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

class SearchResultGoodsListRepository {
  SearchResultGoodsListRepository({@required this.reqData});

  /// 当前页面
  int _currentPage = 1;

  /// 最大条数
  final int MAX = 10;

  /// 是否还有更多数据
  bool _hasNomore = true;

  /// 数据
  List<HomeGoodsModel> _oldDatas = [];

  /// 显示样式
  bool _isShowOneColumn = true;

  /// 查询数据参数
  Map<String, dynamic> reqData = {};
  Map<String, String> _urlArgs = {};

  /// 初始化
  Future<List<HomeGoodsModel>> fetchInitData() async {
    _currentPage = 1;
    _hasNomore = true;
    return _baseInitData(true, reqData);
  }

  /// 下拉刷新
  Future<List<HomeGoodsModel>> fetchRefreshData() async {
    // 参数清除
    // _urlArgs.clear();
    _currentPage = 1;
    _hasNomore = true;
    return _baseInitData(true, reqData);
  }

  /// 上拉更多
  Future<List<HomeGoodsModel>> fetchLoadData() async {
    /// 只有更多数据的时候才进行加载
    if (_hasNomore) {
      return _baseInitData(false, reqData);
    } else {
      return null;
    }
  }

  /// 修改显示样式
  Map<String, dynamic> fetchChangeStyle() {
    _isShowOneColumn = !_isShowOneColumn;
    return {'style': _isShowOneColumn, 'datas': _oldDatas};
  }

  /// 输入框修改关键字
  Future<List<HomeGoodsModel>> fetchSearchSubmit(String keywords) async {
    if (!EmptyUtil.isEmpty(keywords)) {
      reqData['reqData'] = keywords;
      _currentPage = 1;
      _hasNomore = true;
      return _baseInitData(true, reqData);
    }
    return null;
  }

  /// 排序
  Future<List<HomeGoodsModel>> fetchSort(String arg, String id, bool remove) async {
    _urlArgs[id] = arg;
    if(EmptyUtil.isEmpty(arg) || remove){
      _urlArgs.remove(id);
    }
    _currentPage = 1;
    _hasNomore = true;
    return _baseInitData(true, reqData);
  }

  /// 综合排序
  Future<List<HomeGoodsModel>> fetchZhSort(String arg) async {
    _urlArgs['zh'] = arg;
    _currentPage = 1;
    _hasNomore = true;
    return _baseInitData(true, reqData);
  }

  /// 补贴
  Future<List<HomeGoodsModel>> fetchBt(String arg) async {
    _urlArgs['bt'] = arg;
    _currentPage = 1;
    _hasNomore = true;
    return _baseInitData(true, reqData);
  }

  /// 优惠券
  Future<List<HomeGoodsModel>> fetchYhq(String arg) async {
    _urlArgs['yhq'] = arg;
    _currentPage = 1;
    _hasNomore = true;
    return _baseInitData(true, reqData);
  }

  /// 筛选
  Future<List<HomeGoodsModel>> fetchSX(String arg) async {
    _urlArgs['sx'] = arg;
    _currentPage = 1;
    _hasNomore = true;
    return _baseInitData(true, reqData);
  }

  /// 查询
  Future<List<HomeGoodsModel>> _baseInitData(bool refresh, final Map<String, dynamic> model) async {
    String keyword = model['keywords'] ?? '';
    String type = model.containsKey('type') ? model['type'] : 'taobao';
    if (EmptyUtil.isEmpty(keyword)) return null;
    /// 构造url
    String url = _buildUrl(type);
    var result = await NetUtil.post(url,
        params: {
          'keyword': keyword,
          'size': MAX.toString(),
          'p': _currentPage.toString(),
        },
        method: NetMethod.POST);
    try {
      // search_list
      if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
        List data = List.from(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]['search_list']);
        if (data.length >= MAX) {
          _hasNomore = true;
          ++_currentPage;
        }
        // 下拉刷新需要清理
        if (refresh) {
          _oldDatas.clear();
        }

        data.forEach((item) {
          _oldDatas.add(HomeGoodsModel.fromJson(item));
        });

        List<HomeGoodsModel> newData = [];
        newData.addAll(_oldDatas);

        return newData;
      }
    } catch (e) {
      Logger.error(e);
    }
    _hasNomore = false;
    return null;
  }

  /// 通过筛选条件构造请求链接
  String _buildUrl(String type) {
    String url = '/api/v1/s/$type';
    try {
      StringBuffer sb = StringBuffer();
      if (EmptyUtil.isEmpty(_urlArgs) && _urlArgs.length > 0) return url;
      sb.write(url);
      int index = 0;
      _urlArgs.keys.forEach((key) {
        String temp = _urlArgs[key];
        if (!EmptyUtil.isEmpty(temp)) {
          if(index == 0) {
            sb.write('?$temp');
          }else{
            sb.write('&$temp');
          }
          ++index;
        }
      });
      return sb.toString();
    } catch (e) {
      return url;
    }
  }
}
