import 'dart:convert';

import 'package:zhiying_comm/zhiying_comm.dart';

class SearchResultItemRepository {
  List<Map<String, dynamic>> _pageData;

  /// 初始化
  Future<List<Map<String, dynamic>>> fetchInitData(final Map<String, dynamic> model) async {
    String type = model['type'];
    String keywords = model.containsKey('keywords') ? model['keywords'] : '';
    if (EmptyUtil.isEmpty(type)) return null;
    var result = await NetUtil.post('/api/v1/mod/pub.flutter.search_result.$type', method: NetMethod.GET, cache: true);
    if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result)) {
      try {
        List<Map<String, dynamic>> modList = List.from(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]['mod_list']);

        modList.forEach((Map<String, dynamic> item) {
          var data = jsonDecode(item['data']);
          data['keywords'] = keywords;
          item['data'] = jsonEncode(data);
          _pageData.add(item);
        });

        return _pageData;
      } catch (e) {
        Logger.error(e.toString());
      }
    }
    return null;
  }

  /// 获取缓存数据
  Future<List<Map<String, dynamic>>> fetchCacheData(final Map<String, dynamic> model) async {
    String type = model['type'] ?? '';
    String keywords = model.containsKey('keywords') ? model['keywords'] : '';
    if (EmptyUtil.isEmpty(type)) return null;
    var result = await NetUtil.getRequestCachedData('/api/v1/mod/pub.flutter.search_result.$type');
    try {
      if (!EmptyUtil.isEmpty(result)) {
        List<Map<String, dynamic>> modList = List.from(result['mod_list']);
        List<Map<String, dynamic>> _pageData = [];

        modList.forEach((Map<String, dynamic> item) {
          var data = jsonDecode(item['data']);
          data['keywords'] = keywords;
          item['data'] = jsonEncode(data);
          _pageData.add(item);
        });
        return _pageData;
      }
    } catch (e) {}
    return null;
  }
}
