using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using NavisworksTransport.Core;
using NavisworksTransport.Core.Models;
using NavisworksTransport.Commands;

namespace NavisworksTransport.UI.WPF.ViewModels
{
    /// <summary>
    /// 批处理队列管理ViewModel - 简化的FIFO队列界面
    /// </summary>
    public class BatchTaskManagementViewModel : ViewModelBase
    {
        #region 字段

        private PathPlanningManager _pathPlanningManager;
        private BatchQueueManager _queueManager;
        private readonly UIStateManager _uiStateManager;

        private ObservableCollection<BatchQueueItem> _queueItems;
        private BatchQueueItem _selectedItem;
        private BatchQueueStatus _statusFilter = BatchQueueStatus.All;
        private string _progressText;
        private bool _isExecuting;
        private bool _useMultiProcess = true; // 默认开启，构造函数从配置加载

        #endregion

        #region 属性

        /// <summary>
        /// 队列项列表
        /// </summary>
        public ObservableCollection<BatchQueueItem> QueueItems
        {
            get => _queueItems;
            set => SetProperty(ref _queueItems, value);
        }

        /// <summary>
        /// 选中的队列项
        /// </summary>
        public BatchQueueItem SelectedItem
        {
            get => _selectedItem;
            set => SetProperty(ref _selectedItem, value);
        }

        /// <summary>
        /// 状态筛选器
        /// </summary>
        public BatchQueueStatus StatusFilter
        {
            get => _statusFilter;
            set
            {
                if (SetProperty(ref _statusFilter, value))
                {
                    _ = LoadQueueItemsAsync();
                }
            }
        }

        /// <summary>
        /// 进度文本
        /// </summary>
        public string ProgressText
        {
            get => _progressText;
            set => SetProperty(ref _progressText, value);
        }

        /// <summary>
        /// 是否启用多进程并行批处理（绑定 config.toml [batch] use_multi_process，默认开启）
        /// </summary>
        public bool UseMultiProcess
        {
            get => _useMultiProcess;
            set
            {
                if (SetProperty(ref _useMultiProcess, value))
                {
                    // 同步并保存到配置
                    var config = NavisworksTransport.Core.Config.ConfigManager.Instance.Current;
                    if (config?.Batch != null)
                    {
                        config.Batch.UseMultiProcess = value;
                        NavisworksTransport.Core.Config.ConfigManager.Instance.SaveConfig(config, notifyChange: false);
                    }
                }
            }
        }

        /// <summary>
        /// 是否正在执行
        /// </summary>
        public bool IsExecuting
        {
            get => _isExecuting;
            set => SetProperty(ref _isExecuting, value);
        }

        /// <summary>
        /// 是否可以执行队列
        /// </summary>
        public bool CanExecuteQueue => !IsExecuting && HasPendingItems;

        /// <summary>
        /// 是否可以停止执行
        /// </summary>
        public bool CanStopExecution => IsExecuting;

        /// <summary>
        /// 是否可以删除选中项
        /// </summary>
        public bool CanDeleteItem => SelectedItem != null && 
            (SelectedItem.Status == BatchQueueStatus.Pending || 
             SelectedItem.Status == BatchQueueStatus.Completed || 
             SelectedItem.Status == BatchQueueStatus.Failed);

        /// <summary>
        /// 是否可以查看报告
        /// </summary>
        public bool CanViewReport => SelectedItem != null && SelectedItem.Status == BatchQueueStatus.Completed;

        /// <summary>
        /// 是否有待处理项
        /// </summary>
        public bool HasPendingItems => QueueItems?.Any(item => item.Status == BatchQueueStatus.Pending) ?? false;

        #endregion

        #region 命令

        public ICommand ExecuteQueueCommand { get; }
        public ICommand StopExecutionCommand { get; }
        public ICommand DeleteItemCommand { get; }
        public ICommand ViewReportCommand { get; }
        public ICommand RefreshCommand { get; }

        #endregion

        #region 构造函数

