using System.Collections.Concurrent;
using System.Diagnostics;
using System.Timers;
using Timer = System.Timers.Timer;

namespace NavisworksTransport.Core.UIUpdate
{
    /// <summary>
    /// UI更新监控器
    /// 提供UI更新操作的性能监控、诊断和分析功能
    /// </summary>
    public class UIUpdateMonitor : IDisposable
    {
        #region 嵌套类型定义

        /// <summary>
        /// UI更新性能指标
        /// </summary>
        public class UIUpdateMetrics
        {
            /// <summary>
            /// 更新操作ID
            /// </summary>
            public string UpdateId { get; set; }

            /// <summary>
            /// 更新操作名称
            /// </summary>
            public string UpdateName { get; set; }

            /// <summary>
            /// 操作类型
            /// </summary>
            public string OperationType { get; set; }

            /// <summary>
            /// 优先级
            /// </summary>
            public UIUpdatePriority Priority { get; set; }

            /// <summary>
            /// 开始时间
            /// </summary>
            public DateTime StartTime { get; set; }

            /// <summary>
            /// 结束时间
            /// </summary>
            public DateTime? EndTime { get; set; }

            /// <summary>
            /// 执行耗时（毫秒）
            /// </summary>
            public long ElapsedMilliseconds { get; set; }

            /// <summary>
            /// 是否成功
            /// </summary>
            public bool IsSuccess { get; set; }

            /// <summary>
            /// 错误消息
            /// </summary>
            public string ErrorMessage { get; set; }

            /// <summary>
            /// 内存使用量（字节）
            /// </summary>
            public long MemoryUsage { get; set; }

            /// <summary>
            /// CPU使用率（百分比）
            /// </summary>
            public double CpuUsage { get; set; }

            /// <summary>
            /// 重试次数
            /// </summary>
            public int RetryCount { get; set; }

            /// <summary>
            /// 是否需要UI线程
            /// </summary>
            public bool RequiredUIThread { get; set; }

            /// <summary>
            /// 额外元数据
            /// </summary>
            public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
        }

        /// <summary>
        /// 性能统计信息
        /// </summary>
        public class PerformanceStatistics
        {
            /// <summary>
            /// 总操作数
            /// </summary>
            public int TotalOperations { get; set; }

            /// <summary>
            /// 成功操作数
            /// </summary>
            public int SuccessfulOperations { get; set; }

            /// <summary>
            /// 失败操作数
            /// </summary>
            public int FailedOperations { get; set; }

            /// <summary>
            /// 成功率（百分比）
            /// </summary>
            public double SuccessRate => TotalOperations > 0 ? (double)SuccessfulOperations / TotalOperations * 100 : 0;

            /// <summary>
            /// 平均执行时间（毫秒）
            /// </summary>
            public double AverageExecutionTime { get; set; }

            /// <summary>
            /// 最小执行时间（毫秒）
            /// </summary>
            public long MinExecutionTime { get; set; }

            /// <summary>
            /// 最大执行时间（毫秒）
            /// </summary>
            public long MaxExecutionTime { get; set; }

            /// <summary>
            /// 第95百分位执行时间（毫秒）
            /// </summary>
            public long P95ExecutionTime { get; set; }

            /// <summary>
            /// 第99百分位执行时间（毫秒）
            /// </summary>
            public long P99ExecutionTime { get; set; }

            /// <summary>
            /// 平均内存使用量（字节）
            /// </summary>
            public double AverageMemoryUsage { get; set; }

            /// <summary>
            /// 平均CPU使用率（百分比）
            /// </summary>
            public double AverageCpuUsage { get; set; }

            /// <summary>
            /// 统计时间范围开始
            /// </summary>
            public DateTime PeriodStart { get; set; }

            /// <summary>
            /// 统计时间范围结束
            /// </summary>
            public DateTime PeriodEnd { get; set; }

            /// <summary>
            /// 按优先级分组的统计
            /// </summary>
            public Dictionary<UIUpdatePriority, int> OperationsByPriority { get; set; } = new Dictionary<UIUpdatePriority, int>();

            /// <summary>
            /// 按操作类型分组的统计
            /// </summary>
            public Dictionary<string, int> OperationsByType { get; set; } = new Dictionary<string, int>();
        }

