import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/model/home_quick_entry_model.dart';
import 'package:zhiying_comm/util/net_util.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'home_quick_entry_event.dart';

class HomeQuickEntryRepository {
  /// 获取数据
  Future<HomeQuickEntryModel> fetchData({@required HomeQuickEntryInitEvent event}) async {
    var result = await NetUtil.post('/api/v1/mod/${event.model['mod_id']}', params: { 'ids': [event.model['mod_id']]}, cache: true, method: NetMethod.GET);

    if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
      Map<String, dynamic> data = result[GlobalConfig.HTTP_RESPONSE_KEY_DATA];
      return _getHomeQuickEntryModel(data);
    }
    return null;
  }

  /// 获取父页面传进来的数据
  Future<HomeQuickEntryModel> fetchPreantData({@required HomeQuickEntryInitEvent event}) async{
    try{
      String jsonStr = event.model['data'];
      return HomeQuickEntryModel.fromJson(json.decode(jsonStr));
    }catch(e){
      Logger.log(e);
    }
    return null;
  }

  /// 获取缓存数据
  Future<HomeQuickEntryModel> fetchCachedData({@required HomeQuickEntryInitEvent event}) async {
    var result = await NetUtil.getRequestCachedData('/api/v1/mod/${event.model['mod_id']}', params: {'ids': [event.model['mod_id']]});
    if (!EmptyUtil.isEmpty(result)) {
      return _getHomeQuickEntryModel(result);
    }
    return null;
  }

  HomeQuickEntryModel _getHomeQuickEntryModel(var data) {
    try {
      if (!EmptyUtil.isEmpty(data) && !EmptyUtil.isEmpty(data['data'])) {
        var jsonData = jsonDecode(data['data']);
        if (!EmptyUtil.isEmpty(jsonData)) {
          HomeQuickEntryModel model = HomeQuickEntryModel.fromJson(jsonData);
          if (null != model) {
            return model;
          }
        }
      }
    } catch (e) {
      Logger.log(e);
    }
    return null;
  }
}
