import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferencesUtil {
  // 单例对象
  static final SharedPreferencesUtil _singleton = SharedPreferencesUtil._internal();

  // 私有构造函数
  SharedPreferencesUtil._internal();

  // 工厂构造函数返回单例对象
  factory SharedPreferencesUtil() => _singleton;

  // 获取 SharedPreferences 实例
  Future<SharedPreferences> get _instance async => await SharedPreferences.getInstance();



  // 存储字符串
  Future<void> setString(String key, String value) async {
    final prefs = await _instance;
    prefs.setString(key, value);
  }

  // 读取字符串
  Future<String?> getString(String key) async {
    final prefs = await _instance;
    return prefs.getString(key);
  }

  // 存储JSON数组
  Future<void> setJsonList(String key, List<Map<String, dynamic>> jsonList) async {
    final prefs = await _instance;
    final jsonString = jsonEncode(jsonList);
    prefs.setString(key, jsonString);
  }

  // 读取JSON数组
  Future<List<Map<String, dynamic>>?> getJsonList(String key) async {
    final prefs = await _instance;
    final jsonString = prefs.getString(key);
    return jsonString != null ? List<Map<String, dynamic>>.from(jsonDecode(jsonString)) : null;
  }

  // 存储可以转化为 JSON 的对象
  Future<void> setObject(String key, Map<String, dynamic> jsonValue) async {
    final prefs = await _instance;
    final jsonString = jsonEncode(jsonValue);
    prefs.setString(key, jsonString);
  }

  // 读取 JSON 对象，并返回 Map<String, dynamic>
  Future<Map<String, dynamic>?> getObject(String key) async {
    final prefs = await _instance;
    final jsonString = prefs.getString(key);
    return jsonString != null ? jsonDecode(jsonString) as Map<String, dynamic> : null;
  }

  // 删除指定键的数据
  Future<void> delete(String key) async {
    final prefs = await _instance;
    prefs.remove(key);
  }

  // 删除所有数据
  Future<void> deleteAll() async {
    final prefs = await _instance;
    prefs.clear();
  }
}
