Files
MsAddIns/QuickModeling/ViewModels/ConfigurationPropsAttachViewModel.cs
2026-02-28 21:01:57 +08:00

268 lines
10 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using Bentley.DgnPlatformNET;
using Bentley.ECObjects.Instance;
using Bentley.MstnPlatformNET;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QuickModeling.Models;
using QuickModeling.Views;
namespace QuickModeling.ViewModels
{
public partial class ConfigurationPropsAttachViewModel : ObservableRecipient, IRecipient<string>, IRecipient<ComponentConfig>
{
private List<ComponentConfig> allConfigs;
[ObservableProperty]
private List<ComponentConfig> configs;
private ICollectionView cv;
/// <summary>
/// 配置文件路径
/// </summary>
private readonly string path = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"Configs",
"Configurations.json");
[ObservableProperty]
private ComponentType selectedComponentType;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ModifyConfigCommand), nameof(AddToModelsCommand))]
private ComponentConfig selectedConfig;
public ConfigurationPropsAttachViewModel()
{
WeakReferenceMessenger.Default.Register<string, string>(this, "manager");
WeakReferenceMessenger.Default.Register<ComponentConfig, string>(this, "config");
try
{
EnsureConfigFileExists();
//读取配置文件
var jsonString = File.ReadAllText(path);
allConfigs = JsonConvert.DeserializeObject<List<ComponentConfig>>(jsonString)
.Where(s => s.IsEnabled)
.ToList();
Configs = allConfigs.Where(s => s.ComponentType == SelectedComponentType).ToList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
[RelayCommand(CanExecute = nameof(CanOperate))]
private void AddToModels(ComponentConfig config)
{
if (config == null)
{
MessageBox.Show("请选择要添加的配置", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
//选中参数
var agenda = new ElementAgenda();
SelectionSetManager.BuildAgenda(ref agenda);
if (agenda.IsEmpty)
{
MessageBox.Show("请先选择要添加属性的元素", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
try
{
//var lib = ItemTypesHelpers.GetOrCreateItemTypeLibrary(config.Name);
//ItemType分组
var groups = config.Parameters.GroupBy(p => p.Group);
//var itemTypes = lib.ItemTypes;
//将ItemType添加到ItemTypeLibrary中即dgnfile中
foreach (var g in groups)
{
var itemType = ItemTypesHelpers.GetOrCreateItemType(config.Name, g.Key);
foreach (var p in g)
{
//存在参数,则不加
var prop = itemType.GetPropertyByName(p.Name);
if (prop == null)
{
ItemTypesHelpers.AddPropertyToItemType(
itemType,
p.Name,
(CustomProperty.TypeKind)p.DataType,
p.Value);
}
else//更新属性定义
{
prop.Type = (CustomProperty.TypeKind)p.DataType;
prop.DefaultValue = p.Value;
itemType.Library.Write();
}
}
//lib.AddItemType(itemType.Name);
}
//ItemType添加到模型中
//var dgnFile = Session.Instance.GetActiveDgnFile();
foreach (var g in groups)
{
//ItemTypesHelpers.AttachItemTypeToElement(libName, g.Key);
for (uint i = 0; i < agenda.GetCount(); i++)
{
var element = agenda.GetEntry(i);
//ItemType添加到元素
var ecIns = ItemTypesHelpers.AttachItemTypeToElement(element, config.Name, g.Key);
foreach (var param in g)
{
string valueStr = param.Value?.ToString();
switch (param.DataType)
{
case TypeKind.Boolean:
if (bool.TryParse(valueStr, out bool boolValue))
ecIns.SetBoolean(param.Name, boolValue);
break;
case TypeKind.Double:
if (double.TryParse(valueStr, out double doubleValue))
ecIns.SetDouble(param.Name, doubleValue);
break;
case TypeKind.Integer:
if (int.TryParse(valueStr, out int intValue))
ecIns.SetInteger(param.Name, intValue);
break;
case TypeKind.String:
ecIns.SetString(param.Name, valueStr ?? string.Empty);
break;
default:
// 可记录日志或抛出异常
System.Diagnostics.Debug.WriteLine($"不支持的参数值类型: {param.DataType}");
break;
}
}
ecIns.WriteChanges();
}
}
}
catch (System.Exception ex)
{
MessageBox.Show($"添加配置到模型时发生错误:{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private bool CanOperate(ComponentConfig config) => SelectedConfig != null;
[RelayCommand]
private void ConfigManager()
{
ConfigurationManagerViewModel configManagerViewModel = new ConfigurationManagerViewModel();
ConfigurationsManagerView view = new() { DataContext = configManagerViewModel };
view.ShowDialog();
}
/// <summary>
/// 确保配置文件存在,如果不存在则创建
/// </summary>
private void EnsureConfigFileExists()
{
var dir = Path.GetDirectoryName(path);
if (Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
if (!File.Exists(path))
{
File.Create(path).Close();
}
}
[RelayCommand(CanExecute = nameof(CanOperate))]
private void ModifyConfig(ComponentConfig config)
{
if (config != null)
{
var copy = config.Clone() as ComponentConfig;
copy.Guid = config.Guid;
var configViewModel = new ConfigurationViewModel(copy);
var configurationView = new ConfigurationView
{
DataContext = configViewModel
};
configurationView.ShowDialog();
}
}
partial void OnSelectedComponentTypeChanged(ComponentType value)
{ Configs = allConfigs.Where(s => s.ComponentType == value).ToList(); }
partial void OnSelectedConfigChanged(ComponentConfig value)
{
if (value == null)
return;
cv = CollectionViewSource.GetDefaultView(value.Parameters);
cv.GroupDescriptions.Clear();
cv.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
}
/// <summary>
/// 接收新的配置列表
/// </summary>
/// <g name="message"></g>
public void Receive(string message)
{
//allConfigs = new List<ComponentConfig>(message);
//Configs = allConfigs.Where(s => s.ComponentType == SelectedComponentType).ToList();
var jsonString = File.ReadAllText(path);
allConfigs = JsonConvert.DeserializeObject<List<ComponentConfig>>(jsonString)
.Where(s => s.IsEnabled)
.ToList();
Configs = allConfigs.Where(s => s.ComponentType == SelectedComponentType).ToList();
SelectedConfig = Configs.FirstOrDefault();
}
/// <summary>
/// 修改当前模板的配置接收
/// </summary>
/// <param name="message"></param>
public void Receive(ComponentConfig message)
{
var existCofig = allConfigs.Where(c => c.Guid == message.Guid).FirstOrDefault();
//接收返回的配置,如果存在则更新,否则添加新的配置
if (existCofig != null)
{
var index = allConfigs.IndexOf(existCofig);
allConfigs[index] = message;
var jsonStr = JsonConvert.SerializeObject(allConfigs, Formatting.Indented);
EnsureConfigFileExists();
File.WriteAllText(path, jsonStr);
//更新配置列表
var jsonString = File.ReadAllText(path);
allConfigs = JsonConvert.DeserializeObject<List<ComponentConfig>>(jsonString)
.Where(s => s.IsEnabled)
.ToList();
SelectedComponentType = message.ComponentType;
Configs = allConfigs.Where(s => s.ComponentType == SelectedComponentType).ToList();
SelectedConfig = Configs.FirstOrDefault(c => c.Guid == message.Guid);
//Configs.Remove(existCofig);
//Configs.Insert(index, message);
//.ToList().ForEach(c => Configs.Remove(c));
}
}
}
}