using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Navisworks.Api;

namespace NavisworksTransport.Core.Models
{
    /// <summary>
    /// 分析策略常量定义
    /// </summary>
    public static class AnalysisStrategies
    {
        public const string SafetyFirst = "安全优先";
        public const string EfficiencyFirst = "效率优先";
        public const string Balanced = "平衡模式";

        /// <summary>
        /// 策略权重配置（四维度）
        /// 顺序: 安全、效率、转弯、直达
        /// </summary>
        public static readonly Dictionary<string, double[]> Weights = new Dictionary<string, double[]>
        {
            [SafetyFirst] = new[] { 0.50, 0.20, 0.15, 0.15 },
            [EfficiencyFirst] = new[] { 0.20, 0.40, 0.20, 0.20 },
            [Balanced] = new[] { 0.35, 0.30, 0.175, 0.175 }
        };

        /// <summary>
        /// 获取所有可用策略列表
        /// </summary>
        public static List<string> GetAllStrategies()
        {
            return new List<string> { SafetyFirst, EfficiencyFirst, Balanced };
        }

        /// <summary>
        /// 验证策略名称是否有效
        /// </summary>
        public static bool IsValidStrategy(string strategy)
        {
            return Weights.ContainsKey(strategy);
        }

        /// <summary>
        /// 获取策略权重，无效策略返回平衡模式权重
        /// </summary>
        public static double[] GetWeights(string strategy)
        {
            if (Weights.TryGetValue(strategy, out var weights))
                return weights;
            return Weights[Balanced];
        }
    }

    /// <summary>
    /// 单条路径的详细分析结果
    /// </summary>
    public class PathDetailedAnalysis
    {
        /// <summary>
        /// 路径ID
        /// </summary>
        public string RouteId { get; set; }

        /// <summary>
        /// 路径名称
        /// </summary>
        public string RouteName { get; set; }

        /// <summary>
        /// 路径总长度（米）
        /// </summary>
        public double TotalLength { get; set; }

        /// <summary>
        /// 预估通行时间（秒）
        /// </summary>
        public double EstimatedTime { get; set; }

        /// <summary>
        /// 碰撞数量
        /// </summary>
        public int CollisionCount { get; set; }

        /// <summary>
        /// 碰撞热点数量
        /// </summary>
        public int HotspotCount { get; set; }

        /// <summary>
        /// 碰撞热点列表
        /// </summary>
        public List<CollisionHotspot> Hotspots { get; set; } = new List<CollisionHotspot>();

        // ========== 五维度评分（0-100）==========

        /// <summary>
        /// 安全性分数（碰撞风险指数）
        /// </summary>
        public double SafetyScore { get; set; }

        /// <summary>
        /// 效率分数（通行效率指数）
        /// </summary>
        public double EfficiencyScore { get; set; }

        /// <summary>
        /// 转弯难度分数
        /// </summary>
        public double TurnDifficultyScore { get; set; }

        /// <summary>
        /// 路径曲折度分数
        /// </summary>
        public double TortuosityScore { get; set; }

        /// <summary>
        /// 通道冗余度分数
        /// </summary>
        public double RedundancyScore { get; set; }

        /// <summary>
        /// 综合加权评分
        /// </summary>
        public double WeightedScore { get; set; }

        /// <summary>
        /// 分析使用的策略
        /// </summary>
        public string Strategy { get; set; }

        /// <summary>
        /// 分析时间
        /// </summary>
        public DateTime AnalysisTime { get; set; }

        // ========== 组内排名信息 ==========

        /// <summary>
        /// 所属终点组ID
        /// </summary>
        public string GroupId { get; set; }

        /// <summary>
        /// 在组内排名（1开始）
        /// </summary>
        public int GroupRanking { get; set; }

        /// <summary>
        /// 是否为组内最佳路径
        /// </summary>
        public bool IsBestInGroup => GroupRanking == 1;

        /// <summary>
        /// 获取四维度分数数组（用于雷达图）
        /// 顺序: 安全、效率、转弯、直达
        /// </summary>
        public double[] GetDimensionScores()
        {
            return new[] { SafetyScore, EfficiencyScore, TurnDifficultyScore, TortuosityScore };
        }

