using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Input;

namespace NavisworksTransport.UI.WPF.ViewModels
{
    /// <summary>
    /// 路径分析视图模型
    /// 用于路径规划分析对话框的数据绑定和业务逻辑
    /// </summary>
    public class PathAnalysisViewModel : INotifyPropertyChanged
    {
        #region 字段
        
        private string _analysisStrategy = "安全优先";
        private bool _isAnalyzing = false;
        private PathAnalysisItem _recommendedPath;
        private string _analysisStatus = "准备就绪";
        
        #endregion

        #region 属性

        /// <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<OptimizationSuggestion> OptimizationSuggestions { get; set; }

        /// <summary>
        /// 瓶颈位置列表
        /// </summary>
        public ObservableCollection<BottleneckLocation> BottleneckLocations { get; set; }

        /// <summary>
        /// 开始分析命令
        /// </summary>
        public ICommand StartAnalysisCommand { get; private set; }

        /// <summary>
        /// 全选命令
        /// </summary>
        public ICommand SelectAllCommand { get; private set; }

        /// <summary>
        /// 清空选择命令
        /// </summary>
        public ICommand ClearSelectionCommand { get; private set; }

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

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化路径分析视图模型
        /// </summary>
        public PathAnalysisViewModel()
        {
            try
            {
                InitializeCollections();
                InitializeCommands();

                // 确保PathPlanningManager的数据库已初始化
                EnsurePathDatabaseInitialized();

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

        /// <summary>
        /// 初始化命令
        /// </summary>
        private void InitializeCommands()
        {
            StartAnalysisCommand = new RelayCommand(ExecuteStartAnalysis, CanExecuteStartAnalysis);
            SelectAllCommand = new RelayCommand(SelectAll);
            ClearSelectionCommand = new RelayCommand(ClearSelection);
            ExportReportCommand = new RelayCommand(ExportReport, CanExportReport);
        }

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

        private void ExecuteStartAnalysis()
        {
            PerformAnalysis();
        }

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

        #endregion

        #region 初始化方法

        /// <summary>
        /// 初始化集合
        /// </summary>
        private void InitializeCollections()
        {
            AvailablePaths = new ObservableCollection<PathAnalysisItem>();
            SelectedPaths = new ObservableCollection<PathAnalysisItem>();
            OptimizationSuggestions = new ObservableCollection<OptimizationSuggestion>();
            BottleneckLocations = new ObservableCollection<BottleneckLocation>();
        }

        /// <summary>
        /// 加载真实路径数据
        /// </summary>
        private void LoadPathData()
        {
            try
            {
                // 从PathPlanningManager获取所有路径（包括数据库中的历史路径）
                var allRoutes = PathPlanningManager.Instance.GetAllRoutes();

                if (allRoutes == null || allRoutes.Count == 0)
                {
                    LogManager.Info("当前没有可用的路径数据");
                    AnalysisStatus = "暂无可用路径数据，请先规划路径";
                    return;
                }

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

                // 将路径数据转换为UI显示项
                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
                    };

                    // 如果数据库中有分析结果，加载相关数据
                    if (route.CollisionCount.HasValue)
                    {
                        item.CollisionCount = route.CollisionCount.Value;
                        item.Score = (int)route.OverallScore.GetValueOrDefault(0);
                        item.AffectedObjects = route.CollisionCount.Value; // 简化：使用碰撞数作为受影响对象数
                    }
                    else
                    {
                        item.CollisionCount = 0;
                        item.Score = 0;
                        item.AffectedObjects = 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);
                }

                LogManager.Info($"加载路径数据完成：共{AvailablePaths.Count}条路径（包括历史路径）");
                AnalysisStatus = $"已加载 {AvailablePaths.Count} 条路径，请选择要分析的路径";
            }
            catch (Exception ex)
            {
                LogManager.Error($"加载真实路径数据失败: {ex.Message}", ex);
                AnalysisStatus = "加载路径数据失败";
            }
        }


        #endregion

        #region 业务逻辑方法

        /// <summary>
        /// 全选所有路径
        /// </summary>
        private void SelectAll()
        {
            foreach (var path in AvailablePaths)
            {
                path.IsSelected = true;
            }
            CommandManager.InvalidateRequerySuggested();
        }

        /// <summary>
        /// 清空所有选择
        /// </summary>
        private void ClearSelection()
        {
            foreach (var path in AvailablePaths)
            {
                path.IsSelected = false;
            }
            CommandManager.InvalidateRequerySuggested();
        }

