EPLAN_PROD_Plugin/Sinvo.EplanHpD.Plugin.WPFUI/View/WireCheck/MainWindow.xaml.cs

645 lines
24 KiB
C#

using EPLAN.Harness.Common;
using EPLAN.Harness.Common.Extensions;
using EPLAN.Harness.Core.Common;
using EPLAN.Harness.Core.Controls;
using EPLAN.Harness.Core.Events;
using EPLAN.Harness.Core.Lampy;
using EPLAN.Harness.Core.Settings;
using EPLAN.Harness.IO;
using EPLAN.Harness.ProjectCore;
using EPLAN.Harness.ProjectCore.Occurrences;
using EPLAN.Harness.ProjectCore.Occurrences.Designer;
using EPLAN.Harness.ProjectCore.Report;
using HandyControl.Controls;
using Microsoft.Win32;
using Sinvo.EplanHpD.Plugin.WPFUI.Enum;
using Sinvo.EplanHpD.Plugin.WPFUI.Extension;
using Sinvo.EplanHpD.Plugin.WPFUI.Models;
using Sinvo.EplanHpD.Plugin.WPFUI.Utils;
using Sinvo.EplanHpD.Plugin.WPFUI.ViewModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace Sinvo.EplanHpD.Plugin.WPFUI;
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : System.Windows.Window
{
private MainViewModel ViewModel;
public delegate void UpdateDataGridColumns(List<DataGridColumn> columns, DataGridType type);
private IEnumerable<BaseReportEntry> datas;
private List<ReportColumn> reportColumns;
private FlexReport _report;
public MainWindow(FlexReport report)
{
InitializeComponent();
_report = report;
Init();
Application.Current.SetMainWindow(this);
}
private void Init()
{
this.DataContext = ViewModel = new MainViewModel();
ViewModel.UpdateDataGridColumns = UpdateDataGridColumnsByType;
var columns = _report.Reporter.Formater.RepColumns;
var datas = _report.GetAllReportEntries();
this.datas = datas;
this.reportColumns = columns;
ViewModel.DataColumns = [];
ViewModel.Data = [];
ViewModel.StuffedData = [];
ViewModel.ExportData = [];
ViewModel.SearchedData = [];
}
/// <summary>
/// 更新列
/// </summary>
/// <param name="columns"></param>
/// <param name="type"></param>
public void UpdateDataGridColumnsByType(List<DataGridColumn> columns, DataGridType type)
{
try
{
//this.Dispatcher.BeginInvoke(delegate ()
//{
switch (type)
{
case DataGridType.Originial:
UpdateOriginialDataGridColumns(columns);
break;
case DataGridType.Import:
UpdateImportDataGridColumns(columns);
break;
default:
break;
}
//});
}
catch (System.Exception ex)
{
FlexMessageBox.Error($"{ex}");
}
}
public void UpdateOriginialDataGridColumns(List<DataGridColumn> columns)
{
OriginialDataGrid.Columns.Clear();
//var columns = ViewModel.DataColumns;
foreach (var column in columns)
{
OriginialDataGrid.Columns.Add(column);
}
}
public void UpdateImportDataGridColumns(List<DataGridColumn> columns)
{
ImportDataGrid.Columns.Clear();
//var columns = ViewModel.DataColumns;
foreach (var column in columns)
{
ImportDataGrid.Columns.Add(column);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
DataTabControl.SelectedIndex = 1;
LoadingMask.Visibility = Visibility.Visible;
try
{
ViewModel.CheckAll(ViewModel.StuffedData);
}
catch (System.Exception ex)
{
Trace.WriteLine(ex.ToString());
}
LoadingMask.Visibility = Visibility.Collapsed;
}
/// <summary>
/// 生成模板数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GenTemplateBtn_Click(object sender, RoutedEventArgs e)
{
try
{
DataTabControl.SelectedIndex = 2;
ViewModel.GenExportData();
}
catch (System.Exception ex)
{
FlexMessageBox.Error($"{ex}");
}
}
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
Growl.Register("Message", GrowlParent);
LoadingMask.Visibility = Visibility.Visible;
await this.Dispatcher.BeginInvoke(async delegate ()
{
ExcelHelper.CheckAndGetCache(true);
await LoadDataAsync(datas, reportColumns);
});
}
catch (System.Exception ex)
{
FlexMessageBox.Error($"{ex}");
}
}
/// <summary>
/// 异步加载数据
/// </summary>
/// <param name="reportData"></param>
/// <param name="columns"></param>
/// <returns></returns>
public async Task LoadDataAsync(IEnumerable<BaseReportEntry> reportData, List<ReportColumn> columns)
{
var dataColumns = ViewModel.GetColumns(columns);
var data = ViewModel.LoadReportDataAsync(reportData, columns);
Task.WaitAll(dataColumns, data);
var stuffedData = ViewModel.StuffData(data.Result);
_ = stuffedData.ContinueWith(x =>
{
_ = this.Dispatcher.BeginInvoke(delegate ()
{
try
{
ViewModel.DataColumns?.Clear();
dataColumns.Result.Where(it => it != null).ForEach(ViewModel.DataColumns.Add);
ViewModel.Data?.Clear();
data.Result.Where(it => it != null).ForEach(ViewModel.Data.Add);
ViewModel.StuffedData?.Clear();
stuffedData.Result.Where(it => it != null).ForEach(ViewModel.StuffedData.Add);
UpdateDataGridColumnsByType([.. ViewModel.DataColumns], DataGridType.Originial);
ViewModel.SearchByWireName(null);
}
catch (Exception ex)
{
Trace.WriteLine($"{ex}");
}
LoadingMask.Visibility = Visibility.Collapsed;
});
});
}
/// <summary>
/// 导出报表数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ExportDataBtn_Click(object sender, RoutedEventArgs e)
{
try
{
if (ViewModel.ExportData == null || ViewModel.ExportData.Count <= 0)
{
FlexMessageBox.Info($"无数据可导出,请先点击上方生成导入模板数据!");
}
else
{
if (ViewModel.NameType == ExportFileNameType.ProjectNo && string.IsNullOrEmpty(ViewModel.ProjectNo))
{
FlexMessageBox.Warning($"请输入项目号!");
}
else
{
SaveFileDialog saveFileDialog = new()
{
Filter = "MS Excel (*.xlsx)|*.xlsx",//Singleton<LRS>.Instance["Report_ExpFilter", "Report_ExpFilter"],
FilterIndex = 1,
//FileName = $"{单芯线下单}{DateTime.Now:yyyy_MM_dd}.xlsx",
FileName = $"{GetFileName()}.xlsx",
AddExtension = true,
InitialDirectory = StudioSettings.Instance.ReportExport_Path,
CheckPathExists = true
};
if (saveFileDialog.ShowDialog() == true)
{
ExcelHelper.SaveByTemplate(ViewModel.ExportData, Path.Combine(FlexIOBase.GetParentPath(saveFileDialog.FileName), saveFileDialog.FileName));
FlexMessageBox.Info($"导出完成!");
}
}
}
}
catch (System.Exception ex)
{
FlexMessageBox.Error($"{ex}");
}
}
private string GetFileName()
{
if (ViewModel.NameType == ExportFileNameType.ProjectNo)
{
return $"{ViewModel.ProjectNo}";
}
if (ViewModel.NameType == ExportFileNameType.Mechanism)
{
return $"{ViewModel.MechanismNo}&{ViewModel.MechanismName}";
}
return $"{ViewModel.CustomFileName}";
}
/// <summary>
/// 忽略异常
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void IgnoreSelectedError_Click(object sender, RoutedEventArgs e)
{
bool isContinue = false;
if (FlexMessageBox.Warning(FlexMessageBox.Buttons.OK_CANCEL,
"Report",
"忽略异常后在导出下单报表时,将不会再进行管控,是否继续?", false) == System.Windows.Forms.DialogResult.OK)
{
isContinue = true;
}
if (isContinue)
if (ModelGenDataGrid.SelectedItems != null)
{
var selectedRows = ModelGenDataGrid.SelectedItems;
foreach (var item in selectedRows)
{
if (item is StuffedDataModel model)
{
//var stuffedItem = ViewModel.StuffedData.Where(it => it.WireName == model.WireName).First();
if (model.IsError)
{
//stuffedItem.IsIgnore = true;
model.IsIgnore = true;
}
}
}
}
}
private void Copy_Click(object sender, RoutedEventArgs e)
{
try
{
if (sender is MenuItem item)
{
var selectItems = ModelGenDataGrid.SelectedItems;
if (item.Tag?.ToString() == "MNo")
{
var str = string.Join("\n", selectItems.Cast<StuffedDataModel>().Select(item => item.WireCode));
Clipboard.SetText(str);
}
if (item.Tag?.ToString() == "ErrMsg")
{
var str = string.Join("\n", selectItems.Cast<StuffedDataModel>().Select(item => item.CheckedMsg));
Clipboard.SetText(str);
}
if (item.Tag?.ToString() == "MNoAndErrMsg")
{
var str = string.Join("\n", selectItems.Cast<StuffedDataModel>().Select(item => $"{item.WireCode}\t{item.CheckedMsg}"));
Clipboard.SetText(str);
}
if (item.Tag?.ToString() == "WireName")
{
var str = string.Join("\n", selectItems.Cast<StuffedDataModel>().Select(item => $"{item.WireName}"));
Clipboard.SetText(str);
}
}
e.Handled = true;
}
catch (Exception ex)
{
FlexMessageBox.Error(ex.Message);
}
}
/// <summary>
/// 取消忽略异常
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UnIgnoreSelectedError_Click(object sender, RoutedEventArgs e)
{
if (ModelGenDataGrid.SelectedItems != null)
{
var selectedRows = ModelGenDataGrid.SelectedItems;
foreach (var item in selectedRows)
{
if (item is StuffedDataModel model)
{
model.IsIgnore = false;
}
}
}
}
private void GoToSource()
{
var selectItems = ModelGenDataGrid.SelectedItems;
if (selectItems != null && selectItems.Count > 0)
//if (selectItems is List<StuffedDataModel> reportItems)
{
//foreach (ReportModel item in selectItems)
StuffedDataModel item = (StuffedDataModel)selectItems[0];
if (item != null)
{
var repoetEntry = datas.FirstOrDefault(it => it.ID == item.OccPartId);
_report.DataSources.GetSources();
if (repoetEntry.OrigDocIDs == null || repoetEntry.OrigDocIDs.Count == 0)
{
repoetEntry.OrigDocIDs = new List<string>();
foreach (IDataSource dataSource in _report.DataSources.GetSources())
{
IFlexStudioDocument documentByID = FlexProject.CurrentProject.GetDocumentByID(dataSource.ParentID);
FlexDesigner designer;
if ((designer = (documentByID as FlexDesigner)) != null)
{
FlexProject.CurrentProject.LoadDesignerMetadata(designer);
}
if (repoetEntry.OrigID != null && SelfControler<BaseOccurrence>.FindInstance(repoetEntry.OrigID) != null)
{
repoetEntry.OrigDocIDs.Add(documentByID.ID);
}
FlexProject.CurrentProject.CloseAllUsedDocuments();
}
}
foreach (string text in repoetEntry.OrigDocIDs.Distinct<string>())
{
FlexDesigner flexDesigner;
if (text != string.Empty && (flexDesigner = (SelfControler<FlexBaseOrganizer>.FindInstance(text) as FlexDesigner)) != null && (flexDesigner is not FlexWorkdesk || Lamparna.Instance.IsWorkdeskAvailable()) && (flexDesigner is not FlexWorkspace || Lamparna.Instance.IsWorkspaceAvailable()))
{
Singleton<EventProvider>.Instance.Invoke(NamedEvents.Open_Studio_Document, this._report,
[
flexDesigner
]);
if (flexDesigner.ReaderStatus != DataReaderStatus.Full)
{
break;
}
flexDesigner.SelectSet.Clear();
string origID = repoetEntry.OrigID;
List<BaseOccurrence> list = [];
BaseOccurrence baseOccurrence = SelfControler<BaseOccurrence>.FindInstance(origID);
if (baseOccurrence != null && flexDesigner.IsOccRegistered(baseOccurrence))
{
Singleton<EventProvider>.Instance.Invoke(NamedEvents.TreeView_BeginUpdate, this, []);
if (_report.Reporter is AggregatedBOMReporter)
{
using (List<string>.Enumerator enumerator3 = flexDesigner.GetOccurrencesWithSameLibID(new GUIDVerClass(baseOccurrence.LibID, baseOccurrence.LibVersion), false).GetEnumerator())
{
while (enumerator3.MoveNext())
{
string objID = enumerator3.Current;
list.Add(SelfControler<BaseOccurrence>.FindInstance(objID));
}
}
this.AddToDesignerSelectSet(flexDesigner, list);
Singleton<EventProvider>.Instance.Invoke(NamedEvents.TreeView_EndUpdate, this, []);
flexDesigner.FitToSelectSet();
continue;
}
if (baseOccurrence is OccSurfaceProtectionBase)
{
using (IEnumerator<IOccBundle> enumerator4 = (baseOccurrence as OccSurfaceProtectionBase).GetParentBundles().GetEnumerator())
{
while (enumerator4.MoveNext())
{
IOccBundle occBundle = enumerator4.Current;
list.Add(occBundle as BaseOccurrence);
}
}
this.AddToDesignerSelectSet(flexDesigner, list);
Singleton<EventProvider>.Instance.Invoke(NamedEvents.TreeView_EndUpdate, this, []);
flexDesigner.FitToSelectSet();
continue;
}
//if (_report.Reporter is AccessoryReporter && (baseOccurrence is OccAttachedPart || baseOccurrence is OccAttachedPartEC || baseOccurrence is BaseEncapsulatedOcc))
//{
// this.GoToSourceAttachedPart(baseOccurrence);
// Singleton<EventProvider>.Instance.Invoke(NamedEvents.TreeView_EndUpdate, this, Array.Empty<object>());
// break;
//}
list.Add(baseOccurrence);
this.AddToDesignerSelectSet(flexDesigner, list);
Singleton<EventProvider>.Instance.Invoke(NamedEvents.TreeView_EndUpdate, this, []);
flexDesigner.FitToSelectSet();
//flexDesigner.
flexDesigner.SelectSet.OnSelectionChanged();
}
}
}
}
}
}
private void AddToDesignerSelectSet(FlexDesigner designerDoc, List<BaseOccurrence> occurrences)
{
try
{
List<BaseOccurrence> list = new List<BaseOccurrence>();
foreach (BaseOccurrence baseOccurrence in occurrences)
{
bool? flag;
if (baseOccurrence == null)
{
flag = null;
}
else
{
FlexBaseOrganizer parentOrganizer = baseOccurrence.GetParentOrganizer();
flag = ((parentOrganizer != null) ? new bool?(parentOrganizer.IsOccRegistered(baseOccurrence)) : null);
}
if (flag ?? false)
{
baseOccurrence.SetVisibility(true, null);
list.Add(baseOccurrence);
}
}
designerDoc.SelectSet.Add(list);
}
catch (Exception ex)
{
FlexMessageBox.Error(ex.Message);
}
//designerDoc.
}
private void GoToSource_Click(object sender, RoutedEventArgs e)
{
try
{
//HideOthers();
GoToSource();
if (ViewModel.ToSourceAndMinSelf)
{
this.WindowState = WindowState.Minimized;
}
}
catch (Exception ex)
{
FlexMessageBox.Error(ex.Message);
}
}
private void OthersWireShow(bool show = false)
{
var selectItems = ModelGenDataGrid.SelectedItems;
if (selectItems != null && selectItems.Count > 0)
//if (selectItems is List<StuffedDataModel> reportItems)
{
//foreach (ReportModel item in selectItems)
StuffedDataModel item = (StuffedDataModel)selectItems[0];
if (item != null)
{
var reportEntry = datas.FirstOrDefault(it => it.Properties["WireName"].ValueString() == item.WireName);
_report.DataSources.GetSources();
if (reportEntry.OrigDocIDs == null || reportEntry.OrigDocIDs.Count == 0)
{
reportEntry.OrigDocIDs = new List<string>();
foreach (IDataSource dataSource in _report.DataSources.GetSources())
{
IFlexStudioDocument documentByID = FlexProject.CurrentProject.GetDocumentByID(dataSource.ParentID);
FlexDesigner designer;
if ((designer = (documentByID as FlexDesigner)) != null)
{
FlexProject.CurrentProject.LoadDesignerMetadata(designer);
}
if (reportEntry.OrigID != null && SelfControler<BaseOccurrence>.FindInstance(reportEntry.OrigID) != null)
{
reportEntry.OrigDocIDs.Add(documentByID.ID);
}
FlexProject.CurrentProject.CloseAllUsedDocuments();
}
}
if (reportEntry.OrigDocIDs != null && reportEntry.OrigDocIDs.Any())
{
var docId = reportEntry.OrigDocIDs.First();
var flexDesigner = SelfControler<FlexBaseOrganizer>.FindInstance(docId) as FlexDesigner;
if (flexDesigner != null)
{
var cables = flexDesigner.GetAllOccurrencesByLibID(true);
foreach (var cable in cables)
{
Debug.WriteLine("");
Debug.Write(cable.Key);
Debug.Write("-->");
//Debug.Write(string.Join(",", cable.Value));
Debug.WriteLine("");
cable.Value.ForEach(it =>
{
var occ = SelfControler<BaseOccurrence>.FindInstance(it);
if (occ is OccWire wire)
{
wire.SetVisibility(show, null);
Debug.WriteLine($"{wire.Name} SetVisibility {show}");
}
});
//Debug.Write("-->");
}
}
}
}
}
}
private void SearchBar_SearchStarted(object sender, HandyControl.Data.FunctionEventArgs<string> e)
{
Trace.WriteLine(e.Info.ToString());
ViewModel.SearchByWireName(e.Info);
}
private void RefreshReportDataBtn_Click(object sender, RoutedEventArgs e)
{
if (_report != null)
{
var isNeedUpdate = FlexReport.IsUpToDate(_report);
if (!isNeedUpdate)
{
if (FlexMessageBox.Warning(FlexMessageBox.Buttons.OK_CANCEL,
"Report",
"是否更新报表数据?", false) == System.Windows.Forms.DialogResult.OK)
{
_report.UpdateReport();
Init();
try
{
LoadingMask.Visibility = Visibility.Visible;
this.Dispatcher.BeginInvoke(async delegate ()
{
ExcelHelper.CheckAndGetCache(true);
await LoadDataAsync(datas, reportColumns);
});
}
catch (System.Exception ex)
{
FlexMessageBox.Error($"{ex}");
}
}
}
else
{
try
{
Growl.Success("报表数据已是最新!", "Message");
}
catch (Exception)
{
}
}
}
}
private void ToSourceAndHideOthers_Click(object sender, RoutedEventArgs e)
{
try
{
OthersWireShow();
GoToSource();
if (ViewModel.ToSourceAndMinSelf)
{
this.WindowState = WindowState.Minimized;
}
}
catch (Exception ex)
{
FlexMessageBox.Error(ex.Message);
}
}
private void ShowAllWire_Click(object sender, RoutedEventArgs e)
{
OthersWireShow(true);
GoToSource();
}
}