| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219 | using System;using System.Collections.Generic;using System.Linq;using UnityEngine;namespace GFGGame{    public sealed class AccountManager    {        private const string SAVE_KEY = "RecentAccountsData";        private const int MAX_ACCOUNT_COUNT = 20;        private List<AccountData> _cachedAccounts = new List<AccountData>();        // 单例实例        private static readonly Lazy<AccountManager> _instance = new Lazy<AccountManager>(() => new AccountManager());        public static AccountManager Instance => _instance.Value;        // 私有构造函数,防止外部实例化        private AccountManager()        {            LoadAccounts();        }        /// <summary>        /// 登录成功时调用此方法        /// </summary>        /// <param name="username">用户名</param>        /// <param name="plainPassword">明文密码</param>        public void SaveAccount(string username, string plainPassword)        {            // 1. 加密密码            string encryptedPwd = null;            if (plainPassword != null)            {                encryptedPwd = AesEncryption.Encrypt(plainPassword);            }            // 2. 检查列表中是否已有该账号            AccountData existingAccount = _cachedAccounts.FirstOrDefault(a => a.username == username);            if (existingAccount != null)            {                // 如果存在,更新密码和时间戳,并移到列表最前面(表示最新)                existingAccount.encryptedPassword = encryptedPwd;                existingAccount.timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss");                _cachedAccounts.Remove(existingAccount);                _cachedAccounts.Insert(0, existingAccount);            }            else            {                // 如果不存在,创建新账号数据并添加到最前面                AccountData newAccount = new AccountData(username, encryptedPwd);                _cachedAccounts.Insert(0, newAccount);            }            // 3. 如果超出最大数量,移除最旧的一个(列表最后一个)            if (_cachedAccounts.Count > MAX_ACCOUNT_COUNT)            {                _cachedAccounts.RemoveAt(_cachedAccounts.Count - 1);            }            // 4. 立即保存            SaveAccounts();        }        /// <summary>        /// 获取存储的所有账号信息(密码已解密)        /// </summary>        public List<AccountPasswordModel> GetAccounts()        {            List<AccountPasswordModel> result = new List<AccountPasswordModel>();            foreach (var acc in _cachedAccounts)            {                string decryptedPwd = null;                if (acc.encryptedPassword != null)                {                    decryptedPwd = AesEncryption.Decrypt(acc.encryptedPassword);                }                AccountPasswordModel accountPasswordModel = new AccountPasswordModel()                {                    Account = acc.username,                    Password = decryptedPwd                };                result.Add(accountPasswordModel);            }            return result;        }        /// <summary>        /// 删除指定的账号缓存        /// </summary>        /// <param name="username">要删除的用户名</param>        /// <returns>是否成功删除</returns>        public bool DeleteAccount(string username)        {            // 查找要删除的账号            AccountData accountToDelete = _cachedAccounts.FirstOrDefault(a => a.username == username);            if (accountToDelete != null)            {                // 从缓存列表中移除                _cachedAccounts.Remove(accountToDelete);                // 立即保存                SaveAccounts();                Debug.Log($"已成功删除账号: {username}");                return true;            }            else            {                Debug.LogWarning($"未找到账号: {username},删除失败");                return false;            }        }        /// <summary>        /// 批量删除多个账号缓存        /// </summary>        /// <param name="usernames">要删除的用户名列表</param>        /// <returns>成功删除的数量</returns>        public int DeleteAccounts(List<string> usernames)        {            int deletedCount = 0;            foreach (string username in usernames)            {                if (DeleteAccount(username))                {                    deletedCount++;                }            }            Debug.Log($"成功删除了 {deletedCount} 个账号");            return deletedCount;        }        /// <summary>        /// 清除所有账号记录        /// </summary>        public void ClearAllAccounts()        {            _cachedAccounts.Clear();            PlayerPrefs.DeleteKey(SAVE_KEY);            PlayerPrefs.Save();            Debug.Log("已清除所有账号记录");        }        /// <summary>        /// 检查指定账号是否存在        /// </summary>        public bool HasAccount(string username)        {            return _cachedAccounts.Any(a => a.username == username);        }        /// <summary>        /// 获取缓存的账号数量        /// </summary>        public int GetAccountCount()        {            return _cachedAccounts.Count;        }        // 内部方法:从PlayerPrefs加载账号列表        private void LoadAccounts()        {            _cachedAccounts.Clear();            string encryptedJson = PlayerPrefs.GetString(SAVE_KEY, null);            if (!string.IsNullOrEmpty(encryptedJson))            {                string decryptedJson = AesEncryption.Decrypt(encryptedJson);                if (!string.IsNullOrEmpty(decryptedJson))                {                    try                    {                        // 反序列化JSON字符串到对象                        AccountDataList loadedData = JsonUtility.FromJson<AccountDataList>(decryptedJson);                        if (loadedData != null && loadedData.accounts != null)                        {                            // 按时间戳降序排序,最新的在最前面                            _cachedAccounts = loadedData.accounts                                .OrderByDescending(a => a.timestamp)                                .ToList();                        }                    }                    catch (Exception e)                    {                        Debug.LogError("Failed to parse account data: " + e.Message);                    }                }            }        }        // 内部方法:保存账号列表到PlayerPrefs        private void SaveAccounts()        {            // 包装列表            AccountDataList dataToSave = new AccountDataList();            dataToSave.accounts = _cachedAccounts;            // 序列化为JSON            string json = JsonUtility.ToJson(dataToSave);            // 加密JSON字符串            string encryptedJson = AesEncryption.Encrypt(json);            // 保存到PlayerPrefs            PlayerPrefs.SetString(SAVE_KEY, encryptedJson);            PlayerPrefs.Save(); // 确保立即写入磁盘        }    }    public class AccountPasswordModel    {        public string Account { get; set; }        public string Password { get; set; }    }}
 |