using System;
using System.Windows;
using System.Windows.Controls;
using NavisworksTransport.UI.WPF.ViewModels;
using NavisworksTransport.UI.WPF.Views;
using NavisworksTransport.Utils;
using NavisApplication = Autodesk.Navisworks.Api.Application;

namespace NavisworksTransport.UI.WPF
{
    /// <summary>
    /// LogisticsControlPanel.xaml 的交互逻辑
    /// </summary>
    public partial class LogisticsControlPanel : UserControl
    {
        // ViewModel实例
        public LogisticsControlViewModel ViewModel { get; private set; }
        public SystemManagementViewModel SystemManagementViewModel { get; private set; }

        // 分层管理视图
        private LayerManagementView _layerManagementView;

        // 类别设置视图
        private ModelSettingsView _modelSettingsView;

        // 动画控制视图
        public AnimationControlView AnimationControlView { get; private set; }

        // 批处理任务管理视图
        private BatchTaskManagementView _batchTaskManagementView;

        // 管理器实例
        private PathPlanningManager _pathPlanningManager;
        private static bool _isSessionInitialized = false;

        public LogisticsControlPanel()
        {
            InitializeComponent();

            // 创建并设置ViewModel
            ViewModel = new LogisticsControlViewModel();
            SystemManagementViewModel = new SystemManagementViewModel(ViewModel); // 传递主ViewModel引用
            DataContext = ViewModel;

            // 为SystemManagementView设置独立的DataContext
            SystemManagementView.DataContext = SystemManagementViewModel;

            InitializeSession();
            InitializeViews();
            InitializeEventHandlers();
        }

        // 注意：现在使用XAML定义的界面，不再需要手动创建

