using System.Collections.Concurrent;
using System.Diagnostics;

namespace NavisworksTransport.Core.UIUpdate
{
    /// <summary>
    /// UI更新服务实现
    /// 提供统一的UI更新机制，支持事务、批量操作、优先级队列等高级功能
    /// </summary>
    public class UIUpdateService : IUIUpdateService, IDisposable
    {
        #region 字段和属性

        private readonly UIStateManager _uiStateManager;
        private readonly UIUpdateServiceConfiguration _configuration;
        private readonly ConcurrentQueue<QueuedUIUpdate> _updateQueue;
        private readonly ConcurrentDictionary<string, IUIUpdateTransaction> _activeTransactions;
        private readonly SemaphoreSlim _concurrencyControl;
        private readonly Timer _queueProcessingTimer;
        private readonly Timer _cleanupTimer;

        private volatile UIUpdateServiceStatus _status = UIUpdateServiceStatus.NotInitialized;
        private volatile int _activeUpdatesCount = 0;
        private volatile bool _isDisposed = false;

        /// <summary>
        /// 获取当前是否在UI线程中
        /// </summary>
        public bool IsUIThread => _uiStateManager.IsUIThread;

        /// <summary>
        /// 获取当前待处理的更新操作数量
        /// </summary>
        public int PendingUpdatesCount => _updateQueue.Count;

        /// <summary>
        /// 获取当前正在执行的更新操作数量
        /// </summary>
        public int ActiveUpdatesCount => _activeUpdatesCount;

        /// <summary>
        /// 获取服务当前状态
        /// </summary>
        public UIUpdateServiceStatus Status => _status;

        #endregion

        #region 事件

        /// <summary>
        /// UI更新操作开始时触发
        /// </summary>
        public event EventHandler<UIUpdateStartedEventArgs> UpdateStarted;

        /// <summary>
        /// UI更新操作完成时触发
        /// </summary>
        public event EventHandler<UIUpdateCompletedEventArgs> UpdateCompleted;

        /// <summary>
        /// UI更新操作失败时触发
        /// </summary>
        public event EventHandler<UIUpdateFailedEventArgs> UpdateFailed;

        /// <summary>
        /// 服务状态变化时触发
        /// </summary>
        public event EventHandler<UIUpdateServiceStatusChangedEventArgs> StatusChanged;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化UI更新服务
        /// </summary>
        /// <param name="configuration">服务配置</param>
        public UIUpdateService(UIUpdateServiceConfiguration configuration = null)
        {
            _configuration = configuration ?? UIUpdateServiceConfiguration.Default();
            _uiStateManager = UIStateManager.Instance;
            _updateQueue = new ConcurrentQueue<QueuedUIUpdate>();
            _activeTransactions = new ConcurrentDictionary<string, IUIUpdateTransaction>();
            _concurrencyControl = new SemaphoreSlim(_configuration.MaxConcurrentUpdates, _configuration.MaxConcurrentUpdates);

            // 初始化定时器
            _queueProcessingTimer = new Timer(ProcessQueueCallback, null, Timeout.Infinite, Timeout.Infinite);
            _cleanupTimer = new Timer(CleanupCallback, null, Timeout.Infinite, Timeout.Infinite);

            LogManager.Info("[UIUpdateService] UI更新服务已创建");
        }

        #endregion

        #region IUIUpdateService接口实现

        /// <summary>
        /// 初始化UI更新服务
        /// </summary>
        /// <param name="configuration">服务配置</param>
        public async Task InitializeAsync(UIUpdateServiceConfiguration configuration = null)
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException(nameof(UIUpdateService));
            }

            if (_status != UIUpdateServiceStatus.NotInitialized)
            {
                LogManager.Warning("[UIUpdateService] 服务已经初始化，跳过重复初始化");
                return;
            }

