using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NavisworksTransport.Core.Models;
using NavisworksTransport.Utils;

namespace NavisworksTransport.Core
{
    /// <summary>
    /// 路径分析报告HTML生成器
    /// 生成包含图表的专业HTML报告
    /// </summary>
    public class PathAnalysisReportGenerator
    {
        private readonly string _chartJsPath;

        public PathAnalysisReportGenerator()
        {
            // Chart.js本地路径
            _chartJsPath = Path.Combine(
                PathHelper.GetPluginDirectory(),
                "resources", "js", "chart.min.js"
            );
        }

        /// <summary>
        /// 生成完整HTML报告
        /// </summary>
        public string GenerateHtmlReport(PathAnalysisReportData data)
        {
            var html = new StringBuilder();
            
            // HTML头部
            html.AppendLine(GenerateHtmlHead(data));
            
            // 报告主体
            html.AppendLine("<body>");
            html.AppendLine(GenerateHeader(data));
            html.AppendLine(GenerateExecutiveSummary(data));
            
            // 如果有组数据，显示组分析
            if (data.Groups?.Count > 0)
            {
                foreach (var group in data.Groups)
                {
                    html.AppendLine(GenerateGroupAnalysis(group));
                }
            }
            
            html.AppendLine(GenerateAllPathsTable(data));
            html.AppendLine(GenerateSuggestions(data));
            html.AppendLine(GenerateTechnicalParameters(data));
            html.AppendLine(GenerateFooter(data));
            html.AppendLine("</body>");
            html.AppendLine("</html>");
            
            return html.ToString();
        }

        /// <summary>
        /// 保存报告到指定文件路径
        /// </summary>
        /// <param name="data">报告数据</param>
        /// <param name="filePath">完整的文件路径</param>
        /// <returns>是否保存成功</returns>
        public bool SaveReportToFile(PathAnalysisReportData data, string filePath)
        {
            try
            {
                // 确保目录存在
                string directory = Path.GetDirectoryName(filePath);
                if (!string.IsNullOrEmpty(directory))
                {
                    PathHelper.EnsureDirectoryExists(directory);
                }
                
                string htmlContent = GenerateHtmlReport(data);
                File.WriteAllText(filePath, htmlContent, Encoding.UTF8);
                
                LogManager.Info($"路径分析报告已保存: {filePath}");
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Error($"保存路径分析报告失败: {ex.Message}", ex);
                return false;
            }
        }

        #region HTML生成方法

