import 'package:shared_preferences/shared_preferences.dart';
import 'package:special_equipment_flutter/model/user_bo.dart';

///数据库相关的工具
class SPAccountUtil {
  static const String ACCOUNT_NUMBER = "account_number";
  static const String USERNAME = "username";
  static const String PASSWORD = "password";

  ///删掉单个账号
  static void delUser(UserBo user, index) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    List<UserBo> list = await getUsers();
    // list.remove(user);
    list.removeAt(index);
    saveUsers(list, sp);
  }

  ///保存账号，如果重复，就将最近登录账号放在第一个
  static void saveUser(UserBo user) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    List<UserBo> list = await getUsers();
    addNoRepeat(list, user);
    saveUsers(list, sp);
  }

  ///去重并维持次序
  static void addNoRepeat(List<UserBo> users, UserBo user) {
    for (int i = 0; i < users.length; i++) {
      if (users[i].account == user.account) {
        users.removeAt(i);
      }
    }
    users.insert(0, user);
  }

  ///获取已经登录的账号列表
  static Future<List<UserBo>> getUsers() async {
    List<UserBo> list = [];
    SharedPreferences sp = await SharedPreferences.getInstance();
    int num = sp.getInt(ACCOUNT_NUMBER) ?? 0;
    for (int i = 0; i < num; i++) {
      String? username = sp.getString("$USERNAME$i");
      String? password = sp.getString("$PASSWORD$i");
      list.add(UserBo(username, password));
    }
    return list;
  }

  ///保存账号列表
  static saveUsers(List<UserBo> users, SharedPreferences sp) {
    sp.clear();
    int size = users.length;
    for (int i = 0; i < size; i++) {
      sp.setString("$USERNAME$i", users[i].account!);
      sp.setString("$PASSWORD$i", users[i].password!);
    }
    sp.setInt(ACCOUNT_NUMBER, size);
  }
}
