import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:zhiying_comm/util/shared_prefe_util.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/util/global_config.dart';

import 'model/login_style_model.dart';

/// 登陆数据管理工具类
class LoginStyleUtil {
  static final String _URL = '/api/v1/sign/in';

  static void init() async {
    String key = _getCacheKey();

    /// 清除数据缓存
    await SharedPreferencesUtil.setNetCacheResult(key, '');
  }

  /// 获取数据
  static Future<LoginStyleModel> getLoginModel() async {
    var cache = await fetchCachePageData();
    if (!EmptyUtil.isEmpty(cache)) return cache;
    var result = await fetchNetPageData();
    if (!EmptyUtil.isEmpty(result)) return result;

    return null;
  }

  /// 获取缓存的key
  static String _getCacheKey() {
    return NetUtil.getRequestParamsCachedKey(null, _URL);
  }

  /// 获取缓存的页面数据
  static Future<LoginStyleModel> fetchCachePageData() async {
    var result = await NetUtil.getRequestCachedData(_URL);
    if (!EmptyUtil.isEmpty(result)) {
      LoginStyleModel model = LoginStyleModel.fromJson(result);
      return model;
    }
    return null;
  }

  /// 获取页面数据
  static Future<LoginStyleModel> fetchNetPageData() async {
    var result = await NetUtil.post(_URL, method: NetMethod.GET, cache: true);
    if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
      LoginStyleModel model = LoginStyleModel.fromJson(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
      return model;
    }
    return null;
  }
}