        public BatchTaskManagementViewModel()
        {
            try
            {
                _pathPlanningManager = null;
                _queueManager = null;
                _uiStateManager = UIStateManager.Instance;

                _queueItems = new ObservableCollection<BatchQueueItem>();

                // 从配置加载多进程开关（默认开启）
                var batchConfig = NavisworksTransport.Core.Config.ConfigManager.Instance.Current?.Batch;
                if (batchConfig != null)
                {
                    _useMultiProcess = batchConfig.UseMultiProcess;
                }

                // 初始化命令
                ExecuteQueueCommand = new RelayCommand(async () => await ExecuteQueueAsync(), () => CanExecuteQueue);
                StopExecutionCommand = new RelayCommand(StopExecution, () => true);
                DeleteItemCommand = new RelayCommand(async () => await DeleteItemAsync(), () => CanDeleteItem);
                ViewReportCommand = new RelayCommand(async () => await ViewReportAsync(), () => CanViewReport);
                RefreshCommand = new RelayCommand(async () => await LoadQueueItemsAsync()); 
            }
            catch (Exception ex)
            {
                LogManager.Error($"BatchTaskManagementViewModel构造函数异常: {ex.Message}", ex);
                _queueItems = new ObservableCollection<BatchQueueItem>();
            }
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 设置PathPlanningManager（由LogisticsControlPanel在初始化时调用）
        /// </summary>
        public void SetPathPlanningManager(PathPlanningManager pathPlanningManager)
        {
            try
            {
                _pathPlanningManager = pathPlanningManager;
                _queueManager = BatchQueueManager.Instance;
                
                // 订阅队列管理器事件
                if (_queueManager != null)
                {
                    _queueManager.ItemAdded += OnItemAdded;
                    _queueManager.ItemStarted += OnItemStarted;
                    _queueManager.ItemCompleted += OnItemCompleted;
                }
                
                // 订阅路径规划管理器事件（用于在数据库初始化后重新加载队列列表）
                if (_pathPlanningManager != null)
                {
                    _pathPlanningManager.RoutesLoaded += OnRoutesLoaded;
                }
                
                // 尝试加载队列列表（如果数据库已初始化）
                _ = LoadQueueItemsAsync();
                
                LogManager.Info("[BatchQueueManagement] PathPlanningManager已设置");
            }
            catch (Exception ex)
            {
                LogManager.Error($"[BatchQueueManagement] 设置PathPlanningManager失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取数据库（延迟加载）
        /// </summary>
        private PathDatabase GetDatabase()
        {
            return _pathPlanningManager?.GetPathDatabase();
        }

        /// <summary>
        /// 加载队列项列表
        /// </summary>
        public async Task LoadQueueItemsAsync()
        {
            try
            {
                var database = GetDatabase();
                if (database == null)
                {
                    return;
                }

                var items = await database.GetBatchQueueItemsAsync(statusFilter: StatusFilter, limit: 1000);

                // 按创建时间倒序
                items = items.OrderByDescending(item => item.CreatedTime).ToList();

                LogManager.Info($"[BatchQueueManagement] 加载队列列表完成，共 {items.Count} 项");

                await _uiStateManager.ExecuteUIUpdateAsync(() =>
                {
                    QueueItems.Clear();
                    foreach (var item in items)
                    {
                        QueueItems.Add(item);
                    }

                    // 通知属性变化以更新按钮状态
                    OnPropertyChanged(nameof(HasPendingItems));
                    OnPropertyChanged(nameof(CanExecuteQueue));
                });
            }
            catch (Exception ex)
            {
                LogManager.Error($"[BatchQueueManagement] 加载队列列表失败: {ex.Message}");
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 执行队列
        /// </summary>
        private async Task ExecuteQueueAsync()
        {
            try
            {
                if (_queueManager == null) return;

                await _queueManager.ProcessQueueAsync();
                LogManager.Info("[BatchQueueManagement] 已开始执行队列");
            }
            catch (Exception ex)
            {
                LogManager.Error($"[BatchQueueManagement] 执行队列失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 停止执行
        /// </summary>
        private void StopExecution()
        {
            try
            {
                if (_queueManager != null)
                {
                    _queueManager.StopExecution();
                    LogManager.Info("[BatchQueueManagement] 已请求停止批处理执行");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[BatchQueueManagement] 停止执行失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除队列项
        /// </summary>
        private async Task DeleteItemAsync()
        {
            try
            {
                if (SelectedItem == null) return;

                var database = GetDatabase();
                if (database == null) return;

                var result = MessageBox.Show(
                    $"确定要删除队列项\"{SelectedItem.PathRouteName}\"吗？",
                    "确认删除",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question
                );

                if (result == MessageBoxResult.Yes)
                {
                    await database.DeleteBatchQueueItemAsync(SelectedItem.Id);
                    LogManager.Info($"[BatchQueueManagement] 已删除队列项，ID: {SelectedItem.Id}");
                    await LoadQueueItemsAsync();
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[BatchQueueManagement] 删除队列项失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 查看报告 - 复用碰撞历史列表中的报告按钮代码
        /// </summary>
        private async Task ViewReportAsync()
        {
            try
            {
                if (SelectedItem == null || string.IsNullOrEmpty(SelectedItem.ClashDetectiveTestName))
                {
                    MessageBox.Show("未找到碰撞检测结果", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var testName = SelectedItem.ClashDetectiveTestName;
                LogManager.Info($"[批处理队列] 开始生成历史碰撞报告: {testName}");

                // 复用碰撞历史列表中的报告按钮代码
                // 历史报告需要重新高亮，所以 hasHighlighted=false
                var command = GenerateCollisionReportCommand.CreateComprehensive(hasHighlighted: false);
                command.SetTestName(testName);
                await command.ExecuteAsync();
            }
            catch (Exception ex)
            {
                LogManager.Error($"[批处理队列] 生成历史报告失败: {ex.Message}", ex);
                MessageBox.Show($"生成历史报告失败: {ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        #region 事件处理

        private async void OnRoutesLoaded(object sender, RoutesLoadedEventArgs e)
        {
            // 数据库初始化完成，重新加载队列列表
            await _uiStateManager.ExecuteUIUpdateAsync(async () =>
            {
                await LoadQueueItemsAsync();
            });
        }

        private async void OnItemAdded(object sender, BatchQueueItemEventArgs e)
        {
            // 自动刷新列表
            await _uiStateManager.ExecuteUIUpdateAsync(async () =>
            {
                await LoadQueueItemsAsync();
            });
        }

        private async void OnItemStarted(object sender, BatchQueueItemEventArgs e)
        {
            await _uiStateManager.ExecuteUIUpdateAsync(() =>
            {
                IsExecuting = true;
                ProgressText = $"正在执行: {e.Item.PathRouteName}";
            });
        }

        private async void OnItemCompleted(object sender, BatchQueueItemEventArgs e)
        {
            await _uiStateManager.ExecuteUIUpdateAsync(async () =>
            {
                IsExecuting = false;
                ProgressText = $"完成: {e.Item.PathRouteName} - 碰撞数: {e.Item.CollisionCount ?? 0}";
                await LoadQueueItemsAsync();
            });
        }

        #endregion
    }
}