Decompiled source of DspZhibo v1.1.0

DspZhibo.Mod.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")]
[assembly: AssemblyCompany("DspZhibo.Mod")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DspZhibo.Mod")]
[assembly: AssemblyTitle("DspZhibo.Mod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DspZhibo.Mod
{
	public class BattleManager
	{
		private PunishmentConfig _config;

		public BattleManager()
		{
			_config = PunishmentConfig.Load();
		}

		public void TriggerPunishment(string ticketName)
		{
			try
			{
				float punishmentChance = GetPunishmentChance(ticketName);
				if (punishmentChance <= 0f)
				{
					Debug.Log((object)("[" + ticketName + "] 不会触发黑雾惩罚"));
					return;
				}
				if (Random.value > punishmentChance)
				{
					Debug.Log((object)("[" + ticketName + "] 幸运逃过一劫!本次不触发惩罚"));
					return;
				}
				UIRealtimeTip.Popup(_config.punishmentMessage + " (" + ticketName + ")", true, 0);
				IncreaseDarkFogThreat();
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("触发惩罚失败: " + ex.Message + "\n" + ex.StackTrace));
			}
		}

		private void IncreaseDarkFogThreat()
		{
			try
			{
				if (GameMain.data == null || GameMain.data.mainPlayer == null)
				{
					Debug.LogWarning((object)"无法获取玩家数据,跳过威胁度增加");
					return;
				}
				PlanetData localPlanet = GameMain.data.localPlanet;
				if (localPlanet == null)
				{
					Debug.LogWarning((object)"无法获取当前行星数据");
					return;
				}
				StarData star = localPlanet.star;
				if (star == null)
				{
					Debug.LogWarning((object)"无法获取星区数据");
					return;
				}
				int enemyCount = _config.GetEnemyCount();
				int id = star.id;
				Debug.Log((object)$"[黑雾惩罚] 星区 {star.displayName} ({id}) 威胁度已增加!预计生成 {enemyCount} 波敌人");
				UIRealtimeTip.Popup("⚠\ufe0f 黑雾感知到你的存在!星区 " + star.displayName + " 威胁度上升!", true, 0);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("增加黑雾威胁度失败: " + ex.Message + "\n" + ex.StackTrace));
			}
		}

		private float GetPunishmentChance(string ticketName)
		{
			if (ticketName.Contains("普通"))
			{
				return 0.5f;
			}
			if (ticketName.Contains("稀有"))
			{
				return 0.1f;
			}
			if (ticketName.Contains("VIP"))
			{
				return 0f;
			}
			if (!_config.ShouldTriggerPunishment())
			{
				return 0f;
			}
			return _config.spawnChance;
		}

		public void ReloadConfig()
		{
			_config = PunishmentConfig.Load();
			Debug.Log((object)"惩罚配置已重新加载");
		}

		public PunishmentConfig GetConfig()
		{
			return _config;
		}
	}
	public class Config
	{
		public ConfigEntry<bool> EnableUI { get; }

		public ConfigEntry<string> PipeName { get; }

		public ConfigEntry<int> UIPositionX { get; }

		public ConfigEntry<int> UIPositionY { get; }

		public Config(ConfigFile config)
		{
			EnableUI = config.Bind<bool>("General", "EnableUI", true, "是否启用游戏内UI");
			PipeName = config.Bind<string>("Network", "PipeName", "DspZhiboPipe", "命名管道名称");
			UIPositionX = config.Bind<int>("UI", "PositionX", 20, "UI窗口X位置");
			UIPositionY = config.Bind<int>("UI", "PositionY", 20, "UI窗口Y位置");
		}
	}
	[Serializable]
	public class GiftConfig
	{
		public bool enabled = true;

		public Dictionary<string, GiftReward> giftRewards = new Dictionary<string, GiftReward>();

		private static string _configPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DspZhibo", "GiftConfig.json");

		public static GiftConfig Load()
		{
			GiftConfig giftConfig = new GiftConfig();
			try
			{
				string directoryName = Path.GetDirectoryName(_configPath);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				if (File.Exists(_configPath))
				{
					giftConfig = JsonUtility.FromJson<GiftConfig>(File.ReadAllText(_configPath));
				}
				else
				{
					giftConfig = GetDefaultConfig();
					giftConfig.Save();
				}
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("加载礼物配置失败: " + ex.Message));
				giftConfig = GetDefaultConfig();
			}
			return giftConfig;
		}

		public void Save()
		{
			try
			{
				string directoryName = Path.GetDirectoryName(_configPath);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				string contents = JsonUtility.ToJson((object)this, true);
				File.WriteAllText(_configPath, contents);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("保存礼物配置失败: " + ex.Message));
			}
		}

		private static GiftConfig GetDefaultConfig()
		{
			return new GiftConfig
			{
				enabled = true,
				giftRewards = new Dictionary<string, GiftReward>
				{
					["VIP奖券"] = new GiftReward
					{
						enabled = true,
						message = "感谢您的支持!赠送您额外奖励:",
						rewards = new List<ItemReward>
						{
							new ItemReward
							{
								itemId = 1001,
								itemName = "磁铁矿",
								count = 50
							},
							new ItemReward
							{
								itemId = 1002,
								itemName = "煤矿",
								count = 50
							},
							new ItemReward
							{
								itemId = 1003,
								itemName = "铜矿",
								count = 50
							}
						}
					},
					["稀有奖券"] = new GiftReward
					{
						enabled = true,
						message = "稀有奖励已发放!",
						rewards = new List<ItemReward>
						{
							new ItemReward
							{
								itemId = 1101,
								itemName = "磁铁",
								count = 20
							},
							new ItemReward
							{
								itemId = 1103,
								itemName = "铜块",
								count = 20
							}
						}
					},
					["普通奖券"] = new GiftReward
					{
						enabled = true,
						message = "感谢使用!",
						rewards = new List<ItemReward>
						{
							new ItemReward
							{
								itemId = 1001,
								itemName = "磁铁矿",
								count = 10
							}
						}
					}
				}
			};
		}

		public GiftReward GetReward(string ticketName)
		{
			if (!enabled)
			{
				return null;
			}
			foreach (string key in giftRewards.Keys)
			{
				if (ticketName.Contains(key))
				{
					GiftReward giftReward = giftRewards[key];
					return giftReward.enabled ? giftReward : null;
				}
			}
			return null;
		}
	}
	[Serializable]
	public class GiftReward
	{
		public bool enabled = true;

		public string message = "";

		public List<ItemReward> rewards = new List<ItemReward>();
	}
	[Serializable]
	public class ItemReward
	{
		public int itemId;

		public string itemName;

		public int count;
	}
	internal static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "com.dspzhibo.mod";

		public const string PLUGIN_NAME = "DspZhibo Mod";

		public const string PLUGIN_VERSION = "1.0.0";
	}
	public class NamedPipeServer
	{
		private readonly string _pipeName;

		private NamedPipeServerStream? _pipeServer;

		private Thread? _listenThread;

		private bool _isRunning;

		private readonly Queue<Action> _mainThreadActions = new Queue<Action>();

		private readonly object _lockObject = new object();

		private GiftConfig _giftConfig;

		private BattleManager _battleManager;

		public NamedPipeServer(string pipeName)
		{
			_pipeName = pipeName;
			_giftConfig = GiftConfig.Load();
			_battleManager = new BattleManager();
		}

		public void Start()
		{
			_isRunning = true;
			_listenThread = new Thread(ListenForClients)
			{
				IsBackground = true
			};
			_listenThread.Start();
		}

		private void ListenForClients()
		{
			while (_isRunning)
			{
				try
				{
					using (_pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
					{
						Debug.Log((object)"等待客户端连接...");
						_pipeServer.WaitForConnection();
						Debug.Log((object)"客户端已连接!");
						StreamReader streamReader = new StreamReader(_pipeServer, Encoding.UTF8);
						string message;
						while ((message = streamReader.ReadLine()) != null)
						{
							lock (_lockObject)
							{
								_mainThreadActions.Enqueue(delegate
								{
									ProcessMessage(message);
								});
							}
						}
					}
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("命名管道错误: " + ex.Message));
				}
			}
		}

		private void ProcessMessage(string message)
		{
			try
			{
				string[] array = message.Split(new char[1] { '|' });
				if (array.Length >= 5 && array[0] == "TICKET_GIFT")
				{
					string text = array[1];
					int num = int.Parse(array[2]);
					string text2 = array[3];
					string text3 = array[4];
					Plugin.TicketManager?.AddTicket(text, num);
					Plugin.TicketManager?.AddGiftRecord(text2, text3, text, num);
					Debug.Log((object)$"收到礼物: {text2} 送出 {text3} → {text} x{num}");
					GiveGiftRewards(text, num);
					_battleManager?.TriggerPunishment(text);
				}
				else if (array.Length >= 3 && array[0] == "TICKET_ADD")
				{
					string text4 = array[1];
					int num2 = int.Parse(array[2]);
					Plugin.TicketManager?.AddTicket(text4, num2);
					Debug.Log((object)$"收到票券: {text4} x{num2}");
					GiveGiftRewards(text4, num2);
					_battleManager?.TriggerPunishment(text4);
				}
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("处理消息错误: " + ex.Message));
			}
		}

		private void GiveGiftRewards(string ticketName, int ticketCount)
		{
			try
			{
				GiftReward reward = _giftConfig.GetReward(ticketName);
				if (reward == null || reward.rewards == null || reward.rewards.Count == 0 || GameMain.data == null)
				{
					return;
				}
				Player mainPlayer = GameMain.data.mainPlayer;
				if (mainPlayer == null)
				{
					return;
				}
				StorageComponent package = mainPlayer.package;
				if (package == null)
				{
					return;
				}
				string text = string.Empty;
				int num2 = default(int);
				foreach (ItemReward reward2 in reward.rewards)
				{
					int num = reward2.count * ticketCount;
					package.AddItem(reward2.itemId, num, 0, ref num2, false);
					ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(reward2.itemId);
					if (val != null)
					{
						text += $"{((Proto)val).name} x{num}, ";
					}
				}
				Debug.Log((object)("礼物回赠(" + ticketName + "): " + text.TrimEnd(',', ' ')));
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("礼物回赠失败: " + ex.Message));
			}
		}

		public void ProcessMessages()
		{
			lock (_lockObject)
			{
				while (_mainThreadActions.Count > 0)
				{
					_mainThreadActions.Dequeue()?.Invoke();
				}
			}
		}

		public void Stop()
		{
			_isRunning = false;
			_pipeServer?.Dispose();
			_listenThread?.Join();
		}
	}
	[BepInPlugin("com.dspzhibo.mod", "DspZhibo Mod", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		internal static Config Config;

		internal static NamedPipeServer? PipeServer;

		internal static TicketManager? TicketManager;

		private ConfigEntry<KeyboardShortcut> ToggleUIKey { get; set; }

		private void Awake()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			ToggleUIKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("快捷键", "切换UI", new KeyboardShortcut((KeyCode)291, Array.Empty<KeyCode>()), "按此键切换奖券系统UI显示");
			Config = new Config(((BaseUnityPlugin)this).Config);
			TicketManager = new TicketManager();
			PipeServer = new NamedPipeServer("DspZhiboPipe");
			PipeServer.Start();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"插件 DspZhibo Mod 1.0.0 已加载!");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"命名管道服务器已启动,等待客户端连接...");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"快捷键: F10 切换UI显示");
		}

		private void Update()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			PipeServer?.ProcessMessages();
			KeyboardShortcut value = ToggleUIKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				TicketManager?.ToggleUI();
			}
		}

		private void OnDestroy()
		{
			PipeServer?.Stop();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"插件已卸载");
		}

		private void OnGUI()
		{
			TicketManager?.OnGUI();
		}
	}
	[Serializable]
	public class PunishmentConfig
	{
		public bool enabled = true;

		public float spawnChance = 0.1f;

		public int minEnemyCount = 1;

		public int maxEnemyCount = 3;

		public string punishmentMessage = "小心!黑雾来袭!";

		private static string _configPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DspZhibo", "PunishmentConfig.json");

		public static PunishmentConfig Load()
		{
			PunishmentConfig punishmentConfig = new PunishmentConfig();
			try
			{
				string directoryName = Path.GetDirectoryName(_configPath);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				if (File.Exists(_configPath))
				{
					punishmentConfig = JsonUtility.FromJson<PunishmentConfig>(File.ReadAllText(_configPath));
				}
				else
				{
					punishmentConfig = GetDefaultConfig();
					punishmentConfig.Save();
				}
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("加载惩罚配置失败: " + ex.Message));
				punishmentConfig = GetDefaultConfig();
			}
			return punishmentConfig;
		}

		public void Save()
		{
			try
			{
				string directoryName = Path.GetDirectoryName(_configPath);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				string contents = JsonUtility.ToJson((object)this, true);
				File.WriteAllText(_configPath, contents);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("保存惩罚配置失败: " + ex.Message));
			}
		}

		private static PunishmentConfig GetDefaultConfig()
		{
			return new PunishmentConfig
			{
				enabled = true,
				spawnChance = 0.1f,
				minEnemyCount = 1,
				maxEnemyCount = 3,
				punishmentMessage = "小心!黑雾来袭!"
			};
		}

		public bool ShouldTriggerPunishment()
		{
			if (!enabled)
			{
				return false;
			}
			return Random.value < spawnChance;
		}

		public int GetEnemyCount()
		{
			return Random.Range(minEnemyCount, maxEnemyCount + 1);
		}
	}
	public class TicketData
	{
		public int TicketId { get; set; }

		public string TicketName { get; set; } = string.Empty;


		public int Count { get; set; }

		public long Timestamp { get; set; }
	}
	public class TicketManager
	{
		[Serializable]
		private class TicketContainer
		{
			public List<TicketData> Tickets = new List<TicketData>();
		}

		[Serializable]
		public class GiftRecord
		{
			public string userName;

			public string giftName;

			public string ticketName;

			public int ticketCount;

			public long timestamp;
		}

		private readonly List<TicketData> _tickets = new List<TicketData>();

		private readonly string _savePath;

		private bool _showUI = true;

		private Rect _windowRect = new Rect(20f, 20f, 450f, 400f);

		private Vector2 _scrollPosition;

		private Vector2 _historyScrollPosition;

		private string _resultMessage = string.Empty;

		private float _resultMessageTime;

		private List<ItemProto> _cachedItems;

		private List<GiftRecord> _giftHistory = new List<GiftRecord>();

		public TicketManager()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			_savePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DspZhibo", "tickets.json");
			LoadTickets();
			CacheItems();
		}

		private void CacheItems()
		{
			try
			{
				if ((Object)(object)LDB.items != (Object)null && ((ProtoSet<ItemProto>)(object)LDB.items).dataArray != null)
				{
					_cachedItems = ((ProtoSet<ItemProto>)(object)LDB.items).dataArray.Where((ItemProto item) => item != null && ((Proto)item).ID > 0 && item.GridIndex >= 0).ToList();
					Debug.Log((object)$"已缓存 {_cachedItems.Count} 个物品");
				}
				else
				{
					_cachedItems = new List<ItemProto>();
					Debug.LogWarning((object)"物品数据库未初始化");
				}
			}
			catch (Exception ex)
			{
				_cachedItems = new List<ItemProto>();
				Debug.LogError((object)("缓存物品失败: " + ex.Message));
			}
		}

		public void AddTicket(string ticketName, int count)
		{
			TicketData ticketData = _tickets.FirstOrDefault((TicketData t) => t.TicketName == ticketName);
			if (ticketData != null)
			{
				ticketData.Count += count;
			}
			else
			{
				_tickets.Add(new TicketData
				{
					TicketId = ((_tickets.Count <= 0) ? 1 : (_tickets.Max((TicketData t) => t.TicketId) + 1)),
					TicketName = ticketName,
					Count = count,
					Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
				});
			}
			SaveTickets();
		}

		public void AddGiftRecord(string userName, string giftName, string ticketName, int ticketCount)
		{
			try
			{
				GiftRecord item = new GiftRecord
				{
					userName = userName,
					giftName = giftName,
					ticketName = ticketName,
					ticketCount = ticketCount,
					timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
				};
				_giftHistory.Add(item);
				if (_giftHistory.Count > 50)
				{
					_giftHistory.RemoveAt(0);
				}
				Debug.Log((object)$"礼物记录: {userName} 送出 {giftName} → {ticketName} x{ticketCount}");
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("添加礼物记录失败: " + ex.Message));
			}
		}

		public void UseTicket(int ticketId)
		{
			try
			{
				TicketData ticketData = _tickets.FirstOrDefault((TicketData t) => t.TicketId == ticketId);
				if (ticketData != null)
				{
					GiveRandomItems(ticketData.TicketName);
					ticketData.Count--;
					if (ticketData.Count <= 0)
					{
						_tickets.Remove(ticketData);
					}
					SaveTickets();
				}
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("使用奖券失败: " + ex.Message + "\n" + ex.StackTrace));
			}
		}

		private void GiveRandomItems(string ticketName)
		{
			try
			{
				if (GameMain.data == null)
				{
					Debug.LogWarning((object)"GameMain.data 为空,无法发放奖励");
					return;
				}
				Player mainPlayer = GameMain.data.mainPlayer;
				if (mainPlayer == null)
				{
					Debug.LogWarning((object)"玩家为空,无法发放奖励");
					return;
				}
				StorageComponent package = mainPlayer.package;
				if (package == null)
				{
					Debug.LogWarning((object)"背包为空,无法发放奖励");
					return;
				}
				int rewardCount = GetRewardCount(ticketName);
				Dictionary<int, int> randomItems = GetRandomItems(rewardCount);
				string text = string.Empty;
				int num = default(int);
				foreach (KeyValuePair<int, int> item in randomItems)
				{
					int key = item.Key;
					int value = item.Value;
					package.AddItem(key, value, 0, ref num, false);
					try
					{
						ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(key);
						if (val != null)
						{
							text += $"{((Proto)val).name} x{value}, ";
						}
					}
					catch
					{
						text += $"物品{key} x{value}, ";
					}
				}
				_resultMessage = "使用 " + ticketName + " 获得:\n" + text.TrimEnd(',', ' ');
				_resultMessageTime = Time.realtimeSinceStartup;
				Debug.Log((object)("奖券使用: " + ticketName + " - " + text));
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("发放奖励失败: " + ex.Message + "\n" + ex.StackTrace));
			}
		}

		private int GetRewardCount(string ticketName)
		{
			if (ticketName.Contains("VIP"))
			{
				return 5;
			}
			if (ticketName.Contains("稀有"))
			{
				return 2;
			}
			return 1;
		}

		private Dictionary<int, int> GetRandomItems(int count)
		{
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			Random random = new Random();
			if (_cachedItems == null || _cachedItems.Count == 0)
			{
				Debug.LogWarning((object)"物品缓存为空,尝试重新加载");
				CacheItems();
			}
			if (_cachedItems == null || _cachedItems.Count == 0)
			{
				Debug.LogWarning((object)"没有可用的物品");
				return dictionary;
			}
			for (int i = 0; i < count; i++)
			{
				int index = random.Next(_cachedItems.Count);
				ItemProto val = _cachedItems[index];
				if (dictionary.ContainsKey(((Proto)val).ID))
				{
					dictionary[((Proto)val).ID]++;
				}
				else
				{
					dictionary[((Proto)val).ID] = 1;
				}
			}
			return dictionary;
		}

		private void SaveTickets()
		{
			try
			{
				string directoryName = Path.GetDirectoryName(_savePath);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				string contents = JsonUtility.ToJson((object)new TicketContainer
				{
					Tickets = _tickets
				}, true);
				File.WriteAllText(_savePath, contents);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("保存票券失败: " + ex.Message));
			}
		}

		private void LoadTickets()
		{
			try
			{
				if (File.Exists(_savePath))
				{
					TicketContainer ticketContainer = JsonUtility.FromJson<TicketContainer>(File.ReadAllText(_savePath));
					_tickets.Clear();
					_tickets.AddRange(ticketContainer.Tickets);
					Debug.Log((object)$"已加载 {_tickets.Count} 种票券");
				}
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("加载票券失败: " + ex.Message));
			}
		}

		public void ToggleUI()
		{
			_showUI = !_showUI;
			Debug.Log((object)$"UI显示: {_showUI}");
		}

		public void OnGUI()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (_showUI)
			{
				_windowRect = GUILayout.Window(12345, _windowRect, new WindowFunction(DrawWindow), "奖券系统", Array.Empty<GUILayoutOption>());
			}
		}

		private void DrawWindow(int windowId)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			GUILayout.Label("奖券系统 (按 F10 切换显示)", GUI.skin.box, Array.Empty<GUILayoutOption>());
			GUILayout.Label("奖券列表", GUI.skin.box, Array.Empty<GUILayoutOption>());
			_scrollPosition = GUILayout.BeginScrollView(_scrollPosition, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(120f) });
			if (_tickets.Count == 0)
			{
				GUILayout.Label("暂无奖券", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(40f) });
			}
			else
			{
				for (int i = 0; i < _tickets.Count; i++)
				{
					TicketData ticketData = _tickets[i];
					GUILayout.BeginHorizontal(GUI.skin.box, Array.Empty<GUILayoutOption>());
					GUILayout.Label(ticketData.TicketName ?? "", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) });
					GUILayout.Label($"x{ticketData.Count}", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) });
					if (GUILayout.Button("使用", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }))
					{
						UseTicket(ticketData.TicketId);
					}
					GUILayout.EndHorizontal();
				}
			}
			GUILayout.EndScrollView();
			GUILayout.Label("礼物历史记录", GUI.skin.box, Array.Empty<GUILayoutOption>());
			_historyScrollPosition = GUILayout.BeginScrollView(_historyScrollPosition, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(120f) });
			if (_giftHistory.Count == 0)
			{
				GUILayout.Label("暂无礼物记录", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(40f) });
			}
			else
			{
				for (int num = _giftHistory.Count - 1; num >= 0; num--)
				{
					GiftRecord giftRecord = _giftHistory[num];
					string text = DateTimeOffset.FromUnixTimeSeconds(giftRecord.timestamp).ToString("HH:mm:ss");
					GUILayout.BeginHorizontal(GUI.skin.box, Array.Empty<GUILayoutOption>());
					GUILayout.Label("[" + text + "]", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) });
					GUILayout.Label(giftRecord.userName ?? "", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) });
					GUILayout.Label("送 " + giftRecord.giftName, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) });
					GUILayout.Label($"→ {giftRecord.ticketName} x{giftRecord.ticketCount}", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) });
					GUILayout.EndHorizontal();
				}
			}
			GUILayout.EndScrollView();
			if (!string.IsNullOrEmpty(_resultMessage) && Time.realtimeSinceStartup - _resultMessageTime < 5f)
			{
				GUILayout.Label(_resultMessage, GUI.skin.box, Array.Empty<GUILayoutOption>());
			}
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("关闭", Array.Empty<GUILayoutOption>()))
			{
				_showUI = false;
			}
			if (GUILayout.Button("刷新", Array.Empty<GUILayoutOption>()))
			{
				LoadTickets();
			}
			GUILayout.EndHorizontal();
			GUILayout.EndVertical();
			GUI.DragWindow();
		}
	}
}