DataViewModel.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Data;
  14. using System.Windows.Forms;
  15. using Aitex.Core.RT.Log;
  16. using Aitex.Sorter.Common;
  17. using MECF.Framework.Common.DataCenter;
  18. using MECF.Framework.Common.Equipment;
  19. using MECF.Framework.UI.Client.CenterViews.DataLogs.Event;
  20. using MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory;
  21. #if !EXPORT_TO_CSV
  22. using MECF.Framework.Common.Utilities;
  23. #endif
  24. using MECF.Framework.UI.Client.CenterViews.Operations.RealTime;
  25. using MECF.Framework.UI.Client.ClientBase;
  26. using MECF.Framework.UI.Client.ClientBase.Charting;
  27. using MECF.Framework.UI.Client.ClientBase.EventArgs;
  28. using MECF.Framework.UI.Client.ClientBase.Pipelines;
  29. using MECF.Framework.UI.Client.ClientBase.Tree;
  30. using SciChart.Charting.Model.DataSeries;
  31. using SciChart.Charting.Visuals.Axes;
  32. using SciChart.Charting.Visuals.RenderableSeries;
  33. using SciChart.Core.Extensions;
  34. using SciChart.Core.Framework;
  35. using SciChart.Data.Model;
  36. using Cali = Caliburn.Micro;
  37. using DataGridCell = System.Windows.Controls.DataGridCell;
  38. using DateRange = SciChart.Data.Model.DateRange;
  39. using MessageBox = System.Windows.MessageBox;
  40. using TreeNode = MECF.Framework.UI.Client.ClientBase.Tree.TreeNode;
  41. namespace MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory
  42. {
  43. public class DataViewModel : BusyIndicateableUiViewModelBase
  44. {
  45. #region Variables
  46. /// <summary>
  47. /// 一次最多查询的项目数。
  48. /// </summary>
  49. private const int MAX_ITEMS_PER_QUERY = 50;
  50. private IRange _timeRange;
  51. private IRange _visibleRangeValue;
  52. private AutoRange _autoRange;
  53. private CancellationTokenSource _cancellationTokenSource;
  54. /// <summary>
  55. /// 更新报告导出信息。
  56. /// </summary>
  57. private readonly IProgress<ProgressUpdatingEventArgs> _progCsvExport;
  58. /// <summary>
  59. /// 查询进度信息更新。
  60. /// </summary>
  61. private IProgress<ProgressUpdatingEventArgs> _progQueryUpdate;
  62. /// <summary>
  63. /// 挂起或恢复Chart更新
  64. /// </summary>
  65. private readonly IProgress<bool> _progChartSuspendUpdating;
  66. private IUpdateSuspender _suspender;
  67. /// <summary>
  68. /// 打开错误消息对话框。
  69. /// </summary>
  70. private readonly IProgress<string> _progShowErrorMessageBox;
  71. #endregion
  72. #region Constructors
  73. public DataViewModel()
  74. {
  75. DisplayName = "Data History";
  76. SelectedData = new ChartingLineSeriesCollection(DisplayName);
  77. var now = DateTime.Today;
  78. SearchBeginTime = DateTime.Now.AddHours(-1); // -new TimeSpan(1, 0, 0, 0);
  79. SearchEndTime = DateTime.Now;
  80. //SearchBeginTime = new DateTime(now.Year, now.Month, now.Day, 00, 00, 00); ;// -new TimeSpan(1, 0, 0, 0);
  81. //SearchEndTime = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
  82. var provider = new RealtimeProvider();
  83. ParameterNodes = new TreeNode(DisplayName)
  84. {
  85. MaxTerminalSelectionAllowed = MAX_ITEMS_PER_QUERY
  86. };
  87. ParameterNodes.ChildNodes.AddRange(provider.GetTreeNodeParameters());
  88. VisibleRangeTime = new DateRange(DateTime.Now.AddMinutes(-60), DateTime.Now.AddMinutes(60));
  89. VisibleRangeValue = new DoubleRange(0, 10);
  90. _progQueryUpdate = new Progress<ProgressUpdatingEventArgs>(e =>
  91. {
  92. if (e.CurrentProgress == e.TotalProgress)
  93. {
  94. IsBusy = false;
  95. if (_cancellationTokenSource?.Token.IsCancellationRequested == false)
  96. {
  97. foreach (var renderableSeries in SelectedData)
  98. {
  99. var series = renderableSeries as FastLineSeries;
  100. var dataSeries = series?.GetDataSeries();
  101. try
  102. {
  103. if (series != null && dataSeries != null)
  104. {
  105. var node = series.BackendParameterNode;
  106. if (double.IsInfinity((double)dataSeries.YRange.Diff))
  107. {
  108. node.ClearStatistic();
  109. }
  110. else
  111. {
  112. var min = ((double)dataSeries.YMin);
  113. var max = ((double)dataSeries.YMax);
  114. var average =
  115. dataSeries.Metadata.Cast<ParameterNodePoint>().Average(x => x.Value);
  116. node.SetStatistic(min, max, average);
  117. }
  118. }
  119. }
  120. catch (Exception ex)
  121. {
  122. var err = $"It's failed to load data of {series?.DataName ?? "Unknown"}, {ex.Message}";
  123. LOG.Error(err, ex);
  124. }
  125. }
  126. }
  127. ChartAutoRange = AutoRange.Never;
  128. ((DataView)View).chart.ZoomExtents();
  129. }
  130. BusyIndicatorContent = e.Message;
  131. });
  132. _progCsvExport = new Progress<ProgressUpdatingEventArgs>(e =>
  133. {
  134. BusyIndicatorContent = e.Message;
  135. });
  136. _progChartSuspendUpdating = new Progress<bool>(isSuspend =>
  137. {
  138. if (isSuspend)
  139. _suspender = ((DataView)View).chart.SuspendSuspendUpdates();
  140. else
  141. {
  142. try
  143. {
  144. if (_suspender?.IsSuspended == true)
  145. _suspender?.SafeDispose();
  146. }
  147. catch (Exception)
  148. {
  149. // 查询过程最后会强制恢复挂起一次,可能引发异常,忽略此异常。
  150. }
  151. }
  152. });
  153. _progShowErrorMessageBox = new Progress<string>((error =>
  154. {
  155. System.Windows.Forms.MessageBox.Show(error, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  156. }));
  157. }
  158. #endregion
  159. #region Property
  160. public bool IsPermission => Permission == 3;
  161. private DataView view;
  162. public TreeNode ParameterNodes { get; }
  163. public ChartingLineSeriesCollection SelectedData { get; set; }
  164. public AutoRange ChartAutoRange
  165. {
  166. get => _autoRange;
  167. set
  168. {
  169. _autoRange = value;
  170. NotifyOfPropertyChange(nameof(ChartAutoRange));
  171. }
  172. }
  173. public IRange VisibleRangeTime
  174. {
  175. get => _timeRange;
  176. set
  177. {
  178. _timeRange = value;
  179. NotifyOfPropertyChange(nameof(VisibleRangeTime));
  180. }
  181. }
  182. public IRange VisibleRangeValue
  183. {
  184. get => _visibleRangeValue;
  185. set
  186. {
  187. _visibleRangeValue = value;
  188. NotifyOfPropertyChange(nameof(VisibleRangeValue));
  189. }
  190. }
  191. //public DateTime StartDateTime
  192. //{
  193. // get => ((DataView)View).wfTimeFrom.Value;
  194. // set
  195. // {
  196. // ((DataView)View).wfTimeFrom.Value = value;
  197. // NotifyOfPropertyChange(nameof(StartDateTime));
  198. // }
  199. //}
  200. //public DateTime EndDateTime
  201. //{
  202. // get => ((DataView)View).wfTimeTo.Value;
  203. // set
  204. // {
  205. // ((DataView)View).wfTimeTo.Value = value;
  206. // NotifyOfPropertyChange(nameof(EndDateTime));
  207. // }
  208. //}
  209. public DateTime SearchBeginTime { get; set; }
  210. public DateTime SearchEndTime { get; set; }
  211. #endregion
  212. #region Methods
  213. protected override void OnViewLoaded(object view)
  214. {
  215. base.OnViewLoaded(view);
  216. this.view = (DataView)view;
  217. //StartDateTime = DateTime.Now.Date;
  218. //EndDateTime = DateTime.Now.Date.AddDays(1).AddTicks(-1);
  219. this.view.wfTimeFrom.Content = SearchBeginTime.ToString("yyyy-MM-dd HH:mm:ss");
  220. this.view.wfTimeTo.Content = SearchEndTime.ToString("yyyy-MM-dd HH:mm:ss");
  221. }
  222. public void SelectDate(string SelectType)
  223. {
  224. var windowManager = Caliburn.Micro.Core.IoC.Get<Caliburn.Micro.IWindowManager>();
  225. if (SelectType == "Start")
  226. {
  227. this.SearchBeginTime = Convert.ToDateTime(this.view.wfTimeFrom.Content);
  228. SelectDateViewModel selectdateViewModel = new SelectDateViewModel(SearchBeginTime);
  229. var result = (windowManager as Caliburn.Micro.WindowManager)?.ShowDialogWithTitle(selectdateViewModel, null, "Start Time");
  230. if (result == true)
  231. {
  232. SearchBeginTime = selectdateViewModel.SearchDate;
  233. this.view.wfTimeFrom.Content = selectdateViewModel.SearchDate;
  234. }
  235. }
  236. else
  237. {
  238. this.SearchEndTime = Convert.ToDateTime(this.view.wfTimeTo.Content);
  239. SelectDateViewModel selectdateViewModel = new SelectDateViewModel(SearchEndTime);
  240. var result = (windowManager as Caliburn.Micro.WindowManager)?.ShowDialogWithTitle(selectdateViewModel, null, "End Time");
  241. if (result == true)
  242. {
  243. this.view.wfTimeTo.Content = selectdateViewModel.SearchDate;
  244. }
  245. }
  246. }
  247. public void ToLeftClick()
  248. {
  249. var view = GetView() as DataView;
  250. view.chart.sciChart.ChartModifier.XAxis.Scroll(-50, SciChart.Charting.ClipMode.ClipAtMin);
  251. }
  252. public void ToRightClick()
  253. {
  254. var view = GetView() as DataView;
  255. view.chart.sciChart.ChartModifier.XAxis.Scroll(50, SciChart.Charting.ClipMode.ClipAtMax);
  256. }
  257. public void ZoomInClick()
  258. {
  259. var view = GetView() as DataView;
  260. view.chart.sciChart.ChartModifier.XAxis.ZoomBy(-0.1, -0.1);
  261. view.chart.sciChart.ChartModifier.YAxis.ZoomBy(-0.1, -0.1);
  262. }
  263. public void ZoomOutClick()
  264. {
  265. var view = GetView() as DataView;
  266. view.chart.sciChart.ChartModifier.XAxis.ZoomBy(0.1, 0.1);
  267. view.chart.sciChart.ChartModifier.YAxis.ZoomBy(0.1, 0.1);
  268. }
  269. public void XZoomInClick()
  270. {
  271. var view = GetView() as DataView;
  272. view.chart.sciChart.ChartModifier.XAxis.ZoomBy(-0.1, -0.1);
  273. }
  274. public void XZoomOutClick()
  275. {
  276. var view = GetView() as DataView;
  277. view.chart.sciChart.ChartModifier.XAxis.ZoomBy(0.1, 0.1);
  278. }
  279. public void ToMoveUpClick()
  280. {
  281. var view = GetView() as DataView;
  282. view.chart.sciChart.ChartModifier.YAxis.Scroll(-50, SciChart.Charting.ClipMode.ClipAtMin);
  283. }
  284. public void ToMoveDownClick()
  285. {
  286. var view = GetView() as DataView;
  287. view.chart.sciChart.ChartModifier.YAxis.Scroll(50, SciChart.Charting.ClipMode.ClipAtMax);
  288. }
  289. public void Query(object parameter)
  290. {
  291. WaferHistoryRecipe waferHistoryRecipe = parameter as WaferHistoryRecipe;
  292. if (waferHistoryRecipe != null)
  293. {
  294. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  295. {
  296. if (waferHistoryRecipe.StartTime != DateTime.MinValue)
  297. SearchBeginTime = waferHistoryRecipe.StartTime;
  298. if (waferHistoryRecipe.EndTime != DateTime.MinValue)
  299. SearchEndTime = waferHistoryRecipe.EndTime;
  300. else
  301. SearchEndTime = waferHistoryRecipe.StartTime.AddHours(1);
  302. //ParameterNodes.ForEachDo((x) =>
  303. //{
  304. // x.Selected = true;
  305. // ParameterCheck(x);
  306. //});
  307. QueryData();
  308. }));
  309. }
  310. }
  311. /// <summary>
  312. /// 查询数据。
  313. /// </summary>
  314. /// <exception cref="Exception"></exception>
  315. public void QueryData(bool isAppend = false)
  316. {
  317. this.SearchBeginTime = Convert.ToDateTime(this.view.wfTimeFrom.Content);
  318. this.SearchEndTime = Convert.ToDateTime(this.view.wfTimeTo.Content);
  319. if (SearchBeginTime > SearchEndTime)
  320. {
  321. MessageBox.Show("time range invalid, start time should be early than end time.", "Error",
  322. MessageBoxButton.OK,
  323. MessageBoxImage.Error);
  324. return;
  325. }
  326. // 哪些模组(TreeView的顶层Nodes)有选中项。
  327. var selectedModules = ParameterNodes.ChildNodes.Where(x => x.HasTerminalSelected).ToList();
  328. if (!selectedModules.Any())
  329. {
  330. MessageBox.Show($"No item(s) are selected to query.", "Warning", MessageBoxButton.OK,
  331. MessageBoxImage.Warning);
  332. return;
  333. }
  334. VisibleRangeTime = new DateRange(SearchBeginTime.AddHours(-1), SearchEndTime.AddHours(1));
  335. ChartAutoRange = AutoRange.Always;
  336. BusyIndicatorContent = "Preparing list ...";
  337. IsBusy = true;
  338. _cancellationTokenSource = new CancellationTokenSource();
  339. #region 生成曲线列表
  340. var selectedTerminal =
  341. selectedModules.SelectMany(x => x.Flatten(true).Where(p => p.IsSelected == true)).ToList();
  342. List<IRenderableSeries> appendedSeries = null;
  343. if (isAppend)
  344. appendedSeries = SelectedData.Append(selectedTerminal);
  345. else
  346. {
  347. SelectedData.ReArrange(selectedTerminal);
  348. appendedSeries = SelectedData.ToList();
  349. }
  350. SelectedData.ResetColors();
  351. #endregion
  352. var dataSeriesList = appendedSeries.Select(x => x.DataSeries).ToList();
  353. Task.Run(async () =>
  354. {
  355. // 延时启动,等待UI准备好
  356. await Task.Delay(500);
  357. var pipeline = new TwoStagePipelineBasedTaskExecutor<DataSet, object>();
  358. pipeline.Stage2ActionStarted += (s, e) =>
  359. {
  360. // 挂起Chart
  361. _progChartSuspendUpdating.Report(true);
  362. };
  363. pipeline.Stage2ActionFinished += (s, e) =>
  364. {
  365. // 挂起刷新
  366. _progChartSuspendUpdating.Report(false);
  367. };
  368. pipeline.Stage1Finished += (s, e) =>
  369. {
  370. // 查询完毕,Chart可能仍在渲染。
  371. _progQueryUpdate?.Report(new ProgressUpdatingEventArgs(50, 100, "Still rendering chart ..."));
  372. };
  373. using (pipeline)
  374. {
  375. var plTasks = pipeline.Start(null);
  376. try
  377. {
  378. //! 按时间分段查询,解决查询速度慢导致卡后台业务的问题。
  379. var ts = SearchEndTime - SearchBeginTime;
  380. if (ts.Days <= 1)
  381. {
  382. Query(pipeline, selectedModules, dataSeriesList, view.dataGrid1, SearchBeginTime, SearchEndTime,
  383. _cancellationTokenSource, _progQueryUpdate);
  384. // 结束流水线
  385. pipeline.AppendFunc1(null);
  386. pipeline.AppendFunc2(null);
  387. }
  388. else
  389. {
  390. var daySlices =
  391. DateRangeHelper.SplitInToHours(new DateRangeHelper(SearchBeginTime, SearchEndTime), 12);
  392. foreach (var range in daySlices)
  393. {
  394. Query(pipeline, selectedModules, dataSeriesList, view.dataGrid1, range.Start, range.End,
  395. _cancellationTokenSource, _progQueryUpdate);
  396. if (_cancellationTokenSource.Token.IsCancellationRequested)
  397. break;
  398. await Task.Delay(1);
  399. }
  400. // 结束流水线
  401. pipeline.AppendFunc1(null);
  402. pipeline.AppendFunc2(null);
  403. }
  404. await Task.WhenAll(plTasks.ToArray());
  405. }
  406. catch (ThreadAbortException ex)
  407. {
  408. Thread.Sleep(500);
  409. // 查询操作被取消。
  410. Debug.WriteLine(ex);
  411. }
  412. catch (AggregateException ae)
  413. {
  414. var errs = new StringBuilder();
  415. foreach (var ex in ae.Flatten().InnerExceptions)
  416. {
  417. LOG.Error(ex.Message, ex);
  418. errs.AppendLine(ex.Message);
  419. }
  420. var errMsg = $"It's failed to query data, {errs}";
  421. _progShowErrorMessageBox.Report(errMsg);
  422. LOG.Error(errMsg, ae);
  423. }
  424. catch (Exception ex)
  425. {
  426. var errMsg = $"It's failed to query data, {ex.Message}";
  427. _progShowErrorMessageBox.Report(errMsg);
  428. LOG.Error(errMsg, ex);
  429. }
  430. finally
  431. {
  432. // 等待一下UI
  433. Thread.Sleep(100);
  434. _progQueryUpdate.Report(new ProgressUpdatingEventArgs(100, 100, ""));
  435. // 强制恢复Chart刷新,避免异常情况导致的Chart挂起。
  436. _progChartSuspendUpdating.Report(false);
  437. }
  438. }
  439. });
  440. }
  441. /// <summary>
  442. /// 查询数据
  443. /// </summary>
  444. private static void Query(TwoStagePipelineBasedTaskExecutor<DataSet, object> pipeline, IEnumerable<TreeNode> selectedModules, List<IDataSeries> dataSeriesList, System.Windows.Controls.DataGrid dataGrid, DateTime startTime, DateTime endTime,
  445. CancellationTokenSource cancellation, IProgress<ProgressUpdatingEventArgs> progressReporter = null)
  446. {
  447. pipeline.AppendFunc1(() =>
  448. SearchDataBaseAsync(
  449. selectedModules,
  450. new DateRangeHelper(startTime, endTime),
  451. cancellation,
  452. progressReporter));
  453. pipeline.AppendFunc2(ds =>
  454. {
  455. RenderChartAndTable(ds, dataSeriesList, dataGrid, cancellation, progressReporter);
  456. return null;
  457. });
  458. //pipeline.AppendFunc2(ds =>
  459. //{
  460. // RenderDataGridTable(ds, , cancellation, progressReporter);
  461. // return null;
  462. //});
  463. }
  464. /// <summary>
  465. /// 取消查询。
  466. /// </summary>
  467. public void CancelQuery()
  468. {
  469. Task.Run(() =>
  470. {
  471. if (_cancellationTokenSource?.Token.CanBeCanceled == true)
  472. {
  473. _cancellationTokenSource.Cancel();
  474. }
  475. Thread.Sleep(100);
  476. _progQueryUpdate.Report(new ProgressUpdatingEventArgs(100, 100, ""));
  477. _progChartSuspendUpdating.Report(false);
  478. });
  479. if (View is DataView view)
  480. view.dataGrid.CancelOperation();
  481. }
  482. /// <summary>
  483. /// 检查指定的表名是否存在。
  484. /// </summary>
  485. /// <param name="tableName"></param>
  486. /// <returns></returns>
  487. private static bool CheckTableExists(string tableName)
  488. {
  489. var sql =
  490. $"SELECT EXISTS ( SELECT FROM pg_tables WHERE schemaname = 'public' AND tablename = '{tableName}' );";
  491. var table = QueryDataClient.Instance.Service.QueryData(sql);
  492. if (table == null)
  493. return false;
  494. if (table.Rows.Count <= 0)
  495. return false;
  496. var value = table.Rows[0][0].ToString();
  497. if (value.ToLower() == "true")
  498. return true;
  499. return false;
  500. }
  501. /// <summary>
  502. /// 根据左侧选项查询数据
  503. /// </summary>
  504. /// <returns></returns>
  505. private static DataSet SearchDataBaseAsync(
  506. IEnumerable<TreeNode> modules, DateRangeHelper dateRange,
  507. CancellationTokenSource cancellation = null,
  508. IProgress<ProgressUpdatingEventArgs> progressReporter = null)
  509. {
  510. var ds = new DataSet();
  511. using (cancellation?.Token.Register(Thread.CurrentThread.Abort, true))
  512. {
  513. // 遍历模组
  514. foreach (var module in modules)
  515. {
  516. var sql = new StringBuilder();
  517. //! 因为数据库中按天拆表,无法一次性查询数据,需使用UNION合并多表查询,因此此处按天拼接SQL表达式
  518. // 最终SQL表达式结构为:
  519. // (select xx from date1.xx) union (select xx from date2.xx) union (select xx from date3.xx)
  520. // where time between xxx and xxx
  521. // order by time asc
  522. var ts = dateRange.Diff;
  523. for (var day = 0; day <= ts.Days; day++)
  524. {
  525. // 检查表名是否存在,否则SQL执行出错。
  526. var tblName = $"{dateRange.Start.AddDays(day):yyyyMMdd}.{module}";
  527. if (module.ToString() == "IO")
  528. {
  529. //var node = module.ChildNodes.FirstOrDefault(x => (bool)x.HasTerminalSelected);
  530. tblName = $"{dateRange.Start.AddDays(day):yyyyMMdd}.System";
  531. }
  532. else
  533. if (!ModuleHelper.IsPm(module.ToString()))
  534. {
  535. tblName = $"{dateRange.Start.AddDays(day):yyyyMMdd}.System";
  536. }
  537. if (CheckTableExists(tblName))
  538. {
  539. sql.Append("select \"time\" AS InternalTimeStamp");
  540. var selectedParams = module.Flatten(true)
  541. .Where(x => x.IsSelected == true);
  542. // 添加待查询的列
  543. foreach (var item in selectedParams)
  544. {
  545. sql.Append("," + $"\"{item}\"");
  546. }
  547. sql.Append($" from \"{tblName}\" ");
  548. if (day < ts.Days)
  549. sql.Append(" UNION ");
  550. }
  551. }
  552. // 所有表名不可用,可能是日期范围错误
  553. if (sql.Length <= 0)
  554. {
  555. continue;
  556. }
  557. sql.Append(
  558. $" where \"time\" between {dateRange.Start.Ticks} and {dateRange.End.Ticks} order by InternalTimeStamp asc");
  559. progressReporter?.Report(new ProgressUpdatingEventArgs(20, 100,
  560. $"Querying {dateRange}..."));
  561. if (cancellation?.Token.IsCancellationRequested == true)
  562. return null;
  563. // 查询数据并将返回的结果存储在DataSet中
  564. var dataTable = QueryDataClient.Instance.Service.QueryData(sql.ToString());
  565. if (cancellation?.Token.IsCancellationRequested == true)
  566. return null;
  567. //! 返回的 DataTable 可能不存在,原因是上述代码自动生成的表明可能不存在。
  568. if (dataTable == null)
  569. continue;
  570. dataTable.TableName = module.Name;
  571. ds.Tables.Add(dataTable);
  572. }
  573. }
  574. return ds;
  575. }
  576. /// <summary>
  577. /// 渲染图表。
  578. /// </summary>
  579. /// <param name="ds"></param>
  580. /// <param name="dataSeriesList"></param>
  581. /// <param name="cancellation"></param>
  582. /// <param name="progressReporter"></param>
  583. /// <exception cref="Exception"></exception>
  584. private static void RenderChartAndTable(
  585. DataSet ds, List<IDataSeries> dataSeriesList, System.Windows.Controls.DataGrid dataGrid,
  586. CancellationTokenSource cancellation = null,
  587. IProgress<ProgressUpdatingEventArgs> progressReporter = null)
  588. {
  589. if (ds == null || ds.Tables.Count <= 0)
  590. return;
  591. Dictionary<string, Dictionary<long, string>> bigTable = new Dictionary<string, Dictionary<long, string>>();
  592. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  593. {
  594. dataGrid.Columns.Clear();
  595. DataGridTextColumn dataGridTextColumn = new DataGridTextColumn();
  596. dataGridTextColumn.Header = "Time";
  597. dataGridTextColumn.Binding = new System.Windows.Data.Binding("internaltimestamp");
  598. ((System.Windows.Data.Binding)dataGridTextColumn.Binding).Converter = new StringToDateTimeStringConvert();
  599. dataGrid.Columns.Add(dataGridTextColumn);
  600. }));
  601. // 一个Table一个模组
  602. foreach (var table in ds.Tables.Cast<DataTable>())
  603. {
  604. if (table.Rows.Count <= 0)
  605. continue;
  606. // 一列对应模组中的某个数据记录点
  607. foreach (var col in table.Columns.Cast<DataColumn>())
  608. {
  609. // 忽略时间列
  610. if (col.Ordinal == 0)
  611. continue;
  612. Dictionary<long, string> dictColumn = new Dictionary<long, string>();
  613. var fullName = col.ColumnName;
  614. col.ColumnName = col.ColumnName.Replace(".", "");
  615. var dataSeries =
  616. dataSeriesList.FirstOrDefault(x => x.SeriesName == fullName) as XyDataSeries<DateTime, double>;
  617. if (dataSeries == null)
  618. continue;
  619. var rows = table.Rows;
  620. var dateList = new List<DateTime>();
  621. var valueList = new List<double>();
  622. var metaList = new List<ParameterNodePoint>();
  623. for (var i = 0; i < rows.Count; i++)
  624. {
  625. var date = new DateTime(long.Parse(rows[i][0].ToString()));
  626. var cellValue = rows[i][col];
  627. var value = double.NaN;
  628. if (cellValue is bool b)
  629. value = b ? 1 : 0;
  630. else if (double.TryParse(cellValue.ToString(), out var num))
  631. value = num;
  632. else
  633. value = 0;
  634. dateList.Add(date);
  635. valueList.Add(value);
  636. metaList.Add(new ParameterNodePoint(date, value));
  637. dictColumn.Add(long.Parse(rows[i][0].ToString()), value.ToString());
  638. if (cancellation?.Token.IsCancellationRequested == true)
  639. return;
  640. }
  641. bigTable.Add(fullName.Replace(".", ""), dictColumn);
  642. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  643. {
  644. DataGridTextColumn dataGridTextColumn2 = new DataGridTextColumn();
  645. dataGridTextColumn2.Header = fullName;
  646. dataGridTextColumn2.Binding = new System.Windows.Data.Binding(fullName.Replace(".", ""));
  647. var MyStyle = new Style(typeof(DataGridCell))
  648. {
  649. Setters = {
  650. new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center)
  651. }
  652. };
  653. dataGridTextColumn2.CellStyle = MyStyle;
  654. dataGrid.Columns.Add(dataGridTextColumn2);
  655. }));
  656. if (cancellation?.Token.IsCancellationRequested == true)
  657. return;
  658. dataSeries.Append(dateList, valueList, metaList);
  659. }
  660. if (cancellation?.Token.IsCancellationRequested == true)
  661. return;
  662. // 每一轮更新完毕后会恢复Chart刷新,
  663. // 数据量太小时会频繁挂起和恢复Chart,导致Chart不刷新,需要稍等一下UI。
  664. Thread.Sleep(50);
  665. }
  666. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  667. {
  668. System.Data.DataTable dt = new System.Data.DataTable();
  669. dt = new System.Data.DataTable($"Temp");
  670. dt.Columns.Add("internaltimestamp", typeof(long));
  671. foreach (var item in bigTable.Keys)
  672. {
  673. dt.Columns.Add(item, typeof(string));
  674. }
  675. if (bigTable.Count > 0)
  676. {
  677. foreach (var subitem in bigTable[bigTable.FirstOrDefault().Key].Keys)
  678. {
  679. var row = dt.NewRow();
  680. row[0] = subitem;
  681. foreach (var col in bigTable.Keys)
  682. {
  683. row[col] = bigTable[col][subitem];
  684. }
  685. dt.Rows.Add(row);
  686. }
  687. }
  688. dataGrid.ItemsSource = dt.DefaultView;
  689. }));
  690. }
  691. public void Exporting(object sender, EventArgs e)
  692. {
  693. BusyIndicatorContent = "Exporting Start ...";
  694. IsBusy = true;
  695. }
  696. public void Exported(object sender, EventArgs e)
  697. {
  698. IsBusy = false;
  699. }
  700. public void Deleted(object sender, EventArgs e)
  701. {
  702. ((DataView)View).tvParameterNodes.ClearPresetGroupSelectionOnly();
  703. }
  704. public void ProgressUpdating(object sender, ProgressUpdatingEventArgs e)
  705. {
  706. _progCsvExport.Report(e);
  707. }
  708. #endregion
  709. }
  710. public class StringToDateTimeStringConvert : IValueConverter
  711. {
  712. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  713. {
  714. return new DateTime((Int64)value).ToString("yyyy/MM/dd HH:mm:ss");
  715. }
  716. public object ConvertBack(object value, Type targetTypes, object parameter, System.Globalization.CultureInfo culture)
  717. {
  718. return null;
  719. }
  720. }
  721. }