        /// <summary>
        /// 监控配置
        /// </summary>
        public class MonitorConfiguration
        {
            /// <summary>
            /// 是否启用性能监控
            /// </summary>
            public bool EnablePerformanceMonitoring { get; set; } = true;

            /// <summary>
            /// 是否启用内存监控
            /// </summary>
            public bool EnableMemoryMonitoring { get; set; } = true;

            /// <summary>
            /// 是否启用CPU监控
            /// </summary>
            public bool EnableCpuMonitoring { get; set; } = true;

            /// <summary>
            /// 最大指标保留数量
            /// </summary>
            public int MaxMetricsCount { get; set; } = 1000;

            /// <summary>
            /// 统计报告间隔（毫秒）
            /// </summary>
            public int StatisticsReportIntervalMilliseconds { get; set; } = 60000; // 1分钟

            /// <summary>
            /// 慢操作阈值（毫秒）
            /// </summary>
            public long SlowOperationThresholdMilliseconds { get; set; } = 1000;

            /// <summary>
            /// 是否启用慢操作警告
            /// </summary>
            public bool EnableSlowOperationWarning { get; set; } = true;

            /// <summary>
            /// 是否启用错误操作警告
            /// </summary>
            public bool EnableErrorOperationWarning { get; set; } = true;

            /// <summary>
            /// 是否启用详细日志
            /// </summary>
            public bool EnableVerboseLogging { get; set; } = false;

            /// <summary>
            /// 内存使用警告阈值（MB）
            /// </summary>
            public long MemoryWarningThresholdMB { get; set; } = 100;

            /// <summary>
            /// CPU使用警告阈值（百分比）
            /// </summary>
            public double CpuWarningThreshold { get; set; } = 80.0;
        }

        /// <summary>
        /// 诊断报告
        /// </summary>
        public class DiagnosticsReport
        {
            /// <summary>
            /// 报告生成时间
            /// </summary>
            public DateTime GeneratedTime { get; set; } = DateTime.UtcNow;

            /// <summary>
            /// 性能统计信息
            /// </summary>
            public PerformanceStatistics Statistics { get; set; }

            /// <summary>
            /// 慢操作列表
            /// </summary>
            public List<UIUpdateMetrics> SlowOperations { get; set; } = new List<UIUpdateMetrics>();

            /// <summary>
            /// 错误操作列表
            /// </summary>
            public List<UIUpdateMetrics> ErrorOperations { get; set; } = new List<UIUpdateMetrics>();

            /// <summary>
            /// 系统资源使用情况
            /// </summary>
            public Dictionary<string, object> SystemResourceUsage { get; set; } = new Dictionary<string, object>();

            /// <summary>
            /// 建议和警告
            /// </summary>
            public List<string> Recommendations { get; set; } = new List<string>();

            /// <summary>
            /// 趋势分析
            /// </summary>
            public Dictionary<string, object> TrendAnalysis { get; set; } = new Dictionary<string, object>();
        }

        #endregion

        #region 字段和属性

        private readonly MonitorConfiguration _configuration;
        private readonly ConcurrentQueue<UIUpdateMetrics> _metricsQueue;
        private readonly ConcurrentDictionary<string, UIUpdateMetrics> _activeOperations;
        private readonly Timer _statisticsTimer;
        private readonly PerformanceCounter _cpuCounter;
        private readonly object _lockObject = new object();
        private volatile bool _isDisposed = false;

        /// <summary>
        /// 监控配置
        /// </summary>
        public MonitorConfiguration Configuration => _configuration;

        /// <summary>
        /// 当前活动操作数量
        /// </summary>
        public int ActiveOperationsCount => _activeOperations.Count;

        /// <summary>
        /// 历史指标数量
        /// </summary>
        public int HistoricalMetricsCount => _metricsQueue.Count;

        /// <summary>
        /// 是否正在监控
        /// </summary>
        public bool IsMonitoring { get; private set; }

        #endregion

        #region 事件

        /// <summary>
        /// 慢操作检测事件
        /// </summary>
        public event EventHandler<SlowOperationDetectedEventArgs> SlowOperationDetected;

