using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using Autodesk.Navisworks.Api;
using NavisworksTransport.Core;
using NavisworksTransport.Core.Models;

namespace NavisworksTransport.UI.WPF.ViewModels
{
    /// <summary>
    /// 分析完成事件参数
    /// </summary>
    public class AnalysisCompletedEventArgs : EventArgs
    {
        public List<EndpointGroupViewModel> EndpointGroups { get; set; }
        public EndpointGroupViewModel SelectedGroup { get; set; }
    }

    /// <summary>
    /// 路径分析视图模型 - 扩展版
    /// 支持多维度评分和同终点组分析
    /// </summary>
    public class PathAnalysisViewModel : INotifyPropertyChanged
    {
        #region 字段
        
        private string _analysisStrategy = AnalysisStrategies.Balanced;
        private bool _isAnalyzing = false;
        private PathAnalysisItem _recommendedPath;
        private string _analysisStatus = "准备就绪";
        private EndpointGroupViewModel _selectedGroup;
        private PathDetailedAnalysis _selectedPathAnalysis;
        
        #endregion

        #region 属性

        /// <summary>
        /// 可用策略列表
        /// </summary>
        public List<string> AvailableStrategies => AnalysisStrategies.GetAllStrategies();

        /// <summary>
        /// 可用路径列表
        /// </summary>
        public ObservableCollection<PathAnalysisItem> AvailablePaths { get; set; }

        /// <summary>
        /// 选中的路径列表
        /// </summary>
        public ObservableCollection<PathAnalysisItem> SelectedPaths { get; set; }

        /// <summary>
        /// 分析策略
        /// </summary>
        public string AnalysisStrategy
        {
            get => _analysisStrategy;
            set
            {
                _analysisStrategy = value;
                OnPropertyChanged();
                UpdateRecommendedPath();
            }
        }

