ProcessHistoryViewModel.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Drawing;
  5. using System.Linq;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using Aitex.Core.RT.Log;
  10. using MECF.Framework.Common.ControlDataContext;
  11. using MECF.Framework.Common.DataCenter;
  12. using MECF.Framework.Common.Utilities;
  13. using MECF.Framework.UI.Client.ClientBase;
  14. using SciChart.Charting.Visuals.Axes;
  15. using SciChart.Charting.Visuals.RenderableSeries;
  16. using SciChart.Data.Model;
  17. using Cali = Caliburn.Micro;
  18. namespace MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory
  19. {
  20. public class ProcessHistoryViewModel : UiViewModelBase
  21. {
  22. public bool IsPermission { get => this.Permission == 3; }
  23. public ObservableCollection<IRenderableSeries> SelectedData { get; set; }
  24. public AutoRange ChartAutoRange
  25. {
  26. get { return EnableAutoZoom ? AutoRange.Always : AutoRange.Never; }
  27. }
  28. public AutoRange AutoRangeX
  29. {
  30. get => _autoRangeX;
  31. set { _autoRangeX = value; NotifyOfPropertyChange(nameof(AutoRangeX)); }
  32. }
  33. public AutoRange AutoRangeY
  34. {
  35. get => _autoRangeY;
  36. set { _autoRangeY = value; NotifyOfPropertyChange(nameof(AutoRangeY)); }
  37. }
  38. private bool _enableAutoZoom = true;
  39. public bool EnableAutoZoom
  40. {
  41. get { return _enableAutoZoom; }
  42. set
  43. {
  44. _enableAutoZoom = value;
  45. NotifyOfPropertyChange(nameof(EnableAutoZoom));
  46. NotifyOfPropertyChange(nameof(ChartAutoRange));
  47. }
  48. }
  49. private IRange _TimeRange;
  50. public IRange TimeRange
  51. {
  52. get { return _TimeRange; }
  53. set
  54. {
  55. _TimeRange = value;
  56. NotifyOfPropertyChange("TimeRange");
  57. }
  58. }
  59. private IRange _ValueRange;
  60. public IRange ValueRange
  61. {
  62. get { return _ValueRange; }
  63. set { _ValueRange = value; }
  64. }
  65. private Queue<Color> colorQueue = new Queue<Color>(new Color[]{Color.Red,Color.Orange,Color.Yellow,Color.Green,Color.Blue,Color.Pink,Color.Purple,Color.Aqua,Color.Bisque,Color.Brown,Color.BurlyWood,Color.CadetBlue,
  66. Color.CornflowerBlue,Color.DarkBlue,Color.DarkCyan,Color.DarkGray,Color.DarkGreen,Color.DarkKhaki,Color.DarkMagenta,Color.DarkOliveGreen, Color.DarkOrange,
  67. Color.DarkSeaGreen,Color.DarkSlateBlue,Color.DarkSlateGray,Color.DarkViolet,Color.DeepPink,Color.DeepSkyBlue,Color.DimGray, Color.DodgerBlue,Color.ForestGreen, Color.Gold,
  68. Color.Gray,Color.GreenYellow,Color.HotPink,Color.Indigo,Color.Khaki,Color.LightBlue,Color.LightCoral,Color.LightGreen, Color.LightPink,Color.LightSalmon,Color.LightSkyBlue,
  69. Color.LightSlateGray,Color.LightSteelBlue,Color.LimeGreen,Color.MediumOrchid,Color.MediumPurple,Color.MediumSeaGreen,Color.MediumSlateBlue,Color.MediumSpringGreen,
  70. Color.MediumTurquoise,Color.Moccasin,Color.NavajoWhite,Color.Olive,Color.OliveDrab,Color.OrangeRed,Color.Orchid,Color.PaleGoldenrod,Color.PaleGreen,
  71. Color.PeachPuff,Color.Peru,Color.Plum,Color.PowderBlue,Color.RosyBrown,Color.RoyalBlue,Color.SaddleBrown,Color.Salmon,Color.SeaGreen, Color.Sienna,
  72. Color.SkyBlue,Color.SlateBlue,Color.SlateGray,Color.SpringGreen,Color.Teal,Color.Aquamarine,Color.Tomato,Color.Turquoise,Color.Violet,Color.Wheat, Color.YellowGreen});
  73. Cali.WindowManager wm = new Cali.WindowManager();
  74. SelectDataViewModel selectDataDlg = new SelectDataViewModel();
  75. private AutoRange _autoRangeX;
  76. private AutoRange _autoRangeY;
  77. public ProcessHistoryViewModel()
  78. {
  79. DisplayName = "Process History";
  80. SelectedData = new ObservableCollection<IRenderableSeries>();
  81. TimeRange = new DateRange(DateTime.Now.AddMinutes(-1), DateTime.Now.AddMinutes(59));
  82. AutoRangeX = AutoRange.Once;
  83. AutoRangeY = AutoRange.Once;
  84. }
  85. public void SelectData()
  86. {
  87. selectDataDlg.CheckAllRecipeFlag = false;
  88. selectDataDlg.SelectedRecipes.Clear();
  89. selectDataDlg.SelectedParameters.Clear();
  90. var settings = new Dictionary<string, object> { { "Title", "Select Recipe Data" } };
  91. bool? ret = wm.ShowDialog(selectDataDlg, null, settings);
  92. if (ret == null || !ret.Value)
  93. return;
  94. SelectedData.Clear();
  95. double valueMin = double.MaxValue;
  96. double valueMax = double.MinValue;
  97. DateTime dtMin = DateTime.MaxValue;
  98. DateTime dtMax = DateTime.MinValue;
  99. foreach (var recipe in selectDataDlg.SelectedRecipes)
  100. {
  101. if (Convert.ToDateTime(recipe.StartTime) < dtMin)
  102. dtMin = Convert.ToDateTime(recipe.StartTime);
  103. if (!string.IsNullOrEmpty(recipe.EndTime))
  104. {
  105. if (Convert.ToDateTime(recipe.EndTime) > dtMax)
  106. dtMax = Convert.ToDateTime(recipe.EndTime);
  107. }
  108. QueryData(recipe, selectDataDlg.SelectedParameters, ref valueMin, ref valueMax);
  109. }
  110. TimeRange = new DateRange(dtMin.AddMinutes(-1), dtMax.AddMinutes(5));
  111. ValueRange = new DoubleRange(valueMin - 5, valueMax + 5);
  112. Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  113. {
  114. try
  115. {
  116. var view = GetView() as ProcessHistoryView;
  117. view.dataGrid1.Columns.Clear();
  118. System.Data.DataTable dt = new System.Data.DataTable();
  119. dt = new System.Data.DataTable($"{DisplayName}_{DateTime.Now:yyyyMMdd_HHmmss}");
  120. dt.Columns.Add("Time", typeof(string));
  121. DataGridTextColumn dataGridTextColumn = new DataGridTextColumn();
  122. dataGridTextColumn.Header = "Time";
  123. dataGridTextColumn.Binding = new Binding("Time");
  124. view.dataGrid1.Columns.Add(dataGridTextColumn);
  125. //lock (_lockSelection)
  126. //{
  127. Dictionary<DateTime, double[]> timeValue = new Dictionary<DateTime, double[]>();
  128. for (int i = 0; i < SelectedData.Count; i++)
  129. {
  130. List<Tuple<DateTime, double>> data = (SelectedData[i] as ChartDataLine<DateTime>).Points;
  131. foreach (var tuple in data)
  132. {
  133. if (!timeValue.ContainsKey(tuple.Item1))
  134. timeValue[tuple.Item1] = new double[SelectedData.Count];
  135. timeValue[tuple.Item1][i] = tuple.Item2;
  136. }
  137. dt.Columns.Add((SelectedData[i] as ChartDataLine<DateTime>).DataName.Replace(".", ""), typeof(string));
  138. DataGridTextColumn dataGridTextColumn2 = new DataGridTextColumn();
  139. dataGridTextColumn2.Header = (SelectedData[i] as ChartDataLine<DateTime>).DataName;
  140. dataGridTextColumn2.Binding = new Binding((SelectedData[i] as ChartDataLine<DateTime>).DataName.Replace(".", ""));
  141. view.dataGrid1.Columns.Add(dataGridTextColumn2);
  142. }
  143. foreach (var subitem in timeValue)
  144. {
  145. var row = dt.NewRow();
  146. row[0] = subitem.Key.ToString("yyyy/MM/dd HH:mm:ss");
  147. for (int j = 0; j < subitem.Value.Length; j++)
  148. {
  149. row[j + 1] = subitem.Value[j].ToString();
  150. }
  151. dt.Rows.Add(row);
  152. }
  153. view.dataGrid1.ItemsSource = dt.DefaultView;
  154. //}
  155. }
  156. catch (Exception ex)
  157. {
  158. }
  159. }));
  160. }
  161. public void QueryData(RecipeItem recipe, ObservableCollection<string> keys, ref double min, ref double max)
  162. {
  163. if (string.IsNullOrEmpty(recipe.StartTime))
  164. {
  165. MessageBox.Show($"can not query recipe data, did not record {recipe.Recipe} start time");
  166. return;
  167. }
  168. DateTime dtFrom = Convert.ToDateTime(recipe.StartTime);
  169. DateTime dtTo = dtFrom.AddMinutes(10);
  170. if (!string.IsNullOrEmpty(recipe.EndTime))
  171. {
  172. dtTo = Convert.ToDateTime(recipe.EndTime);
  173. }
  174. Dictionary<string, List<Tuple<DateTime, double>>> result;
  175. if (GetDbData(recipe.Chamber, dtFrom, dtTo, keys, out result, ref min, ref max))
  176. {
  177. foreach (var data in result)
  178. {
  179. ChartDataLine<DateTime> line = new ChartDataLine<DateTime>(data.Key);
  180. line.DataSource = recipe.Recipe;
  181. foreach (var tuple in data.Value)
  182. {
  183. line.Append(tuple.Item1, tuple.Item2);
  184. }
  185. SelectedData.Add(line);
  186. SelectedDataChanged();
  187. }
  188. }
  189. }
  190. public bool GetDbData(string chamber, DateTime from, DateTime to, IEnumerable<string> dataIdList,
  191. out Dictionary<string, List<Tuple<DateTime, double>>> returnDatas, ref double min, ref double max)
  192. {
  193. returnDatas = new Dictionary<string, List<Tuple<DateTime, double>>>();
  194. for (DateTime dfrom = new DateTime(from.Year, from.Month, from.Day); dfrom < to; dfrom += new TimeSpan(1, 0, 0, 0))
  195. {
  196. DateTime begin = (dfrom.Year == from.Year && dfrom.Month == from.Month && dfrom.Day == from.Day) ? from : new DateTime(dfrom.Year, dfrom.Month, dfrom.Day, 0, 0, 0, 0);
  197. DateTime end = (dfrom.Date == to.Date) ? to : new DateTime(dfrom.Year, dfrom.Month, dfrom.Day, 23, 59, 59, 999);
  198. //if (begin.Date > DateTime.Today)
  199. // continue;
  200. try
  201. {
  202. string sql = "select time AS InternalTimeStamp";
  203. foreach (var dataId in dataIdList)
  204. {
  205. if (!returnDatas.Keys.Contains(dataId) && dataId.StartsWith($"{chamber}."))
  206. {
  207. returnDatas[dataId] = new List<Tuple<DateTime, double>>();
  208. sql += "," + string.Format("\"{0}\"", dataId);
  209. }
  210. }
  211. sql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc;",
  212. begin.ToString("yyyyMMdd") + "." + chamber, begin.Ticks, end.Ticks);
  213. using (var table = QueryDataClient.Instance.Service.QueryData(sql))
  214. {
  215. if (table == null || table.Rows.Count == 0)
  216. continue;
  217. DateTime dt = new DateTime();
  218. Dictionary<int, string> colName = new Dictionary<int, string>();
  219. for (int colNo = 0; colNo < table.Columns.Count; colNo++)
  220. colName.Add(colNo, table.Columns[colNo].ColumnName);
  221. for (int rowNo = 0; rowNo < table.Rows.Count; rowNo++)
  222. {
  223. var row = table.Rows[rowNo];
  224. for (int i = 0; i < table.Columns.Count; i++)
  225. {
  226. if (i == 0)
  227. {
  228. long ticks = (long)row[i];
  229. dt = new DateTime(ticks);
  230. }
  231. else
  232. {
  233. string dataId = colName[i];
  234. double value = 0.0;
  235. if (row[i] is DBNull || row[i] == null)
  236. {
  237. value = 0.0;
  238. }
  239. else if (row[i] is bool)
  240. {
  241. value = (bool)row[i] ? 1.0 : 0;
  242. }
  243. else
  244. {
  245. value = (double)float.Parse(row[i].ToString());
  246. }
  247. returnDatas[dataId].Add(Tuple.Create(dt, value));
  248. if (value < min)
  249. min = value;
  250. if (value > max)
  251. max = value;
  252. }
  253. }
  254. }
  255. table.Clear();
  256. }
  257. }
  258. catch (Exception ex)
  259. {
  260. LOG.Write(ex);
  261. return false;
  262. }
  263. }
  264. return true;
  265. }
  266. private void SelectedDataChanged()
  267. {
  268. foreach (var item in SelectedData)
  269. {
  270. if (item.Stroke.Equals(System.Windows.Media.Color.FromArgb(255, 0, 0, 255)))
  271. {
  272. Color drawingColor = colorQueue.Peek();
  273. item.Stroke = System.Windows.Media.Color.FromRgb(drawingColor.R, drawingColor.G, drawingColor.B);
  274. colorQueue.Enqueue(colorQueue.Dequeue());
  275. }
  276. }
  277. }
  278. public void DeleteAll()
  279. {
  280. SelectedData.Clear();
  281. }
  282. public void Delete(ChartDataLine<DateTime> cp)
  283. {
  284. if (cp != null && SelectedData.Contains(cp))
  285. {
  286. SelectedData.Remove(cp);
  287. }
  288. }
  289. public void ExportAll()
  290. {
  291. try
  292. {
  293. if (SelectedData.Count == 0)
  294. {
  295. MessageBox.Show($"Please select the data you want to export.", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  296. return;
  297. }
  298. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  299. dlg.DefaultExt = ".xlsx"; // Default file extension
  300. dlg.Filter = "Excel数据表格文件(*.xlsx)|*.xlsx"; // Filter files by extension
  301. dlg.FileName = $"{DisplayName}_{DateTime.Now:yyyyMMdd_HHmmss}";
  302. Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box
  303. if (result == true) // Process open file dialog box results
  304. {
  305. System.Data.DataSet ds = new System.Data.DataSet();
  306. ds.Tables.Add(new System.Data.DataTable($"Export_{DateTime.Now:yyyyMMdd_HHmmss}"));
  307. ds.Tables[0].Columns.Add("Time");
  308. ds.Tables[0].Columns[0].DataType = typeof(DateTime);
  309. Dictionary<DateTime, double[]> timeValue = new Dictionary<DateTime, double[]>();
  310. for (int i = 0; i < SelectedData.Count; i++)
  311. {
  312. List<Tuple<DateTime, double>> data = (SelectedData[i] as ChartDataLine<DateTime>).Points;
  313. foreach (var tuple in data)
  314. {
  315. if (!timeValue.ContainsKey(tuple.Item1))
  316. timeValue[tuple.Item1] = new double[SelectedData.Count];
  317. timeValue[tuple.Item1][i] = tuple.Item2;
  318. }
  319. ds.Tables[0].Columns.Add((SelectedData[i] as ChartDataLine<DateTime>).DataName);
  320. ds.Tables[0].Columns[i + 1].DataType = typeof(double);
  321. }
  322. foreach (var item in timeValue)
  323. {
  324. var row = ds.Tables[0].NewRow();
  325. row[0] = item.Key;
  326. for (int j = 0; j < item.Value.Length; j++)
  327. {
  328. row[j + 1] = item.Value[j];
  329. }
  330. ds.Tables[0].Rows.Add(row);
  331. }
  332. if (!ExcelHelper.ExportToExcel(dlg.FileName, ds, out string reason))
  333. {
  334. MessageBox.Show($"Export failed, {reason}", "Export", MessageBoxButton.OK,
  335. MessageBoxImage.Warning);
  336. return;
  337. }
  338. MessageBox.Show($"Export succeed, file save as {dlg.FileName}", "Export", MessageBoxButton.OK,
  339. MessageBoxImage.Information);
  340. }
  341. }
  342. catch (Exception ex)
  343. {
  344. LOG.Write(ex);
  345. MessageBox.Show("Write failed," + ex.Message, "export failed", MessageBoxButton.OK, MessageBoxImage.Warning);
  346. }
  347. }
  348. public void Export(ChartDataLine<DateTime> cp)
  349. {
  350. try
  351. {
  352. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  353. dlg.DefaultExt = ".xlsx"; // Default file extension
  354. dlg.Filter = "Excel数据表格文件(*.xlsx)|*.xlsx"; // Filter files by extension
  355. dlg.FileName = $"{cp.DataName}_{DateTime.Now:yyyyMMdd_HHmmss}";
  356. Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box
  357. if (result == true) // Process open file dialog box results
  358. {
  359. System.Data.DataSet ds = new System.Data.DataSet();
  360. ds.Tables.Add(new System.Data.DataTable(cp.DataName));
  361. ds.Tables[0].Columns.Add("Time");
  362. ds.Tables[0].Columns[0].DataType = typeof(DateTime);
  363. ds.Tables[0].Columns.Add(cp.DataName);
  364. ds.Tables[0].Columns[1].DataType = typeof(double);
  365. foreach (var item in cp.Points)
  366. {
  367. var row = ds.Tables[0].NewRow();
  368. row[0] = item.Item1;
  369. row[1] = item.Item2;
  370. ds.Tables[0].Rows.Add(row);
  371. }
  372. if (!ExcelHelper.ExportToExcel(dlg.FileName, ds, out string reason))
  373. {
  374. MessageBox.Show($"Export failed, {reason}", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  375. return;
  376. }
  377. MessageBox.Show($"Export succeed, file save as {dlg.FileName}", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
  378. }
  379. }
  380. catch (Exception ex)
  381. {
  382. LOG.Write(ex);
  383. MessageBox.Show("Write failed," + ex.Message, "export failed", MessageBoxButton.OK, MessageBoxImage.Warning);
  384. }
  385. }
  386. public void SelectColor(ChartDataLine<DateTime> cp)
  387. {
  388. if (cp == null)
  389. return;
  390. var dlg = new System.Windows.Forms.ColorDialog();
  391. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  392. {
  393. cp.Stroke = new System.Windows.Media.Color() { A = dlg.Color.A, B = dlg.Color.B, G = dlg.Color.G, R = dlg.Color.R };
  394. }
  395. }
  396. }
  397. }