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

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// LayerManagementView.xaml 的交互逻辑
    /// 分层管理页签视图的代码后端
    /// </summary>
    public partial class LayerManagementView : UserControl
    {
        /// <summary>
        /// 关联的ViewModel
        /// </summary>
        public LayerManagementViewModel ViewModel { get; private set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public LayerManagementView()
        {
            InitializeComponent();
            
            // 初始化ViewModel
            ViewModel = new LayerManagementViewModel();
            DataContext = ViewModel;
        }

        /// <summary>
        /// 带主ViewModel参数的构造函数，支持统一状态栏
        /// </summary>
        /// <param name="mainViewModel">主ViewModel，用于统一状态栏</param>
        public LayerManagementView(LogisticsControlViewModel mainViewModel)
        {
            InitializeComponent();
            
            // 创建ViewModel，传入主ViewModel引用
            ViewModel = new LayerManagementViewModel(mainViewModel);
            DataContext = ViewModel;
        }

        /// <summary>
        /// 带ViewModel参数的构造函数
        /// </summary>
        /// <param name="viewModel">预初始化的ViewModel</param>
        public LayerManagementView(LayerManagementViewModel viewModel)
        {
            InitializeComponent();
            
            ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel));
            DataContext = ViewModel;
        }

        /// <summary>
        /// 页面加载事件
        /// </summary>
        private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                // 页面加载时刷新当前选择状态
                _ = ViewModel?.UpdateCurrentSelectionAsync();
            }
            catch (Exception ex)
            {
                LogManager.Error($"[LayerManagementView] 页面加载失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 页面卸载事件
        /// </summary>
        private void UserControl_Unloaded(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                // 清理资源
                ViewModel?.Dispose();
            }
            catch (Exception ex)
            {
                LogManager.Error($"[LayerManagementView] 页面卸载失败: {ex.Message}");
            }
        }

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