        /// <summary>
        /// 是否正在分析
        /// </summary>
        public bool IsAnalyzing
        {
            get => _isAnalyzing;
            set
            {
                _isAnalyzing = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 推荐的最佳路径
        /// </summary>
        public PathAnalysisItem RecommendedPath
        {
            get => _recommendedPath;
            set
            {
                _recommendedPath = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 分析状态信息
        /// </summary>
        public string AnalysisStatus
        {
            get => _analysisStatus;
            set
            {
                _analysisStatus = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 同终点组列表
        /// </summary>
        public ObservableCollection<EndpointGroupViewModel> EndpointGroups { get; set; }

        /// <summary>
        /// 当前选中的组
        /// </summary>
        public EndpointGroupViewModel SelectedGroup
        {
            get => _selectedGroup;
            set
            {
                _selectedGroup = value;
                OnPropertyChanged();
                UpdateSelectedGroupDetails();
            }
        }

        /// <summary>
        /// 当前选中的路径详细分析
        /// </summary>
        public PathDetailedAnalysis SelectedPathAnalysis
        {
            get => _selectedPathAnalysis;
            set
            {
                _selectedPathAnalysis = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 优化建议列表（分类）
        /// </summary>
        public ObservableCollection<CategorizedSuggestionViewModel> CategorizedSuggestions { get; set; }

        /// <summary>
        /// 四维度分数
        /// </summary>
        public ObservableCollection<DimensionScoreViewModel> DimensionScores { get; set; }

        /// <summary>
        /// 是否有分析结果（用于控制图表显示）
        /// </summary>
        public bool HasAnalysisResults => EndpointGroups != null && EndpointGroups.Count > 0;

        /// <summary>
        /// 分析完成事件（用于通知UI绘制图表）
        /// </summary>
        public event EventHandler<AnalysisCompletedEventArgs> AnalysisCompleted;

        /// <summary>
        /// 命令
        /// </summary>
        public ICommand StartAnalysisCommand { get; private set; }
        public ICommand SelectAllCommand { get; private set; }
        public ICommand ClearSelectionCommand { get; private set; }
        public ICommand ExportReportCommand { get; private set; }
        public ICommand SelectGroupCommand { get; private set; }
        public ICommand HighlightBestPathCommand { get; private set; }

        #endregion

        #region 构造函数

        public PathAnalysisViewModel()
        {
            try
            {
                InitializeCollections();
                InitializeCommands();
                EnsurePathDatabaseInitialized();
                LoadPathData();
                LogManager.Info("PathAnalysisViewModel初始化完成");
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化PathAnalysisViewModel失败: {ex.Message}", ex);
            }
        }

        private void InitializeCollections()
        {
            AvailablePaths = new ObservableCollection<PathAnalysisItem>();
            SelectedPaths = new ObservableCollection<PathAnalysisItem>();
            EndpointGroups = new ObservableCollection<EndpointGroupViewModel>();
            CategorizedSuggestions = new ObservableCollection<CategorizedSuggestionViewModel>();
            DimensionScores = new ObservableCollection<DimensionScoreViewModel>();
        }

        private void InitializeCommands()
        {
            StartAnalysisCommand = new RelayCommand(ExecuteStartAnalysis, CanExecuteStartAnalysis);
            SelectAllCommand = new RelayCommand(SelectAll);
            ClearSelectionCommand = new RelayCommand(ClearSelection);
            ExportReportCommand = new RelayCommand(ExportReport, CanExportReport);
            SelectGroupCommand = new RelayCommand<EndpointGroupViewModel>(SelectGroup);
            HighlightBestPathCommand = new RelayCommand(HighlightBestPath, CanHighlightBestPath);
        }

        private void EnsurePathDatabaseInitialized()
        {
            try
            {
                var manager = PathPlanningManager.Instance;
                manager.DatabaseInitialize();
            }
            catch (Exception ex)
            {
                LogManager.Error($"确保数据库初始化失败: {ex.Message}", ex);
            }
        }

        #endregion

        #region 数据加载

        private void LoadPathData()
        {
            try
            {
                var allRoutes = PathPlanningManager.Instance.GetAllRoutes();
                if (allRoutes == null || allRoutes.Count == 0)
                {
                    AnalysisStatus = "暂无可用路径数据，请先规划路径";
                    return;
                }

                AvailablePaths.Clear();
                foreach (var route in allRoutes)
                {
                    var item = new PathAnalysisItem
                    {
                        RouteId = route.Id,
                        Name = route.Name,
                        Type = route.CreatedTime != default(DateTime) ? "历史路径" : "当前会话",
                        Length = Math.Round(route.TotalLength, 2),
                        EstimatedTime = (int)route.EstimatedTime,
                        IsSelected = false,
                        CollisionCount = route.CollisionCount ?? 0,
                        Score = (int)(route.OverallScore ?? 0)
                    };

                    if (route.EstimatedTime > 0)
                    {
                        item.AverageSpeed = Math.Round(route.TotalLength / route.EstimatedTime, 2);
                    }

                    item.PropertyChanged += (s, e) =>
                    {
                        if (e.PropertyName == nameof(PathAnalysisItem.IsSelected))
                        {
                            CommandManager.InvalidateRequerySuggested();
                        }
                    };

                    AvailablePaths.Add(item);
                }

                AnalysisStatus = $"已加载 {AvailablePaths.Count} 条路径，请选择要分析的路径";
            }
            catch (Exception ex)
            {
                LogManager.Error($"加载路径数据失败: {ex.Message}", ex);
                AnalysisStatus = "加载路径数据失败";
            }
        }

        #endregion

        #region 命令执行

        private bool CanExecuteStartAnalysis()
        {
            return !IsAnalyzing && AvailablePaths.Any(p => p.IsSelected);
        }

        private void ExecuteStartAnalysis()
        {
            try
            {
                IsAnalyzing = true;
                AnalysisStatus = "正在分析...";

                var selectedRoutes = AvailablePaths.Where(p => p.IsSelected).ToList();
                if (selectedRoutes.Count == 0)
                {
                    AnalysisStatus = "请选择要分析的路径";
                    IsAnalyzing = false;
                    return;
                }

                // 获取完整路径对象
                var allRoutes = PathPlanningManager.Instance.GetAllRoutes();
                var routesToAnalyze = allRoutes.Where(r => selectedRoutes.Any(s => s.RouteId == r.Id)).ToList();

                // 执行分析
                var analysisService = new ExtendedPathAnalysisService(PathPlanningManager.Instance.GetPathDatabase());
                var groups = analysisService.AnalyzePathsWithGrouping(routesToAnalyze, AnalysisStrategy);

                // 更新UI
                UpdateAnalysisResults(groups, selectedRoutes);

                AnalysisStatus = "分析完成";
                IsAnalyzing = false;
            }
            catch (Exception ex)
            {
                IsAnalyzing = false;
                AnalysisStatus = "分析失败";
                LogManager.Error($"执行路径分析失败: {ex.Message}", ex);
            }
        }

        private void UpdateAnalysisResults(List<EndpointGroup> groups, List<PathAnalysisItem> selectedItems)
        {
            LogManager.Info($"[路径分析UI] 开始更新结果: {groups.Count}个组, {selectedItems.Count}条选中路径");
            
            // 清空现有数据
            EndpointGroups.Clear();
            SelectedPaths.Clear();
            CategorizedSuggestions.Clear();

            // 更新选中路径
            foreach (var item in selectedItems)
            {
                SelectedPaths.Add(item);
            }

            // 更新组信息
            foreach (var group in groups)
            {
                var groupVm = new EndpointGroupViewModel
                {
                    GroupId = group.GroupId,
                    GroupName = group.GroupName,
                    EndPointDescription = group.EndPointDescription,
                    RouteCount = group.RouteCount,
                    PathAnalyses = new ObservableCollection<PathDetailedAnalysis>(group.PathAnalyses),
                    BestPath = group.BestPath
                };
                EndpointGroups.Add(groupVm);

                // 收集建议
                foreach (var analysis in group.PathAnalyses)
                {
                    var service = new ExtendedPathAnalysisService(PathPlanningManager.Instance.GetPathDatabase());
                    var suggestions = service.GenerateSuggestionsForView(analysis, group);
                    foreach (var suggestion in suggestions)
                    {
                        CategorizedSuggestions.Add(new CategorizedSuggestionViewModel
                        {
                            Category = suggestion.Category.ToString(),
                            CategoryName = GetCategoryDisplayName(suggestion.Category),
                            Title = suggestion.Title,
                            Description = suggestion.Description,
                            RelatedRouteName = suggestion.RelatedRouteName,
                            Priority = suggestion.Priority
                        });
                    }
                }
            }

            // 设置推荐路径
            var overallBest = groups.Select(g => g.BestPath).OrderByDescending(p => p.WeightedScore).FirstOrDefault();
            if (overallBest != null)
            {
                var bestItem = selectedItems.FirstOrDefault(i => i.RouteId == overallBest.RouteId);
                if (bestItem != null)
                {
                    // 更新分数为分析后的综合评分
                    bestItem.Score = (int)overallBest.WeightedScore;
                    bestItem.CollisionCount = overallBest.CollisionCount;
                    LogManager.Info($"[路径分析UI] 设置推荐路径: {bestItem.Name}, 评分={bestItem.Score}");
                }
                else
                {
                    LogManager.Warning($"[路径分析UI] 未找到推荐路径对应的选中项: RouteId={overallBest.RouteId}");
                }
                RecommendedPath = bestItem;
                
                // 更新雷达图数据
                UpdateDimensionScores(overallBest);
            }
            else
            {
                LogManager.Warning("[路径分析UI] 未找到 overallBest");
            }

            // 默认选中第一个组
            if (EndpointGroups.Count > 0)
            {
                SelectedGroup = EndpointGroups[0];
                LogManager.Info($"[路径分析UI] 选中第一个组: {SelectedGroup.GroupName}");
            }
            
            OnPropertyChanged(nameof(HasAnalysisResults));
            
            // 触发分析完成事件，通知UI绘制图表
            AnalysisCompleted?.Invoke(this, new AnalysisCompletedEventArgs
            {
                EndpointGroups = EndpointGroups.ToList(),
                SelectedGroup = SelectedGroup
            });
            
            LogManager.Info($"[路径分析UI] 更新完成: EndpointGroups={EndpointGroups.Count}, Suggestions={CategorizedSuggestions.Count}");
        }

        private void UpdateDimensionScores(PathDetailedAnalysis analysis)
        {
            DimensionScores.Clear();
            DimensionScores.Add(new DimensionScoreViewModel { Name = "安全性", Score = analysis.SafetyScore, MaxScore = 100 });
            DimensionScores.Add(new DimensionScoreViewModel { Name = "效率", Score = analysis.EfficiencyScore, MaxScore = 100 });
            DimensionScores.Add(new DimensionScoreViewModel { Name = "转弯难度", Score = analysis.TurnDifficultyScore, MaxScore = 100 });
            DimensionScores.Add(new DimensionScoreViewModel { Name = "直达性", Score = analysis.TortuosityScore, MaxScore = 100 });
        }

        private void SelectGroup(EndpointGroupViewModel group)
        {
            if (group != null)
            {
                SelectedGroup = group;
            }
        }

        private void UpdateSelectedGroupDetails()
        {
            if (SelectedGroup?.BestPath != null)
            {
                SelectedPathAnalysis = SelectedGroup.BestPath;
                UpdateDimensionScores(SelectedGroup.BestPath);
                
                // 选中组变更时触发事件（更新雷达图）
                AnalysisCompleted?.Invoke(this, new AnalysisCompletedEventArgs
                {
                    EndpointGroups = EndpointGroups.ToList(),
                    SelectedGroup = SelectedGroup
                });
            }
        }

        private void SelectAll()
        {
            foreach (var path in AvailablePaths)
            {
                path.IsSelected = true;
            }
            CommandManager.InvalidateRequerySuggested();
        }

        private void ClearSelection()
        {
            foreach (var path in AvailablePaths)
            {
                path.IsSelected = false;
            }
            CommandManager.InvalidateRequerySuggested();
        }

        private bool CanExportReport()
        {
            return SelectedPaths != null && SelectedPaths.Count > 0 && RecommendedPath != null;
        }

        private void ExportReport()
        {
            try
            {
                if (SelectedPaths.Count == 0 || RecommendedPath == null)
                {
                    AnalysisStatus = "请先执行分析";
                    return;
                }

                // 构建报告数据
                var reportData = new NavisworksTransport.Core.PathAnalysisReportData
                {
                    ReportTime = DateTime.Now,
                    Strategy = AnalysisStrategy,
                    TotalPathCount = SelectedPaths.Count,
                    GroupCount = EndpointGroups.Count,
                    DocumentName = Application.ActiveDocument?.FileName ?? "未命名文档",
                    Groups = EndpointGroups.Select(g => new EndpointGroup
                    {
                        GroupId = g.GroupId,
                        GroupName = g.GroupName,
                        EndPointDescription = g.EndPointDescription,
                        PathAnalyses = g.PathAnalyses.ToList()
                    }).ToList(),
                    AllPathAnalyses = SelectedGroup?.PathAnalyses.ToList() ?? new List<PathDetailedAnalysis>(),
                    OverallBestPath = SelectedGroup?.BestPath,
                    AllSuggestions = CategorizedSuggestions.Select(s => new CategorizedSuggestion
                    {
                        Category = (SuggestionCategory)Enum.Parse(typeof(SuggestionCategory), s.Category),
                        Title = s.Title,
                        Description = s.Description,
                        RelatedRouteName = s.RelatedRouteName,
                        Priority = s.Priority
                    }).ToList()
                };

                // 弹出保存对话框
                var saveFileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    Title = "导出路径分析报告",
                    Filter = "HTML报告 (*.html)|*.html|所有文件 (*.*)|*.*",
                    DefaultExt = "html",
                    FileName = $"路径分析报告_{DateTime.Now:yyyyMMdd_HHmmss}",
                    AddExtension = true
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    // 生成报告
                    var generator = new PathAnalysisReportGenerator();
                    bool success = generator.SaveReportToFile(reportData, saveFileDialog.FileName);

                    if (success)
                    {
                        AnalysisStatus = $"报告已保存: {saveFileDialog.FileName}";
                        LogManager.Info($"路径分析报告已导出: {saveFileDialog.FileName}");
                        
                        // 打开报告所在目录并选中文件
                        System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{saveFileDialog.FileName}\"");
                    }
                    else
                    {
                        AnalysisStatus = "报告保存失败";
                        System.Windows.MessageBox.Show("报告保存失败，请检查文件路径是否有写入权限。", "保存失败", 
                            System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    }
                }
                else
                {
                    LogManager.Info("用户取消了路径分析报告导出");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"导出报告失败: {ex.Message}", ex);
                AnalysisStatus = "导出报告失败";
                System.Windows.MessageBox.Show($"导出报告失败: {ex.Message}", "错误", 
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        private bool CanHighlightBestPath()
        {
            return RecommendedPath != null;
        }

        private void HighlightBestPath()
        {
            try
            {
                if (RecommendedPath == null) return;

                // 通过PathPlanningManager设置当前路径，触发高亮显示
                var manager = PathPlanningManager.Instance;
                var route = manager.GetAllRoutes().FirstOrDefault(r => r.Id == RecommendedPath.RouteId);
                
                if (route != null)
                {
                    manager.SetCurrentRoute(route);
                    LogManager.Info($"已高亮显示最佳路径: {RecommendedPath.Name}");
                }
                else
                {
                    LogManager.Warning($"未找到路径: {RecommendedPath.RouteId}");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"高亮显示路径失败: {ex.Message}");
            }
        }

        private void UpdateRecommendedPath()
        {
            // 策略改变时重新计算
            if (SelectedPaths.Count > 0)
            {
                ExecuteStartAnalysis();
            }
        }

        private 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 "组内对比";
                default: return "一般建议";
            }
        }

        #endregion

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }

    #region 视图模型辅助类

    public class EndpointGroupViewModel
    {
        public string GroupId { get; set; }
        public string GroupName { get; set; }
        public string EndPointDescription { get; set; }
        public int RouteCount { get; set; }
        public ObservableCollection<PathDetailedAnalysis> PathAnalyses { get; set; }
        public PathDetailedAnalysis BestPath { get; set; }
    }

    public class CategorizedSuggestionViewModel
    {
        public string Category { get; set; }
        public string CategoryName { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string RelatedRouteName { get; set; }
        public int Priority { get; set; }
    }

    public class DimensionScoreViewModel
    {
        public string Name { get; set; }
        public double Score { get; set; }
        public double MaxScore { get; set; }
        public double Percentage => MaxScore > 0 ? Score / MaxScore * 100 : 0;
    }

    #endregion

    #region 原有数据模型（保留兼容）

    public class PathAnalysisItem : INotifyPropertyChanged
    {
        private bool _isSelected;
        private int _collisionCount;
        private int _affectedObjects;
        private double _averageSpeed;
        private int _score;

        public string RouteId { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public double Length { get; set; }
        public int EstimatedTime { get; set; }

        public int CollisionCount
        {
            get => _collisionCount;
            set { _collisionCount = value; OnPropertyChanged(); }
        }

        public int AffectedObjects
        {
            get => _affectedObjects;
            set { _affectedObjects = value; OnPropertyChanged(); }
        }

        public double AverageSpeed
        {
            get => _averageSpeed;
            set { _averageSpeed = value; OnPropertyChanged(); }
        }

        public int Score
        {
            get => _score;
            set { _score = value; OnPropertyChanged(); }
        }

        public bool IsSelected
        {
            get => _isSelected;
            set { _isSelected = value; OnPropertyChanged(); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class OptimizationSuggestion
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string Priority { get; set; }
        public string Status { get; set; }
    }

    public class BottleneckLocation
    {
        public string Name { get; set; }
        public int AffectedPaths { get; set; }
        public string Severity { get; set; }
        public string Suggestion { get; set; }
    }

    #endregion
}
