import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/widgets/custom/multi_nav/model/custom_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 'custom_quick_entry_event.dart';

class CustomQuickEntryRepository {
  /// 获取数据
  Future<CustomQuickEntryModel> fetchData({@required CustomQuickEntryInitEvent event}) async {
    try {
      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);
      }
    } catch (e, s) {
      Logger.error(e, s);
    }

    return null;
  }

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

  /// 获取缓存数据
  Future<CustomQuickEntryModel> fetchCachedData({@required CustomQuickEntryInitEvent event}) async {
    try {
      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);
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

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