using System;
using System.Collections;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;
public class DateManager : MonoBehaviour
{
private string EndTimer;//结束时间
private string RecordData;
public GameObject ui;
public TextMeshProUGUI text;
public Button btn;
private void Awake()
{
ui.gameObject.SetActive(false);
btn.onClick.AddListener(() =>
{
Application.Quit();
});
#if UNITY_WEBGL
StartCoroutine(WebUpdateTime());
#else
UpdateTime(DecryptFileReader.ReadAndDecryptData("Timer.txt"), ShowTip, ShowTip, () =>
{
gameObject.SetActive(false);
});
#endif
}
public void ShowTip(string str)
{
gameObject.SetActive(true);
ui.SetActive(true);
text.text = str;
}
public IEnumerator WebUpdateTime()
{
string path = Path.Combine(Application.streamingAssetsPath, "Timer.txt");
using (UnityWebRequest request = new UnityWebRequest(path))
{
request.downloadHandler = new DownloadHandlerBuffer();
yield return request.SendWebRequest();
if (string.IsNullOrEmpty(request.error))
{
string datas = DecryptFileReader.ReadAndDecryptData(request.downloadHandler.data);
UpdateTime(datas, ShowTip, ShowTip, () =>
{
gameObject.SetActive(false);
});
}
else
{
Debug.LogError(request.error);
}
}
}
///
/// 更新系统时间
///
public void UpdateTime(string datas, UnityAction error = null, UnityAction timeOut = null, UnityAction updateTimer = null)
{
try
{
EndTimer = datas.Split('|')[0];
RecordData = datas.Split('|')[1];
//第一次获取获取系统时间
DateTime currentDateTime = DateTime.Now;
string Data = currentDateTime.ToString("yyyy-MM-dd HH:mm:ss");
if (DateTime.TryParse(RecordData, out DateTime recordDateTime) && DateTime.TryParse(Data, out DateTime nowDateTime))
{
if (recordDateTime > nowDateTime)
{
Debug.Log("仿真文件被损坏,请联系管理员进行修复");
error?.Invoke("仿真文件被损坏,请联系管理员进行修复");
}
else
{
#if !UNITY_WEBGL
//把上一次存储得系统时间更新到最新
string timer = "Timer.txt";
RecordData = Data;
string strMerge = EndTimer + "|" + RecordData;
EncryptFileCreator.EncryptAndSaveData(strMerge, timer);
#endif
updateTimer?.Invoke();
}
}
}
catch (Exception e)
{
Debug.LogError($"数据出错: {e.Message}");
error?.Invoke($"数据出错: {e.Message}");
return;
}
if (JudgeExpire())
{
Debug.Log("请联系管理员进行升级");
timeOut?.Invoke("请联系管理员进行升级");
return;
}
}
///
/// 判断是否到期
///
///
public bool JudgeExpire()
{
if (DateTime.TryParse(EndTimer, out DateTime endDataTime) && DateTime.TryParse(RecordData, out DateTime recordDateTime))
{
//结束日期小于目前日期代表到期
if (endDataTime < recordDateTime)
{
return true;
}
}
return false;
}
///
/// 给客户打包的时候,需要设置EndTimer,然后运行一次生成文件并注释掉
///
public void CreatTimer()
{
//第一次获取获取系统时间
DateTime currentDateTime = DateTime.Now;
RecordData = currentDateTime.ToString("yyyy-MM-dd HH:mm:ss");
string strMerge = EndTimer + "|" + RecordData;
EncryptFileCreator.EncryptAndSaveData(strMerge, "Timer.txt");
}
}