        /// <summary>
        /// 错误操作检测事件
        /// </summary>
        public event EventHandler<ErrorOperationDetectedEventArgs> ErrorOperationDetected;

        /// <summary>
        /// 性能统计更新事件
        /// </summary>
        public event EventHandler<PerformanceStatisticsUpdatedEventArgs> PerformanceStatisticsUpdated;

        /// <summary>
        /// 资源使用警告事件
        /// </summary>
        public event EventHandler<ResourceUsageWarningEventArgs> ResourceUsageWarning;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化UI更新监控器
        /// </summary>
        /// <param name="configuration">监控配置</param>
        public UIUpdateMonitor(MonitorConfiguration configuration = null)
        {
            _configuration = configuration ?? new MonitorConfiguration();
            _metricsQueue = new ConcurrentQueue<UIUpdateMetrics>();
            _activeOperations = new ConcurrentDictionary<string, UIUpdateMetrics>();

            // 初始化性能计数器
            try
            {
                _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                _cpuCounter.NextValue(); // 初始调用
            }
            catch (Exception ex)
            {
                LogManager.Warning($"[UIUpdateMonitor] 无法初始化CPU性能计数器: {ex.Message}");
            }

            // 初始化统计定时器
            _statisticsTimer = new Timer(_configuration.StatisticsReportIntervalMilliseconds);
            _statisticsTimer.Elapsed += OnStatisticsTimerElapsed;
            _statisticsTimer.AutoReset = true;

            LogManager.Info("[UIUpdateMonitor] UI更新监控器已创建");
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 启动监控
        /// </summary>
        public void Start()
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException(nameof(UIUpdateMonitor));
            }

            lock (_lockObject)
            {
                if (!IsMonitoring)
                {
                    _statisticsTimer.Start();
                    IsMonitoring = true;
                    LogManager.Info("[UIUpdateMonitor] UI更新监控已启动");
                }
            }
        }

        /// <summary>
        /// 停止监控
        /// </summary>
        public void Stop()
        {
            lock (_lockObject)
            {
                if (IsMonitoring)
                {
                    _statisticsTimer.Stop();
                    IsMonitoring = false;
                    LogManager.Info("[UIUpdateMonitor] UI更新监控已停止");
                }
            }
        }