        /// <summary>
        /// 获取维度分数字典
        /// </summary>
        public Dictionary<string, double> GetDimensionScoreDict()
        {
            return new Dictionary<string, double>
            {
                ["安全性"] = SafetyScore,
                ["效率"] = EfficiencyScore,
                ["转弯难度"] = TurnDifficultyScore,
                ["直达性"] = TortuosityScore
            };
        }
    }

    /// <summary>
    /// 碰撞热点
    /// </summary>
    public class CollisionHotspot
    {
        /// <summary>
        /// 热点ID
        /// </summary>
        public string Id { get; set; } = Guid.NewGuid().ToString("N").Substring(0, 8);

        /// <summary>
        /// 热点中心位置
        /// </summary>
        public Point3D Center { get; set; }

        /// <summary>
        /// 热点半径（米）
        /// </summary>
        public double Radius { get; set; } = 3.0;

        /// <summary>
        /// 范围内碰撞数量
        /// </summary>
        public int CollisionCount { get; set; }

        /// <summary>
        /// 碰撞对象名称列表
        /// </summary>
        public List<string> CollidedObjectNames { get; set; } = new List<string>();

        /// <summary>
        /// 热点严重程度
        /// </summary>
        public HotspotSeverity Severity
        {
            get
            {
                if (CollisionCount >= 5) return HotspotSeverity.Critical;
                if (CollisionCount >= 3) return HotspotSeverity.High;
                return HotspotSeverity.Medium;
            }
        }

        /// <summary>
        /// 获取热点描述
        /// </summary>
        public string GetDescription()
        {
            return $"位置({Center.X:F2}, {Center.Y:F2}, {Center.Z:F2})范围内有{CollisionCount}次碰撞";
        }
    }

    /// <summary>
    /// 热点严重程度
    /// </summary>
    public enum HotspotSeverity
    {
        /// <summary>
        /// 中等（2次碰撞）
        /// </summary>
        Medium,

        /// <summary>
        /// 严重（3-4次碰撞）
        /// </summary>
        High,

        /// <summary>
        /// 危急（5次及以上）
        /// </summary>
        Critical
    }

    /// <summary>
    /// 同终点路径组
    /// </summary>
    public class EndpointGroup
    {
        /// <summary>
        /// 组ID
        /// </summary>
        public string GroupId { get; set; }

        /// <summary>
        /// 组名称（基于终点描述）
        /// </summary>
        public string GroupName { get; set; }

        /// <summary>
        /// 终点位置（组中心点）
        /// </summary>
        public Point3D EndPoint { get; set; }

        /// <summary>
        /// 终点描述
        /// </summary>
        public string EndPointDescription { get; set; }

        /// <summary>
        /// 组内所有路径的分析结果
        /// </summary>
        public List<PathDetailedAnalysis> PathAnalyses { get; set; } = new List<PathDetailedAnalysis>();

        /// <summary>
        /// 路径数量
        /// </summary>
        public int RouteCount => PathAnalyses?.Count ?? 0;

        /// <summary>
        /// 组内最短路径长度
        /// </summary>
        public double MinLength => PathAnalyses.Min(p => p.TotalLength);

        /// <summary>
        /// 组内最短通行时间
        /// </summary>
        public double MinTime => PathAnalyses.Min(p => p.EstimatedTime);

        /// <summary>
        /// 组内最少碰撞数
        /// </summary>
        public int MinCollisionCount => PathAnalyses.Min(p => p.CollisionCount);

        /// <summary>
        /// 组内最佳路径（按当前策略）
        /// </summary>
        public PathDetailedAnalysis BestPath => PathAnalyses.OrderByDescending(p => p.WeightedScore).FirstOrDefault();

        /// <summary>
        /// 获取组内某路径的排名
        /// </summary>
        public int GetRanking(string routeId)
        {
            var sorted = PathAnalyses.OrderByDescending(p => p.WeightedScore).ToList();
            var index = sorted.FindIndex(p => p.RouteId == routeId);
            return index >= 0 ? index + 1 : 0;
        }

