NavisworksTransport/SystemManagementViewModel_Design.cs

897 lines
28 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
{
/// <summary>
/// 系统管理ViewModel - 参照PathEditingViewModel的设计模式
/// 专门负责系统管理相关功能,包括:日志管理、设置管理、性能监控、版本控制、配置管理等
/// </summary>
public class SystemManagementViewModel : ViewModelBase
{
#region
// 依赖注入的核心服务
private readonly UIStateManager _uiStateManager;
// 系统管理相关的管理器实例(通过依赖注入)
private ISystemLogManager _logManager;
private ISystemConfigManager _configManager;
private IPerformanceMonitor _performanceMonitor;
private IModelSplitterManager _modelSplitterManager;
// 日志管理相关字段
private ObservableCollection<string> _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<string> _availableProfiles;
private bool _hasUnsavedChanges = false;
#endregion
#region
#region
/// <summary>
/// 可用日志级别集合
/// </summary>
public ObservableCollection<string> LogLevels
{
get => _logLevels;
set => SetProperty(ref _logLevels, value);
}
/// <summary>
/// 选中的日志级别
/// </summary>
public string SelectedLogLevel
{
get => _selectedLogLevel;
set
{
if (SetProperty(ref _selectedLogLevel, value))
{
OnLogLevelChanged();
}
}
}
/// <summary>
/// 日志系统状态
/// </summary>
public string LogStatus
{
get => _logStatus;
set => SetProperty(ref _logStatus, value);
}
/// <summary>
/// 日志条目数量
/// </summary>
public int LogEntryCount
{
get => _logEntryCount;
set => SetProperty(ref _logEntryCount, value);
}
/// <summary>
/// 日志文件路径
/// </summary>
public string LogFilePath
{
get => _logFilePath;
set => SetProperty(ref _logFilePath, value);
}
#endregion
#region
/// <summary>
/// 是否启用自动保存
/// </summary>
public bool IsAutoSaveEnabled
{
get => _isAutoSaveEnabled;
set
{
if (SetProperty(ref _isAutoSaveEnabled, value))
{
OnAutoSaveSettingChanged();
}
}
}
/// <summary>
/// 是否启用调试模式
/// </summary>
public bool IsDebugModeEnabled
{
get => _isDebugModeEnabled;
set
{
if (SetProperty(ref _isDebugModeEnabled, value))
{
OnDebugModeChanged();
}
}
}
/// <summary>
/// 设置状态
/// </summary>
public string SettingsStatus
{
get => _settingsStatus;
set => SetProperty(ref _settingsStatus, value);
}
/// <summary>
/// 自动保存间隔(秒)
/// </summary>
public int AutoSaveInterval
{
get => _autoSaveInterval;
set
{
if (SetProperty(ref _autoSaveInterval, value))
{
OnAutoSaveIntervalChanged();
}
}
}
/// <summary>
/// 工作目录
/// </summary>
public string WorkingDirectory
{
get => _workingDirectory;
set => SetProperty(ref _workingDirectory, value);
}
#endregion
#region
/// <summary>
/// 插件版本
/// </summary>
public string PluginVersion
{
get => _pluginVersion;
set => SetProperty(ref _pluginVersion, value);
}
/// <summary>
/// Navisworks版本
/// </summary>
public string NavisworksVersion
{
get => _navisworksVersion;
set => SetProperty(ref _navisworksVersion, value);
}
/// <summary>
/// 系统状态
/// </summary>
public string SystemStatus
{
get => _systemStatus;
set => SetProperty(ref _systemStatus, value);
}
/// <summary>
/// 系统状态颜色
/// </summary>
public string SystemStatusColor
{
get => _systemStatusColor;
set => SetProperty(ref _systemStatusColor, value);
}
/// <summary>
/// 最后更新检查时间
/// </summary>
public string LastUpdateCheck
{
get => _lastUpdateCheck;
set => SetProperty(ref _lastUpdateCheck, value);
}
#endregion
#region
/// <summary>
/// 内存使用情况
/// </summary>
public string MemoryUsage
{
get => _memoryUsage;
set => SetProperty(ref _memoryUsage, value);
}
/// <summary>
/// 运行时间
/// </summary>
public string RunningTime
{
get => _runningTime;
set => SetProperty(ref _runningTime, value);
}
/// <summary>
/// 性能信息
/// </summary>
public string PerformanceInfo
{
get => _performanceInfo;
set => SetProperty(ref _performanceInfo, value);
}
/// <summary>
/// CPU使用率
/// </summary>
public double CpuUsage
{
get => _cpuUsage;
set => SetProperty(ref _cpuUsage, value);
}
/// <summary>
/// 线程数量
/// </summary>
public int ThreadsCount
{
get => _threadsCount;
set => SetProperty(ref _threadsCount, value);
}
#endregion
#region
/// <summary>
/// 模型分层拆分状态
/// </summary>
public string ModelSplitterStatus
{
get => _modelSplitterStatus;
set => SetProperty(ref _modelSplitterStatus, value);
}
/// <summary>
/// 是否可以运行模型分割器
/// </summary>
public bool CanRunModelSplitter
{
get => _canRunModelSplitter;
set => SetProperty(ref _canRunModelSplitter, value);
}
/// <summary>
/// 最后分割结果
/// </summary>
public string LastSplitResult
{
get => _lastSplitResult;
set => SetProperty(ref _lastSplitResult, value);
}
#endregion
#region
/// <summary>
/// 当前配置档案
/// </summary>
public string CurrentConfigProfile
{
get => _currentConfigProfile;
set => SetProperty(ref _currentConfigProfile, value);
}
/// <summary>
/// 可用配置档案
/// </summary>
public ObservableCollection<string> AvailableProfiles
{
get => _availableProfiles;
set => SetProperty(ref _availableProfiles, value);
}
/// <summary>
/// 是否有未保存的更改
/// </summary>
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
/// <summary>
/// 构造函数 - 参照PathEditingViewModel的设计模式
/// </summary>
/// <param name="logManager">日志管理器(可选,用于依赖注入)</param>
/// <param name="configManager">配置管理器(可选,用于依赖注入)</param>
/// <param name="performanceMonitor">性能监控器(可选,用于依赖注入)</param>
/// <param name="modelSplitterManager">模型分割器管理器(可选,用于依赖注入)</param>
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<string>();
AvailableProfiles = new ThreadSafeObservableCollection<string>();
// 初始化命令
InitializeCommands();
// 初始化系统管理设置(异步)
InitializeSystemManagementAsync();
LogManager.Info("SystemManagementViewModel构造函数执行完成");
}
catch (Exception ex)
{
LogManager.Error($"SystemManagementViewModel构造函数异常: {ex.Message}", ex);
SystemStatus = "初始化失败,请检查日志";
SystemStatusColor = "Red";
throw;
}
}
#endregion
#region
/// <summary>
/// 初始化命令
/// </summary>
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<string>(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());
}
/// <summary>
/// 异步初始化系统管理设置
/// </summary>
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
/// <summary>
/// 处理日志级别改变事件
/// </summary>
private void OnLogLevelChanged()
{
SafeExecute(() =>
{
_logManager?.SetLogLevel(SelectedLogLevel);
LogStatus = $"日志级别已设置为: {SelectedLogLevel}";
}, "设置日志级别");
}
/// <summary>
/// 处理自动保存设置改变事件
/// </summary>
private void OnAutoSaveSettingChanged()
{
SafeExecute(() =>
{
_configManager?.SetAutoSaveEnabled(IsAutoSaveEnabled);
SettingsStatus = $"自动保存: {(IsAutoSaveEnabled ? "" : "")}";
HasUnsavedChanges = true;
}, "设置自动保存");
}
/// <summary>
/// 处理调试模式改变事件
/// </summary>
private void OnDebugModeChanged()
{
SafeExecute(() =>
{
_configManager?.SetDebugMode(IsDebugModeEnabled);
SettingsStatus = $"调试模式: {(IsDebugModeEnabled ? "" : "")}";
HasUnsavedChanges = true;
}, "设置调试模式");
}
/// <summary>
/// 处理自动保存间隔改变事件
/// </summary>
private void OnAutoSaveIntervalChanged()
{
SafeExecute(() =>
{
_configManager?.SetAutoSaveInterval(AutoSaveInterval);
SettingsStatus = $"自动保存间隔: {AutoSaveInterval}秒";
HasUnsavedChanges = true;
}, "设置自动保存间隔");
}
#endregion
#region
/// <summary>
/// 安全执行异步操作
/// </summary>
private async Task SafeExecuteAsync(Func<Task> action, string operationName = "未知操作")
{
try
{
await action();
}
catch (Exception ex)
{
LogManager.Error($"{operationName}发生异常: {ex.Message}", ex);
SystemStatus = $"{operationName}失败: {ex.Message}";
SystemStatusColor = "Red";
}
}
/// <summary>
/// 安全执行同步操作
/// </summary>
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
/// <summary>
/// 启动性能监控
/// </summary>
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 = "性能监控已启动";
}, "启动性能监控");
}
/// <summary>
/// 更新性能信息
/// </summary>
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
/// <summary>
/// 清理资源
/// </summary>
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
}
}
// 接口定义(这些接口将在单独的文件中定义)
/// <summary>
/// 系统日志管理器接口
/// </summary>
public interface ISystemLogManager : IDisposable
{
Task OpenLogViewerAsync();
Task ClearLogsAsync();
Task<string> ExportLogsAsync();
Task<LogStatus> GetLogStatusAsync();
void SetLogLevel(string level);
}
/// <summary>
/// 系统配置管理器接口
/// </summary>
public interface ISystemConfigManager : IDisposable
{
void SetAutoSaveEnabled(bool enabled);
void SetDebugMode(bool enabled);
void SetAutoSaveInterval(int seconds);
Task SaveConfigAsync();
Task LoadConfigAsync();
}
/// <summary>
/// 性能监控器接口
/// </summary>
public interface IPerformanceMonitor : IDisposable
{
Task<PerformanceData> GetCurrentPerformanceAsync();
Task StartMonitoringAsync();
Task StopMonitoringAsync();
}
/// <summary>
/// 模型分割器管理器接口
/// </summary>
public interface IModelSplitterManager : IDisposable
{
Task<bool> RunModelSplitterAsync();
Task ConfigureAsync();
bool CanRun { get; }
}
/// <summary>
/// 日志状态数据结构
/// </summary>
public class LogStatus
{
public string Message { get; set; }
public int EntryCount { get; set; }
public string FilePath { get; set; }
}
/// <summary>
/// 性能数据结构
/// </summary>
public class PerformanceData
{
public double CpuUsage { get; set; }
public long MemoryUsage { get; set; }
public int ThreadCount { get; set; }
public TimeSpan RunningTime { get; set; }
}