        /// <summary>
        /// 记录操作开始
        /// </summary>
        /// <param name="updateId">更新操作ID</param>
        /// <param name="updateName">更新操作名称</param>
        /// <param name="operationType">操作类型</param>
        /// <param name="priority">优先级</param>
        /// <param name="requiresUIThread">是否需要UI线程</param>
        public void RecordOperationStart(string updateId, string updateName, string operationType, UIUpdatePriority priority, bool requiresUIThread)
        {
            if (!_configuration.EnablePerformanceMonitoring || _isDisposed)
            {
                return;
            }

            try
            {
                var metrics = new UIUpdateMetrics
                {
                    UpdateId = updateId,
                    UpdateName = updateName,
                    OperationType = operationType,
                    Priority = priority,
                    StartTime = DateTime.UtcNow,
                    RequiredUIThread = requiresUIThread,
                    MemoryUsage = _configuration.EnableMemoryMonitoring ? GC.GetTotalMemory(false) : 0,
                    CpuUsage = _configuration.EnableCpuMonitoring ? GetCurrentCpuUsage() : 0
                };

                _activeOperations[updateId] = metrics;

                if (_configuration.EnableVerboseLogging)
                {
                    LogManager.Debug($"[UIUpdateMonitor] 记录操作开始: {updateName} ({updateId})");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[UIUpdateMonitor] 记录操作开始失败: {updateId}", ex);
            }
        }

        /// <summary>
        /// 记录操作完成
        /// </summary>
        /// <param name="updateId">更新操作ID</param>
        /// <param name="isSuccess">是否成功</param>
        /// <param name="errorMessage">错误消息</param>
        /// <param name="retryCount">重试次数</param>
        public void RecordOperationEnd(string updateId, bool isSuccess, string errorMessage = null, int retryCount = 0)
        {
            if (!_configuration.EnablePerformanceMonitoring || _isDisposed)
            {
                return;
            }

            try
            {
                if (_activeOperations.TryRemove(updateId, out var metrics))
                {
                    var endTime = DateTime.UtcNow;
                    metrics.EndTime = endTime;
                    metrics.ElapsedMilliseconds = (long)(endTime - metrics.StartTime).TotalMilliseconds;
                    metrics.IsSuccess = isSuccess;
                    metrics.ErrorMessage = errorMessage;
                    metrics.RetryCount = retryCount;

                    // 更新内存和CPU使用情况
                    if (_configuration.EnableMemoryMonitoring)
                    {
                        var currentMemory = GC.GetTotalMemory(false);
                        metrics.MemoryUsage = currentMemory - metrics.MemoryUsage;
                    }

                    if (_configuration.EnableCpuMonitoring)
                    {
                        var currentCpu = GetCurrentCpuUsage();
                        metrics.CpuUsage = (metrics.CpuUsage + currentCpu) / 2; // 平均值
                    }

                    // 添加到指标队列
                    _metricsQueue.Enqueue(metrics);

                    // 限制队列大小
                    while (_metricsQueue.Count > _configuration.MaxMetricsCount)
                    {
                        _metricsQueue.TryDequeue(out _);
                    }

                    // 检查慢操作
                    if (_configuration.EnableSlowOperationWarning && 
                        metrics.ElapsedMilliseconds > _configuration.SlowOperationThresholdMilliseconds)
                    {
                        OnSlowOperationDetected(new SlowOperationDetectedEventArgs(metrics));
                    }

                    // 检查错误操作
                    if (_configuration.EnableErrorOperationWarning && !isSuccess)
                    {
                        OnErrorOperationDetected(new ErrorOperationDetectedEventArgs(metrics));
                    }

                    // 检查资源使用
                    CheckResourceUsage(metrics);

                    if (_configuration.EnableVerboseLogging)
                    {
                        LogManager.Debug($"[UIUpdateMonitor] 记录操作完成: {metrics.UpdateName} ({updateId}) - {metrics.ElapsedMilliseconds}ms - {(isSuccess ? "成功" : "失败")}");
                    }
                }
                else
                {
                    LogManager.Warning($"[UIUpdateMonitor] 无法找到操作开始记录: {updateId}");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[UIUpdateMonitor] 记录操作完成失败: {updateId}", ex);
            }
        }

        /// <summary>
        /// 获取性能统计信息
        /// </summary>
        /// <param name="periodStart">统计开始时间</param>
        /// <param name="periodEnd">统计结束时间</param>
        /// <returns>性能统计信息</returns>
        public PerformanceStatistics GetPerformanceStatistics(DateTime? periodStart = null, DateTime? periodEnd = null)
        {
            var start = periodStart ?? DateTime.UtcNow.AddHours(-1);
            var end = periodEnd ?? DateTime.UtcNow;

            var metrics = _metricsQueue
                .Where(m => m.StartTime >= start && m.StartTime <= end)
                .ToList();

            if (metrics.Count == 0)
            {
                return new PerformanceStatistics
                {
                    PeriodStart = start,
                    PeriodEnd = end
                };
            }

            var statistics = new PerformanceStatistics
            {
                TotalOperations = metrics.Count,
                SuccessfulOperations = metrics.Count(m => m.IsSuccess),
                FailedOperations = metrics.Count(m => !m.IsSuccess),
                AverageExecutionTime = metrics.Average(m => m.ElapsedMilliseconds),
                MinExecutionTime = metrics.Min(m => m.ElapsedMilliseconds),
                MaxExecutionTime = metrics.Max(m => m.ElapsedMilliseconds),
                AverageMemoryUsage = metrics.Average(m => m.MemoryUsage),
                AverageCpuUsage = metrics.Average(m => m.CpuUsage),
                PeriodStart = start,
                PeriodEnd = end
            };

            // 计算百分位数
            var sortedTimes = metrics.Select(m => m.ElapsedMilliseconds).OrderBy(t => t).ToList();
            statistics.P95ExecutionTime = GetPercentile(sortedTimes, 0.95);
            statistics.P99ExecutionTime = GetPercentile(sortedTimes, 0.99);

            // 按优先级分组
            statistics.OperationsByPriority = metrics
                .GroupBy(m => m.Priority)
                .ToDictionary(g => g.Key, g => g.Count());

            // 按操作类型分组
            statistics.OperationsByType = metrics
                .GroupBy(m => m.OperationType)
                .ToDictionary(g => g.Key, g => g.Count());

            return statistics;
        }

        /// <summary>
        /// 生成诊断报告
        /// </summary>
        /// <param name="includeTrendAnalysis">是否包含趋势分析</param>
        /// <returns>诊断报告</returns>
        public DiagnosticsReport GenerateDiagnosticsReport(bool includeTrendAnalysis = true)
        {
            try
            {
                LogManager.Info("[UIUpdateMonitor] 开始生成诊断报告");

                var report = new DiagnosticsReport
                {
                    Statistics = GetPerformanceStatistics(),
                    SlowOperations = GetSlowOperations(),
                    ErrorOperations = GetErrorOperations(),
                    SystemResourceUsage = GetSystemResourceUsage()
                };

                // 生成建议
                GenerateRecommendations(report);

                // 趋势分析
                if (includeTrendAnalysis)
                {
                    GenerateTrendAnalysis(report);
                }

                LogManager.Info("[UIUpdateMonitor] 诊断报告生成完成");
                return report;
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateMonitor] 生成诊断报告失败", ex);
                return new DiagnosticsReport();
            }
        }

        /// <summary>
        /// 获取慢操作列表
        /// </summary>
        /// <param name="count">返回数量</param>
        /// <returns>慢操作列表</returns>
        public List<UIUpdateMetrics> GetSlowOperations(int count = 10)
        {
            return _metricsQueue
                .Where(m => m.ElapsedMilliseconds > _configuration.SlowOperationThresholdMilliseconds)
                .OrderByDescending(m => m.ElapsedMilliseconds)
                .Take(count)
                .ToList();
        }

        /// <summary>
        /// 获取错误操作列表
        /// </summary>
        /// <param name="count">返回数量</param>
        /// <returns>错误操作列表</returns>
        public List<UIUpdateMetrics> GetErrorOperations(int count = 10)
        {
            return _metricsQueue
                .Where(m => !m.IsSuccess)
                .OrderByDescending(m => m.StartTime)
                .Take(count)
                .ToList();
        }

        /// <summary>
        /// 清除历史指标
        /// </summary>
        public void ClearMetrics()
        {
            while (_metricsQueue.TryDequeue(out _)) { }
            LogManager.Info("[UIUpdateMonitor] 已清除所有历史指标");
        }

        /// <summary>
        /// 导出指标数据
        /// </summary>
        /// <param name="filePath">导出文件路径</param>
        /// <param name="format">导出格式（csv, json）</param>
        /// <returns>是否成功</returns>
        public async Task<bool> ExportMetricsAsync(string filePath, string format = "csv")
        {
            try
            {
                LogManager.Info($"[UIUpdateMonitor] 开始导出指标数据到: {filePath}");

                var metrics = _metricsQueue.ToList();
                
                if (format.ToLower() == "csv")
                {
                    await ExportToCsvAsync(metrics, filePath);
                }
                else if (format.ToLower() == "json")
                {
                    await ExportToJsonAsync(metrics, filePath);
                }
                else
                {
                    throw new ArgumentException($"不支持的导出格式: {format}");
                }

                LogManager.Info($"[UIUpdateMonitor] 成功导出{metrics.Count}条指标数据");
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[UIUpdateMonitor] 导出指标数据失败: {filePath}", ex);
                return false;
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 获取当前CPU使用率
        /// </summary>
        /// <returns>CPU使用率（百分比）</returns>
        private double GetCurrentCpuUsage()
        {
            try
            {
                return _cpuCounter?.NextValue() ?? 0;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 计算百分位数
        /// </summary>
        /// <param name="values">数值列表</param>
        /// <param name="percentile">百分位（0-1）</param>
        /// <returns>百分位数值</returns>
        private long GetPercentile(List<long> values, double percentile)
        {
            if (values.Count == 0) return 0;
            
            int index = (int)Math.Ceiling(values.Count * percentile) - 1;
            return values[Math.Max(0, Math.Min(index, values.Count - 1))];
        }

        /// <summary>
        /// 检查资源使用情况
        /// </summary>
        /// <param name="metrics">操作指标</param>
        private void CheckResourceUsage(UIUpdateMetrics metrics)
        {
            try
            {
                var warnings = new List<string>();

                // 检查内存使用
                if (_configuration.EnableMemoryMonitoring)
                {
                    var memoryMB = metrics.MemoryUsage / (1024.0 * 1024.0);
                    if (memoryMB > _configuration.MemoryWarningThresholdMB)
                    {
                        warnings.Add($"内存使用过高: {memoryMB:F2} MB");
                    }
                }

                // 检查CPU使用
                if (_configuration.EnableCpuMonitoring)
                {
                    if (metrics.CpuUsage > _configuration.CpuWarningThreshold)
                    {
                        warnings.Add($"CPU使用率过高: {metrics.CpuUsage:F2}%");
                    }
                }

                if (warnings.Count > 0)
                {
                    OnResourceUsageWarning(new ResourceUsageWarningEventArgs(metrics, warnings));
                }
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateMonitor] 检查资源使用情况失败", ex);
            }
        }

        /// <summary>
        /// 获取系统资源使用情况
        /// </summary>
        /// <returns>系统资源使用信息</returns>
        private Dictionary<string, object> GetSystemResourceUsage()
        {
            var usage = new Dictionary<string, object>();

            try
            {
                // 内存使用情况
                var totalMemory = GC.GetTotalMemory(false);
                var workingSet = Environment.WorkingSet;
                
                usage["TotalManagedMemory"] = totalMemory;
                usage["WorkingSet"] = workingSet;
                usage["AvailableMemory"] = GC.GetTotalMemory(true);

                // CPU使用情况
                usage["CurrentCpuUsage"] = GetCurrentCpuUsage();

                // 线程信息
                usage["ThreadCount"] = Process.GetCurrentProcess().Threads.Count;

                // GC信息
                usage["Gen0Collections"] = GC.CollectionCount(0);
                usage["Gen1Collections"] = GC.CollectionCount(1);
                usage["Gen2Collections"] = GC.CollectionCount(2);
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateMonitor] 获取系统资源使用情况失败", ex);
                usage["Error"] = ex.Message;
            }

            return usage;
        }

        /// <summary>
        /// 生成建议
        /// </summary>
        /// <param name="report">诊断报告</param>
        private void GenerateRecommendations(DiagnosticsReport report)
        {
            try
            {
                var recommendations = report.Recommendations;

                // 性能建议
                if (report.Statistics.AverageExecutionTime > 500)
                {
                    recommendations.Add("平均执行时间较长，建议优化UI更新操作或使用批量更新");
                }

                if (report.Statistics.SuccessRate < 95)
                {
                    recommendations.Add($"成功率偏低({report.Statistics.SuccessRate:F1}%)，建议检查错误操作并改进错误处理");
                }

                // 慢操作建议
                if (report.SlowOperations.Count > 0)
                {
                    recommendations.Add($"检测到{report.SlowOperations.Count}个慢操作，建议优化或使用异步处理");
                }

                // 错误操作建议
                if (report.ErrorOperations.Count > 0)
                {
                    var commonErrors = report.ErrorOperations
                        .GroupBy(e => e.ErrorMessage)
                        .OrderByDescending(g => g.Count())
                        .Take(3);
                    
                    foreach (var error in commonErrors)
                    {
                        recommendations.Add($"常见错误({error.Count()}次): {error.Key}");
                    }
                }

                // 资源使用建议
                if (report.Statistics.AverageMemoryUsage > 10 * 1024 * 1024) // 10MB
                {
                    recommendations.Add("平均内存使用较高，建议检查内存泄漏或优化数据结构");
                }

                if (report.Statistics.AverageCpuUsage > 50)
                {
                    recommendations.Add("平均CPU使用率较高，建议优化算法或使用更高效的操作");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateMonitor] 生成建议失败", ex);
            }
        }

        /// <summary>
        /// 生成趋势分析
        /// </summary>
        /// <param name="report">诊断报告</param>
        private void GenerateTrendAnalysis(DiagnosticsReport report)
        {
            try
            {
                var trendAnalysis = report.TrendAnalysis;

                // 获取最近几个时间段的统计
                var now = DateTime.UtcNow;
                var periods = new[]
                {
                    new { Name = "Last1Hour", Start = now.AddHours(-1), End = now },
                    new { Name = "Last6Hours", Start = now.AddHours(-6), End = now.AddHours(-1) },
                    new { Name = "Last24Hours", Start = now.AddDays(-1), End = now.AddHours(-6) }
                };

                foreach (var period in periods)
                {
                    var stats = GetPerformanceStatistics(period.Start, period.End);
                    trendAnalysis[$"{period.Name}_Operations"] = stats.TotalOperations;
                    trendAnalysis[$"{period.Name}_AvgTime"] = stats.AverageExecutionTime;
                    trendAnalysis[$"{period.Name}_SuccessRate"] = stats.SuccessRate;
                }

                // 趋势计算
                var periods1h = (double)trendAnalysis["Last1Hour_Operations"];
                var periods6h = (double)trendAnalysis["Last6Hours_Operations"];
                
                if (periods6h > 0)
                {
                    var operationTrend = (periods1h - periods6h / 6) / (periods6h / 6) * 100;
                    trendAnalysis["OperationTrend"] = operationTrend; // 正值表示增长，负值表示下降
                }
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateMonitor] 生成趋势分析失败", ex);
            }
        }

        /// <summary>
        /// 导出到CSV文件
        /// </summary>
        /// <param name="metrics">指标数据</param>
        /// <param name="filePath">文件路径</param>
        private async Task ExportToCsvAsync(List<UIUpdateMetrics> metrics, string filePath)
        {
            var csv = new System.Text.StringBuilder();
            
            // CSV头部
            csv.AppendLine("UpdateId,UpdateName,OperationType,Priority,StartTime,EndTime,ElapsedMilliseconds,IsSuccess,ErrorMessage,MemoryUsage,CpuUsage,RetryCount,RequiredUIThread");
            
            // 数据行
            foreach (var metric in metrics)
            {
                csv.AppendLine($"{metric.UpdateId},{metric.UpdateName},{metric.OperationType},{metric.Priority},{metric.StartTime:yyyy-MM-dd HH:mm:ss},{metric.EndTime:yyyy-MM-dd HH:mm:ss},{metric.ElapsedMilliseconds},{metric.IsSuccess},\"{metric.ErrorMessage}\",{metric.MemoryUsage},{metric.CpuUsage},{metric.RetryCount},{metric.RequiredUIThread}");
            }

            await System.IO.File.WriteAllTextAsync(filePath, csv.ToString(), System.Text.Encoding.UTF8);
        }

        /// <summary>
        /// 导出到JSON文件
        /// </summary>
        /// <param name="metrics">指标数据</param>
        /// <param name="filePath">文件路径</param>
        private async Task ExportToJsonAsync(List<UIUpdateMetrics> metrics, string filePath)
        {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(metrics, Newtonsoft.Json.Formatting.Indented);
            await System.IO.File.WriteAllTextAsync(filePath, json, System.Text.Encoding.UTF8);
        }

        /// <summary>
        /// 统计定时器事件
        /// </summary>
        private void OnStatisticsTimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (_isDisposed)
            {
                return;
            }

            _ = Task.Run(() =>
            {
                try
                {
                    var statistics = GetPerformanceStatistics();
                    OnPerformanceStatisticsUpdated(new PerformanceStatisticsUpdatedEventArgs(statistics));

                    if (_configuration.EnableVerboseLogging)
                    {
                        LogManager.Info($"[UIUpdateMonitor] 性能统计更新 - 总操作: {statistics.TotalOperations}, 平均耗时: {statistics.AverageExecutionTime:F2}ms, 成功率: {statistics.SuccessRate:F1}%");
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Error("[UIUpdateMonitor] 更新性能统计时发生异常", ex);
                }
            });
        }

        #endregion

        #region 事件触发方法

        /// <summary>
        /// 触发慢操作检测事件
        /// </summary>
        protected virtual void OnSlowOperationDetected(SlowOperationDetectedEventArgs args)
        {
            try
            {
                SlowOperationDetected?.Invoke(this, args);
                LogManager.Warning($"[UIUpdateMonitor] 检测到慢操作: {args.Metrics.UpdateName} - {args.Metrics.ElapsedMilliseconds}ms");
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateMonitor] 触发慢操作检测事件时发生异常", ex);
            }
        }

        /// <summary>
        /// 触发错误操作检测事件
        /// </summary>
        protected virtual void OnErrorOperationDetected(ErrorOperationDetectedEventArgs args)
        {
            try
            {
                ErrorOperationDetected?.Invoke(this, args);
                LogManager.Warning($"[UIUpdateMonitor] 检测到错误操作: {args.Metrics.UpdateName} - {args.Metrics.ErrorMessage}");
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateMonitor] 触发错误操作检测事件时发生异常", ex);
            }
        }