        /// <summary>
        /// 初始化子视图
        /// </summary>
        private void InitializeViews()
        {
            try
            {
                LogManager.Info("开始初始化子视图");

                // 创建分层管理视图，传入主ViewModel以启用统一状态栏
                _layerManagementView = new LayerManagementView(ViewModel);

                // 将分层管理视图添加到主界面
                LayerManagementContent.Content = _layerManagementView;

                // 创建类别设置视图，传入主ViewModel引用以启用统一状态栏
                _modelSettingsView = new ModelSettingsView(ViewModel);

                // 将类别设置视图添加到主界面
                ModelSettingsContent.Content = _modelSettingsView;

                // 初始化PathEditingView（必须在InitializeAnimationControlView之前，因为需要同步参数）
                InitializePathEditingView();

                // AnimationControlView已经在XAML中定义，在这里初始化其数据绑定
                // 确保AnimationControlView能够接收当前选中的路径
                InitializeAnimationControlView();

                // 初始化SystemManagementView
                InitializeSystemManagementView();

                // 初始化BatchTaskManagementView
                InitializeBatchTaskManagementView();

                LogManager.Info("子视图初始化完成");
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化子视图失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 初始化插件会话
        /// </summary>
        private void InitializeSession()
        {
            GlobalExceptionHandler.SafeExecute(() =>
            {
                if (!_isSessionInitialized)
                {
                    LogManager.Info("=== 物流路径规划插件初始化开始 ===");

                    // 全局异常处理器已在Main构造函数中初始化，此处无需重复初始化

                    // 初始化路径规划管理器
                    InitializePathPlanningManager();

                    LogManager.Info("插件会话初始化完成");
                    _isSessionInitialized = true;
                }
            }, "初始化会话");
        }

        /// <summary>
        /// 初始化路径规划管理器并设置事件订阅
        /// </summary>
        private void InitializePathPlanningManager()
        {
            try
            {
                LogManager.Info("开始初始化PathPlanningManager");

                // 获取或创建唯一的PathPlanningManager实例
                _pathPlanningManager = PathPlanningManager.GetActivePathManager();
                if (_pathPlanningManager == null)
                {
                    _pathPlanningManager = new PathPlanningManager();
                    LogManager.Info("创建了新的PathPlanningManager实例");
                }
                else
                {
                    LogManager.Info("使用已存在的PathPlanningManager实例");
                }

                // 连接文档对应的路径数据库（覆盖插件后于文档加载的场景）
                var activeDoc = NavisApplication.ActiveDocument;
                if (!string.IsNullOrEmpty(activeDoc?.FileName))
                {
                    _pathPlanningManager.DatabaseInitialize(createIfMissing: false);
                }

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

        /// <summary>
        /// 初始化AnimationControlView
        /// </summary>
        private void InitializeAnimationControlView()
        {
            try
            {
                // 创建AnimationControlView，传入主ViewModel引用
                var newAnimationControlView = new AnimationControlView(ViewModel);

                // 设置到ContentControl中
                if (AnimationControlContent != null)
                {
                    AnimationControlContent.Content = newAnimationControlView;

                    // 更新引用
                    AnimationControlView = newAnimationControlView;

                    // 设置PathPlanningManager（用于批处理队列功能）
                    if (AnimationControlView?.ViewModel != null && _pathPlanningManager != null)
                    {
                        AnimationControlView.ViewModel.SetPathPlanningManager(_pathPlanningManager);
                        LogManager.Info("AnimationControlView初始化完成 - 已设置PathPlanningManager");
                    }

                    // 初始化时同步物体参数
                    SyncObjectParametersToAnimationView();

                    LogManager.Info("AnimationControlView初始化完成 - 支持统一状态栏和虚拟物体");
                }
                else
                {
                    LogManager.Error("AnimationControlContent占位符未找到");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化AnimationControlView失败: {ex.Message}");
            }
        }

        /// <summary>
        /// PathEditingView引用
        /// </summary>
        private PathEditingView PathEditingView;

        /// <summary>
        /// 初始化PathEditingView
        /// </summary>
        private void InitializePathEditingView()
        {
            try
            {
                // 创建PathEditingView，传入主ViewModel引用
                var newPathEditingView = new PathEditingView(ViewModel);

                // 设置到ContentControl中
                if (PathEditingContent != null)
                {
                    PathEditingContent.Content = newPathEditingView;

                    // 更新引用
                    PathEditingView = newPathEditingView;
                }

                if (PathEditingView?.ViewModel != null)
                {
                    // 将PathPlanningManager传递给PathEditingView
                    PathEditingView.ViewModel.PathPlanningManager = _pathPlanningManager;

                    LogManager.Info("PathEditingView初始化完成 - 支持统一状态栏");
                }
                else
                {
                    LogManager.Error("PathEditingContent占位符未找到");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化PathEditingView失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 初始化SystemManagementView
        /// </summary>
        private void InitializeSystemManagementView()
        {
            try
            {
                if (SystemManagementView?.DataContext != null)
                {
                    LogManager.Info("SystemManagementView初始化完成");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化SystemManagementView失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 初始化BatchTaskManagementView
        /// </summary>
        private void InitializeBatchTaskManagementView()
        {
            try
            {
                // 创建批处理任务管理视图，传入主ViewModel
                var newBatchTaskManagementView = new BatchTaskManagementView(ViewModel);

                // 设置到ContentControl
                if (BatchTaskManagementContent != null)
                {
                    BatchTaskManagementContent.Content = newBatchTaskManagementView;
                }
                else
                {
                    LogManager.Error("BatchTaskManagementContent占位符未找到");
                }

                _batchTaskManagementView = newBatchTaskManagementView;
                
                // 设置PathPlanningManager（类似PathEditingView的设置方式）
                if (_batchTaskManagementView?.ViewModel != null && _pathPlanningManager != null)
                {
                    _batchTaskManagementView.ViewModel.SetPathPlanningManager(_pathPlanningManager);
                    LogManager.Info("BatchTaskManagementView初始化完成 - 已设置PathPlanningManager");
                }
                
                LogManager.Info("BatchTaskManagementView初始化完成");
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化BatchTaskManagementView失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 初始化事件处理器
        /// </summary>
        private void InitializeEventHandlers()
        {
            try
            {
                // 订阅Navisworks选择变化事件
                if (NavisApplication.ActiveDocument != null)
                {
                    NavisApplication.ActiveDocument.CurrentSelection.Changed += OnSelectionChanged;
                }

                // 订阅TabControl选择变化事件
                if (MainTabControl != null)
                {
                    MainTabControl.SelectionChanged += OnTabSelectionChanged;
                }

                // 订阅主ViewModel的路径选择变化事件
                if (ViewModel != null)
                {
                    ViewModel.PropertyChanged += OnMainViewModelPropertyChanged;
                }

                // 订阅PathEditingView的路径选择变化事件
                if (PathEditingView?.ViewModel != null)
                {
                    PathEditingView.ViewModel.PropertyChanged += OnPathEditingViewModelPropertyChanged;
                }

                LogManager.Info("事件处理器初始化完成");
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化事件处理器失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 帮助按钮点击事件
        /// </summary>
        private void HelpButton_Click(object sender, RoutedEventArgs e)
        {
            GlobalExceptionHandler.SafeExecute(() =>
            {
                DialogHelper.ShowDialog(new Views.HelpDialog(), this);
            }, "显示帮助");
        }

        /// <summary>
        /// 关于按钮点击事件
        /// </summary>
        private void AboutButton_Click(object sender, RoutedEventArgs e)
        {
            GlobalExceptionHandler.SafeExecute(() =>
            {
                DialogHelper.ShowDialog(new Views.AboutDialog(), this);
            }, "显示关于");
        }

        /// <summary>
        /// 清理资源和事件订阅
        /// </summary>
        public void Cleanup()
        {
            try
            {
                LogManager.Info("开始清理LogisticsControlPanel资源");

                // 取消Navisworks事件订阅
                if (NavisApplication.ActiveDocument != null)
                {
                    NavisApplication.ActiveDocument.CurrentSelection.Changed -= OnSelectionChanged;
                }

                // 取消TabControl事件订阅
                if (MainTabControl != null)
                {
                    MainTabControl.SelectionChanged -= OnTabSelectionChanged;
                }

                // 取消主ViewModel事件订阅
                if (ViewModel != null)
                {
                    ViewModel.PropertyChanged -= OnMainViewModelPropertyChanged;
                }

                // 取消PathEditingView事件订阅
                if (PathEditingView?.ViewModel != null)
                {
                    PathEditingView.ViewModel.PropertyChanged -= OnPathEditingViewModelPropertyChanged;
                }

                // 清理AnimationControlView
                AnimationControlView?.Cleanup();

                // 清理PathEditingView
                PathEditingView?.Cleanup();

                // 🔧 修复：清理ModelSettingsView（会调用ViewModel的Dispose）
                _modelSettingsView?.Cleanup();

                // 🔧 修复：清理LayerManagementView（会调用ViewModel的Dispose）
                _layerManagementView?.Cleanup();

                // 清理SystemManagementViewModel
                SystemManagementViewModel?.Cleanup();

                // 清理 Clash Detective 集成
                GlobalExceptionHandler.CleanupClashDetectiveIntegration();

                LogManager.Info("LogisticsControlPanel资源清理完成");
            }
            catch (Exception ex)
            {
                LogManager.Error($"清理LogisticsControlPanel资源失败: {ex.Message}");
            }
        }

        #region 事件处理器

        /// <summary>
        /// TabControl选择变化事件处理
        /// </summary>
        private void OnTabSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (e.Source is TabControl tabControl && e.AddedItems.Count > 0)
                {
                    var selectedTab = e.AddedItems[0] as TabItem;
                    if (selectedTab?.Name == "AnimationControlTab")
                    {
                        // 当切换到动画控制页签时，同步当前选中的路径
                        SyncCurrentPathToAnimationView();
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"TabControl选择变化处理失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 主ViewModel属性变化事件处理
        /// </summary>
        private void OnMainViewModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            try
            {
                // 主ViewModel已不再包含路径相关属性，路径管理由PathEditingViewModel负责
                // 这里可以处理其他属性变化事件
            }
            catch (Exception ex)
            {
                LogManager.Error($"主ViewModel属性变化处理失败: {ex.Message}");
            }
        }

        /// <summary>
        /// PathEditingViewModel属性变化事件处理
        /// </summary>
        private void OnPathEditingViewModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            try
            {
                if (e.PropertyName == nameof(PathEditingViewModel.SelectedPathRoute))
                {
                    // 当PathEditingViewModel的选中路径变化时，同步到AnimationControlView
                    SyncCurrentPathToAnimationView();
                    LogManager.Info("PathEditingView路径选择已变化，同步到动画控制视图");
                }
                // 当物体参数变化时，同步到AnimationControlView
                else if (e.PropertyName == nameof(PathEditingViewModel.ObjectLength) ||
                         e.PropertyName == nameof(PathEditingViewModel.ObjectWidth) ||
                         e.PropertyName == nameof(PathEditingViewModel.ObjectHeight) ||
                         e.PropertyName == nameof(PathEditingViewModel.SafetyMargin))
                {
                    SyncObjectParametersToAnimationView();
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"PathEditingViewModel属性变化处理失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步物体参数到动画控制视图
        /// </summary>
        private void SyncObjectParametersToAnimationView()
        {
            try
            {
                if (AnimationControlView?.ViewModel != null && PathEditingView?.ViewModel != null)
                {
                    var pathEditingVM = PathEditingView.ViewModel;
                    AnimationControlView.ViewModel.SetVirtualObjectParameters(
                        pathEditingVM.ObjectLength,
                        pathEditingVM.ObjectWidth,
                        pathEditingVM.ObjectHeight,
                        pathEditingVM.SafetyMargin
                    );
                    LogManager.Debug($"物体参数已同步到动画控制视图: {pathEditingVM.ObjectLength:F1}×{pathEditingVM.ObjectWidth:F1}×{pathEditingVM.ObjectHeight:F1}m, 检测间隙: {pathEditingVM.SafetyMargin:F2}m");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"同步物体参数到动画控制视图失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步当前路径到动画控制视图
        /// </summary>
        private void SyncCurrentPathToAnimationView()
        {
            try
            {
                if (AnimationControlView?.ViewModel != null)
                {
                    // 优先从PathEditingView获取选中的路径
                    PathRouteViewModel selectedPath = null;

                    if (PathEditingView?.ViewModel?.SelectedPathRoute != null)
                    {
                        selectedPath = PathEditingView.ViewModel.SelectedPathRoute;
                        LogManager.Info($"从PathEditingView同步路径: {selectedPath.Name}");
                    }

                    if (selectedPath != null)
                    {
                        AnimationControlView.ViewModel.SetCurrentPath(selectedPath);
                        LogManager.Info($"路径已同步到动画控制视图: {selectedPath.Name}");
                    }
                    else
                    {
                        // 清空动画控制视图的路径
                        AnimationControlView.ViewModel.SetCurrentPath(null);
                        LogManager.Info("已清空动画控制视图的路径");
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"同步路径到动画控制视图失败: {ex.Message}");
            }
        }

        private void OnSelectionChanged(object sender, EventArgs e)
        {
            // 使用Dispatcher确保在UI线程上更新ViewModel
            Dispatcher.BeginInvoke(new Action(async () =>
            {
                // 同时更新分层管理视图的ViewModel
                if (_layerManagementView?.ViewModel != null)
                {
                    await _layerManagementView.ViewModel.UpdateCurrentSelectionAsync();
                }

                // 同时更新类别设置视图的ViewModel
                if (_modelSettingsView?.DataContext is ModelSettingsViewModel modelSettingsViewModel)
                {
                    if (modelSettingsViewModel.RefreshSelectionCommand.CanExecute(null))
                    {
                        modelSettingsViewModel.RefreshSelectionCommand.Execute(null);
                    }
                }
            }));
        }

        // TODO: 其他事件处理器将在后续任务中实现
        // 暂时注释掉避免编译错误

        #endregion
    }
}