        /// <summary>
        /// 更新推荐路径
        /// </summary>
        private void UpdateRecommendedPath()
        {
            try
            {
                if (!SelectedPaths.Any()) return;

                PathAnalysisItem recommended = null;

                switch (AnalysisStrategy)
                {
                    case "安全优先":
                        // 优先选择碰撞次数最少的路径
                        recommended = SelectedPaths.OrderBy(p => p.CollisionCount)
                                                  .ThenBy(p => p.AffectedObjects)
                                                  .FirstOrDefault();
                        break;

                    case "效率优先":
                        // 优先选择路径最短的路径
                        recommended = SelectedPaths.OrderBy(p => p.Length)
                                                  .ThenBy(p => p.EstimatedTime)
                                                  .FirstOrDefault();
                        break;

                    default:
                        // 默认按综合评分选择
                        recommended = SelectedPaths.OrderByDescending(p => p.Score)
                                                  .FirstOrDefault();
                        break;
                }

                RecommendedPath = recommended;
                AnalysisStatus = recommended != null ? $"推荐方案: {recommended.Name}" : "暂无推荐";

                LogManager.Info($"根据{AnalysisStrategy}策略更新推荐路径: {recommended?.Name}");
            }
            catch (Exception ex)
            {
                LogManager.Error($"更新推荐路径失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 执行路径分析
        /// </summary>
        public void PerformAnalysis()
        {
            try
            {
                IsAnalyzing = true;
                AnalysisStatus = "正在分析...";

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

                // 更新选中路径列表用于UI显示
                SelectedPaths.Clear();
                foreach (var route in selectedRoutes)
                {
                    SelectedPaths.Add(route);
                }

                // 执行真实的路径分析
                var result = PathPlanningManager.Instance.AnalyzePathsAndCompare(
                    selectedRoutes.Select(p => p.RouteId).ToList(),
                    AnalysisStrategy
                );

                if (result != null)
                {
                    // 更新UI数据
                    UpdateAnalysisResults(result);
                    AnalysisStatus = "分析完成";
                    LogManager.Info($"路径分析完成，最佳路径: {result.BestRouteName}");
                }
                else
                {
                    AnalysisStatus = "分析失败";
                }

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

        /// <summary>
        /// 导出报告
        /// </summary>
        private void ExportReport()
        {
            try
            {
                if (RecommendedPath == null || SelectedPaths.Count == 0)
                {
                    LogManager.Warning("没有分析结果可以导出");
                    return;
                }

                // 生成报告文件名
                var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                var fileName = $"路径分析报告_{timestamp}.txt";
                var filePath = System.IO.Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                    fileName
                );

                // 生成报告内容
                var report = new System.Text.StringBuilder();
                report.AppendLine("====================================");
                report.AppendLine("       物流路径分析报告");
                report.AppendLine("====================================");
                report.AppendLine();
                report.AppendLine($"生成时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                report.AppendLine($"分析策略：{AnalysisStrategy}");
                report.AppendLine();

                report.AppendLine("【分析路径列表】");
                report.AppendLine("----------------------------------------");
                foreach (var path in SelectedPaths)
                {
                    report.AppendLine($"路径名称：{path.Name}");
                    report.AppendLine($"  - 长度：{path.Length:F2} 米");
                    report.AppendLine($"  - 预估时间：{path.EstimatedTime} 秒");
                    report.AppendLine($"  - 碰撞数量：{path.CollisionCount}");
                    report.AppendLine($"  - 综合评分：{path.Score}");
                    report.AppendLine();
                }

                report.AppendLine("【推荐路径】");
                report.AppendLine("----------------------------------------");
                if (RecommendedPath != null)
                {
                    report.AppendLine($"推荐路径：{RecommendedPath.Name}");
                    report.AppendLine($"推荐理由：基于{AnalysisStrategy}策略，该路径具有最优综合评分");
                    report.AppendLine();
                }

                report.AppendLine("【优化建议】");
                report.AppendLine("----------------------------------------");
                if (OptimizationSuggestions.Count > 0)
                {
                    int index = 1;
                    foreach (var suggestion in OptimizationSuggestions)
                    {
                        report.AppendLine($"{index}. {suggestion.Title}");
                        index++;
                    }
                }
                else
                {
                    report.AppendLine("暂无优化建议");
                }

                // 写入文件
                System.IO.File.WriteAllText(filePath, report.ToString(), System.Text.Encoding.UTF8);

                AnalysisStatus = $"报告已导出到：{filePath}";
                LogManager.Info($"分析报告已导出：{filePath}");

                // 打开文件所在目录并选中文件
                System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{filePath}\"");
            }
            catch (Exception ex)
            {
                LogManager.Error($"导出报告失败：{ex.Message}", ex);
                AnalysisStatus = "导出报告失败";
            }
        }

        /// <summary>
        /// 判断是否可以导出报告
        /// </summary>
        private bool CanExportReport()
        {
            return SelectedPaths != null && SelectedPaths.Count > 0 && RecommendedPath != null;
        }

        /// <summary>
        /// 更新分析结果到UI
        /// </summary>
        private void UpdateAnalysisResults(PathComparisonResult result)
        {
            // 更新路径的碰撞和评分数据
            foreach (var analysis in result.Analyses)
            {
                // 更新AvailablePaths中的数据
                var pathItem = AvailablePaths.FirstOrDefault(p => p.RouteId == analysis.RouteId);
                if (pathItem != null)
                {
                    pathItem.CollisionCount = analysis.CollisionCount;
                    pathItem.Score = (int)analysis.OverallScore;
                    pathItem.AverageSpeed = pathItem.Length / pathItem.EstimatedTime;
                    pathItem.AffectedObjects = analysis.CollisionCount; // 简化：使用碰撞数作为受影响对象数
                }

                // 同时更新SelectedPaths中的数据
                var selectedItem = SelectedPaths.FirstOrDefault(p => p.RouteId == analysis.RouteId);
                if (selectedItem != null)
                {
                    selectedItem.CollisionCount = analysis.CollisionCount;
                    selectedItem.Score = (int)analysis.OverallScore;
                    selectedItem.AverageSpeed = selectedItem.Length / selectedItem.EstimatedTime;
                    selectedItem.AffectedObjects = analysis.CollisionCount;
                }
            }

            // 设置推荐路径
            RecommendedPath = SelectedPaths.FirstOrDefault(p => p.RouteId == result.BestRouteId);

            // 更新优化建议
            OptimizationSuggestions.Clear();
            foreach (var suggestion in result.Suggestions)
            {
                OptimizationSuggestions.Add(new OptimizationSuggestion
                {
                    Title = suggestion,
                    Priority = "中",
                    Status = "待处理"
                });
            }
        }

        #endregion

        #region INotifyPropertyChanged实现

        public event PropertyChangedEventHandler PropertyChanged;

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

        #endregion
    }

    #region 数据模型

    /// <summary>
    /// 路径分析项目
    /// </summary>
    public class PathAnalysisItem : INotifyPropertyChanged
    {
        private bool _isSelected;
        private int _collisionCount;
        private int _affectedObjects;
        private double _averageSpeed;
        private int _score;

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

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

        /// <summary>路径类型</summary>
        public string Type { get; set; }

        /// <summary>路径长度(米)</summary>
        public double Length { get; set; }

        /// <summary>估算时间(秒)</summary>
        public int EstimatedTime { get; set; }

        /// <summary>碰撞次数</summary>
        public int CollisionCount
        {
            get => _collisionCount;
            set
            {
                _collisionCount = value;
                OnPropertyChanged();
            }
        }

        /// <summary>受影响对象数</summary>
        public int AffectedObjects
        {
            get => _affectedObjects;
            set
            {
                _affectedObjects = value;
                OnPropertyChanged();
            }
        }

        /// <summary>平均速度(m/s)</summary>
        public double AverageSpeed
        {
            get => _averageSpeed;
            set
            {
                _averageSpeed = value;
                OnPropertyChanged();
            }
        }

        /// <summary>综合评分</summary>
        public int Score
        {
            get => _score;
            set
            {
                _score = value;
                OnPropertyChanged();
            }
        }

        /// <summary>是否被选中用于分析</summary>
        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));
        }
    }

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

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

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

        /// <summary>状态</summary>
        public string Status { get; set; }
    }

    /// <summary>
    /// 瓶颈位置
    /// </summary>
    public class BottleneckLocation
    {
        /// <summary>位置名称</summary>
        public string Name { get; set; }

        /// <summary>影响路径数</summary>
        public int AffectedPaths { get; set; }

        /// <summary>严重程度</summary>
        public string Severity { get; set; }

        /// <summary>改进建议</summary>
        public string Suggestion { get; set; }
    }

    #endregion
}