        /// <summary>
        /// 触发性能统计更新事件
        /// </summary>
        protected virtual void OnPerformanceStatisticsUpdated(PerformanceStatisticsUpdatedEventArgs args)
        {
            try
            {
                PerformanceStatisticsUpdated?.Invoke(this, args);
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateMonitor] 触发性能统计更新事件时发生异常", ex);
            }
        }

        /// <summary>
        /// 触发资源使用警告事件
        /// </summary>
        protected virtual void OnResourceUsageWarning(ResourceUsageWarningEventArgs args)
        {
            try
            {
                ResourceUsageWarning?.Invoke(this, args);
                LogManager.Warning($"[UIUpdateMonitor] 资源使用警告: {args.Metrics.UpdateName} - {string.Join(", ", args.Warnings)}");
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIUpdateMonitor] 触发资源使用警告事件时发生异常", ex);
            }
        }

        #endregion

        #region IDisposable实现

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

            try
            {
                LogManager.Info("[UIUpdateMonitor] 开始释放UI更新监控器");

                // 停止监控
                Stop();

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

                // 释放性能计数器
                _cpuCounter?.Dispose();

                // 清理数据
                _activeOperations.Clear();
                ClearMetrics();

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

        #endregion
    }

    #region 事件参数类

    /// <summary>
    /// 慢操作检测事件参数
    /// </summary>
    public class SlowOperationDetectedEventArgs : EventArgs
    {
        public UIUpdateMonitor.UIUpdateMetrics Metrics { get; }
        public DateTime DetectedTime { get; }

        public SlowOperationDetectedEventArgs(UIUpdateMonitor.UIUpdateMetrics metrics)
        {
            Metrics = metrics;
            DetectedTime = DateTime.UtcNow;
        }
    }

    /// <summary>
    /// 错误操作检测事件参数
    /// </summary>
    public class ErrorOperationDetectedEventArgs : EventArgs
    {
        public UIUpdateMonitor.UIUpdateMetrics Metrics { get; }
        public DateTime DetectedTime { get; }

        public ErrorOperationDetectedEventArgs(UIUpdateMonitor.UIUpdateMetrics metrics)
        {
            Metrics = metrics;
            DetectedTime = DateTime.UtcNow;
        }
    }

    /// <summary>
    /// 性能统计更新事件参数
    /// </summary>
    public class PerformanceStatisticsUpdatedEventArgs : EventArgs
    {
        public UIUpdateMonitor.PerformanceStatistics Statistics { get; }
        public DateTime UpdatedTime { get; }

        public PerformanceStatisticsUpdatedEventArgs(UIUpdateMonitor.PerformanceStatistics statistics)
        {
            Statistics = statistics;
            UpdatedTime = DateTime.UtcNow;
        }
    }

    /// <summary>
    /// 资源使用警告事件参数
    /// </summary>
    public class ResourceUsageWarningEventArgs : EventArgs
    {
        public UIUpdateMonitor.UIUpdateMetrics Metrics { get; }
        public List<string> Warnings { get; }
        public DateTime WarningTime { get; }

        public ResourceUsageWarningEventArgs(UIUpdateMonitor.UIUpdateMetrics metrics, List<string> warnings)
        {
            Metrics = metrics;
            Warnings = warnings ?? new List<string>();
            WarningTime = DateTime.UtcNow;
        }
    }

    #endregion
}