using System;
using TMPro;
using UnityEngine;
///
/// 时间更新组件
/// 独立于BasePanel的Update系统,专门用于更新UI中的时间显示
///
public class TimeUpdateComponent : MonoBehaviour
{
[Header("时间显示组件")]
public TextMeshProUGUI DateTimeText;
[Header("更新设置")]
public float UpdateInterval = 1f; // 更新间隔(秒)
public string TimeFormat = "yyyy-MM-dd HH:mm:ss"; // 时间格式
public bool UseLocalTime = true; // 使用本地时间还是UTC时间
private float _lastUpdateTime;
private bool _isActive = true;
void Start()
{
// 立即更新一次
UpdateDateTime();
}
void Update()
{
if (!_isActive || DateTimeText == null) return;
// 检查是否需要更新
if (Time.time - _lastUpdateTime >= UpdateInterval)
{
UpdateDateTime();
_lastUpdateTime = Time.time;
}
}
///
/// 更新时间显示
///
private void UpdateDateTime()
{
if (DateTimeText != null)
{
// 从SystemSettingsService获取统一时间(默认跟随系统时钟,可选自定义偏移)
var settingsService = ServiceLocator.Get();
DateTime displayTime = settingsService != null
? settingsService.SystemTime
: (UseLocalTime ? DateTime.Now : DateTime.UtcNow);
DateTimeText.text = displayTime.ToString(TimeFormat);
}
}
///
/// 启用或禁用时间更新
///
public void SetActive(bool active)
{
_isActive = active;
if (active)
{
UpdateDateTime(); // 激活时立即更新
}
}
///
/// 设置时间格式
///
public void SetTimeFormat(string format)
{
if (!string.IsNullOrEmpty(format))
{
TimeFormat = format;
UpdateDateTime(); // 格式改变后立即更新
}
}
///
/// 设置更新间隔
///
public void SetUpdateInterval(float interval)
{
if (interval > 0)
{
UpdateInterval = interval;
}
}
///
/// 刷新配置时间(从SystemSettingsService重新读取)
///
public void RefreshConfigTime()
{
UpdateDateTime();
Debug.Log("TimeUpdateComponent: 已刷新配置时间");
}
///
/// 获取当前显示的时间(包括偏移计算)
///
public DateTime GetCurrentDisplayTime()
{
var settingsService = ServiceLocator.Get();
if (settingsService != null)
{
return settingsService.SystemTime;
}
return UseLocalTime ? DateTime.Now : DateTime.UtcNow;
}
}