            try
            {
                SetStatus(UIUpdateServiceStatus.Initializing);

                LogManager.Info("[UIUpdateService] 开始初始化UI更新服务");

                // 更新配置（如果提供）
                if (configuration != null)
                {
                    // 这里可以动态更新某些配置项
                    LogManager.Info($"[UIUpdateService] 应用新配置: MaxConcurrentUpdates={configuration.MaxConcurrentUpdates}");
                }

                // 启动队列处理定时器
                _queueProcessingTimer.Change(0, _configuration.QueueProcessingIntervalMilliseconds);

                // 启动清理定时器
                _cleanupTimer.Change(_configuration.AutoCleanupIntervalMilliseconds, _configuration.AutoCleanupIntervalMilliseconds);

                SetStatus(UIUpdateServiceStatus.Running);

                LogManager.Info("[UIUpdateService] UI更新服务初始化完成");
            }
            catch (Exception ex)
            {
                SetStatus(UIUpdateServiceStatus.Error);
                LogManager.Error("[UIUpdateService] 初始化UI更新服务失败", ex);
                throw;
            }
        }

        /// <summary>
        /// 执行单个UI更新操作（异步）
        /// </summary>
        /// <param name="update">UI更新操作</param>
        /// <param name="context">更新上下文</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> ExecuteUpdateAsync(IUIUpdate update, UIUpdateContext context = null, CancellationToken cancellationToken = default)
        {
            if (_isDisposed)
            {
                return UIUpdateResult.Failure("服务已被释放", null, update?.Id);
            }

            if (_status != UIUpdateServiceStatus.Running)
            {
                return UIUpdateResult.Failure($"服务状态不正确: {_status}", null, update?.Id);
            }

            if (update == null)
            {
                return UIUpdateResult.Failure("更新操作不能为空");
            }

            var stopwatch = Stopwatch.StartNew();

            try
            {
                // 触发开始事件
                OnUpdateStarted(new UIUpdateStartedEventArgs(update.Id, update.Name, update.Priority));

                // 获取并发控制信号量
                await _concurrencyControl.WaitAsync(cancellationToken);
                Interlocked.Increment(ref _activeUpdatesCount);

                try
                {
                    // 应用默认上下文
                    context = context ?? UIUpdateContext.Default();
                    ApplyDefaultConfiguration(context);

                    // 执行更新操作
                    var result = await ExecuteUpdateWithRetryAsync(update, context, cancellationToken);
                    result.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;

                    // 触发完成或失败事件
                    if (result.IsSuccess)
                    {
                        OnUpdateCompleted(new UIUpdateCompletedEventArgs(update.Id, update.Name, result));
                    }
                    else
                    {
                        OnUpdateFailed(new UIUpdateFailedEventArgs(update.Id, update.Name, result.Exception));
                    }

                    return result;
                }
                finally
                {
                    Interlocked.Decrement(ref _activeUpdatesCount);
                    _concurrencyControl.Release();
                }
            }
            catch (Exception ex)
            {
                var result = UIUpdateResult.Failure($"执行更新操作时发生异常: {ex.Message}", ex, update.Id);
                result.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;

                OnUpdateFailed(new UIUpdateFailedEventArgs(update.Id, update.Name, ex));
                return result;
            }
            finally
            {
                stopwatch.Stop();
            }
        }

        /// <summary>
        /// 执行批量UI更新操作（原子性）
        /// </summary>
        /// <param name="updates">UI更新操作集合</param>
        /// <param name="context">更新上下文</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>批量更新结果</returns>
        public async Task<UIBatchUpdateResult> ExecuteBatchUpdateAsync(IEnumerable<IUIUpdate> updates, UIUpdateContext context = null, CancellationToken cancellationToken = default)
        {
            if (_isDisposed)
            {
                return new UIBatchUpdateResult
                {
                    IsSuccess = false,
                    Message = "服务已被释放",
                    TotalCount = 0,
                    SuccessCount = 0,
                    FailureCount = 0
                };
            }

            if (_status != UIUpdateServiceStatus.Running)
            {
                return new UIBatchUpdateResult
                {
                    IsSuccess = false,
                    Message = $"服务状态不正确: {_status}",
                    TotalCount = 0,
                    SuccessCount = 0,
                    FailureCount = 0
                };
            }

            var updateList = updates?.ToList() ?? new List<IUIUpdate>();
            var stopwatch = Stopwatch.StartNew();
            var result = new UIBatchUpdateResult
            {
                TotalCount = updateList.Count,
                Results = new List<UIUpdateResult>()
            };

            try
            {
                LogManager.Info($"[UIUpdateService] 开始执行批量更新，共{updateList.Count}个操作");

                context = context ?? UIUpdateContext.Default();
                ApplyDefaultConfiguration(context);

                var exceptions = new List<Exception>();

                // 并行执行更新操作
                var tasks = updateList.Select(async update =>
                {
                    try
                    {
                        var updateResult = await ExecuteUpdateAsync(update, context, cancellationToken);
                        result.Results.Add(updateResult);
                        
                        if (updateResult.IsSuccess)
                        {
                            Interlocked.Increment(ref result.SuccessCount);
                        }
                        else
                        {
                            Interlocked.Increment(ref result.FailureCount);
                            if (updateResult.Exception != null)
                            {
                                lock (exceptions)
                                {
                                    exceptions.Add(updateResult.Exception);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Interlocked.Increment(ref result.FailureCount);
                        result.Results.Add(UIUpdateResult.Failure($"更新操作异常: {ex.Message}", ex, update.Id));
                        
                        lock (exceptions)
                        {
                            exceptions.Add(ex);
                        }
                    }
                });

                await Task.WhenAll(tasks);

                result.IsSuccess = result.FailureCount == 0;
                result.Message = result.IsSuccess ? "批量更新全部成功" : $"批量更新完成，成功{result.SuccessCount}个，失败{result.FailureCount}个";

                if (exceptions.Count > 0)
                {
                    result.AggregateException = new AggregateException(exceptions);
                }

                LogManager.Info($"[UIUpdateService] 批量更新完成: {result.Message}");
                return result;
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateService] 批量更新过程中发生异常", ex);
                
                result.IsSuccess = false;
                result.Message = $"批量更新失败: {ex.Message}";
                result.AggregateException = new AggregateException(ex);
                
                return result;
            }
            finally
            {
                result.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
                stopwatch.Stop();
            }
        }

        /// <summary>
        /// 排队UI更新操作（延迟执行）
        /// </summary>
        /// <param name="update">UI更新操作</param>
        /// <param name="priority">操作优先级</param>
        /// <param name="context">更新上下文</param>
        public void QueueUpdate(IUIUpdate update, UIUpdatePriority priority = UIUpdatePriority.Normal, UIUpdateContext context = null)
        {
            if (_isDisposed || update == null)
            {
                return;
            }

            if (_status != UIUpdateServiceStatus.Running && _status != UIUpdateServiceStatus.Paused)
            {
                LogManager.Warning($"[UIUpdateService] 服务状态不正确，无法排队更新操作: {_status}");
                return;
            }

            if (_updateQueue.Count >= _configuration.MaxQueueLength)
            {
                LogManager.Warning("[UIUpdateService] 更新队列已满，丢弃新的更新操作");
                return;
            }

            var queuedUpdate = new QueuedUIUpdate
            {
                Update = update,
                Priority = priority,
                Context = context ?? UIUpdateContext.Default(),
                QueueTime = DateTime.UtcNow
            };

            _updateQueue.Enqueue(queuedUpdate);

            if (_configuration.EnableVerboseLogging)
            {
                LogManager.Info($"[UIUpdateService] 已将更新操作{update.Name}排队，优先级: {priority}");
            }
        }

        /// <summary>
        /// 开始UI更新事务
        /// </summary>
        /// <param name="transactionName">事务名称</param>
        /// <returns>事务句柄</returns>
        public IUIUpdateTransaction BeginTransaction(string transactionName = null)
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException(nameof(UIUpdateService));
            }

            if (!_configuration.EnableTransactionSupport)
            {
                throw new NotSupportedException("事务支持未启用");
            }

            var transaction = new UIUpdateTransaction(transactionName, _configuration.MaxTransactionTimeoutMilliseconds);
            _activeTransactions.TryAdd(transaction.Id, transaction);

            LogManager.Info($"[UIUpdateService] 开始事务: {transaction.Name} ({transaction.Id})");
            return transaction;
        }

        /// <summary>
        /// 在事务中执行UI更新操作
        /// </summary>
        /// <param name="transaction">事务句柄</param>
        /// <param name="updates">UI更新操作集合</param>
        /// <param name="context">更新上下文</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>事务执行结果</returns>
        public async Task<UITransactionResult> ExecuteInTransactionAsync(IUIUpdateTransaction transaction, IEnumerable<IUIUpdate> updates, UIUpdateContext context = null, CancellationToken cancellationToken = default)
        {
            if (_isDisposed)
            {
                return new UITransactionResult
                {
                    IsSuccess = false,
                    TransactionId = transaction?.Id,
                    TransactionName = transaction?.Name,
                    FinalStatus = UITransactionStatus.Failed,
                    Message = "服务已被释放"
                };
            }

            if (transaction == null)
            {
                return new UITransactionResult
                {
                    IsSuccess = false,
                    FinalStatus = UITransactionStatus.Failed,
                    Message = "事务句柄不能为空"
                };
            }

            var stopwatch = Stopwatch.StartNew();

            try
            {
                LogManager.Info($"[UIUpdateService] 在事务{transaction.Name}中执行更新操作");

                // 添加更新操作到事务
                transaction.AddUpdates(updates);

                // 执行批量更新
                var batchResult = await ExecuteBatchUpdateAsync(updates, context, cancellationToken);

                // 根据结果提交或回滚事务
                UITransactionResult transactionResult;
                if (batchResult.IsSuccess)
                {
                    transactionResult = await transaction.CommitAsync(cancellationToken);
                }
                else
                {
                    transactionResult = await transaction.RollbackAsync(cancellationToken);
                }

                transactionResult.UpdateResults = batchResult;
                transactionResult.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;

                return transactionResult;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[UIUpdateService] 事务{transaction.Name}执行过程中发生异常", ex);

                try
                {
                    await transaction.RollbackAsync(cancellationToken);
                }
                catch (Exception rollbackEx)
                {
                    LogManager.Error($"[UIUpdateService] 事务{transaction.Name}回滚失败", rollbackEx);
                }

                return new UITransactionResult
                {
                    IsSuccess = false,
                    TransactionId = transaction.Id,
                    TransactionName = transaction.Name,
                    FinalStatus = UITransactionStatus.Failed,
                    Message = $"事务执行失败: {ex.Message}",
                    Exception = ex,
                    ElapsedMilliseconds = stopwatch.ElapsedMilliseconds
                };
            }
            finally
            {
                // 清理事务
                _activeTransactions.TryRemove(transaction.Id, out _);
                stopwatch.Stop();
            }
        }

        /// <summary>
        /// 暂停UI更新服务
        /// </summary>
        public async Task PauseAsync()
        {
            if (_status == UIUpdateServiceStatus.Running)
            {
                SetStatus(UIUpdateServiceStatus.Paused);
                LogManager.Info("[UIUpdateService] UI更新服务已暂停");
            }
        }

        /// <summary>
        /// 恢复UI更新服务
        /// </summary>
        public async Task ResumeAsync()
        {
            if (_status == UIUpdateServiceStatus.Paused)
            {
                SetStatus(UIUpdateServiceStatus.Running);
                LogManager.Info("[UIUpdateService] UI更新服务已恢复");
            }
        }

        /// <summary>
        /// 关闭UI更新服务并清理资源
        /// </summary>
        public async Task ShutdownAsync()
        {
            if (_isDisposed || _status == UIUpdateServiceStatus.Shutdown)
            {
                return;
            }

            try
            {
                SetStatus(UIUpdateServiceStatus.Shutting);
                LogManager.Info("[UIUpdateService] 开始关闭UI更新服务");

                // 停止定时器
                _queueProcessingTimer?.Change(Timeout.Infinite, Timeout.Infinite);
                _cleanupTimer?.Change(Timeout.Infinite, Timeout.Infinite);

                // 等待当前操作完成
                var timeout = TimeSpan.FromSeconds(10);
                var startTime = DateTime.UtcNow;
                
                while (_activeUpdatesCount > 0 && DateTime.UtcNow - startTime < timeout)
                {
                    await Task.Delay(100);
                }

                // 处理剩余的队列项目（可选）
                await ProcessRemainingQueueItems();

                // 清理活动事务
                foreach (var transaction in _activeTransactions.Values)
                {
                    try
                    {
                        await transaction.RollbackAsync();
                    }
                    catch (Exception ex)
                    {
                        LogManager.Error($"[UIUpdateService] 清理事务{transaction.Name}失败", ex);
                    }
                }
                _activeTransactions.Clear();

                SetStatus(UIUpdateServiceStatus.Shutdown);
                LogManager.Info("[UIUpdateService] UI更新服务已关闭");
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateService] 关闭UI更新服务时发生异常", ex);
                SetStatus(UIUpdateServiceStatus.Error);
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 设置服务状态
        /// </summary>
        /// <param name="newStatus">新状态</param>
        private void SetStatus(UIUpdateServiceStatus newStatus)
        {
            var oldStatus = _status;
            _status = newStatus;

            if (oldStatus != newStatus)
            {
                OnStatusChanged(new UIUpdateServiceStatusChangedEventArgs(oldStatus, newStatus));
            }
        }

        /// <summary>
        /// 应用默认配置到上下文
        /// </summary>
        /// <param name="context">更新上下文</param>
        private void ApplyDefaultConfiguration(UIUpdateContext context)
        {
            if (context.TargetFramework == UIFrameworkType.Auto)
            {
                context.TargetFramework = _configuration.DefaultFramework;
            }

            if (context.TimeoutMilliseconds <= 0)
            {
                context.TimeoutMilliseconds = _configuration.DefaultTimeoutMilliseconds;
            }
        }

        /// <summary>
        /// 执行带重试的更新操作
        /// </summary>
        /// <param name="update">更新操作</param>
        /// <param name="context">更新上下文</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        private async Task<UIUpdateResult> ExecuteUpdateWithRetryAsync(IUIUpdate update, UIUpdateContext context, CancellationToken cancellationToken)
        {
            var maxRetries = context.EnableRetry ? context.MaxRetryCount : 0;
            var retryInterval = context.RetryIntervalMilliseconds;

            for (int attempt = 0; attempt <= maxRetries; attempt++)
            {
                try
                {
                    var result = await update.ExecuteAsync(context, cancellationToken);
                    
                    if (result.IsSuccess || attempt == maxRetries)
                    {
                        return result;
                    }

                    // 重试前等待
                    if (attempt < maxRetries && retryInterval > 0)
                    {
                        await Task.Delay(retryInterval, cancellationToken);
                    }
                }
                catch (OperationCanceledException)
                {
                    return UIUpdateResult.Failure("操作被取消", null, update.Id);
                }
                catch (Exception ex)
                {
                    if (attempt == maxRetries)
                    {
                        return UIUpdateResult.Failure($"更新操作失败（重试{maxRetries}次后）: {ex.Message}", ex, update.Id);
                    }

                    LogManager.Warning($"[UIUpdateService] 更新操作{update.Name}第{attempt + 1}次尝试失败，准备重试: {ex.Message}");

                    // 重试前等待
                    if (retryInterval > 0)
                    {
                        await Task.Delay(retryInterval, cancellationToken);
                    }
                }
            }

            return UIUpdateResult.Failure("未知错误", null, update.Id);
        }

        /// <summary>
        /// 队列处理回调
        /// </summary>
        /// <param name="state">状态对象</param>
        private void ProcessQueueCallback(object state)
        {
            if (_isDisposed || _status != UIUpdateServiceStatus.Running)
            {
                return;
            }

            _ = Task.Run(async () =>
            {
                try
                {
                    await ProcessQueuedUpdates();
                }
                catch (Exception ex)
                {
                    LogManager.Error("[UIUpdateService] 处理队列更新时发生异常", ex);
                }
            });
        }

        /// <summary>
        /// 处理队列中的更新操作
        /// </summary>
        private async Task ProcessQueuedUpdates()
        {
            var processedCount = 0;
            var batchSize = Math.Min(10, _configuration.MaxConcurrentUpdates); // 批量处理
            var updates = new List<QueuedUIUpdate>();

            // 收集一批更新操作
            while (updates.Count < batchSize && _updateQueue.TryDequeue(out var queuedUpdate))
            {
                updates.Add(queuedUpdate);
            }

            if (updates.Count == 0)
            {
                return;
            }

            // 按优先级排序
            updates = updates.OrderByDescending(u => u.Priority).ToList();

            // 并行执行更新操作
            var tasks = updates.Select(async queuedUpdate =>
            {
                try
                {
                    await ExecuteUpdateAsync(queuedUpdate.Update, queuedUpdate.Context);
                    Interlocked.Increment(ref processedCount);
                }
                catch (Exception ex)
                {
                    LogManager.Error($"[UIUpdateService] 执行队列更新{queuedUpdate.Update.Name}失败", ex);
                }
            });

            await Task.WhenAll(tasks);

            if (_configuration.EnableVerboseLogging && processedCount > 0)
            {
                LogManager.Info($"[UIUpdateService] 处理了{processedCount}个队列更新操作");
            }
        }

        /// <summary>
        /// 处理剩余的队列项目
        /// </summary>
        private async Task ProcessRemainingQueueItems()
        {
            var remainingCount = _updateQueue.Count;
            if (remainingCount > 0)
            {
                LogManager.Info($"[UIUpdateService] 处理剩余的{remainingCount}个队列项目");
                await ProcessQueuedUpdates();
            }
        }

        /// <summary>
        /// 清理回调
        /// </summary>
        /// <param name="state">状态对象</param>
        private void CleanupCallback(object state)
        {
            if (_isDisposed)
            {
                return;
            }

            try
            {
                // 清理过期的事务
                var now = DateTime.UtcNow;
                var expiredTransactions = _activeTransactions.Values
                    .Where(t => now - t.StartTime > TimeSpan.FromMilliseconds(_configuration.MaxTransactionTimeoutMilliseconds))
                    .ToList();

                foreach (var transaction in expiredTransactions)
                {
                    try
                    {
                        _ = transaction.RollbackAsync();
                        _activeTransactions.TryRemove(transaction.Id, out _);
                        LogManager.Warning($"[UIUpdateService] 清理过期事务: {transaction.Name}");
                    }
                    catch (Exception ex)
                    {
                        LogManager.Error($"[UIUpdateService] 清理过期事务{transaction.Name}失败", ex);
                    }
                }

                // 强制垃圾回收（可选）
                if (_configuration.EnablePerformanceMonitoring)
                {
                    GC.Collect(0, GCCollectionMode.Optimized);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateService] 自动清理过程中发生异常", ex);
            }
        }

        #endregion

        #region 事件触发方法

        /// <summary>
        /// 触发更新开始事件
        /// </summary>
        /// <param name="args">事件参数</param>
        protected virtual void OnUpdateStarted(UIUpdateStartedEventArgs args)
        {
            try
            {
                UpdateStarted?.Invoke(this, args);
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateService] 触发UpdateStarted事件时发生异常", ex);
            }
        }

        /// <summary>
        /// 触发更新完成事件
        /// </summary>
        /// <param name="args">事件参数</param>
        protected virtual void OnUpdateCompleted(UIUpdateCompletedEventArgs args)
        {
            try
            {
                UpdateCompleted?.Invoke(this, args);
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateService] 触发UpdateCompleted事件时发生异常", ex);
            }
        }

        /// <summary>
        /// 触发更新失败事件
        /// </summary>
        /// <param name="args">事件参数</param>
        protected virtual void OnUpdateFailed(UIUpdateFailedEventArgs args)
        {
            try
            {
                UpdateFailed?.Invoke(this, args);
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateService] 触发UpdateFailed事件时发生异常", ex);
            }
        }

        /// <summary>
        /// 触发状态变化事件
        /// </summary>
        /// <param name="args">事件参数</param>
        protected virtual void OnStatusChanged(UIUpdateServiceStatusChangedEventArgs args)
        {
            try
            {
                StatusChanged?.Invoke(this, args);
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateService] 触发StatusChanged事件时发生异常", ex);
            }
        }

        #endregion

        #region IDisposable实现

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            try
            {
                // 异步关闭服务
                _ = ShutdownAsync();

                // 释放定时器
                _queueProcessingTimer?.Dispose();
                _cleanupTimer?.Dispose();

                // 释放信号量
                _concurrencyControl?.Dispose();

                _isDisposed = true;
                LogManager.Info("[UIUpdateService] UI更新服务已释放");
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateService] 释放UI更新服务时发生异常", ex);
            }
        }

        #endregion
    }

    #region 内部辅助类

    /// <summary>
    /// 队列中的UI更新操作
    /// </summary>
    internal class QueuedUIUpdate
    {
        public IUIUpdate Update { get; set; }
        public UIUpdatePriority Priority { get; set; }
        public UIUpdateContext Context { get; set; }
        public DateTime QueueTime { get; set; }
    }

    #endregion
}