        /// <summary>
        /// 获取组内某路径与最佳路径的长度差异率
        /// </summary>
        public double GetLengthDiffPercent(string routeId)
        {
            var path = PathAnalyses.FirstOrDefault(p => p.RouteId == routeId);
            if (path == null || MinLength <= 0) return 0;
            return (path.TotalLength - MinLength) / MinLength * 100;
        }

        /// <summary>
        /// 获取组内某路径与最快路径的时间差异率
        /// </summary>
        public double GetTimeDiffPercent(string routeId)
        {
            var path = PathAnalyses.FirstOrDefault(p => p.RouteId == routeId);
            if (path == null || MinTime <= 0) return 0;
            return (path.EstimatedTime - MinTime) / MinTime * 100;
        }
    }

    /// <summary>
    /// 路径对比结果
    /// </summary>
    public class PathComparison
    {
        /// <summary>
        /// 路径A ID
        /// </summary>
        public string PathAId { get; set; }

        /// <summary>
        /// 路径A名称
        /// </summary>
        public string PathAName { get; set; }

        /// <summary>
        /// 路径B ID
        /// </summary>
        public string PathBId { get; set; }

        /// <summary>
        /// 路径B名称
        /// </summary>
        public string PathBName { get; set; }

        /// <summary>
        /// 长度差异（米）
        /// </summary>
        public double LengthDiff { get; set; }

        /// <summary>
        /// 长度差异率（%）
        /// </summary>
        public double LengthDiffPercent { get; set; }

        /// <summary>
        /// 时间差异（秒）
        /// </summary>
        public double TimeDiff { get; set; }

        /// <summary>
        /// 时间差异率（%）
        /// </summary>
        public double TimeDiffPercent { get; set; }

        /// <summary>
        /// 碰撞数差异
        /// </summary>
        public int CollisionDiff { get; set; }

        /// <summary>
        /// 综合评分差异
        /// </summary>
        public double ScoreDiff { get; set; }

        /// <summary>
        /// 优势方（A更优、B更优、相当）
        /// </summary>
        public string Advantage { get; set; }
    }

    /// <summary>
    /// 分析上下文
    /// </summary>
    public class AnalysisContext
    {
        /// <summary>
        /// 分析策略
        /// </summary>
        public string Strategy { get; set; } = AnalysisStrategies.Balanced;

        /// <summary>
        /// 组内最短通行时间（用于效率计算）
        /// </summary>
        public double GroupMinTime { get; set; }

        /// <summary>
        /// 组内最短路径长度
        /// </summary>
        public double GroupMinLength { get; set; }

        /// <summary>
        /// 路径经过的通道信息
        /// </summary>
        public List<ChannelInfo> Channels { get; set; } = new List<ChannelInfo>();

        /// <summary>
        /// 组内最高成本（用于归一化，如需要）
        /// </summary>
        public double GroupMaxCost { get; set; }
    }

    /// <summary>
    /// 通道信息
    /// </summary>
    public class ChannelInfo
    {
        /// <summary>
        /// 通道模型ID
        /// </summary>
        public string ModelItemId { get; set; }

        /// <summary>
        /// 通道显示名称
        /// </summary>
        public string DisplayName { get; set; }

        /// <summary>
        /// 通道类型
        /// </summary>
        public CategoryAttributeManager.LogisticsElementType ChannelType { get; set; }

        /// <summary>
        /// 宽度限制（米）
        /// </summary>
        public double WidthLimit { get; set; }

        /// <summary>
        /// 高度限制（米）
        /// </summary>
        public double HeightLimit { get; set; }

        /// <summary>
        /// 速度限制（m/s）
        /// </summary>
        public double SpeedLimit { get; set; }
    }

    /// <summary>
    /// 分类优化建议
    /// </summary>
    public class CategorizedSuggestion
    {
        /// <summary>
        /// 建议类别
        /// </summary>
        public SuggestionCategory Category { get; set; }

