using System; using Newtonsoft.Json; using UnityEngine; namespace Activity.Data { /// /// 使用本次登录绑定的存档提供方,保留活动类型名作为存档键。 /// public class EventDataRepository : IEventDataRepository { readonly game.PlayerDataStorage.IPlayerSaveStore store; public EventDataRepository(game.PlayerDataStorage.IPlayerSaveStore store) { this.store = store ?? throw new ArgumentNullException(nameof(store)); } public void Save(T data) where T : IEventData { if (data == null) { Debug.LogWarning($"[EventDataRepository] Cannot save null data for {typeof(T).Name}"); return; } try { var json = JsonConvert.SerializeObject(data); #if UNITY_EDITOR Debug.Log($"[EventDataRepository] Saving {typeof(T).Name}: {json}"); #endif store.Write(typeof(T).Name, json).RequireAccepted(); } catch (Exception e) { Debug.LogError($"[EventDataRepository] Failed to save {typeof(T).Name}: {e.Message}\n{e.StackTrace}"); throw; } } public T Load() where T : IEventData, new() { try { var read = store.Read(typeof(T).Name); var dataStr = read.ValueOrThrow(); if (read.Found == false) return new T(); if (string.IsNullOrWhiteSpace(dataStr) || dataStr.Trim() == "null") throw new JsonSerializationException("Stored activity data cannot be empty or null."); // #if UNITY_EDITOR // Debug.Log($"[EventDataRepository] Load {typeof(T).Name}: {dataStr}"); // #endif var data = JsonConvert.DeserializeObject(dataStr); if (data == null) throw new JsonSerializationException("Stored activity data cannot be null."); return data; } catch (Exception e) { Debug.LogError($"[EventDataRepository] Failed to load {typeof(T).Name}: {e.Message}\n{e.StackTrace}"); throw; } } public bool Exists() where T : IEventData { var read = store.Read(typeof(T).Name); read.ValueOrThrow(); return read.Found.Value; } } }