/*
 * @Author: XianKaiQun
 * @Date: 2020-04-01 14:25:13
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-05-18 09:26:03
 * @Descripttion: 持久化储存工具类
 */
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

///持久化储存
///
///已封装成类似微信小程序的方法
///
class WisStorageUtil {
  static SharedPreferences? _instance;
  static set _getInstance(SharedPreferences? data) {
    _instance = data;
  }

  static SharedPreferences? get _getInstance {
    assert(_instance != null, '请在main中初始化, WisStorageUtil.init()');
    return _instance;
  }

  ///初始化
  ///
  ///在main中调用此函数
  static Future init() async {
    _getInstance = await SharedPreferences.getInstance();
  }

  ///设置本地储存
  ///
  ///[key]   指定的key
  ///
  ///[data]  可选类型为 [Map,  List, int,  double, String]
  ///
  static Future<bool> set({required String key, required data}) async {
    bool back;
    if (data is Map) {
      try {
        data = json.encode(data);
      } catch (e) {}
      back = await _getInstance!.setString(key, data);
    } else if (data is List) {
      try {
        data = json.encode(data);
      } catch (e) {}
      back = await _getInstance!.setString(key, data);
    } else if (data is String) {
      back = await _getInstance!.setString(key, data.toString());
    } else if (data is int) {
      back = await _getInstance!.setInt(key, data);
    } else if (data is bool) {
      back = await _getInstance!.setBool(key, data);
    } else if (data is double) {
      back = await _getInstance!.setDouble(key, data);
    } else {
      back = false;
    }
    // 重置getInstance   让下次调用保证最新的getInstance
    _getInstance = await SharedPreferences.getInstance();
    return back;
  }

  ///获取本地储存
  ///
  ///[key]   指定的key
  ///
  ///会自动格式化储存的内容  [Map,  List, int,  double, String]
  ///
  static T? get<T>({required String key}) {
    var back = _getInstance!.get(key);
    if (back is String) {
      try {
        back = json.decode(back);
      } catch (e) {}
    }
    return back as T?;
  }

  ///从本地缓存中移除指定 key
  ///
  ///[key]   指定的key
  ///
  static Future<bool> remove({required String key}) async {
    bool back = false;
    back = await _getInstance!.remove(key);
    // 重置getInstance   让下次调用保证最新的getInstance
    _getInstance = await SharedPreferences.getInstance();
    return back;
  }
}
