using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Microsoft.Win32;

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// 日志查看器对话框
    /// </summary>
    public partial class LogViewerDialog : Window
    {
        #region 私有字段

        private readonly DispatcherTimer _refreshTimer;
        private long _lastFileSize = 0;
        private string _originalLogContent = string.Empty;

        #endregion

        #region 构造函数

        public LogViewerDialog()
        {
            try
            {
                InitializeComponent();
                
                // 初始化刷新定时器
                _refreshTimer = new DispatcherTimer();
                _refreshTimer.Interval = TimeSpan.FromSeconds(2);
                _refreshTimer.Tick += RefreshTimer_Tick;
                
                // 加载初始日志内容
                LoadLogContent();
                
                // 启动自动刷新
                _refreshTimer.Start();
                
                LogManager.Info("日志查看器对话框已打开");
            }
            catch (Exception ex)
            {
                LogManager.Error($"日志查看器初始化失败: {ex.Message}", ex);
                MessageBox.Show($"日志查看器初始化失败: {ex.Message}", "错误", 
                              MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        #region 事件处理

        /// <summary>
        /// 刷新按钮点击事件
        /// </summary>
        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LoadLogContent();
                StatusLabel.Content = "日志已刷新";
                LogManager.Info("手动刷新日志");
            }
            catch (Exception ex)
            {
                LogManager.Error($"手动刷新日志失败: {ex.Message}", ex);
                StatusLabel.Content = "刷新失败";
            }
        }

        /// <summary>
        /// 清空日志按钮点击事件
        /// </summary>
        private void ClearLogButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = MessageBox.Show("确定要清空日志吗？此操作不可撤销。", "确认清空", 
                                           MessageBoxButton.YesNo, MessageBoxImage.Question);
                
                if (result == MessageBoxResult.Yes)
                {
                    LogManager.ClearLog();
                    LoadLogContent();
                    StatusLabel.Content = "日志已清空";
                    LogManager.Info("通过日志查看器清空日志");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"清空日志失败: {ex.Message}", ex);
                StatusLabel.Content = "清空失败";
                MessageBox.Show($"清空日志失败: {ex.Message}", "错误", 
                              MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 导出日志按钮点击事件
        /// </summary>
        private void ExportLogButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Title = "导出日志文件",
                    Filter = "日志文件 (*.log)|*.log|文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                    DefaultExt = "log",
                    FileName = $"NavisworksTransport_Log_{DateTime.Now:yyyyMMdd_HHmmss}.log"
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    // 从日志文件复制到目标位置
                    var logFilePath = LogManager.LogFilePath;
                    if (File.Exists(logFilePath))
                    {
                        File.Copy(logFilePath, saveFileDialog.FileName, true);
                        StatusLabel.Content = $"日志已导出到: {Path.GetFileName(saveFileDialog.FileName)}";
                        LogManager.Info($"日志已导出到: {saveFileDialog.FileName}");
                    }
                    else
                    {
                        File.WriteAllText(saveFileDialog.FileName, LogContentTextBox.Text);
                        StatusLabel.Content = $"日志已导出到: {Path.GetFileName(saveFileDialog.FileName)}";
                        LogManager.Info($"日志内容已导出到: {saveFileDialog.FileName}");
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"导出日志失败: {ex.Message}", ex);
                StatusLabel.Content = "导出失败";
                MessageBox.Show($"导出日志失败: {ex.Message}", "错误", 
                              MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 搜索文本框内容变化事件
        /// </summary>
        private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                PerformSearch();
            }
            catch (Exception ex)
            {
                LogManager.Error($"搜索功能异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 清除搜索按钮点击事件
        /// </summary>
        private void ClearSearchButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SearchTextBox.Text = string.Empty;
                LogContentTextBox.Text = _originalLogContent;
                StatusLabel.Content = "搜索已清除";
            }
            catch (Exception ex)
            {
                LogManager.Error($"清除搜索失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 路径文件操作按钮点击事件 - 过滤显示路径文件操作相关的日志
        /// </summary>
        private void PathFileOperationsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                const string filterTag = "[路径文件操作]";
                
                // 设置搜索框文本
                SearchTextBox.Text = filterTag;
                
                // 执行过滤
                PerformSearch();
                
                StatusLabel.Content = "已过滤：路径文件操作历史";
                LogManager.Info("日志查看器：过滤显示路径文件操作历史");
            }
            catch (Exception ex)
            {
                LogManager.Error($"过滤路径文件操作日志失败: {ex.Message}", ex);
                StatusLabel.Content = "过滤失败";
            }
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 窗口关闭事件
        /// </summary>
        protected override void OnClosed(EventArgs e)
        {
            try
            {
                _refreshTimer?.Stop();
                LogManager.Info("日志查看器对话框已关闭");
            }
            catch (Exception ex)
            {
                LogManager.Error($"关闭日志查看器时发生错误: {ex.Message}", ex);
            }
            
            base.OnClosed(e);
        }

        /// <summary>
        /// 自动刷新定时器事件
        /// </summary>
        private void RefreshTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                // 检查日志文件是否有变化
                var logFilePath = LogManager.LogFilePath;
                if (File.Exists(logFilePath))
                {
                    var fileInfo = new FileInfo(logFilePath);
                    if (fileInfo.Length != _lastFileSize)
                    {
                        LoadLogContent();
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"自动刷新日志时发生错误: {ex.Message}", ex);
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 加载日志内容
        /// </summary>
        private void LoadLogContent()
        {
            try
            {
                var logFilePath = LogManager.LogFilePath;
                
                if (File.Exists(logFilePath))
                {
                    // 读取日志文件内容
                    _originalLogContent = File.ReadAllText(logFilePath);
                    LogContentTextBox.Text = _originalLogContent;
                    
                    // 更新文件信息
                    var fileInfo = new FileInfo(logFilePath);
                    _lastFileSize = fileInfo.Length;
                    
                    // 更新状态信息
                    LogSizeLabel.Content = $"大小: {FormatFileSize(fileInfo.Length)}";
                    LineCountLabel.Content = $"行数: {LogContentTextBox.LineCount}";
                    
                    // 自动滚动到底部
                    if (AutoScrollCheckBox.IsChecked == true)
                    {
                        LogContentTextBox.ScrollToEnd();
                    }
                }
                else
                {
                    _originalLogContent = "日志文件不存在或为空";
                    LogContentTextBox.Text = _originalLogContent;
                    _lastFileSize = 0;
                    LogSizeLabel.Content = "大小: 0 KB";
                    LineCountLabel.Content = "行数: 0";
                }
                
                // 如果有搜索文本，重新执行搜索
                if (!string.IsNullOrEmpty(SearchTextBox.Text))
                {
                    PerformSearch();
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"加载日志内容失败: {ex.Message}", ex);
                LogContentTextBox.Text = $"加载日志失败: {ex.Message}";
                StatusLabel.Content = "加载失败";
            }
        }

        /// <summary>
        /// 执行搜索
        /// </summary>
        private void PerformSearch()
        {
            try
            {
                var searchText = SearchTextBox.Text?.Trim();
                
                if (string.IsNullOrEmpty(searchText))
                {
                    LogContentTextBox.Text = _originalLogContent;
                    StatusLabel.Content = "日志已加载";
                    return;
                }

                // 简单的文本搜索 - 显示包含搜索词的行
                var lines = _originalLogContent.Split('\n');
                var filteredLines = new System.Collections.Generic.List<string>();
                
                foreach (var line in lines)
                {
                    if (line.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        filteredLines.Add(line);
                    }
                }
                
                LogContentTextBox.Text = string.Join("\n", filteredLines);
                StatusLabel.Content = $"找到 {filteredLines.Count} 行匹配结果";
            }
            catch (Exception ex)
            {
                LogManager.Error($"搜索执行失败: {ex.Message}", ex);
                StatusLabel.Content = "搜索失败";
            }
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long bytes)
        {
            if (bytes < 1024)
                return $"{bytes} B";
            else if (bytes < 1024 * 1024)
                return $"{bytes / 1024.0:F1} KB";
            else if (bytes < 1024 * 1024 * 1024)
                return $"{bytes / (1024.0 * 1024.0):F1} MB";
            else
                return $"{bytes / (1024.0 * 1024.0 * 1024.0):F1} GB";
        }

        #endregion
    }
}