using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.IO; using System.Net.Http; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using log4net; using Microsoft.Win32; using PdmSwPlugin.Commmon.Util.UI; using PdmSwPlugin.Common; using PdmSwPlugin.Common.Constants; using PdmSwPlugin.Common.Entity; using PdmSwPlugin.Common.Interface; using PdmSwPlugin.Common.Setting; using PdmSwPlugin.Common.Util; using PdmSwPlugin.Common.Util.Http; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; namespace PdmSwPlugin.PropertySetting { /// /// UserControl1.xaml 的交互逻辑 /// [PdmSwPlugin(Title = "属性设置")] public partial class PropertySettingControl : UserControl, ISwAppSetter, INotifyPropertyChanged, IActiveDocChangeHandler { private static ILog Logger = LogManager.GetLogger("PropertySetting"); #region 不能公用的东西,真有你的啊C# public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } public void RaiseAndSetIfChanged(ref T old, T @new, [CallerMemberName] string propertyName = null) { old = @new; if (propertyName != null) { RaisePropertyChanged(propertyName); } } #endregion #region 属性 public SldWorks SwApp { get; private set; } public ModelDoc2 LastModelDoc { set; get; } public ModelDoc2 ActiveDoc { set; get; } public Component2 Component { set; get; } public CustomPropertyManager swCuspro1; private HttpClient Client { get; set; } #endregion #region UI绑定 private string _activeDocPath; public string ActiveDocPath { get => _activeDocPath; set => RaiseAndSetIfChanged(ref _activeDocPath, value); } private int _activeDocType; public int ActiveDocType { get => _activeDocType; set { RaiseAndSetIfChanged(ref _activeDocType, value); } } private string _materialType; public string MaterialType { get => _materialType; set { RaiseAndSetIfChanged(ref _materialType, value); GetStuffItemSource(); } } private string _stuffType; public string StuffType { get => _stuffType; set { RaiseAndSetIfChanged(ref _stuffType, value); GetSurfaceItemSource(); GetHeatItemSource(); } } private string _surfaceType; public string SurfaceType { get => _surfaceType; set => RaiseAndSetIfChanged(ref _surfaceType, value); } private string _heatType; public string HeatType { get => _heatType; set => RaiseAndSetIfChanged(ref _heatType, value); } private ObservableCollection _materialTypeItemSource; public ObservableCollection MaterialTypeItemSource { get => _materialTypeItemSource; set => RaiseAndSetIfChanged(ref _materialTypeItemSource, value); } private ObservableCollection _stuffItemSource; public ObservableCollection StuffItemSource { get => _stuffItemSource; set => RaiseAndSetIfChanged(ref _stuffItemSource, value); } private ObservableCollection _surfaceItemSource; public ObservableCollection SurfaceItemSource { get => _surfaceItemSource; set => RaiseAndSetIfChanged(ref _surfaceItemSource, value); } private ObservableCollection _heatItemSource; public ObservableCollection HeatItemSource { get => _heatItemSource; set => RaiseAndSetIfChanged(ref _heatItemSource, value); } private ObservableCollection _propertyDataSource_2D; public ObservableCollection PropertyDataSource_2D { get => _propertyDataSource_2D; set => RaiseAndSetIfChanged(ref _propertyDataSource_2D, value); } #endregion private HttpClientCreator clientCreator { get; set; } public PropertySettingControl() { clientCreator = new HttpClientCreator(new HttpConfig(PluginSetting.Instance.BaseAddress)); InitializeComponent(); self.DataContext = this; } public PropertySettingControl(SldWorks SwApp) : this() { this.SwApp = SwApp; } private void InitPropertyData() { if (Client == null) { Client = clientCreator.GetClient(); } LoadComboxItemSource(); } /// /// 从服务器加载各种选项 /// private void LoadComboxItemSource() { GetMaterialTypeItemSource(); GetStuffItemSource(); GetSurfaceItemSource(); GetHeatItemSource(); } /// /// 查询加工件类型 /// private async void GetMaterialTypeItemSource() { try { Result> httpResult = await Client.GetAsyncAction>("openApi/wpf/materialType/select"); var temp = httpResult.HandleResult(); temp = temp ?? new ObservableCollection(); temp.Insert(0, "无"); MaterialTypeItemSource = temp; } catch (Exception e) { Logger.Error("获取加工件类型数据异常!", e); var temp = new ObservableCollection(); temp.Insert(0, "无"); MaterialTypeItemSource = temp; MessageBox.Show("获取加工件类型数据异常!", "错误", MessageBoxButton.OK, MessageBoxImage.Error); } } /// /// 查询材料类型 /// private async void GetStuffItemSource() { if (string.IsNullOrEmpty(MaterialType)) { StuffItemSource = new ObservableCollection { "无" }; return; } try { Result> httpResult = await Client.GetAsyncAction>("openApi/wpf/stuff/select", new Dictionary { ["materialType"] = MaterialType } ); var temp = httpResult.HandleResult(); temp = temp ?? new ObservableCollection(); temp.Insert(0, "无"); StuffItemSource = temp; } catch (Exception e) { Logger.Error("获取材料数据异常!", e); var temp = new ObservableCollection(); temp.Insert(0, "无"); StuffItemSource = temp; MessageBox.Show("获取材料数据异常!", "错误", MessageBoxButton.OK, MessageBoxImage.Error); } } /// /// 查询表处理类型 /// private async void GetSurfaceItemSource() { try { Result> httpResult = await Client.GetAsyncAction>("openApi/wpf/surface/select", new Dictionary { ["materialType"] = MaterialType, ["stuffType"] = StuffType }); var temp = httpResult.HandleResult(); temp = temp ?? new ObservableCollection(); temp.Insert(0, "无"); SurfaceItemSource = temp; } catch (Exception e) { var temp = new ObservableCollection(); temp.Insert(0, "无"); SurfaceItemSource = temp; MessageBox.Show("获取表面处理数据异常!", "错误", MessageBoxButton.OK, MessageBoxImage.Error); } } /// /// 查询热处理类型 /// private async void GetHeatItemSource() { try { Result> httpResult = await Client.GetAsyncAction>("openApi/wpf/heat/select", new Dictionary { ["materialType"] = MaterialType, ["stuffType"] = StuffType }); var temp = httpResult.HandleResult(); temp = temp ?? new ObservableCollection(); temp.Insert(0, "无"); HeatItemSource = temp; } catch (Exception e) { var temp = new ObservableCollection(); temp.Insert(0, "无"); HeatItemSource = temp; MessageBox.Show("获取热处理数据异常!", "错误", MessageBoxButton.OK, MessageBoxImage.Error); } } /// /// 根据激活的文档类型,变更属性可视 /// private void SwitchVisiable() { // 2D图纸 if (ActiveDocType == (int)swDocumentTypes_e.swDocDRAWING) { mainPanel.Visibility = Visibility.Collapsed; dataGridPanel.Visibility = Visibility.Visible; } else { mainPanel.Visibility = Visibility.Visible; dataGridPanel.Visibility = Visibility.Collapsed; } // 零件 if (ActiveDocType == (int)swDocumentTypes_e.swDocPART) { materialTypePanel.Visibility = Visibility.Visible; stuffPanel.Visibility = Visibility.Visible; surfacePanel.Visibility = Visibility.Visible; heatPanel.Visibility = Visibility.Visible; pricePanel.Visibility = Visibility.Visible; } // 装配体 else if (ActiveDocType == (int)swDocumentTypes_e.swDocASSEMBLY) { materialTypePanel.Visibility = Visibility.Collapsed; stuffPanel.Visibility = Visibility.Collapsed; surfacePanel.Visibility = Visibility.Collapsed; heatPanel.Visibility = Visibility.Collapsed; pricePanel.Visibility = Visibility.Collapsed; } } /// /// 从激活的文档中读取参数 /// private async void LoadDocProperties() { string tempStr; HashSet skipValue = new HashSet { "$PRP:\"SW-File Name\"" }; Dictionary properties; if (ActiveDocType == (int)swDocumentTypes_e.swDocPART) { properties = CustomPropertyUtil.GetCustomProperties(ActiveDoc, true, skipValue); // 零件 version.Text = "A"; materialCode.Text = properties.GetCustomValue(PropertyName.PART_NO); materialModel.Text = properties.GetCustomValue(PropertyName.PART_MODEL); materialName.Text = properties.GetCustomValue(PropertyName.PART_NAME); tempStr = properties.GetCustomValue("Rev"); // 版本 Rev if (string.IsNullOrEmpty(tempStr) == false) { version.Text = tempStr; } tempStr = properties.GetCustomValue(PropertyName.JGJ_TYPE); // 加工件类型 jgjlx if (string.IsNullOrEmpty(tempStr) == false) { MaterialType = tempStr; } else { materialType.SelectedIndex = 0; } tempStr = properties.GetCustomValue(PropertyName.STUFF_TYPE); // 材料名称 MATERIAL if (string.IsNullOrEmpty(tempStr) == false) { StuffType = tempStr; } else { stuff.SelectedIndex = 0; } // 表面处理 Finished tempStr = properties.GetCustomValue(PropertyName.SURFACE_TYPE); if (string.IsNullOrEmpty(tempStr) == false) { SurfaceType = tempStr; } else { surface.SelectedIndex = 0; } // 热处理 HEAT TREATMENT tempStr = properties.GetCustomValue(PropertyName.HEAT_TYPE); if (string.IsNullOrEmpty(tempStr) == false) { HeatType = tempStr; } else { heat.SelectedIndex = 0; } // 价格 jgjPrice tempStr = properties.GetCustomValue("jgjPrice"); if (string.IsNullOrEmpty(tempStr) == false) { price.Text = tempStr; } else { price.Text = "0.00"; } return; } else if (ActiveDocType == (int)swDocumentTypes_e.swDocASSEMBLY) { properties = CustomPropertyUtil.GetCustomProperties(ActiveDoc, true, skipValue); // 装配体 version.Text = "装配体"; materialCode.Text = properties.GetCustomValue(PropertyName.PART_NO); materialModel.Text = properties.GetCustomValue(PropertyName.PART_MODEL); materialName.Text = properties.GetCustomValue(PropertyName.PART_NAME); } else if (ActiveDocType == (int)swDocumentTypes_e.swDocDRAWING) { // 2D图纸 PropertyDataSource_2D = PropertyDataSource_2D ?? new ObservableCollection(); PropertyDataSource_2D.Clear(); if (!EngineeringDrawingPropertiesClass.SetDesigner(ActiveDoc, System.Environment.UserName)) { // GlobalFileLogger.Log("往工程图{0}里写入设计者{1}属性时失败", activeDoc.GetPathName(), System.Environment.UserName); } NameValueCollection allProperties = EngineeringDrawingPropertiesClass .ReadViaNotesAtFirstView(ActiveDoc, EngineeringDrawingPropertiesClass.PredefinedProperties); if (allProperties != null) { foreach (var v in allProperties.AllKeys) { PropertyDataSource_2D.Add(new PropertyInfo_2D(v, allProperties[v])); } } } } private void ClearDocProperties() { version.Text = ""; materialCode.Text = ""; materialModel.Text = ""; materialName.Text = ""; version.Text = ""; MaterialType = ""; StuffType = ""; SurfaceType = ""; HeatType = ""; price.Text = "0.00"; } private void SetDocProperties(Dictionary datas, bool forceUpdate) { } /// /// 获取当前页面的属性信息,防止变更文件后属性也变了 /// /// 属性集合 private Dictionary GetCurrentProperties() { Dictionary props = new Dictionary(); // 零件 if (ActiveDocType == (int)swDocumentTypes_e.swDocPART) { props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[0]] = materialCode.Text; props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[1]] = materialModel.Text; props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[2]] = materialName.Text; props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[3]] = MaterialType; props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[4]] = StuffType; props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[5]] = SurfaceType; props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[6]] = HeatType; props["Rev"] = version.Text; if (!price.IsReadOnly) { if (decimal.TryParse(price.Text, out decimal priceValue) && priceValue > 0) { props["jgjPrice"] = price.Text; } } // CustomerPropertiesWrapper.SetSingle(doc, GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[6], HeatType); } else if (ActiveDocType == (int)swDocumentTypes_e.swDocASSEMBLY) { props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[0]] = materialCode.Text; props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[1]] = materialModel.Text; props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[2]] = materialName.Text; props[GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[3]] = MaterialType; } return props; } /// /// 将属性设置进文档,注意,并没有保存 /// /// 文档 private void SetDocProperty(ModelDoc2 doc, Dictionary props) { props = props ?? GetCurrentProperties(); foreach (string name in doc.GetConfigurationNames()) { // 遍历所有的配置 Configuration config = doc.GetConfigurationByName(name) as Configuration; if (config.CustomPropertyManager != null) { // 只要该配置的自定义属性管理器不为空 foreach (KeyValuePair keyValuePair in props) { if (config.CustomPropertyManager.Add3(keyValuePair.Key, (int)swCustomInfoType_e.swCustomInfoText, keyValuePair.Value, 1) == (int)swCustomInfoAddResult_e.swCustomInfoAddResult_AddedOrChanged) { // 增加或改变成功 } } if (!props.ContainsKey("jgjPrice")) { // 如果没有加工件价格,就删除它 config.CustomPropertyManager.Delete2("jgjPrice"); } } } } public void SetSwApp(SldWorks SwApp) { this.SwApp = SwApp; } private void SaveButton_Click(object sender, RoutedEventArgs e) { if (ActiveDoc == null) { return; } if (Component != null) { ModelDoc2 doc = SwApp.IActiveDoc2; if (!DocUtil.IsSameDoc(ActiveDoc, doc)) { this.Warning("当前属性与Solidworks打开的文档不同,请先刷新!"); return; } // 不知道在干啥 swComponentSuppressionState_e CompState = (swComponentSuppressionState_e)Component.GetSuppression(); if (CompState == swComponentSuppressionState_e.swComponentLightweight) { swSuppressionError_e result = (swSuppressionError_e)Component.SetSuppression2((int)swComponentSuppressionState_e.swComponentResolved); if (result != swSuppressionError_e.swSuppressionChangeOk) { return; } } SetDocProperty(ActiveDoc, null); // swComponentLightweight int value = Component.SetSuppression2((int)swComponentSuppressionState_e.swComponentLightweight); Component.Select2(false, -1); ActiveDoc.Save(); this.Info("保存成功"); } else { SetDocProperty(ActiveDoc, null); int errors = 0, warnings = 0; ActiveDoc.Save3((int)swSaveAsOptions_e.swSaveAsOptions_AvoidRebuildOnSave, ref errors, ref warnings); this.Info("保存成功"); } } private void SaveAsButton_Click(object sender, RoutedEventArgs e) { if (ActiveDoc == null) { return; } ModelDoc2 doc = SwApp.IActiveDoc2; if (!DocUtil.IsSameDoc(ActiveDoc, doc)) { this.Warning("当前属性与Solidworks打开的文档不同,请先刷新!"); return; } string originDocPath = ActiveDoc.GetPathName(); string ext = Path.GetExtension(originDocPath); SaveFileDialog dlg = new SaveFileDialog { Title = "另存为", FileName = Path.GetFileNameWithoutExtension(originDocPath), DefaultExt = ext, Filter = $"(*{ext})|*{ext}", InitialDirectory = Path.GetDirectoryName(originDocPath), }; if (dlg.ShowDialog() == true) { // 把属性写入原文件,不保存,直接另存 SetDocProperty(ActiveDoc, null); ActiveDoc.SaveAs3(dlg.FileName, 0, 2); // 打开新文件,关闭旧文件 ModelDoc2 docTemp = SwApp.OpenDoc(dlg.FileName, (int)swDocumentTypes_e.swDocPART) as ModelDoc2; docTemp.Save(); SwApp.CloseDoc(originDocPath); } } private void DoReLoad() { try { ModelDoc2 doc = SwApp.IActiveDoc2; Component2 comp = null; if (doc != null) { Configuration activeConfiguration = doc.GetActiveConfiguration() as Configuration; if (activeConfiguration == null) { return; } comp = activeConfiguration.GetRootComponent3(false); } Dispatcher.Invoke( delegate { ActiveDoc = doc; if (doc == null) { ActiveDocPath = ""; Component = null; ClearDocProperties(); return; } ActiveDocPath = doc.GetPathName(); Component = comp; if (doc == LastModelDoc) { return; } LastModelDoc = doc; ActiveDocType = doc.GetType(); // 这里委托 SwitchVisiable(); // 读取文件,设置参数 LoadDocProperties(); }); } catch (Exception ex) { Logger.Error($"读取参数异常,文件:[{ActiveDocPath}]!", ex); this.Error($"读取参数异常:{ex.Message}"); } } private async void Refresh_Click(object sender, RoutedEventArgs e) { MaskAdorner.ShowMask(mainPanel); try { await Task.Run(() => { DoReLoad(); }); } finally { MaskAdorner.HideMask(mainPanel); } } private void LoadComboBox_Click(object sender, RoutedEventArgs e) { LoadComboxItemSource(); } private void PropertySettingControl_Initialized(object sender, EventArgs e) { InitPropertyData(); } /// /// 激活的文档变更触发 /// /// /// /// public void OnSwActiveDocChange(ModelDoc2 lastDoc, ModelDoc2 doc, Component2 comp) { // 因为里面有更新UI的操作,所以委托主线程去做下面的任务 // WPF真难用 // 2023-09-04 把自动更新注释了 //Dispatcher.Invoke( // delegate // { // try // { // ActiveDoc = doc; // ActiveDocPath = doc.GetPathName(); // Component = comp; // if (doc == null) // { // ClearDocProperties(); // return; // } // if (doc == LastModelDoc) // { // return; // } // LastModelDoc = doc; // ActiveDocType = doc.GetType(); // // 这里委托 // SwitchVisiable(); // // 读取文件,设置参数 // LoadDocProperties(); // // CustomerPropertiesWrapper.GetSingle(doc, GetDocumentPropertiesViaDM.PropertyNamesOftenUsed[0], false); // } // catch (Exception ex) // { // throw new PdmException("init初始化时发生异常", ex); // } // }); } public void OnSwActiveDocSaved(ModelDoc2 doc, Component2 comp) { // 读取文件,设置参数 // LoadDocProperties(); } public void OnCustomPropertyChange(string propName, string Configuration, string oldValue, string NewValue, int valueType) { } public void OnDocDestroy(ModelDoc2 doc) { } public void AfterDocDestroy() { } public void DisabledHandler() { } } }