        /// <summary>
        /// 类别显示名称
        /// </summary>
        public string CategoryName => GetCategoryDisplayName(Category);

        /// <summary>
        /// 建议标题
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 建议详细描述
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// 关联的路径ID
        /// </summary>
        public string RelatedRouteId { get; set; }

        /// <summary>
        /// 关联的路径名称
        /// </summary>
        public string RelatedRouteName { get; set; }

        /// <summary>
        /// 优先级（1-5，5最高）
        /// </summary>
        public int Priority { get; set; }

        /// <summary>
        /// 获取类别显示名称
        /// </summary>
        private static string GetCategoryDisplayName(SuggestionCategory category)
        {
            switch (category)
            {
                case SuggestionCategory.Safety: return "安全建议";
                case SuggestionCategory.Efficiency: return "效率建议";
                case SuggestionCategory.TurnComplexity: return "转弯建议";
                case SuggestionCategory.Redundancy: return "冗余建议";
                case SuggestionCategory.GroupComparison: return "组内对比";
                case SuggestionCategory.General: return "一般建议";
                default: return "其他";
            }
        }
    }

    /// <summary>
    /// 建议类别
    /// </summary>
    public enum SuggestionCategory
    {
        /// <summary>
        /// 安全建议
        /// </summary>
        Safety,

        /// <summary>
        /// 效率建议
        /// </summary>
        Efficiency,

        /// <summary>
        /// 转弯复杂度建议
        /// </summary>
        TurnComplexity,

        /// <summary>
        /// 冗余度建议
        /// </summary>
        Redundancy,

        /// <summary>
        /// 组内对比建议
        /// </summary>
        GroupComparison,

        /// <summary>
        /// 一般建议
        /// </summary>
        General
    }

    /// <summary>
    /// 完整分析报告数据
    /// </summary>
    public class PathAnalysisReportData
    {
        /// <summary>
        /// 报告生成时间
        /// </summary>
        public DateTime ReportTime { get; set; }

        /// <summary>
        /// 分析策略
        /// </summary>
        public string Strategy { get; set; }

        /// <summary>
        /// 分析的路径总数
        /// </summary>
        public int TotalPathCount { get; set; }

        /// <summary>
        /// 同终点组数量
        /// </summary>
        public int GroupCount { get; set; }

        /// <summary>
        /// 所有同终点组
        /// </summary>
        public List<EndpointGroup> Groups { get; set; } = new List<EndpointGroup>();

        /// <summary>
        /// 所有路径分析结果
        /// </summary>
        public List<PathDetailedAnalysis> AllPathAnalyses { get; set; } = new List<PathDetailedAnalysis>();

        /// <summary>
        /// 全局最佳路径
        /// </summary>
        public PathDetailedAnalysis OverallBestPath { get; set; }

        /// <summary>
        /// 所有优化建议
        /// </summary>
        public List<CategorizedSuggestion> AllSuggestions { get; set; } = new List<CategorizedSuggestion>();

        /// <summary>
        /// 文档名称
        /// </summary>
        public string DocumentName { get; set; }

        /// <summary>
        /// 物体参数信息
        /// </summary>
        public ObjectParameters ObjectParams { get; set; }
    }

    /// <summary>
    /// 物体参数
    /// </summary>
    public class ObjectParameters
    {
        /// <summary>
        /// 物体长度（米）
        /// </summary>
        public double Length { get; set; }

        /// <summary>
        /// 物体宽度（米）
        /// </summary>
        public double Width { get; set; }

        /// <summary>
        /// 物体高度（米）
        /// </summary>
        public double Height { get; set; }

        /// <summary>
        /// 安全间隙（米）
        /// </summary>
        public double SafetyMargin { get; set; }

        /// <summary>
        /// 有效宽度（含间隙）
        /// </summary>
        public double EffectiveWidth => Width + SafetyMargin * 2;

        /// <summary>
        /// 有效高度（含间隙）
        /// </summary>
        public double EffectiveHeight => Height + SafetyMargin;
    }
}
