using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Threading;
namespace NavisworksTransport.UI.WPF.ViewModels
{
///
/// 系统管理ViewModel - 参照PathEditingViewModel的设计模式
/// 专门负责系统管理相关功能,包括:日志管理、设置管理、性能监控、版本控制、配置管理等
///
public class SystemManagementViewModel : ViewModelBase
{
#region 私有字段
// 依赖注入的核心服务
private readonly UIStateManager _uiStateManager;
// 系统管理相关的管理器实例(通过依赖注入)
private ISystemLogManager _logManager;
private ISystemConfigManager _configManager;
private IPerformanceMonitor _performanceMonitor;
private IModelSplitterManager _modelSplitterManager;
// 日志管理相关字段
private ObservableCollection _logLevels;
private string _selectedLogLevel = "Info";
private string _logStatus = "日志系统正常";
private int _logEntryCount = 0;
private string _logFilePath = "未设置";
// 系统设置相关字段
private bool _isAutoSaveEnabled = true;
private bool _isDebugModeEnabled = false;
private string _settingsStatus = "设置已加载";
private int _autoSaveInterval = 300; // 秒
private string _workingDirectory = "";
// 版本和系统信息相关字段
private string _pluginVersion = "v1.0";
private string _navisworksVersion = "2026";
private string _systemStatus = "正常";
private string _systemStatusColor = "Green";
private string _lastUpdateCheck = "未检查";
// 性能监控相关字段
private string _memoryUsage = "0 MB";
private string _runningTime = "00:00:00";
private string _performanceInfo = "性能监控就绪";
private double _cpuUsage = 0.0;
private int _threadsCount = 0;
private DispatcherTimer _performanceTimer;
// 模型分割器相关字段
private string _modelSplitterStatus = "就绪";
private bool _canRunModelSplitter = true;
private string _lastSplitResult = "未执行";
// 配置管理相关字段
private string _currentConfigProfile = "默认配置";
private ObservableCollection _availableProfiles;
private bool _hasUnsavedChanges = false;
#endregion
#region 公共属性
#region 日志管理属性
///
/// 可用日志级别集合
///
public ObservableCollection LogLevels
{
get => _logLevels;
set => SetProperty(ref _logLevels, value);
}
///
/// 选中的日志级别
///
public string SelectedLogLevel
{
get => _selectedLogLevel;
set
{
if (SetProperty(ref _selectedLogLevel, value))
{
OnLogLevelChanged();
}
}
}
///
/// 日志系统状态
///
public string LogStatus
{
get => _logStatus;
set => SetProperty(ref _logStatus, value);
}
///
/// 日志条目数量
///
public int LogEntryCount
{
get => _logEntryCount;
set => SetProperty(ref _logEntryCount, value);
}
///
/// 日志文件路径
///
public string LogFilePath
{
get => _logFilePath;
set => SetProperty(ref _logFilePath, value);
}
#endregion
#region 系统设置属性
///
/// 是否启用自动保存
///
public bool IsAutoSaveEnabled
{
get => _isAutoSaveEnabled;
set
{
if (SetProperty(ref _isAutoSaveEnabled, value))
{
OnAutoSaveSettingChanged();
}
}
}
///
/// 是否启用调试模式
///
public bool IsDebugModeEnabled
{
get => _isDebugModeEnabled;
set
{
if (SetProperty(ref _isDebugModeEnabled, value))
{
OnDebugModeChanged();
}
}
}
///
/// 设置状态
///
public string SettingsStatus
{
get => _settingsStatus;
set => SetProperty(ref _settingsStatus, value);
}
///
/// 自动保存间隔(秒)
///
public int AutoSaveInterval
{
get => _autoSaveInterval;
set
{
if (SetProperty(ref _autoSaveInterval, value))
{
OnAutoSaveIntervalChanged();
}
}
}
///
/// 工作目录
///
public string WorkingDirectory
{
get => _workingDirectory;
set => SetProperty(ref _workingDirectory, value);
}
#endregion
#region 版本和系统信息属性
///
/// 插件版本
///
public string PluginVersion
{
get => _pluginVersion;
set => SetProperty(ref _pluginVersion, value);
}
///
/// Navisworks版本
///
public string NavisworksVersion
{
get => _navisworksVersion;
set => SetProperty(ref _navisworksVersion, value);
}
///
/// 系统状态
///
public string SystemStatus
{
get => _systemStatus;
set => SetProperty(ref _systemStatus, value);
}
///
/// 系统状态颜色
///
public string SystemStatusColor
{
get => _systemStatusColor;
set => SetProperty(ref _systemStatusColor, value);
}
///
/// 最后更新检查时间
///
public string LastUpdateCheck
{
get => _lastUpdateCheck;
set => SetProperty(ref _lastUpdateCheck, value);
}
#endregion
#region 性能监控属性
///
/// 内存使用情况
///
public string MemoryUsage
{
get => _memoryUsage;
set => SetProperty(ref _memoryUsage, value);
}
///
/// 运行时间
///
public string RunningTime
{
get => _runningTime;
set => SetProperty(ref _runningTime, value);
}
///
/// 性能信息
///
public string PerformanceInfo
{
get => _performanceInfo;
set => SetProperty(ref _performanceInfo, value);
}
///
/// CPU使用率
///
public double CpuUsage
{
get => _cpuUsage;
set => SetProperty(ref _cpuUsage, value);
}
///
/// 线程数量
///
public int ThreadsCount
{
get => _threadsCount;
set => SetProperty(ref _threadsCount, value);
}
#endregion
#region 模型分割器属性
///
/// 模型分层拆分状态
///
public string ModelSplitterStatus
{
get => _modelSplitterStatus;
set => SetProperty(ref _modelSplitterStatus, value);
}
///
/// 是否可以运行模型分割器
///
public bool CanRunModelSplitter
{
get => _canRunModelSplitter;
set => SetProperty(ref _canRunModelSplitter, value);
}
///
/// 最后分割结果
///
public string LastSplitResult
{
get => _lastSplitResult;
set => SetProperty(ref _lastSplitResult, value);
}
#endregion
#region 配置管理属性
///
/// 当前配置档案
///
public string CurrentConfigProfile
{
get => _currentConfigProfile;
set => SetProperty(ref _currentConfigProfile, value);
}
///
/// 可用配置档案
///
public ObservableCollection AvailableProfiles
{
get => _availableProfiles;
set => SetProperty(ref _availableProfiles, value);
}
///
/// 是否有未保存的更改
///
public bool HasUnsavedChanges
{
get => _hasUnsavedChanges;
set => SetProperty(ref _hasUnsavedChanges, value);
}
#endregion
#endregion
#region 命令定义
// 日志管理命令
public ICommand ViewLogCommand { get; private set; }
public ICommand ClearLogCommand { get; private set; }
public ICommand ExportLogCommand { get; private set; }
public ICommand RefreshLogStatusCommand { get; private set; }
// 设置管理命令
public ICommand OpenSettingsCommand { get; private set; }
public ICommand ResetSettingsCommand { get; private set; }
public ICommand SaveSettingsCommand { get; private set; }
public ICommand LoadSettingsCommand { get; private set; }
// 配置管理命令
public ICommand ImportConfigCommand { get; private set; }
public ICommand ExportConfigCommand { get; private set; }
public ICommand CreateProfileCommand { get; private set; }
public ICommand DeleteProfileCommand { get; private set; }
public ICommand SwitchProfileCommand { get; private set; }
// 系统管理命令
public ICommand CheckUpdateCommand { get; private set; }
public ICommand RestartSystemCommand { get; private set; }
public ICommand SystemDiagnosticsCommand { get; private set; }
// 性能管理命令
public ICommand GeneratePerformanceReportCommand { get; private set; }
public ICommand StartPerformanceMonitoringCommand { get; private set; }
public ICommand StopPerformanceMonitoringCommand { get; private set; }
public ICommand ClearPerformanceDataCommand { get; private set; }
// 模型分割器命令
public ICommand RunModelSplitterCommand { get; private set; }
public ICommand ConfigureModelSplitterCommand { get; private set; }
#endregion
#region 构造函数
///
/// 构造函数 - 参照PathEditingViewModel的设计模式
///
/// 日志管理器(可选,用于依赖注入)
/// 配置管理器(可选,用于依赖注入)
/// 性能监控器(可选,用于依赖注入)
/// 模型分割器管理器(可选,用于依赖注入)
public SystemManagementViewModel(
ISystemLogManager logManager = null,
ISystemConfigManager configManager = null,
IPerformanceMonitor performanceMonitor = null,
IModelSplitterManager modelSplitterManager = null) : base()
{
try
{
// 获取UI状态管理器
_uiStateManager = UIStateManager.Instance;
if (_uiStateManager == null)
{
throw new InvalidOperationException("UIStateManager初始化失败");
}
// 设置依赖(如果为null则使用默认实现)
_logManager = logManager ?? CreateDefaultLogManager();
_configManager = configManager ?? CreateDefaultConfigManager();
_performanceMonitor = performanceMonitor ?? CreateDefaultPerformanceMonitor();
_modelSplitterManager = modelSplitterManager ?? CreateDefaultModelSplitterManager();
// 初始化集合
LogLevels = new ThreadSafeObservableCollection();
AvailableProfiles = new ThreadSafeObservableCollection();
// 初始化命令
InitializeCommands();
// 初始化系统管理设置(异步)
InitializeSystemManagementAsync();
LogManager.Info("SystemManagementViewModel构造函数执行完成");
}
catch (Exception ex)
{
LogManager.Error($"SystemManagementViewModel构造函数异常: {ex.Message}", ex);
SystemStatus = "初始化失败,请检查日志";
SystemStatusColor = "Red";
throw;
}
}
#endregion
#region 初始化方法
///
/// 初始化命令
///
private void InitializeCommands()
{
// 日志管理命令
ViewLogCommand = new RelayCommand(async () => await ExecuteViewLogAsync());
ClearLogCommand = new RelayCommand(async () => await ExecuteClearLogAsync());
ExportLogCommand = new RelayCommand(async () => await ExecuteExportLogAsync());
RefreshLogStatusCommand = new RelayCommand(async () => await ExecuteRefreshLogStatusAsync());
// 设置管理命令
OpenSettingsCommand = new RelayCommand(async () => await ExecuteOpenSettingsAsync());
ResetSettingsCommand = new RelayCommand(async () => await ExecuteResetSettingsAsync());
SaveSettingsCommand = new RelayCommand(async () => await ExecuteSaveSettingsAsync());
LoadSettingsCommand = new RelayCommand(async () => await ExecuteLoadSettingsAsync());
// 配置管理命令
ImportConfigCommand = new RelayCommand(async () => await ExecuteImportConfigAsync());
ExportConfigCommand = new RelayCommand(async () => await ExecuteExportConfigAsync());
CreateProfileCommand = new RelayCommand(async () => await ExecuteCreateProfileAsync());
DeleteProfileCommand = new RelayCommand(async () => await ExecuteDeleteProfileAsync());
SwitchProfileCommand = new RelayCommand(async (profile) => await ExecuteSwitchProfileAsync(profile));
// 系统管理命令
CheckUpdateCommand = new RelayCommand(async () => await ExecuteCheckUpdateAsync());
RestartSystemCommand = new RelayCommand(async () => await ExecuteRestartSystemAsync());
SystemDiagnosticsCommand = new RelayCommand(async () => await ExecuteSystemDiagnosticsAsync());
// 性能管理命令
GeneratePerformanceReportCommand = new RelayCommand(async () => await ExecuteGeneratePerformanceReportAsync());
StartPerformanceMonitoringCommand = new RelayCommand(async () => await ExecuteStartPerformanceMonitoringAsync());
StopPerformanceMonitoringCommand = new RelayCommand(async () => await ExecuteStopPerformanceMonitoringAsync());
ClearPerformanceDataCommand = new RelayCommand(async () => await ExecuteClearPerformanceDataAsync());
// 模型分割器命令
RunModelSplitterCommand = new RelayCommand(async () => await ExecuteRunModelSplitterAsync(), () => CanRunModelSplitter);
ConfigureModelSplitterCommand = new RelayCommand(async () => await ExecuteConfigureModelSplitterAsync());
}
///
/// 异步初始化系统管理设置
///
private async void InitializeSystemManagementAsync()
{
await SafeExecuteAsync(async () =>
{
await _uiStateManager.ExecuteUIUpdateAsync(() =>
{
// 初始化日志级别
LogLevels.Clear();
var logLevels = new[] { "Debug", "Info", "Warning", "Error" };
foreach (var level in logLevels)
{
LogLevels.Add(level);
}
SelectedLogLevel = "Info";
// 初始化配置档案
AvailableProfiles.Clear();
var profiles = new[] { "默认配置", "开发配置", "生产配置", "测试配置" };
foreach (var profile in profiles)
{
AvailableProfiles.Add(profile);
}
CurrentConfigProfile = "默认配置";
// 初始化系统信息
PluginVersion = GetPluginVersion();
NavisworksVersion = GetNavisworksVersion();
SystemStatus = "正常";
SystemStatusColor = "Green";
WorkingDirectory = GetWorkingDirectory();
LogFilePath = GetLogFilePath();
});
// 启动性能监控
await StartPerformanceMonitoring();
LogManager.Info("系统管理设置初始化完成");
}, "初始化系统管理设置");
}
#endregion
#region 命令实现
// 这里只展示架构框架,具体实现方法将在后续详细说明
#region 日志管理命令实现
private async Task ExecuteViewLogAsync()
{
await SafeExecuteAsync(async () =>
{
// TODO: 实现日志查看功能
await _logManager.OpenLogViewerAsync();
LogStatus = "日志查看器已打开";
}, "查看日志");
}
private async Task ExecuteClearLogAsync()
{
await SafeExecuteAsync(async () =>
{
// TODO: 实现日志清空功能
await _logManager.ClearLogsAsync();
LogEntryCount = 0;
LogStatus = "日志已清空";
}, "清空日志");
}
private async Task ExecuteExportLogAsync()
{
await SafeExecuteAsync(async () =>
{
// TODO: 实现日志导出功能
var exportPath = await _logManager.ExportLogsAsync();
LogStatus = $"日志已导出到: {exportPath}";
}, "导出日志");
}
private async Task ExecuteRefreshLogStatusAsync()
{
await SafeExecuteAsync(async () =>
{
// TODO: 实现日志状态刷新功能
var status = await _logManager.GetLogStatusAsync();
LogStatus = status.Message;
LogEntryCount = status.EntryCount;
LogFilePath = status.FilePath;
}, "刷新日志状态");
}
#endregion
// 其他命令实现方法...
// (这里省略具体实现,在实际代码中会完整实现)
#endregion
#region 事件处理
///
/// 处理日志级别改变事件
///
private void OnLogLevelChanged()
{
SafeExecute(() =>
{
_logManager?.SetLogLevel(SelectedLogLevel);
LogStatus = $"日志级别已设置为: {SelectedLogLevel}";
}, "设置日志级别");
}
///
/// 处理自动保存设置改变事件
///
private void OnAutoSaveSettingChanged()
{
SafeExecute(() =>
{
_configManager?.SetAutoSaveEnabled(IsAutoSaveEnabled);
SettingsStatus = $"自动保存: {(IsAutoSaveEnabled ? "已启用" : "已禁用")}";
HasUnsavedChanges = true;
}, "设置自动保存");
}
///
/// 处理调试模式改变事件
///
private void OnDebugModeChanged()
{
SafeExecute(() =>
{
_configManager?.SetDebugMode(IsDebugModeEnabled);
SettingsStatus = $"调试模式: {(IsDebugModeEnabled ? "已启用" : "已禁用")}";
HasUnsavedChanges = true;
}, "设置调试模式");
}
///
/// 处理自动保存间隔改变事件
///
private void OnAutoSaveIntervalChanged()
{
SafeExecute(() =>
{
_configManager?.SetAutoSaveInterval(AutoSaveInterval);
SettingsStatus = $"自动保存间隔: {AutoSaveInterval}秒";
HasUnsavedChanges = true;
}, "设置自动保存间隔");
}
#endregion
#region 辅助方法
///
/// 安全执行异步操作
///
private async Task SafeExecuteAsync(Func action, string operationName = "未知操作")
{
try
{
await action();
}
catch (Exception ex)
{
LogManager.Error($"{operationName}发生异常: {ex.Message}", ex);
SystemStatus = $"{operationName}失败: {ex.Message}";
SystemStatusColor = "Red";
}
}
///
/// 安全执行同步操作
///
private void SafeExecute(Action action, string operationName = "未知操作")
{
try
{
action();
}
catch (Exception ex)
{
LogManager.Error($"{operationName}发生异常: {ex.Message}", ex);
SystemStatus = $"{operationName}失败: {ex.Message}";
SystemStatusColor = "Red";
}
}
#endregion
#region 性能监控
///
/// 启动性能监控
///
private async Task StartPerformanceMonitoring()
{
await SafeExecuteAsync(async () =>
{
var startTime = DateTime.Now;
// 使用定时器更新性能信息
_performanceTimer = new DispatcherTimer();
_performanceTimer.Interval = TimeSpan.FromSeconds(5);
_performanceTimer.Tick += async (s, e) =>
{
try
{
await UpdatePerformanceInfo(startTime);
}
catch (Exception ex)
{
LogManager.Error($"性能监控更新失败: {ex.Message}");
}
};
_performanceTimer.Start();
PerformanceInfo = "性能监控已启动";
}, "启动性能监控");
}
///
/// 更新性能信息
///
private async Task UpdatePerformanceInfo(DateTime startTime)
{
await _uiStateManager.ExecuteUIUpdateAsync(() =>
{
// 更新内存使用
var process = Process.GetCurrentProcess();
var memoryMB = process.WorkingSet64 / (1024 * 1024);
MemoryUsage = $"{memoryMB} MB";
// 更新运行时间
var runTime = DateTime.Now - startTime;
RunningTime = $"{runTime.Hours:D2}:{runTime.Minutes:D2}:{runTime.Seconds:D2}";
// 更新线程数
ThreadsCount = process.Threads.Count;
// 更新性能信息
PerformanceInfo = $"CPU: 正常, 内存: {memoryMB}MB, 线程: {ThreadsCount}, 运行时间: {RunningTime}";
});
}
#endregion
#region 默认实现创建方法
private ISystemLogManager CreateDefaultLogManager()
{
// TODO: 创建默认日志管理器实现
return new DefaultSystemLogManager();
}
private ISystemConfigManager CreateDefaultConfigManager()
{
// TODO: 创建默认配置管理器实现
return new DefaultSystemConfigManager();
}
private IPerformanceMonitor CreateDefaultPerformanceMonitor()
{
// TODO: 创建默认性能监控器实现
return new DefaultPerformanceMonitor();
}
private IModelSplitterManager CreateDefaultModelSplitterManager()
{
// TODO: 创建默认模型分割器管理器实现
return new DefaultModelSplitterManager();
}
#endregion
#region 系统信息获取方法
private string GetPluginVersion()
{
// TODO: 从程序集获取插件版本
return "v1.0";
}
private string GetNavisworksVersion()
{
// TODO: 从Navisworks API获取版本信息
return "2026";
}
private string GetWorkingDirectory()
{
// TODO: 获取当前工作目录
return Environment.CurrentDirectory;
}
private string GetLogFilePath()
{
// TODO: 获取日志文件路径
return Path.Combine(GetWorkingDirectory(), "Logs", "NavisworksTransport.log");
}
#endregion
#region 资源清理
///
/// 清理资源
///
public void Cleanup()
{
try
{
LogManager.Info("开始清理SystemManagementViewModel资源");
// 停止性能监控定时器
if (_performanceTimer != null)
{
_performanceTimer.Stop();
_performanceTimer = null;
}
// 清理管理器资源
_logManager?.Dispose();
_configManager?.Dispose();
_performanceMonitor?.Dispose();
_modelSplitterManager?.Dispose();
LogManager.Info("SystemManagementViewModel资源清理完成");
}
catch (Exception ex)
{
LogManager.Error($"SystemManagementViewModel清理失败: {ex.Message}");
}
}
#endregion
}
}
// 接口定义(这些接口将在单独的文件中定义)
///
/// 系统日志管理器接口
///
public interface ISystemLogManager : IDisposable
{
Task OpenLogViewerAsync();
Task ClearLogsAsync();
Task ExportLogsAsync();
Task GetLogStatusAsync();
void SetLogLevel(string level);
}
///
/// 系统配置管理器接口
///
public interface ISystemConfigManager : IDisposable
{
void SetAutoSaveEnabled(bool enabled);
void SetDebugMode(bool enabled);
void SetAutoSaveInterval(int seconds);
Task SaveConfigAsync();
Task LoadConfigAsync();
}
///
/// 性能监控器接口
///
public interface IPerformanceMonitor : IDisposable
{
Task GetCurrentPerformanceAsync();
Task StartMonitoringAsync();
Task StopMonitoringAsync();
}
///
/// 模型分割器管理器接口
///
public interface IModelSplitterManager : IDisposable
{
Task RunModelSplitterAsync();
Task ConfigureAsync();
bool CanRun { get; }
}
///
/// 日志状态数据结构
///
public class LogStatus
{
public string Message { get; set; }
public int EntryCount { get; set; }
public string FilePath { get; set; }
}
///
/// 性能数据结构
///
public class PerformanceData
{
public double CpuUsage { get; set; }
public long MemoryUsage { get; set; }
public int ThreadCount { get; set; }
public TimeSpan RunningTime { get; set; }
}