using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using NavisworksTransport.Utils;
using NavisworksTransport.Commands;
using System.IO;
using System.Text;
using Microsoft.Win32;
using System.Threading.Tasks;

namespace NavisworksTransport.UI.WPF.ViewModels
{
    /// <summary>
    /// 碰撞报告显示状态枚举
    /// </summary>
    public enum CollisionReportStatus
    {
        /// <summary>正在生成报告</summary>
        Generating,
        /// <summary>报告已生成</summary>
        Generated,
        /// <summary>生成失败</summary>
        Failed,
        /// <summary>空报告</summary>
        Empty
    }

    /// <summary>
    /// 碰撞报告项目UI模型
    /// </summary>
    public class CollisionReportItem
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string StatusText { get; set; }
        public string StatusColor { get; set; }
        public string Details { get; set; }
        public CollisionResult CollisionData { get; set; }
    }

    /// <summary>
    /// 碰撞报告统计信息UI模型
    /// </summary>
    public class CollisionReportStatistics
    {
        public int TotalCollisions { get; set; }
        public int AnimationCollisions { get; set; }
        public int NewCollisions { get; set; }
        public int ActiveCollisions { get; set; }
        public int ReviewedCollisions { get; set; }
        public int ApprovedCollisions { get; set; }
        public int ResolvedCollisions { get; set; }
        public string GenerationTime { get; set; }
        public string ReportType { get; set; }
    }

    /// <summary>
    /// 碰撞报告对话框ViewModel
    /// </summary>
    public class CollisionReportViewModel : ViewModelBase
    {
        #region 私有字段

        private CollisionReportStatus _reportStatus;
        private string _reportTitle;
        private CollisionReportStatistics _statistics;
        private ObservableCollection<CollisionReportItem> _animationCollisions;
        private string _progressMessage;
        private int _progressPercentage;
        private bool _isGenerating;
        private bool _hasCollisions;
        private string _summaryMessage;
        private string _recommendationMessage;
        private string _movingObjectInfo;
        private ObservableCollection<string> _collidedObjectsList;
        private int _uniqueCollidedObjectsCount;
        private string _pathName;
        private int _frameRate;
        private double _duration;
        private double _detectionGap;

        #endregion

        #region 公共属性

        /// <summary>
        /// 报告状态
        /// </summary>
        public CollisionReportStatus ReportStatus
        {
            get => _reportStatus;
            set => SetProperty(ref _reportStatus, value);
        }

        /// <summary>
        /// 报告标题
        /// </summary>
        public string ReportTitle
        {
            get => _reportTitle;
            set => SetProperty(ref _reportTitle, value);
        }

        /// <summary>
        /// 统计信息
        /// </summary>
        public CollisionReportStatistics Statistics
        {
            get => _statistics;
            set => SetProperty(ref _statistics, value);
        }

        /// <summary>
        /// 动画过程碰撞列表
        /// </summary>
        public ObservableCollection<CollisionReportItem> AnimationCollisions
        {
            get => _animationCollisions;
            set => SetProperty(ref _animationCollisions, value);
        }


        /// <summary>
        /// 进度消息
        /// </summary>
        public string ProgressMessage
        {
            get => _progressMessage;
            set => SetProperty(ref _progressMessage, value);
        }

        /// <summary>
        /// 进度百分比
        /// </summary>
        public int ProgressPercentage
        {
            get => _progressPercentage;
            set => SetProperty(ref _progressPercentage, value);
        }

        /// <summary>
        /// 是否正在生成报告
        /// </summary>
        public bool IsGenerating
        {
            get => _isGenerating;
            set => SetProperty(ref _isGenerating, value);
        }

        /// <summary>
        /// 是否有碰撞
        /// </summary>
        public bool HasCollisions
        {
            get => _hasCollisions;
            set => SetProperty(ref _hasCollisions, value);
        }

        /// <summary>
        /// 总结消息
        /// </summary>
        public string SummaryMessage
        {
            get => _summaryMessage;
            set => SetProperty(ref _summaryMessage, value);
        }

        /// <summary>
        /// 建议消息
        /// </summary>
        public string RecommendationMessage
        {
            get => _recommendationMessage;
            set => SetProperty(ref _recommendationMessage, value);
        }

        /// <summary>
        /// 运动构件信息
        /// </summary>
        public string MovingObjectInfo
        {
            get => _movingObjectInfo;
            set => SetProperty(ref _movingObjectInfo, value);
        }

        /// <summary>
        /// 被撞物体清单
        /// </summary>
        public ObservableCollection<string> CollidedObjectsList
        {
            get => _collidedObjectsList;
            set => SetProperty(ref _collidedObjectsList, value);
        }

        /// <summary>
        /// 去重后的被撞物体总数
        /// </summary>
        public int UniqueCollidedObjectsCount
        {
            get => _uniqueCollidedObjectsCount;
            set => SetProperty(ref _uniqueCollidedObjectsCount, value);
        }

        /// <summary>
        /// 路径名称
        /// </summary>
        public string PathName
        {
            get => _pathName;
            set => SetProperty(ref _pathName, value);
        }

        /// <summary>
        /// 动画帧率
        /// </summary>
        public int FrameRate
        {
            get => _frameRate;
            set => SetProperty(ref _frameRate, value);
        }

        /// <summary>
        /// 动画时长
        /// </summary>
        public double Duration
        {
            get => _duration;
            set => SetProperty(ref _duration, value);
        }

        /// <summary>
        /// 检测间隙
        /// </summary>
        public double DetectionGap
        {
            get => _detectionGap;
            set => SetProperty(ref _detectionGap, value);
        }

        #endregion

        #region 命令属性

        /// <summary>
        /// 导出报告命令
        /// </summary>
        public ICommand ExportReportCommand { get; }

        /// <summary>
        /// 关闭窗口命令
        /// </summary>
        public ICommand CloseCommand { get; }


        /// <summary>
        /// 高亮碰撞对象命令
        /// </summary>
        public ICommand HighlightCollisionCommand { get; }

        #endregion

        #region 构造函数

        public CollisionReportViewModel()
        {
            // 初始化集合
            AnimationCollisions = new ObservableCollection<CollisionReportItem>();
            CollidedObjectsList = new ObservableCollection<string>();

            Statistics = new CollisionReportStatistics();

            // 初始化命令
            ExportReportCommand = new RelayCommand(async () => await ExportReportAsync(), () => !IsGenerating && HasCollisions);
            CloseCommand = new RelayCommand(CloseWindow);
            HighlightCollisionCommand = new RelayCommand<CollisionReportItem>(HighlightCollision, item => item?.CollisionData != null);

            // 初始化状态
            ReportStatus = CollisionReportStatus.Generating;
            ReportTitle = "NavisworksTransport - 碰撞检测报告";
            IsGenerating = false;
            HasCollisions = false;
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 初始化报告数据
        /// </summary>
        /// <param name="reportResult">报告结果</param>
        public void InitializeReport(CollisionReportResult reportResult)
        {
            if (reportResult == null)
            {
                SetEmptyReport();
                return;
            }

            try
            {
                IsGenerating = true;
                ReportStatus = CollisionReportStatus.Generating;
                ProgressMessage = "正在解析报告数据...";
                ProgressPercentage = 0;

                // 清空现有数据
                AnimationCollisions.Clear();
                CollidedObjectsList.Clear();

                // 设置运动构件信息
                MovingObjectInfo = reportResult.MovingObjectInfo;

                // 设置被撞物体清单和计数
                UniqueCollidedObjectsCount = reportResult.UniqueCollidedObjectsCount;
                if (reportResult.CollidedObjectsList != null)
                {
                    foreach (var objName in reportResult.CollidedObjectsList)
                    {
                        CollidedObjectsList.Add(objName);
                    }
                }

                // 设置动画参数
                PathName = reportResult.PathName;
                FrameRate = reportResult.FrameRate;
                Duration = reportResult.Duration;
                DetectionGap = reportResult.DetectionGap;

                // 更新统计信息
                UpdateStatistics(reportResult);

                // 分类并添加碰撞项
                ProcessCollisionData(reportResult.AllCollisions);

                // 生成总结和建议
                GenerateSummaryAndRecommendations(reportResult);

                // 更新状态
                HasCollisions = reportResult.TotalCollisions > 0;
                ReportStatus = HasCollisions ? CollisionReportStatus.Generated : CollisionReportStatus.Empty;
                
                ProgressMessage = "报告生成完成";
                ProgressPercentage = 100;

                LogManager.Info($"碰撞报告ViewModel初始化完成，发现 {reportResult.TotalCollisions} 个碰撞");
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化碰撞报告失败: {ex.Message}");
                SetFailedReport(ex.Message);
            }
            finally
            {
                IsGenerating = false;
            }
        }

        /// <summary>
        /// 更新进度
        /// </summary>
        /// <param name="percentage">进度百分比</param>
        /// <param name="message">进度消息</param>
        public void UpdateProgress(int percentage, string message)
        {
            SafeExecute(() =>
            {
                ProgressPercentage = Math.Max(0, Math.Min(100, percentage));
                ProgressMessage = message ?? "";
            }, "更新报告生成进度", true);
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 更新统计信息
        /// </summary>
        private void UpdateStatistics(CollisionReportResult reportResult)
        {
            Statistics = new CollisionReportStatistics
            {
                TotalCollisions = reportResult.TotalCollisions,
                AnimationCollisions = reportResult.AnimationCollisions,
                GenerationTime = $"{reportResult.GenerationTimeMs}ms",
                ReportType = "综合碰撞报告"
            };

            // 计算状态统计
            if (reportResult.AllCollisions?.Count > 0)
            {
                Statistics.NewCollisions = reportResult.AllCollisions.Count(c => c.Status == Autodesk.Navisworks.Api.Clash.ClashResultStatus.New);
                Statistics.ActiveCollisions = reportResult.AllCollisions.Count(c => c.Status == Autodesk.Navisworks.Api.Clash.ClashResultStatus.Active);
                Statistics.ReviewedCollisions = reportResult.AllCollisions.Count(c => c.Status == Autodesk.Navisworks.Api.Clash.ClashResultStatus.Reviewed);
                Statistics.ApprovedCollisions = reportResult.AllCollisions.Count(c => c.Status == Autodesk.Navisworks.Api.Clash.ClashResultStatus.Approved);
                Statistics.ResolvedCollisions = reportResult.AllCollisions.Count(c => c.Status == Autodesk.Navisworks.Api.Clash.ClashResultStatus.Resolved);
            }
        }

        /// <summary>
        /// 处理碰撞数据
        /// </summary>
        private void ProcessCollisionData(List<CollisionResult> collisions)
        {
            if (collisions == null || collisions.Count == 0)
                return;

            var collisionItems = new List<CollisionReportItem>();

            foreach (var collision in collisions)
            {
                var item = CreateCollisionReportItem(collision);
                collisionItems.Add(item);
            }

            // 更新UI集合
            SafeExecute(() =>
            {
                foreach (var item in collisionItems.OrderBy(i => i.Title))
                    AnimationCollisions.Add(item);

            }, "更新碰撞报告项目列表", true);
        }

        /// <summary>
        /// 创建碰撞报告项目
        /// </summary>
        private CollisionReportItem CreateCollisionReportItem(CollisionResult collision)
        {

            // 获取元素名称 - Item1和Item2已经是容器对象（在创建CollisionResult时已用FindNamedParentContainer处理）
            var item1Name = ModelItemAnalysisHelper.GetSafeDisplayName(collision.Item1);
            var item2Name = ModelItemAnalysisHelper.GetSafeDisplayName(collision.Item2);

            var title = $"{item1Name} ↔ {item2Name}";

            var item = new CollisionReportItem
            {
                Title = string.IsNullOrEmpty(title.Trim().Replace("↔", "").Trim()) ? "【空标题测试】" : title,
                Description = collision.DisplayName ?? "【空描述测试】",
                StatusText = GetStatusDisplayText(collision.Status),
                StatusColor = GetStatusColor(collision.Status),
                Details = $"距离: {collision.Distance:F3}m\n位置: ({collision.Center.X:F2}, {collision.Center.Y:F2}, {collision.Center.Z:F2})\nGUID: {collision.ClashGuid}",
                CollisionData = collision
            };

            return item;
        }


        /// <summary>
        /// 获取状态显示文本
        /// </summary>
        private string GetStatusDisplayText(Autodesk.Navisworks.Api.Clash.ClashResultStatus status)
        {
            switch (status)
            {
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.New:
                    return "新发现";
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.Active:
                    return "活跃";
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.Reviewed:
                    return "已审阅";
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.Approved:
                    return "已批准";
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.Resolved:
                    return "已解决";
                default:
                    return "未知";
            }
        }

        /// <summary>
        /// 获取状态颜色
        /// </summary>
        private string GetStatusColor(Autodesk.Navisworks.Api.Clash.ClashResultStatus status)
        {
            switch (status)
            {
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.New:
                    return "#FF6B6B";        // 红色 - 新问题
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.Active:
                    return "#FFA500";        // 橙色 - 活跃
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.Reviewed:
                    return "#87CEEB";        // 天蓝色 - 已审阅
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.Approved:
                    return "#98FB98";        // 浅绿色 - 已批准
                case Autodesk.Navisworks.Api.Clash.ClashResultStatus.Resolved:
                    return "#90EE90";        // 绿色 - 已解决
                default:
                    return "#D3D3D3";        // 灰色 - 未知
            }
        }

        /// <summary>
        /// 生成总结和建议
        /// </summary>
        private void GenerateSummaryAndRecommendations(CollisionReportResult reportResult)
        {
            if (reportResult.TotalCollisions == 0)
            {
                SummaryMessage = "✅ 未发现碰撞问题，路径规划良好。";
                RecommendationMessage = "当前路径设计合理，无需调整。建议定期进行碰撞检测以确保持续的安全性。";
            }
            else
            {
                SummaryMessage = $"⚠️ 发现 {reportResult.TotalCollisions} 个碰撞问题，需要采取措施处理。";
                
                var recommendations = new List<string>
                {
                    "1. 调整路径规划，避开碰撞区域",
                    "2. 检查车辆尺寸和安全边距设置",
                    "3. 考虑增加临时障碍物标记",
                    "4. 重新评估物流流程设计",
                    "5. 建议进行更详细的碰撞检测分析"
                };

                RecommendationMessage = string.Join("\n", recommendations);
            }
        }


        /// <summary>
        /// 设置空报告状态
        /// </summary>
        private void SetEmptyReport()
        {
            ReportStatus = CollisionReportStatus.Empty;
            IsGenerating = false;
            HasCollisions = false;
            SummaryMessage = "📄 暂无碰撞数据";
            RecommendationMessage = "请先运行碰撞检测或动画播放以生成碰撞数据。";
            Statistics = new CollisionReportStatistics { ReportType = "空报告" };
        }

        /// <summary>
        /// 设置失败报告状态
        /// </summary>
        private void SetFailedReport(string errorMessage)
        {
            ReportStatus = CollisionReportStatus.Failed;
            IsGenerating = false;
            HasCollisions = false;
            SummaryMessage = "❌ 报告生成失败";
            RecommendationMessage = $"错误信息: {errorMessage}";
            Statistics = new CollisionReportStatistics { ReportType = "生成失败" };
        }

        #endregion

        #region 命令方法

        /// <summary>
        /// 导出报告
        /// </summary>
        private async Task ExportReportAsync()
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Title = "导出碰撞报告",
                    Filter = "碰撞报告 (*.txt)|*.txt|HTML报告 (*.html)|*.html|所有文件 (*.*)|*.*",
                    DefaultExt = "txt",
                    FileName = $"NavisworksTransport_CollisionReport_{DateTime.Now:yyyyMMdd_HHmmss}"
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    await Task.Run(() =>
                    {
                        var content = GenerateExportContent(Path.GetExtension(saveFileDialog.FileName).ToLower());
                        File.WriteAllText(saveFileDialog.FileName, content, Encoding.UTF8);
                    });

                    LogManager.Info($"碰撞报告已导出到: {saveFileDialog.FileName}");
                    
                    // 这里可以显示导出成功的提示
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"导出碰撞报告失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 生成导出内容
        /// </summary>
        private string GenerateExportContent(string fileExtension)
        {
            if (fileExtension == ".html")
            {
                return GenerateHtmlReport();
            }
            else
            {
                return GenerateTextReport();
            }
        }

        /// <summary>
        /// 生成文本报告
        /// </summary>
        private string GenerateTextReport()
        {
            var report = new StringBuilder();
            var now = DateTime.Now;

            // 报告头部
            report.AppendLine("========================================");
            report.AppendLine("       NavisworksTransport 碰撞检测报告");
            report.AppendLine("========================================");
            report.AppendLine($"生成时间: {now:yyyy年MM月dd日 HH:mm:ss}");
            report.AppendLine($"报告类型: {Statistics.ReportType}");
            report.AppendLine($"路径名称: {PathName}");

            // 总体统计
            report.AppendLine("=== 总体统计 ===");
            report.AppendLine($"总碰撞数: {Statistics.TotalCollisions}");
            report.AppendLine($"碰撞构件: {UniqueCollidedObjectsCount}个");
            report.AppendLine($"检测点: {Statistics.AnimationCollisions}个");
            report.AppendLine();

            // 动画参数
            report.AppendLine("=== 动画参数 ===");
            report.AppendLine($"帧率: {FrameRate} FPS");
            report.AppendLine($"时长: {Duration:F1} 秒");
            report.AppendLine($"检测间隙: {DetectionGap:F2} 米");
            report.AppendLine();

            // 运动构件信息
            if (!string.IsNullOrEmpty(MovingObjectInfo))
            {
                report.AppendLine($"{MovingObjectInfo}");
            }
            report.AppendLine();

            // 被撞物体清单
            if (CollidedObjectsList?.Count > 0)
            {
                report.AppendLine("=== 碰撞构件清单 ===");
                int index = 1;
                foreach (var objName in CollidedObjectsList.Take(20)) // 限制显示前20个
                {
                    report.AppendLine($"  {index}. {objName}");
                    index++;
                }
                if (CollidedObjectsList.Count > 20)
                {
                    report.AppendLine($"  ... 还有 {CollidedObjectsList.Count - 20} 个构件");
                }
                report.AppendLine();
            }

            // 详细碰撞信息
            if (HasCollisions)
            {
                AddCollisionDetailsToTextReport(report, "碰撞详情", AnimationCollisions);
            }

            // 总结和建议
            report.AppendLine("=== 总结与建议 ===");
            report.AppendLine(SummaryMessage);
            report.AppendLine();
            report.AppendLine("建议措施：");
            report.AppendLine(RecommendationMessage);
            report.AppendLine();

            report.AppendLine("========================================");
            report.AppendLine($"报告生成完成 - {now:HH:mm:ss}");
            report.AppendLine("========================================");

            return report.ToString();
        }

        /// <summary>
        /// 添加碰撞详细信息到文本报告
        /// </summary>
        private void AddCollisionDetailsToTextReport(StringBuilder report, string sectionTitle, ObservableCollection<CollisionReportItem> items)
        {
            if (items?.Count > 0)
            {
                report.AppendLine($"--- {sectionTitle} ---");
                foreach (var item in items.Take(10)) // 限制显示数量
                {
                    report.AppendLine($"• {item.Title}");
                    report.AppendLine($"  状态: {item.StatusText}");
                    report.AppendLine($"  {item.Details.Replace("\n", "\n  ")}");
                    report.AppendLine();
                }
                if (items.Count > 10)
                {
                    report.AppendLine($"... 还有 {items.Count - 10} 个{sectionTitle}未显示");
                }
                report.AppendLine();
            }
        }

        /// <summary>
        /// 生成HTML报告
        /// </summary>
        private string GenerateHtmlReport()
        {
            var html = new StringBuilder();
            var now = DateTime.Now;

            // HTML头部和样式
            html.AppendLine("<!DOCTYPE html>");
            html.AppendLine("<html><head>");
            html.AppendLine("<meta charset='UTF-8'>");
            html.AppendLine("<title>NavisworksTransport 碰撞检测报告</title>");
            html.AppendLine("<style>");
            html.AppendLine("body { font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 20px; line-height: 1.6; }");
            html.AppendLine("h1 { color: #2c5aa0; text-align: center; border-bottom: 2px solid #2c5aa0; padding-bottom: 10px; }");
            html.AppendLine("h2 { color: #2c5aa0; margin-top: 25px; }");
            html.AppendLine(".summary { background: #f8fbff; padding: 15px; border-radius: 8px; margin: 15px 0; border-left: 4px solid #2c5aa0; }");
            html.AppendLine(".stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin: 15px 0; }");
            html.AppendLine(".stat-item { background: white; padding: 15px; border-radius: 6px; border: 1px solid #ddd; text-align: center; }");
            html.AppendLine(".stat-label { font-size: 12px; color: #666; margin-bottom: 5px; }");
            html.AppendLine(".stat-value { font-size: 18px; font-weight: bold; color: #2c5aa0; }");
            html.AppendLine(".moving-object { background: #f0f8ff; padding: 15px; border-radius: 8px; text-align: center; margin: 15px 0; border: 1px solid #b0d4f1; }");
            html.AppendLine(".collided-list { background: #f8fbff; padding: 15px; border-radius: 8px; margin: 15px 0; max-height: 200px; overflow-y: auto; }");
            html.AppendLine(".list-item { margin: 5px 0; padding: 5px; border-left: 3px solid #2c5aa0; padding-left: 10px; }");
            html.AppendLine(".recommendation { background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107; margin: 15px 0; }");
            html.AppendLine(".collision-item { background: white; margin: 10px 0; padding: 15px; border-radius: 6px; border: 1px solid #eee; }");
            html.AppendLine(".collision-title { font-weight: bold; color: #333; margin-bottom: 8px; }");
            html.AppendLine(".collision-status { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 11px; color: white; margin-bottom: 8px; }");
            html.AppendLine(".status-new { background-color: #ff6b6b; } .status-active { background-color: #ffa500; }");
            html.AppendLine(".status-reviewed { background-color: #87ceeb; } .status-approved { background-color: #98fb98; } .status-resolved { background-color: #90ee90; }");
            html.AppendLine("</style>");
            html.AppendLine("</head><body>");

            // 报告标题
            html.AppendLine($"<h1>NavisworksTransport 碰撞检测报告</h1>");
            html.AppendLine($"<p style='text-align: center; color: #666;'>生成时间: {now:yyyy年MM月dd日 HH:mm:ss}</p>");
            html.AppendLine($"<p style='text-align: center; color: #666;'>报告类型: {Statistics.ReportType}</p>");
            html.AppendLine($"<p style='text-align: center; color: #666;'>路径名称: {PathName}</p>");

            // 总体统计
            html.AppendLine("<div class='summary'>");
            html.AppendLine("<h2>总体统计</h2>");
            html.AppendLine("<div class='stats-grid'>");
            html.AppendLine("<div class='stat-item'>");
            html.AppendLine("<div class='stat-label'>总碰撞数</div>");
            html.AppendLine($"<div class='stat-value'>{Statistics.TotalCollisions}</div>");
            html.AppendLine("</div>");
            html.AppendLine("<div class='stat-item'>");
            html.AppendLine("<div class='stat-label'>碰撞构件</div>");
            html.AppendLine($"<div class='stat-value'>{UniqueCollidedObjectsCount}个</div>");
            html.AppendLine("</div>");
            html.AppendLine("<div class='stat-item'>");
            html.AppendLine("<div class='stat-label'>检测点</div>");
            html.AppendLine($"<div class='stat-value'>{Statistics.AnimationCollisions}个</div>");
            html.AppendLine("</div>");
            html.AppendLine("</div>");
            html.AppendLine("</div>");

            // 动画参数
            html.AppendLine("<h2>动画参数</h2>");
            html.AppendLine("<div class='stats-grid'>");
            html.AppendLine("<div class='stat-item'>");
            html.AppendLine("<div class='stat-label'>帧率</div>");
            html.AppendLine($"<div class='stat-value'>{FrameRate} FPS</div>");
            html.AppendLine("</div>");
            html.AppendLine("<div class='stat-item'>");
            html.AppendLine("<div class='stat-label'>时长</div>");
            html.AppendLine($"<div class='stat-value'>{Duration:F1} 秒</div>");
            html.AppendLine("</div>");
            html.AppendLine("<div class='stat-item'>");
            html.AppendLine("<div class='stat-label'>检测间隙</div>");
            html.AppendLine($"<div class='stat-value'>{DetectionGap:F2} 米</div>");
            html.AppendLine("</div>");
            html.AppendLine("</div>");

            // 运动构件信息
            if (!string.IsNullOrEmpty(MovingObjectInfo))
            {
                html.AppendLine("<h2>运动构件信息</h2>");
                html.AppendLine("<div class='moving-object'>");
                html.AppendLine($"<strong>🚛 {MovingObjectInfo}</strong>");
                html.AppendLine("</div>");
            }

            // 碰撞构件清单
            if (CollidedObjectsList?.Count > 0)
            {
                html.AppendLine("<h2>碰撞构件清单</h2>");
                html.AppendLine("<div class='collided-list'>");
                int index = 1;
                foreach (var objName in CollidedObjectsList.Take(50)) // 限制显示前50个
                {
                    html.AppendLine($"<div class='list-item'>{index}. {objName}</div>");
                    index++;
                }
                if (CollidedObjectsList.Count > 50)
                {
                    html.AppendLine($"<div class='list-item'><em>... 还有 {CollidedObjectsList.Count - 50} 个构件</em></div>");
                }
                html.AppendLine("</div>");
            }

            // 总结与建议
            html.AppendLine("<h2>总结与建议</h2>");
            html.AppendLine("<div class='recommendation'>");
            html.AppendLine($"<p><strong>{SummaryMessage}</strong></p>");
            if (!string.IsNullOrEmpty(RecommendationMessage))
            {
                html.AppendLine("<p><strong>建议措施：</strong></p>");
                var recommendations = RecommendationMessage.Split('\n');
                html.AppendLine("<ul>");
                foreach (var recommendation in recommendations)
                {
                    if (!string.IsNullOrWhiteSpace(recommendation))
                    {
                        html.AppendLine($"<li>{recommendation}</li>");
                    }
                }
                html.AppendLine("</ul>");
            }
            html.AppendLine("</div>");

            // 详细碰撞信息（前10个）
            if (HasCollisions && AnimationCollisions?.Count > 0)
            {
                html.AppendLine("<h2>碰撞详情</h2>");
                foreach (var collision in AnimationCollisions.Take(10))
                {
                    html.AppendLine("<div class='collision-item'>");
                    html.AppendLine($"<div class='collision-title'>{collision.Title}</div>");

                    // 状态标签
                    var statusClass = GetStatusCssClass(collision.StatusText);
                    html.AppendLine($"<span class='collision-status {statusClass}'>{collision.StatusText}</span>");

                    html.AppendLine($"<p>{collision.Description}</p>");
                    html.AppendLine($"<p style='font-size: 11px; color: #666;'>{collision.Details}</p>");
                    html.AppendLine("</div>");
                }
                if (AnimationCollisions.Count > 10)
                {
                    html.AppendLine($"<p><em>... 还有 {AnimationCollisions.Count - 10} 个碰撞未显示</em></p>");
                }
            }

            // HTML结尾
            html.AppendLine($"<hr style='margin: 30px 0;'>");
            html.AppendLine($"<p style='text-align: center; color: #999; font-size: 12px;'>报告生成完成 - {now:HH:mm:ss}</p>");
            html.AppendLine("</body></html>");

            return html.ToString();
        }

        /// <summary>
        /// 获取状态对应的CSS类名
        /// </summary>
        private string GetStatusCssClass(string statusText)
        {
            switch (statusText)
            {
                case "新发现": return "status-new";
                case "活跃": return "status-active";
                case "已审阅": return "status-reviewed";
                case "已批准": return "status-approved";
                case "已解决": return "status-resolved";
                default: return "";
            }
        }

        /// <summary>
        /// 高亮碰撞对象
        /// </summary>
        private void HighlightCollision(CollisionReportItem item)
        {
            try
            {
                if (item?.CollisionData == null)
                    return;

                var clashIntegration = ClashDetectiveIntegration.Instance;
                if (clashIntegration != null)
                {
                    var collisions = new List<CollisionResult> { item.CollisionData };
                    var highlightColor = Autodesk.Navisworks.Api.Color.Green; // 使用Navisworks API中可用的绿色
                    clashIntegration.ManageHighlightsByCategory(ModelHighlightHelper.CollisionResultsCategory, collisions, highlightColor, true);
                    LogManager.Info($"高亮碰撞对象: {item.Title}");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"高亮碰撞对象失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        private void CloseWindow()
        {
            // 这个方法会由View中的代码调用
            LogManager.Info("关闭碰撞报告窗口");
        }

        #endregion
    }
}