using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using NavisworksTransport.Core.Config;
using NavisworksTransport.PathPlanning;

namespace NavisworksTransport.UI.WPF.ViewModels
{
    /// <summary>
    /// 时间标签视图模型
    /// 用于时间标签设置对话框的数据绑定和业务逻辑
    /// </summary>
    public class TimeTagViewModel : INotifyPropertyChanged
    {
        #region 字段

        private double _defaultSpeed;
        private bool _useElementSpeedLimit = true;
        private bool _isCalculating = false;
        private double _totalDuration;
        private string _selectedRoute;
        private readonly TimeMarkerCalculationService _timeCalculationService;
        private PathPlanningManager _pathPlanningManager;

        #endregion

        #region 属性

        /// <summary>
        /// 默认速度 (m/s)
        /// </summary>
        public double DefaultSpeed
        {
            get => _defaultSpeed;
            set
            {
                _defaultSpeed = value;
                OnPropertyChanged();
                // 速度改变时重新计算时间
                RecalculateTimeSegments();
            }
        }

        /// <summary>
        /// 是否使用元素限速优先
        /// </summary>
        public bool UseElementSpeedLimit
        {
            get => _useElementSpeedLimit;
            set
            {
                _useElementSpeedLimit = value;
                OnPropertyChanged();
                // 限速设置改变时重新计算
                RecalculateTimeSegments();
            }
        }

