using Muchinfo.MTPClient.Data.Model; using Muchinfo.MTPClient.Infrastructure.Utilities; using Muchinfo.PC.Common.Bosn; using System.Collections.Generic; using System.IO; using System.Linq; namespace Muchinfo.MTPClient.Infrastructure.Users { public class FavoriteManager { private static List _myFavorites; /// /// 初始化自选 /// /// Default name of the favorite. public static void InitializeFavorite(string defaultFavoriteName) { //本地不存在自选板块,则添加个默认"自选" var list = GetMyFavorites(); if (list == null || !list.Any()) { var myFavorite = new MyFavorite() { Id = 0, Name = defaultFavoriteName, ShowIndex = 0, FavoriteGoodses = null, }; AddOrUpdateMyFavorites(myFavorite); } } /// /// 获取自选列表 /// /// IEnumerable{MyFavorite}. public static IEnumerable GetMyFavorites() { if (_myFavorites == null) { var filePath = GetFilePath(true); if (string.IsNullOrWhiteSpace(filePath)) return null; _myFavorites = BsonHelper.LoadData(filePath); } return _myFavorites == null ? null : _myFavorites.OrderBy(z => z.ShowIndex); } /// /// 保存自选板块 /// /// My favorite. public static void AddOrUpdateMyFavorites(MyFavorite myFavorite) { if (myFavorite == null) return; var list = GetMyFavorites(); var result = list == null ? new List() : list.ToList(); //Id为0,则表示增加 if (myFavorite.Id == 0) { myFavorite.Id = result.Count > 0 ? result.Max(z => z.Id) + 1 : 1; result.Add(myFavorite); } else { var item = result.FirstOrDefault(z => z.Id == myFavorite.Id); if (item != null) { result.Remove(item); result.Add(myFavorite); } } var filePath = GetFilePath(false); _myFavorites = result; BsonHelper.SaveData(filePath, result, null, true); } /// /// 删除自选板块 /// /// My favorite identifier. public static void DeleteMyFavorites(int myFavoriteId) { if (_myFavorites == null || !_myFavorites.Any()) return; //默认"自选" 不能删除 if (myFavoriteId == 0) return; var item = _myFavorites.FirstOrDefault(z => z.Id == myFavoriteId); if (item == null) return; _myFavorites.Remove(item); var filePath = GetFilePath(false); BsonHelper.SaveData(filePath, _myFavorites, null, true); } /// /// 获取存储文件路径 /// /// System.String. private static string GetFilePath(bool needValidate) { var filePath = Path.Combine(UserManager.UserDataFolder, "MyFavorite" + UserManager.LocalDataExtensionName); if (needValidate) { if (!File.Exists(filePath)) return string.Empty; } return filePath; } } }