using System;
using System.Windows.Controls;
using NavisworksTransport.UI.WPF.ViewModels;

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// AnimationControlView.xaml 的交互逻辑
    /// 检测动画页签视图，提供动画控制和碰撞检测功能
    /// </summary>
    public partial class AnimationControlView : UserControl
    {
        /// <summary>
        /// 动画控制视图模型
        /// </summary>
        public AnimationControlViewModel ViewModel { get; private set; }

        public AnimationControlView() : this(null)
        {
            // 调用带参数的构造函数，传入null
        }

        /// <summary>
        /// 带主ViewModel参数的构造函数，支持统一状态栏
        /// </summary>
        /// <param name="mainViewModel">主ViewModel，用于统一状态栏</param>
        public AnimationControlView(LogisticsControlViewModel mainViewModel)
        {
            InitializeComponent();
            InitializeViewModel(mainViewModel);
        }

        /// <summary>
        /// 初始化ViewModel
        /// </summary>
        private void InitializeViewModel()
        {
            try
            {
                ViewModel = new AnimationControlViewModel();
                DataContext = ViewModel;
                SubscribeToViewModelEvents();
                LogManager.Info("AnimationControlView ViewModel初始化完成");
            }
            catch (Exception ex)
            {
                LogManager.Error($"AnimationControlView ViewModel初始化失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 初始化ViewModel（支持统一状态栏）
        /// </summary>
        /// <param name="mainViewModel">主ViewModel，用于统一状态栏</param>
        private void InitializeViewModel(LogisticsControlViewModel mainViewModel)
        {
            try
            {
                ViewModel = new AnimationControlViewModel(mainViewModel);
                DataContext = ViewModel;
                SubscribeToViewModelEvents();
                LogManager.Info("AnimationControlView ViewModel初始化完成 - 支持统一状态栏");
            }
            catch (Exception ex)
            {
                LogManager.Error($"AnimationControlView ViewModel初始化失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 订阅ViewModel事件
        /// </summary>
        private void SubscribeToViewModelEvents()
        {
            if (ViewModel == null) return;
            
            // 订阅滚动到历史记录事件
            ViewModel.RequestScrollToClashDetectiveResult += OnRequestScrollToClashDetectiveResult;
        }

        /// <summary>
        /// 处理滚动到碰撞历史记录请求
        /// </summary>
        private void OnRequestScrollToClashDetectiveResult(object sender, ClashDetectiveResultViewModel e)
        {
            try
            {
                // 查找历史记录列表的ListView（通过可视化树查找）
                var listView = FindClashDetectiveResultsListView();
                if (listView != null && e != null)
                {
                    // 使用Dispatcher确保UI更新后再滚动
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        listView.ScrollIntoView(e);
                        LogManager.Debug($"[AnimationControlView] 已滚动到历史记录: {e.Record?.TestName}");
                    }), System.Windows.Threading.DispatcherPriority.Background);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[AnimationControlView] 滚动到历史记录失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 查找碰撞历史记录ListView控件
        /// </summary>
        private System.Windows.Controls.ListView FindClashDetectiveResultsListView()
        {
            try
            {
                // 通过名称查找控件（需要在XAML中设置x:Name）
                return this.FindName("ClashDetectiveResultsListView") as System.Windows.Controls.ListView;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 清理资源
        /// </summary>
        public void Cleanup()
        {
            try
            {
                ViewModel?.Dispose();
                LogManager.Info("AnimationControlView资源清理完成");
            }
            catch (Exception ex)
            {
                LogManager.Error($"AnimationControlView资源清理失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 碰撞检测结果选择变化事件处理
        /// </summary>
        private void OnClashDetectiveResultSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ViewModel == null) return;

                // 获取选中的结果
                var listView = sender as ListView;
                if (listView?.SelectedItem is ClashDetectiveResultViewModel selectedResult)
                {
                    ViewModel.SelectedClashDetectiveResult = selectedResult;
                }
                else
                {
                    ViewModel.SelectedClashDetectiveResult = null;
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[AnimationControlView] 处理碰撞检测结果选择变化失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 碰撞构件选择变化事件处理 - 点选时高亮并聚焦对象
        /// </summary>
        private void OnCollisionObjectSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ViewModel == null || ViewModel.SelectedClashDetectiveResult == null) return;

                // 获取选中的构件
                var listView = sender as ListView;
                if (listView?.SelectedItem is CollisionObjectViewModel selectedObject)
                {
                    // 触发高亮
                    ViewModel.SelectedClashDetectiveResult.ExecuteHighlightCollisionObject(selectedObject);
                    // 聚焦到对象
                    ViewModel.FocusOnCollisionObject(selectedObject);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[AnimationControlView] 处理碰撞构件选择变化失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 排除对象列表选择变化事件处理 - 点选时高亮并聚焦单个对象
        /// </summary>
        private void ExcludedObjectsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ViewModel == null) return;

                // 获取选中的排除对象
                var listView = sender as ListView;
                if (listView?.SelectedItem is ExcludedObjectViewModel selectedObject)
                {
                    // 高亮单个对象
                    ViewModel.HighlightSingleExcludedObject(selectedObject);
                    // 聚焦到对象
                    ViewModel.FocusOnExcludedObject(selectedObject);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[AnimationControlView] 处理排除对象选择变化失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 手工指定对象列表选择变化事件处理 - 单击时聚焦到对象
        /// </summary>
        private void OnManualTargetSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ViewModel == null) return;

                // 获取选中的对象
                var listView = sender as ListView;
                if (listView?.SelectedItem is ManualCollisionTargetViewModel selectedTarget)
                {
                    // 聚焦到对象
                    ViewModel.FocusOnManualTarget(selectedTarget);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[AnimationControlView] 处理手工指定对象选择变化失败: {ex.Message}", ex);
            }
        }
    }
}