        /// <summary>
        /// 是否正在计算
        /// </summary>
        public bool IsCalculating
        {
            get => _isCalculating;
            set
            {
                _isCalculating = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 总时长 (秒)
        /// </summary>
        public double TotalDuration
        {
            get => _totalDuration;
            set
            {
                _totalDuration = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(TotalDurationText));
            }
        }

        /// <summary>
        /// 总时长文本显示
        /// </summary>
        public string TotalDurationText => $"{TotalDuration:F1}秒";

        /// <summary>
        /// 选中的路径名称
        /// </summary>
        public string SelectedRoute
        {
            get => _selectedRoute;
            set
            {
                _selectedRoute = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 时间分段列表
        /// </summary>
        public ObservableCollection<TimeSegmentItem> TimeSegments { get; set; }

        /// <summary>
        /// 时间轴预览项目列表
        /// </summary>
        public ObservableCollection<TimelinePreviewItem> TimelineItems { get; set; }

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化时间标签视图模型
        /// </summary>
        public TimeTagViewModel()
        {
            try
            {
                // 从配置读取默认速度
                var config = ConfigManager.Instance.Current;
                _defaultSpeed = config.Logistics.SpeedLimitMetersPerSecond;

                _timeCalculationService = new TimeMarkerCalculationService();
                _pathPlanningManager = PathPlanningManager.GetActivePathManager();

                InitializeCollections();
                LoadRouteData(_pathPlanningManager.CurrentRoute);

                LogManager.Info($"TimeTagViewModel初始化完成 - 默认速度: {_defaultSpeed:F1}m/s（来自配置）");
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化TimeTagViewModel失败: {ex.Message}", ex);
            }
        }

        #endregion

        #region 初始化方法

        /// <summary>
        /// 初始化集合
        /// </summary>
        private void InitializeCollections()
        {
            TimeSegments = new ObservableCollection<TimeSegmentItem>();
            TimelineItems = new ObservableCollection<TimelinePreviewItem>();
        }

        /// <summary>
        /// 从真实路径数据加载时间分段
        /// </summary>
        /// <param name="route">路径数据</param>
        private void LoadRouteData(PathRoute route)
        {
            try
            {
                if (route == null)
                {
                    LogManager.Info("路径为空，加载演示数据");
                    return;
                }

                LogManager.Info($"开始从路径 '{route.Name}' 加载真实时间数据");

                // 使用TimeMarkerCalculationService计算时间分段
                var result = _timeCalculationService.CalculateTimeMarkers(route);

                if (!result.IsSuccessful)
                {
                    LogManager.Warning($"时标计算失败: {result.ErrorMessage}，回退到演示数据");
                    return;
                }

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

                // 添加路径分段数据
                for (int i = 0; i < result.Segments.Count; i++)
                {
                    var segment = result.Segments[i];
                    var segmentItem = new TimeSegmentItem
                    {
                        Index = i + 1,
                        Length = segment.Distance,
                        Speed = segment.SpeedLimit,
                        Duration = segment.Time,
                        CumulativeTime = segment.CumulativeTime,
                        Remarks = segment.IsValid ? $"{segment.StartPointName}->{segment.EndPointName}" : "无限速"
                    };
                    TimeSegments.Add(segmentItem);
                }

                // 更新总时长（使用实际计算时间，不添加额外等待）
                TotalDuration = result.TotalTime;

                // 更新选中路径名称
                SelectedRoute = route.Name;

                // 生成时间轴预览数据
                GenerateTimelineItems();

                LogManager.Info($"真实时间数据加载完成: 总距离 {result.TotalDistance:F2}m, 总时间 {result.TotalTime:F2}s");
            }
            catch (Exception ex)
            {
                LogManager.Error($"加载路径时间数据失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 生成时间轴预览数据
        /// </summary>
        private void GenerateTimelineItems()
        {
            try
            {
                TimelineItems.Clear();

                if (TotalDuration <= 0) return;

                // 为每个真实路径分段生成时间轴项目（只处理真实的路径段，不包括等待时间）
                foreach (var segment in TimeSegments.Where(s => s.Index > 0))
                {
                    var timelineItem = new TimelinePreviewItem
                    {
                        Name = segment.Remarks, // 使用真实的路径点名称（如"自动起点->自动点1"）
                        Duration = segment.Duration,
                        Color = segment.Index == 1 ? "#FF2B579A" : "#FFFF9800", // 第一段蓝色，其他橙色
                        Percentage = TotalDuration > 0 ? segment.Duration / TotalDuration * 100 : 0
                    };
                    TimelineItems.Add(timelineItem);
                }

                LogManager.Info($"时间轴预览数据生成完成，包含 {TimelineItems.Count} 个项目");
            }
            catch (Exception ex)
            {
                LogManager.Error($"生成时间轴预览数据失败: {ex.Message}", ex);
            }
        }

        #endregion

        #region 业务逻辑方法

        /// <summary>
        /// 重新计算时间分段
        /// </summary>
        private void RecalculateTimeSegments()
        {
            try
            {
                IsCalculating = true;

                // 检查是否有真实路径数据
                if (_pathPlanningManager?.CurrentRoute != null)
                {
                    // 使用真实路径数据重新计算
                    LogManager.Info("使用真实路径数据重新计算时间分段");
                    
                    // 异步计算以避免UI阻塞
                    System.Threading.Tasks.Task.Run(() =>
                    {
                        try
                        {
                            var result = _timeCalculationService.CalculateTimeMarkers(_pathPlanningManager.CurrentRoute);
                            
                            // 在UI线程上更新数据
                            System.Windows.Application.Current.Dispatcher.Invoke(() =>
                            {
                                if (result.IsSuccessful)
                                {
                                    UpdateTimeSegmentsFromCalculation(result);
                                }
                                else
                                {
                                    LogManager.Warning($"重新计算失败: {result.ErrorMessage}");
                                }
                                
                                IsCalculating = false;
                            });
                        }
                        catch (Exception ex)
                        {
                            LogManager.Error($"重新计算时间分段异常: {ex.Message}", ex);
                            System.Windows.Application.Current.Dispatcher.Invoke(() =>
                            {
                                IsCalculating = false;
                            });
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                IsCalculating = false;
                LogManager.Error($"重新计算时间分段失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 从计算结果更新时间分段数据
        /// </summary>
        /// <param name="result">计算结果</param>
        private void UpdateTimeSegmentsFromCalculation(TimeMarkerCalculationService.TimeMarkerResult result)
        {
            try
            {
                // 清空现有数据
                TimeSegments.Clear();

                // 添加路径分段数据
                for (int i = 0; i < result.Segments.Count; i++)
                {
                    var segment = result.Segments[i];
                    var segmentItem = new TimeSegmentItem
                    {
                        Index = i + 1,
                        Length = segment.Distance,
                        Speed = UseElementSpeedLimit ? segment.SpeedLimit : DefaultSpeed,
                        Duration = UseElementSpeedLimit ? segment.Time : (segment.Distance / DefaultSpeed),
                        CumulativeTime = 0, // 稍后重新计算累计时间
                        Remarks = segment.IsValid ? $"{segment.StartPointName}->{segment.EndPointName}" : "无限速"
                    };
                    TimeSegments.Add(segmentItem);
                }

                // 重新计算累计时间
                double cumulativeTime = 0;
                foreach (var segment in TimeSegments.Where(s => s.Index > 0))
                {
                    cumulativeTime += segment.Duration;
                    segment.CumulativeTime = cumulativeTime;
                }

                // 更新总时长（使用实际计算时间，不添加额外等待）
                TotalDuration = cumulativeTime;

                // 重新生成时间轴预览
                GenerateTimelineItems();

                LogManager.Info($"时间分段数据更新完成: 总时长 {TotalDuration:F1}秒");
            }
            catch (Exception ex)
            {
                LogManager.Error($"更新时间分段数据失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 应用时标到路径点
        /// </summary>
        public void ApplyTimeTags()
        {
            try
            {
                LogManager.Info("开始应用时标到路径点");

                // 模拟应用过程
                foreach (var segment in TimeSegments)
                {
                    LogManager.Info($"应用时标 - 段{segment.Index}: 累计时间 {segment.CumulativeTime:F1}秒");
                }

                LogManager.Info("时标应用完成");
            }
            catch (Exception ex)
            {
                LogManager.Error($"应用时标失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 导出时标数据
        /// </summary>
        public void ExportTimeTags()
        {
            try
            {
                LogManager.Info("开始导出时标数据");

                // 模拟导出过程
                var exportData = TimeSegments.Select(s => new
                {
                    Index = s.Index,
                    Length = s.Length,
                    Speed = s.Speed,
                    Duration = s.Duration,
                    CumulativeTime = s.CumulativeTime,
                    Remarks = s.Remarks
                }).ToList();

                LogManager.Info($"时标数据导出完成，共{exportData.Count}个分段");
            }
            catch (Exception ex)
            {
                LogManager.Error($"导出时标数据失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 重置参数 - 从配置读取默认值
        /// </summary>
        public void ResetParameters()
        {
            try
            {
                var config = ConfigManager.Instance.Current;
                DefaultSpeed = config.Logistics.SpeedLimitMetersPerSecond;
                UseElementSpeedLimit = true;
                LogManager.Info($"参数重置完成 - 默认速度: {DefaultSpeed:F1}m/s（来自配置）");
            }
            catch (Exception ex)
            {
                LogManager.Error($"重置参数失败: {ex.Message}", ex);
            }
        }

        #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 TimeSegmentItem : INotifyPropertyChanged
    {
        private double _speed;
        private double _duration;
        private double _cumulativeTime;

        /// <summary>分段序号</summary>
        public int Index { get; set; }

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

        /// <summary>分段速度(m/s)</summary>
        public double Speed
        {
            get => _speed;
            set
            {
                _speed = value;
                OnPropertyChanged();
            }
        }

        /// <summary>分段耗时(秒)</summary>
        public double Duration
        {
            get => _duration;
            set
            {
                _duration = value;
                OnPropertyChanged();
            }
        }

        /// <summary>累计时间(秒)</summary>
        public double CumulativeTime
        {
            get => _cumulativeTime;
            set
            {
                _cumulativeTime = value;
                OnPropertyChanged();
            }
        }

        /// <summary>备注</summary>
        public string Remarks { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

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

    /// <summary>
    /// 时间轴预览项目
    /// </summary>
    public class TimelinePreviewItem
    {
        /// <summary>分段名称</summary>
        public string Name { get; set; }

        /// <summary>持续时间(秒)</summary>
        public double Duration { get; set; }

        /// <summary>颜色</summary>
        public string Color { get; set; }

        /// <summary>百分比</summary>
        public double Percentage { get; set; }
    }

    #endregion
}