        private string GenerateHtmlHead(PathAnalysisReportData data)
        {
            var sb = new StringBuilder();
            sb.AppendLine("<!DOCTYPE html>");
            sb.AppendLine("<html lang=\"zh-CN\">");
            sb.AppendLine("<head>");
            sb.AppendLine("    <meta charset=\"UTF-8\">");
            sb.AppendLine("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
            sb.AppendLine($"    <title>路径分析报告 - {data.DocumentName}</title>");
            sb.AppendLine(GenerateStyles());
            sb.AppendLine(GenerateChartJsInclude());
            sb.AppendLine("</head>");
            return sb.ToString();
        }

        private string GenerateStyles()
        {
            return @"
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif; 
            background: #f5f5f5; 
            line-height: 1.6; 
            color: #333;
        }
        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        
        /* 头部样式 */
        .header { 
            background: linear-gradient(135deg, #2C5AA0 0%, #1e3d6f 100%); 
            color: white; 
            padding: 40px; 
            border-radius: 8px; 
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .header h1 { font-size: 32px; margin-bottom: 10px; }
        .header .meta { opacity: 0.9; font-size: 14px; }
        
        /* 卡片样式 */
        .card { 
            background: white; 
            border-radius: 8px; 
            padding: 25px; 
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .card-title { 
            font-size: 20px; 
            font-weight: bold; 
            color: #2C5AA0; 
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e9ecef;
        }
        
        /* 最佳路径卡片 */
        .best-path-card { 
            background: linear-gradient(135deg, #28A745 0%, #1e7e34 100%); 
            color: white; 
            padding: 30px; 
            border-radius: 10px; 
            margin-bottom: 30px;
        }
        .best-path-card h2 { font-size: 24px; margin-bottom: 15px; }
        .best-path-card .path-name { font-size: 28px; font-weight: bold; margin-bottom: 10px; }
        .best-path-card .path-stats { font-size: 16px; opacity: 0.95; }
        
        /* 表格样式 */
        .data-table { 
            width: 100%; 
            border-collapse: collapse; 
            margin-top: 15px;
        }
        .data-table th { 
            background: #2C5AA0; 
            color: white; 
            padding: 12px; 
            text-align: left; 
            font-weight: 600;
        }
        .data-table td { 
            padding: 12px; 
            border-bottom: 1px solid #e9ecef; 
        }
        .data-table tr:hover { background: #f8f9fa; }
        .data-table .best-row { background: #d4edda !important; font-weight: bold; }
        
        /* 分数条 */
        .score-bar-container { 
            background: #e9ecef; 
            height: 24px; 
            border-radius: 12px; 
            overflow: hidden; 
            position: relative;
        }
        .score-bar { 
            height: 100%; 
            border-radius: 12px; 
            transition: width 0.3s ease;
        }
        .score-bar.high { background: #28A745; }
        .score-bar.medium { background: #FFC107; }
        .score-bar.low { background: #DC3545; }
        .score-text { 
            position: absolute; 
            left: 50%; 
            top: 50%; 
            transform: translate(-50%, -50%); 
            font-weight: bold; 
            font-size: 12px;
            color: #333;
            text-shadow: 0 0 2px rgba(255,255,255,0.8);
        }
        
        /* 建议样式 */
        .suggestion-item { 
            border-left: 4px solid #2C5AA0; 
            padding: 15px 20px; 
            margin-bottom: 15px;
            background: #f8f9fa;
            border-radius: 0 4px 4px 0;
        }
        .suggestion-item.high-priority { border-left-color: #DC3545; }
        .suggestion-item.medium-priority { border-left-color: #FFC107; }
        .suggestion-item.low-priority { border-left-color: #28A745; }
        .suggestion-category { 
            display: inline-block; 
            padding: 3px 10px; 
            border-radius: 3px; 
            font-size: 12px; 
            color: white; 
            margin-bottom: 8px;
        }
        
        /* 图表容器 */
        .chart-container { 
            position: relative; 
            height: 350px; 
            margin: 20px 0;
        }
        
        /* 组分析样式 */
        .group-section { 
            background: #f8f9fa; 
            border-radius: 8px; 
            padding: 20px; 
            margin-bottom: 30px;
        }
        .group-header { 
            font-size: 18px; 
            font-weight: bold; 
            color: #2C5AA0; 
            margin-bottom: 15px;
        }
        
        /* 页脚 */
        .footer { 
            text-align: center; 
            padding: 30px; 
            color: #6c757d; 
            font-size: 12px;
            border-top: 1px solid #e9ecef;
            margin-top: 40px;
        }
        
        /* 网格布局 */
        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; }
        
        /* 指标卡片 */
        .metric-card { 
            background: white; 
            padding: 20px; 
            border-radius: 8px; 
            text-align: center;
            border: 1px solid #e9ecef;
        }
        .metric-value { 
            font-size: 32px; 
            font-weight: bold; 
            color: #2C5AA0; 
            margin: 10px 0;
        }
        .metric-label { color: #6c757d; font-size: 14px; }
    </style>";
        }

        private string GenerateChartJsInclude()
        {
            // 使用内联Chart.js，避免外部依赖
            // 如果本地存在则使用本地，否则使用CDN
            if (File.Exists(_chartJsPath))
            {
                string chartJs = File.ReadAllText(_chartJsPath);
                return $"<script>{chartJs}</script>";
            }
            
            // 使用Chart.js CDN作为备选
            return "<script src=\"https://cdn.jsdelivr.net/npm/chart.js\"></script>";
        }

        private string GenerateHeader(PathAnalysisReportData data)
        {
            var sb = new StringBuilder();
            sb.AppendLine("<div class=\"container\">");
            sb.AppendLine("    <div class=\"header\">");
            sb.AppendLine("        <h1>📊 物流路径规划分析报告</h1>");
            sb.AppendLine("        <div class=\"meta\">");
            sb.AppendLine($"            <p>文档: {EscapeHtml(data.DocumentName)}</p>");
            sb.AppendLine($"            <p>生成时间: {data.ReportTime:yyyy年MM月dd日 HH:mm:ss}</p>");
            sb.AppendLine($"            <p>分析策略: {data.Strategy} | 路径数量: {data.TotalPathCount} | 组数量: {data.GroupCount}</p>");
            sb.AppendLine("        </div>");
            sb.AppendLine("    </div>");
            return sb.ToString();
        }

        private string GenerateExecutiveSummary(PathAnalysisReportData data)
        {
            var sb = new StringBuilder();
            sb.AppendLine("    <div class=\"best-path-card\">");
            sb.AppendLine("        <h2>🏆 推荐最佳路径</h2>");
            
            if (data.OverallBestPath != null)
            {
                var best = data.OverallBestPath;
                sb.AppendLine($"        <div class=\"path-name\">{EscapeHtml(best.RouteName)}</div>");
                sb.AppendLine("        <div class=\"path-stats\">");
                sb.AppendLine($"            长度: {best.TotalLength:F1}米 | ");
                sb.AppendLine($"            碰撞: {best.CollisionCount}次 | ");
                sb.AppendLine($"            综合评分: {best.WeightedScore:F1}分");
                sb.AppendLine("        </div>");
            }
            else
            {
                sb.AppendLine("        <div class=\"path-name\">未找到推荐路径</div>");
            }
            
            sb.AppendLine("    </div>");
            return sb.ToString();
        }

        private string GenerateGroupAnalysis(EndpointGroup group)
        {
            var sb = new StringBuilder();
            sb.AppendLine("    <div class=\"group-section\">");
            sb.AppendLine($"        <div class=\"group-header\">🎯 {EscapeHtml(group.GroupName)} - {group.EndPointDescription}</div>");
            sb.AppendLine($"        <p>共 {group.RouteCount} 条路径到达此终点</p>");
            
            // 生成雷达图
            if (group.BestPath != null)
            {
                string chartId = $"radarChart_{group.GroupId}";
                sb.AppendLine("        <div class=\"chart-container\">");
                sb.AppendLine($"            <canvas id=\"{chartId}\"></canvas>");
                sb.AppendLine("        </div>");
                sb.AppendLine(GenerateRadarChartScript(chartId, group.BestPath));
            }
            
            sb.AppendLine("    </div>");
            return sb.ToString();
        }

        private string GenerateAllPathsTable(PathAnalysisReportData data)
        {
            var sb = new StringBuilder();
            sb.AppendLine("    <div class=\"card\">");
            sb.AppendLine("        <div class=\"card-title\">📋 所有路径详细数据</div>");
            sb.AppendLine("        <table class=\"data-table\">");
            sb.AppendLine("            <thead>");
            sb.AppendLine("                <tr>");
            sb.AppendLine("                    <th>路径名称</th>");
            sb.AppendLine("                    <th>长度(m)</th>");
            sb.AppendLine("                    <th>碰撞</th>");
            sb.AppendLine("                    <th>安全分</th>");
            sb.AppendLine("                    <th>效率分</th>");
            sb.AppendLine("                    <th>转弯分</th>");
            sb.AppendLine("                    <th>直达分</th>");
            sb.AppendLine("                    <th>综合分</th>");
            sb.AppendLine("                </tr>");
            sb.AppendLine("            </thead>");
            sb.AppendLine("            <tbody>");
            
            foreach (var analysis in data.AllPathAnalyses.OrderByDescending(a => a.WeightedScore))
            {
                string rowClass = analysis.IsBestInGroup ? "best-row" : "";
                sb.AppendLine($"                <tr class=\"{rowClass}\">");
                sb.AppendLine($"                    <td>{EscapeHtml(analysis.RouteName)}</td>");
                sb.AppendLine($"                    <td>{analysis.TotalLength:F1}</td>");
                sb.AppendLine($"                    <td>{analysis.CollisionCount}</td>");
                sb.AppendLine($"                    <td>{GenerateScoreBar(analysis.SafetyScore)}</td>");
                sb.AppendLine($"                    <td>{GenerateScoreBar(analysis.EfficiencyScore)}</td>");
                sb.AppendLine($"                    <td>{GenerateScoreBar(analysis.TurnDifficultyScore)}</td>");
                sb.AppendLine($"                    <td>{GenerateScoreBar(analysis.TortuosityScore)}</td>");
                sb.AppendLine($"                    <td><strong>{analysis.WeightedScore:F1}</strong></td>");
                sb.AppendLine("                </tr>");
            }
            
            sb.AppendLine("            </tbody>");
            sb.AppendLine("        </table>");
            sb.AppendLine("    </div>");
            return sb.ToString();
        }

        private string GenerateSuggestions(PathAnalysisReportData data)
        {
            var sb = new StringBuilder();
            sb.AppendLine("    <div class=\"card\">");
            sb.AppendLine("        <div class=\"card-title\">💡 优化建议</div>");
            
            if (data.AllSuggestions?.Count > 0)
            {
                foreach (var suggestion in data.AllSuggestions.OrderByDescending(s => s.Priority))
                {
                    string priorityClass = suggestion.Priority >= 4 ? "high-priority" :
                                          suggestion.Priority >= 3 ? "medium-priority" : "low-priority";
                    string categoryColor = GetCategoryColor(suggestion.Category);
                    
                    sb.AppendLine($"        <div class=\"suggestion-item {priorityClass}\">");
                    sb.AppendLine($"            <span class=\"suggestion-category\" style=\"background: {categoryColor}\">{suggestion.CategoryName}</span>");
                    sb.AppendLine($"            <h4>{EscapeHtml(suggestion.Title)}</h4>");
                    sb.AppendLine($"            <p>{EscapeHtml(suggestion.Description)}</p>");
                    if (!string.IsNullOrEmpty(suggestion.RelatedRouteName))
                    {
                        sb.AppendLine($"            <small>相关路径: {EscapeHtml(suggestion.RelatedRouteName)}</small>");
                    }
                    sb.AppendLine("        </div>");
                }
            }
            else
            {
                sb.AppendLine("        <p>暂无优化建议</p>");
            }
            
            sb.AppendLine("    </div>");
            return sb.ToString();
        }

        private string GenerateTechnicalParameters(PathAnalysisReportData data)
        {
            var sb = new StringBuilder();
            sb.AppendLine("    <div class=\"card\">");
            sb.AppendLine("        <div class=\"card-title\">⚙️ 技术参数</div>");
            
            if (data.ObjectParams != null)
            {
                sb.AppendLine("        <div class=\"grid-3\">");
                sb.AppendLine("            <div class=\"metric-card\">");
                sb.AppendLine("                <div class=\"metric-label\">物体长度</div>");
                sb.AppendLine($"                <div class=\"metric-value\">{data.ObjectParams.Length:F2}m</div>");
                sb.AppendLine("            </div>");
                sb.AppendLine("            <div class=\"metric-card\">");
                sb.AppendLine("                <div class=\"metric-label\">物体宽度</div>");
                sb.AppendLine($"                <div class=\"metric-value\">{data.ObjectParams.Width:F2}m</div>");
                sb.AppendLine("            </div>");
                sb.AppendLine("            <div class=\"metric-card\">");
                sb.AppendLine("                <div class=\"metric-label\">物体高度</div>");
                sb.AppendLine($"                <div class=\"metric-value\">{data.ObjectParams.Height:F2}m</div>");
                sb.AppendLine("            </div>");
                sb.AppendLine("        </div>");
            }
            
            sb.AppendLine("        <div style=\"margin-top: 20px;\">");
            sb.AppendLine("            <p><strong>评分标准:</strong></p>");
            sb.AppendLine("            <ul style=\"margin-left: 20px; margin-top: 10px;\">");
            sb.AppendLine("                <li>安全性: 基于碰撞数量和热点检测</li>");
            sb.AppendLine("                <li>效率: 基于路径长度比较</li>");
            sb.AppendLine("                <li>转弯难度: 基于转弯次数</li>");
            sb.AppendLine("                <li>直达性: 越高表示路径越直接</li>");
            sb.AppendLine("            </ul>");
            sb.AppendLine("        </div>");
            
            sb.AppendLine("    </div>");
            return sb.ToString();
        }

        private string GenerateFooter(PathAnalysisReportData data)
        {
            var sb = new StringBuilder();
            sb.AppendLine("    <div class=\"footer\">");
            sb.AppendLine($"        <p>NavisworksTransport 路径规划分析系统</p>");
            sb.AppendLine($"        <p>报告生成时间: {data.ReportTime:yyyy-MM-dd HH:mm:ss}</p>");
            sb.AppendLine("    </div>");
            sb.AppendLine("</div>"); // 关闭container
            return sb.ToString();
        }

        #endregion

        #region 辅助方法

        private string GenerateScoreBar(double score)
        {
            string barClass = score >= 80 ? "high" : score >= 60 ? "medium" : "low";
            return $"<div class=\"score-bar-container\"><div class=\"score-bar {barClass}\" style=\"width: {score}%\"></div><span class=\"score-text\">{score:F0}</span></div>";
        }

        private string GenerateRadarChartScript(string chartId, PathDetailedAnalysis analysis)
        {
            var labels = new[] { "'安全性'", "'效率'", "'转弯难度'", "'直达性'" };
            var data = new[] { analysis.SafetyScore, analysis.EfficiencyScore, analysis.TurnDifficultyScore, analysis.TortuosityScore };
            
            var sb = new StringBuilder();
            sb.AppendLine("<script>");
            sb.AppendLine($"    new Chart(document.getElementById('{chartId}'), {{");
            sb.AppendLine("        type: 'radar',");
            sb.AppendLine("        data: {");
            sb.AppendLine($"            labels: [{string.Join(", ", labels)}],");
            sb.AppendLine("            datasets: [{");
            sb.AppendLine($"                label: '{EscapeHtml(analysis.RouteName)}',");
            sb.AppendLine($"                data: [{string.Join(", ", data)}],");
            sb.AppendLine("                backgroundColor: 'rgba(44, 90, 160, 0.2)',");
            sb.AppendLine("                borderColor: 'rgba(44, 90, 160, 1)',");
            sb.AppendLine("                pointBackgroundColor: 'rgba(44, 90, 160, 1)',");
            sb.AppendLine("                borderWidth: 2");
            sb.AppendLine("            }]");
            sb.AppendLine("        },");
            sb.AppendLine("        options: {");
            sb.AppendLine("            responsive: true,");
            sb.AppendLine("            maintainAspectRatio: false,");
            sb.AppendLine("            scales: {");
            sb.AppendLine("                r: {");
            sb.AppendLine("                    beginAtZero: true,");
            sb.AppendLine("                    max: 100,");
            sb.AppendLine("                    ticks: { stepSize: 20 }");
            sb.AppendLine("                }");
            sb.AppendLine("            },");
            sb.AppendLine("            plugins: {");
            sb.AppendLine("                legend: { display: false }");
            sb.AppendLine("            }");
            sb.AppendLine("        }");
            sb.AppendLine("    });");
            sb.AppendLine("</script>");
            return sb.ToString();
        }

        private string GetCategoryColor(SuggestionCategory category)
        {
            switch (category)
            {
                case SuggestionCategory.Safety: return "#DC3545";
                case SuggestionCategory.Efficiency: return "#FFC107";
                case SuggestionCategory.TurnComplexity: return "#17A2B8";
                case SuggestionCategory.Redundancy: return "#6C757D";
                case SuggestionCategory.GroupComparison: return "#28A745";
                default: return "#2C5AA0";
            }
        }

        private string EscapeHtml(string text)
        {
            if (string.IsNullOrEmpty(text))
                return "";
            return text
                .Replace("&", "&amp;")
                .Replace("<", "&lt;")
                .Replace(">", "&gt;")
                .Replace("\"", "&quot;")
                .Replace("'", "&#39;");
        }

        #endregion
    }

    /// <summary>
    /// 分析报告数据（与ViewModel数据兼容）
    /// </summary>
    public class PathAnalysisReportData
    {
        public DateTime ReportTime { get; set; }
        public string Strategy { get; set; }
        public int TotalPathCount { get; set; }
        public int GroupCount { get; set; }
        public List<EndpointGroup> Groups { get; set; }
        public List<PathDetailedAnalysis> AllPathAnalyses { get; set; }
        public PathDetailedAnalysis OverallBestPath { get; set; }
        public List<CategorizedSuggestion> AllSuggestions { get; set; }
        public string DocumentName { get; set; }
        public ObjectParameters ObjectParams { get; set; }
    }
}
