ProcessExportAllViewModel.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. using Aitex.Core.RT.Log;
  2. using Aitex.Core.UI.ControlDataContext;
  3. using Aitex.Core.Util;
  4. using Caliburn.Micro;
  5. using Caliburn.Micro.Core;
  6. using DocumentFormat.OpenXml.Spreadsheet;
  7. using MECF.Framework.Common.CommonData;
  8. using MECF.Framework.Common.ControlDataContext;
  9. using MECF.Framework.Common.DataCenter;
  10. using MECF.Framework.Common.Utilities;
  11. using MECF.Framework.UI.Client.CenterViews.Configs.SystemConfig;
  12. using MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory;
  13. using MECF.Framework.UI.Client.CenterViews.Dialogs;
  14. using MECF.Framework.UI.Client.CenterViews.Operations.RealTime;
  15. using MECF.Framework.UI.Client.ClientBase;
  16. using NPOI.SS.UserModel;
  17. using NPOI.XSSF.UserModel;
  18. using OpenSEMI.ClientBase;
  19. using SciChart.Charting.Visuals;
  20. using SciChart.Charting.Visuals.Annotations;
  21. using SciChart.Charting.Visuals.Axes;
  22. using SciChart.Charting.Visuals.RenderableSeries;
  23. using SciChart.Data.Model;
  24. using System;
  25. using System.Collections.Concurrent;
  26. using System.Collections.Generic;
  27. using System.Collections.ObjectModel;
  28. using System.Data;
  29. using System.Diagnostics;
  30. using System.Drawing;
  31. using System.IO;
  32. using System.Linq;
  33. using System.Text;
  34. using System.Threading;
  35. using System.Threading.Tasks;
  36. using System.Windows;
  37. using static MECF.Framework.Common.FAServices.DataVariables;
  38. using Action = System.Action;
  39. using Media = System.Windows.Media;
  40. namespace MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory
  41. {
  42. class ProcessExportAllViewModel<T> : ModuleUiViewModelBase where T : IComparable
  43. {
  44. private ProcessExportAllView view;
  45. private CancellationTokenSource _cancellationTokenSource;
  46. private event EventHandler Exporting;
  47. private const int MAX_PARAMETERS = 1000;
  48. public List<ProcessHistoryLot> RecipeDatas { get; set; }
  49. private ObservableCollection<ParameterNode> _ParameterNodes;
  50. public ObservableCollection<ParameterNode> ParameterNodes
  51. {
  52. get { return _ParameterNodes; }
  53. set { _ParameterNodes = value; NotifyOfPropertyChange("ParameterNodes"); }
  54. }
  55. private Dictionary<string, string> _processDetailDisplayDic = new Dictionary<string, string>();
  56. private Dictionary<string, Dictionary<string, string>> _processProcessDetailAttributeDict = new Dictionary<string, Dictionary<string, string>>();
  57. // public ObservableCollection<IRenderableSeries> SelectedData { get; set; }
  58. public ObservableCollection<ParameterNode> GetParameters()
  59. {
  60. ObservableCollection<ParameterNode> rootNode = new ObservableCollection<ParameterNode>();
  61. try
  62. {
  63. Dictionary<string, string> displayDic = QueryDataClient.Instance.Service.GetData("System.ProcessDetailDisplay") as Dictionary<string, string>;
  64. if (displayDic == null)
  65. return rootNode;
  66. List<string> dataList = new List<string>();
  67. foreach (var key in displayDic.Keys)
  68. {
  69. string[] item = key.Split('.');
  70. if (item != null)
  71. {
  72. if (item.Length == 2)
  73. {
  74. _processDetailDisplayDic.Add($"{item[1]}", displayDic[key]);
  75. dataList.Add($"{item[0]}.{item[1]}");
  76. }
  77. else if (item.Length == 3)
  78. {
  79. _processDetailDisplayDic.Add($"{item[1]} {item[2]}", displayDic[key]);
  80. dataList.Add($"{item[0]}.{item[1]}.{item[2]}");
  81. }
  82. }
  83. Dictionary<string, ParameterNode> indexer = new Dictionary<string, ParameterNode>();
  84. foreach (string dataName in dataList)
  85. {
  86. string[] nodeName = dataName.Split('.');
  87. ParameterNode parentNode = null;
  88. string pathName = "";
  89. for (int i = 0; i < nodeName.Length; i++)
  90. {
  91. pathName = (i == 0 || i == 1) ? nodeName[i] : (pathName + " " + nodeName[i]);
  92. if (!indexer.ContainsKey(pathName))
  93. {
  94. indexer[pathName] = new ParameterNode() { Name = pathName, ChildNodes = new ObservableCollection<ParameterNode>(), ParentNode = parentNode };
  95. if (parentNode == null)
  96. {
  97. rootNode.Add(indexer[pathName]);
  98. }
  99. else
  100. {
  101. parentNode.ChildNodes.Add(indexer[pathName]);
  102. }
  103. }
  104. parentNode = indexer[pathName];
  105. }
  106. }
  107. SortParameterNode(rootNode, "Heater", 0);
  108. SortParameterNode(rootNode, "MFC", 1);
  109. SortParameterNode(rootNode, "Pressure", 2);
  110. SortParameterNode(rootNode, "Boat", 3);
  111. SortParameterNode(rootNode, "HeaterBand", 4);
  112. SortParameterNode(rootNode, "Valve", 5);
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. LOG.Write(ex);
  118. }
  119. return rootNode;
  120. }
  121. void SortParameterNode(ObservableCollection<ParameterNode> rootNode, string Name, int Index)
  122. {
  123. if (rootNode[Index].Name != Name)
  124. {
  125. for (int i = 0; i < rootNode.Count; i++)
  126. {
  127. rootNode[i].Selected = true;
  128. if (rootNode[i].Name == Name)
  129. {
  130. ParameterNode node = rootNode[i];
  131. rootNode.RemoveAt(i);
  132. rootNode.Insert(Index, node);
  133. }
  134. }
  135. }
  136. }
  137. private IRange _timeRange;
  138. public IRange VisibleRangeTime
  139. {
  140. get { return _timeRange; }
  141. set
  142. {
  143. _timeRange = value;
  144. NotifyOfPropertyChange(nameof(VisibleRangeTime));
  145. }
  146. }
  147. private IRange _VisibleRangeValue;
  148. public IRange VisibleRangeValue
  149. {
  150. get { return _VisibleRangeValue; }
  151. set { _VisibleRangeValue = value; NotifyOfPropertyChange(nameof(VisibleRangeValue)); }
  152. }
  153. private AnnotationCollection _annotations;
  154. public AnnotationCollection Annotations
  155. {
  156. get => _annotations;
  157. set
  158. {
  159. _annotations = value;
  160. InvokePropertyChanged(nameof(Annotations));
  161. }
  162. }
  163. //private PeriodicJob _thread;
  164. private List<StepInfo> _stepInfo = new List<StepInfo>();
  165. public List<StepInfo> StepInfo
  166. {
  167. get { return _stepInfo; }
  168. set { _stepInfo = value; this.NotifyOfPropertyChange(nameof(StepInfo)); }
  169. }
  170. private bool _isBusy = false;
  171. private string _busyIndicatorMessage;
  172. /// <summary>
  173. /// 设置或返回忙信息。
  174. /// </summary>
  175. public string BusyIndicatorContent
  176. {
  177. get => _busyIndicatorMessage;
  178. set
  179. {
  180. _busyIndicatorMessage = value;
  181. NotifyOfPropertyChange(nameof(BusyIndicatorContent));
  182. }
  183. }
  184. /// <summary>
  185. /// 设置或返回视图是否正忙。
  186. /// </summary>
  187. public bool IsBusy
  188. {
  189. get => _isBusy;
  190. set
  191. {
  192. _isBusy = value;
  193. NotifyOfPropertyChange(nameof(IsBusy));
  194. }
  195. }
  196. private RealtimeProvider _realtimeProvider;
  197. public ProcessExportAllViewModel(List<ProcessHistoryLot> recipes)
  198. {
  199. DisplayName = "Process Export";
  200. RecipeDatas = recipes;
  201. _realtimeProvider = new RealtimeProvider();
  202. ParameterNodes = _realtimeProvider.GetParameters(out var dict, true);
  203. _processDetailDisplayDic = dict;
  204. _processProcessDetailAttributeDict = _realtimeProvider.GetProcessProcessDetailAttributeDict();
  205. if (recipes == null || recipes.Count == 0)
  206. {
  207. return;
  208. }
  209. //SelectedData = new ObservableCollection<IRenderableSeries>();
  210. var now = DateTime.Now;
  211. VisibleRangeTime = new DateRange(DateTime.Now.AddMinutes(60), DateTime.Now.AddMinutes(-60));
  212. VisibleRangeValue = new DoubleRange(0, 10);
  213. Annotations = new AnnotationCollection();
  214. // _thread = new PeriodicJob(200, MonitorData, "ProcessExport", true);
  215. RecipeDatas.ToList().ForEach(recipe =>
  216. {
  217. QueryStep(recipe);
  218. });
  219. if (StepInfo != null && StepInfo.Count > 0)
  220. {
  221. StepStartTime = StepInfo.FirstOrDefault().StartTime;
  222. StepEndTime = StepInfo.LastOrDefault().EndTime;
  223. }
  224. else
  225. {
  226. if (recipes.Count > 0)
  227. {
  228. StepStartTime = recipes[0].StartTime;
  229. StepEndTime = recipes[0].EndTime;
  230. }
  231. }
  232. }
  233. public bool IsStepVisiable => RecipeDatas.Count == 1;
  234. public DateTime StepStartTime { get; set; }
  235. public DateTime StepEndTime { get; set; }
  236. private bool _isAdding;
  237. private static object _lockSelection = new object();
  238. private ConcurrentBag<QueryIndexer> _lstTokenTimeData = new ConcurrentBag<QueryIndexer>();
  239. public class QueryIndexer
  240. {
  241. public TimeChartDataLine DataLine { get; set; }
  242. public List<string> DataList { get; set; }
  243. public DateTime TimeToken { get; set; }
  244. }
  245. public class TimeChartDataLine : ChartDataLine<T>
  246. {
  247. public string Module { get; set; }
  248. public DateTime StartTime { get; set; }
  249. public DateTime EndTime { get; set; }
  250. public TimeChartDataLine(string dataName, string module, DateTime startTime, DateTime endTime) : base(dataName)
  251. {
  252. StartTime = startTime;
  253. EndTime = endTime;
  254. Module = module;
  255. }
  256. }
  257. private string _resolution;
  258. private AutoRange _autoRange;
  259. public AutoRange ChartAutoRange
  260. {
  261. get { return _autoRange; }
  262. set
  263. {
  264. _autoRange = value;
  265. NotifyOfPropertyChange(nameof(ChartAutoRange));
  266. }
  267. }
  268. public void QueryStep(ProcessHistoryLot historyLot)//, string recipeName去掉查询recipeName名称,有嵌套调用
  269. {
  270. string sql = string.Empty;
  271. DataTable dbData = new DataTable();
  272. if (!string.IsNullOrEmpty(historyLot.PjId))
  273. {
  274. sql = $"SELECT * FROM process_data where pj_id='{historyLot.PjId}'";
  275. dbData = QueryDataClient.Instance.Service.QueryData(sql);
  276. }
  277. if (dbData == null || dbData.Rows.Count == 0)
  278. {
  279. DateTime starTime = historyLot.StartTime.AddMinutes(-1);
  280. DateTime endTime = historyLot.EndTime.AddMinutes(1);
  281. sql = $"SELECT * FROM \"process_data\" where (\"process_begin_time\" >= '{starTime:yyyy/MM/dd HH:mm:ss.fff}' and \"process_end_time\" <= '{endTime:yyyy/MM/dd HH:mm:ss.fff}') order by \"process_begin_time\" DESC;";
  282. dbData = QueryDataClient.Instance.Service.QueryData(sql);
  283. }
  284. if (dbData != null && dbData.Rows.Count > 0)
  285. {
  286. List<ProcessDataLot> ProcessDataLotList = new List<ProcessDataLot>();
  287. for (int i = 0; i < dbData.Rows.Count; i++)
  288. {
  289. ProcessDataLot item = new ProcessDataLot();
  290. item.GUID = dbData.Rows[i]["guid"].ToString();
  291. item.RecipeName = dbData.Rows[i]["recipe_name"].ToString();
  292. item.ProcessStatus = dbData.Rows[i]["process_status"].ToString();
  293. item.WaferDataGUID = dbData.Rows[i]["wafer_data_guid"].ToString();
  294. item.ProcessIn = dbData.Rows[i]["process_in"].ToString();
  295. if (!dbData.Rows[i]["process_begin_time"].Equals(DBNull.Value))
  296. {
  297. item.ProcessBeginTime = (DateTime)dbData.Rows[i]["process_begin_time"];
  298. }
  299. if (!dbData.Rows[i]["process_end_time"].Equals(DBNull.Value))
  300. {
  301. item.ProcessEndTime = (DateTime)dbData.Rows[i]["process_end_time"];
  302. }
  303. ProcessDataLotList.Add(item);
  304. }
  305. if (ProcessDataLotList.Count == 0) { LOG.Warning($"QueryStep:No process data({sql})"); return; }
  306. // Annotations.Add(VerLine(Media.Brushes.Blue, ProcessDataLotList[0].ProcessBeginTime, Media.Brushes.Blue, $"{ProcessDataLotList[0].RecipeName}"));
  307. //Annotations.Add(VerLine(Media.Brushes.Blue, ProcessDataLotList[0].ProcessEndTime, Media.Brushes.Blue, $"Recipe End"));
  308. string sql2 = $"SELECT * FROM \"recipe_step_data\" where";
  309. sql2 += $" \"recipe_step_data\".\"process_data_guid\" = '{ProcessDataLotList[0].GUID.ToString()}'";
  310. sql2 += " order by \"step_begin_time\" ASC;";
  311. using (var table = QueryDataClient.Instance.Service.QueryData(sql2))
  312. {
  313. if (!(table == null || table.Rows.Count == 0))
  314. {
  315. for (int i = 0; i < table.Rows.Count; i++)
  316. {
  317. var item = table.Rows[i];
  318. string startStepTime = "";
  319. string endStepTime = "";
  320. double stepTime = 0;
  321. string subRecipeStepNumber = "";
  322. string subRecipeStepTime = "";
  323. string subRecipeStepName = "";
  324. string subRecipeLoopInfo = "";
  325. string tempCorrection = "";
  326. string tempPid = "";
  327. if (!item["step_begin_time"].Equals(DBNull.Value))
  328. startStepTime = ((DateTime)item["step_begin_time"]).ToString("yyyy/MM/dd HH:mm:ss.fff");
  329. if (!item["step_end_time"].Equals(DBNull.Value))
  330. {
  331. endStepTime = ((DateTime)item["step_end_time"]).ToString("yyyy/MM/dd HH:mm:ss.fff");
  332. }
  333. if (!item["step_time"].Equals(DBNull.Value))
  334. {
  335. stepTime = (float)item["step_time"];
  336. }
  337. if (!item["sub_recipe_step_time"].Equals(DBNull.Value))
  338. {
  339. subRecipeStepTime = item["sub_recipe_step_time"].ToString();
  340. }
  341. if (!item["sub_recipe_step_number"].Equals(DBNull.Value))
  342. {
  343. subRecipeStepNumber = item["sub_recipe_step_number"].ToString();
  344. }
  345. if (!item["sub_recipe_step_name"].Equals(DBNull.Value))
  346. {
  347. subRecipeStepName = item["sub_recipe_step_name"].ToString();
  348. }
  349. if (!item["sub_recipe_loop_info"].Equals(DBNull.Value))
  350. {
  351. subRecipeLoopInfo = item["sub_recipe_loop_info"].ToString();
  352. }
  353. if (!item["temp_correction"].Equals(DBNull.Value))
  354. {
  355. tempCorrection = item["temp_correction"].ToString().Replace(",", ":");
  356. }
  357. if (!item["temp_pid"].Equals(DBNull.Value))
  358. {
  359. tempPid = item["temp_pid"].ToString().Replace(",", ":");
  360. }
  361. string stepNo = item["step_number"].ToString();
  362. string stepName = item["step_name"].ToString();
  363. if (DateTime.TryParse(startStepTime, out DateTime StartTime) && DateTime.TryParse(endStepTime, out DateTime EndTime))
  364. {
  365. //Annotations.Add(VerLine(Media.Brushes.AliceBlue, StartTime, Media.Brushes.Blue, $"{stepNo}"));
  366. var time = StartTime.AddSeconds(stepTime);
  367. if (EndTime < time && time < ProcessDataLotList[0].ProcessEndTime)//解决process过程abort,数据导出问题:数据点时间范围大于recipe结束时间。
  368. {
  369. EndTime = StartTime.AddSeconds(stepTime);
  370. }
  371. _stepInfo.Add(new StepInfo()
  372. {
  373. StartTime = StartTime,
  374. EndTime = EndTime,
  375. StepName = stepName,
  376. StepTime = stepTime,
  377. StepNo = stepNo,
  378. StepEndTime = StartTime.AddSeconds(stepTime),
  379. SubRecipeStepNumber = subRecipeStepNumber,
  380. SubRecipeStepTime = subRecipeStepTime,
  381. SubRecipeStepName = subRecipeStepName,
  382. SubRecipeLoopInfo = subRecipeLoopInfo,
  383. TempCorrection = tempCorrection,
  384. TempPid = tempPid,
  385. });
  386. }
  387. }
  388. }
  389. }
  390. }
  391. }
  392. protected override void OnViewLoaded(object view)
  393. {
  394. base.OnViewLoaded(view);
  395. useMaxRow = (int)QueryDataClient.Instance.Service.GetConfig("System.SetUp.ExportMaxRow");
  396. this.view = (ProcessExportAllView)view;
  397. }
  398. List<string> nodeOrigin = new List<string>();
  399. void GetNode(ParameterNode pNode, bool Selected)
  400. {
  401. foreach (var item in pNode.ChildNodes)
  402. {
  403. if (item.ChildNodes.Count > 0)
  404. {
  405. GetNode(item, Selected);
  406. }
  407. else
  408. {
  409. //if(item.Selected == true)
  410. {
  411. nodeOrigin.Add(item.Name);
  412. }
  413. }
  414. }
  415. }
  416. public static int DivideAndRoundUp(int dividend, int divisor)
  417. {
  418. int result = dividend / divisor;
  419. int remainder = dividend % divisor;
  420. if (remainder > 0)
  421. {
  422. result++;
  423. }
  424. return result;
  425. }
  426. private int useMaxRow = 25000;
  427. string csv = ",";
  428. public async void ExportAll()
  429. {
  430. try
  431. {
  432. nodeOrigin.Clear();
  433. if (StepStartTime.Year == 1 || StepEndTime.Year == 1)
  434. {
  435. MessageBox.Show("No data is available in the selected period!", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  436. return;
  437. }
  438. foreach (var node in ParameterNodes)
  439. {
  440. if (node.Selected == true)
  441. {
  442. GetNode(node, node.Selected);
  443. }
  444. }
  445. if (nodeOrigin.Count == 0)
  446. {
  447. MessageBox.Show($"Please select the data you want to export.", "Export", MessageBoxButton.OK,
  448. MessageBoxImage.Warning);
  449. return;
  450. }
  451. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  452. dlg.DefaultExt = ".csv"; // Default file extension
  453. dlg.Filter = "Excel数据表格文件(*.csv)|*.csv"; // Filter files by extension
  454. //去除创建文件时的文件名中包含的非法字符'\'
  455. dlg.FileName = $"{DisplayName}_{string.Join(",", RecipeDatas.Select(x => x.RecipeName.Replace('\\', '.')))}_{DateTime.Now:yyyyMMdd_HHmmss}";
  456. Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box
  457. if (result == true) // Process open file dialog box results
  458. {
  459. BusyIndicatorContent = "Exporting start ...";
  460. IsBusy = true;
  461. Exporting?.Invoke(this, System.EventArgs.Empty);
  462. _cancellationTokenSource = new CancellationTokenSource();
  463. await Task.Run(() =>
  464. {
  465. DateTime startTime = startTime = StepStartTime;
  466. QueryDataClientFromTable(dlg.FileName, RecipeDatas.FirstOrDefault());
  467. }, _cancellationTokenSource.Token).ContinueWith(t =>
  468. {
  469. if (t.IsCanceled || t.IsFaulted)
  470. {
  471. IsBusy = false;
  472. return;
  473. }
  474. });
  475. if (_cancellationTokenSource?.Token.IsCancellationRequested == true)
  476. {
  477. IsBusy = false;
  478. return;
  479. }
  480. BusyIndicatorContent = "Data is written to Excel file ...";
  481. IsBusy = false;
  482. MessageBox.Show($"Export succeed, file save as {dlg.FileName}", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
  483. Window window = Window.GetWindow(this.view);
  484. window.Close();
  485. }
  486. }
  487. catch (Exception ex)
  488. {
  489. LOG.Write(ex);
  490. MessageBox.Show("Write failed," + ex.Message, "export failed", MessageBoxButton.OK, MessageBoxImage.Warning);
  491. IsBusy = false;
  492. }
  493. }
  494. private void QueryDataClientFromTable(string fileName, ProcessHistoryLot recipeInfo)
  495. {
  496. DateTime startTime = StepStartTime;
  497. DateTime endTime = StepEndTime;
  498. List<string> keys = new List<string>(nodeOrigin);
  499. List<string> pmList = new List<string>();
  500. List<string> systemList = new List<string>();
  501. if (keys != null && keys.Count > 0)
  502. {
  503. foreach (var dataKey in keys)
  504. {
  505. var dataId = _processDetailDisplayDic.ContainsKey(dataKey) ? _processDetailDisplayDic[dataKey] : dataKey;
  506. var module = dataId.Split('.').ToList()[0];
  507. if (module.ToLower() == "pm1")
  508. {
  509. pmList.Add(dataId);
  510. }
  511. else if (module.ToLower() == "system")
  512. {
  513. systemList.Add(dataId);
  514. // systemList.Add(string.Format("\"{0}\"", dataId));
  515. }
  516. }
  517. }
  518. if (StepStartTime.Date == StepEndTime.Date)
  519. {
  520. SaveDataToTable(fileName, pmList, systemList, startTime, endTime, recipeInfo);
  521. }
  522. else
  523. {
  524. endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 23, 59, 59);
  525. while (endTime < StepEndTime)
  526. {
  527. SaveDataToTable(fileName, pmList, systemList, startTime, endTime, recipeInfo);
  528. startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0).AddDays(1);
  529. endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 23, 59, 59);
  530. }
  531. SaveDataToTable(fileName, pmList, systemList, startTime, StepEndTime, recipeInfo);
  532. }
  533. }
  534. private bool firstHeader = false;
  535. private Dictionary<string, string> GetReverseDict()
  536. {
  537. Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
  538. foreach (var kvp in _processDetailDisplayDic)
  539. {
  540. if (!keyValuePairs.ContainsKey(kvp.Value))
  541. keyValuePairs[kvp.Value] = kvp.Key.Trim().Contains(" ") ? kvp.Key.Trim().Substring(kvp.Key.Trim().LastIndexOf(" ") + 1) : kvp.Key;
  542. }
  543. return keyValuePairs;
  544. }
  545. private void SaveDataToTable(string fileName, List<string> pmList, List<string> systemList, DateTime startTime, DateTime endTime, ProcessHistoryLot recipeInfo)
  546. {
  547. string stepID = "", stepName = "", subRecipeLoopInfo = "", subRecipeStepName = "", subRecipeStepNumber = "", tempCorrection = "", tempPid = "";
  548. DataTable pmDataTable = null;
  549. var columnsql = $"select column_name from information_schema.columns where table_name = '{startTime.ToString("yyyyMMdd")}.PM1'";
  550. var columnTable = QueryDataClient.Instance.Service.QueryData(columnsql);
  551. List<string> col = columnTable.Rows.Cast<DataRow>().Select(x => x.ItemArray[0].ToString()).ToList();
  552. pmList = pmList.Where(x => col.Any(y => y == x)).ToList();
  553. string pmsql = $"select time AS InternalTimeStamp, {string.Join(",", pmList.Select(x => string.Format("\"{0}\"", x)))}";
  554. DataTable systemDataTable = null;
  555. pmsql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  556. startTime.ToString("yyyyMMdd") + "." + "PM1", startTime.Ticks, endTime.Ticks);
  557. BusyIndicatorContent = "Example Query PM data ...";
  558. pmDataTable = QueryDataClient.Instance.Service.QueryData(pmsql);
  559. var sysColumnsql = $"select column_name from information_schema.columns where table_name = '{startTime.ToString("yyyyMMdd")}.System'";
  560. var sysColumnTable = QueryDataClient.Instance.Service.QueryData(sysColumnsql);
  561. List<string> systemCol = sysColumnTable?.Rows.Cast<DataRow>().Select(x => x.ItemArray[0].ToString()).ToList();
  562. systemList = systemList.Where(x => systemCol.Any(y => y == x)).ToList();
  563. string systemsql = $"select time AS InternalTimeStamp, {string.Join(",", systemList.Select(x => string.Format("\"{0}\"", x)))}";
  564. systemsql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  565. startTime.ToString("yyyyMMdd") + "." + "System", startTime.Ticks, endTime.Ticks);
  566. BusyIndicatorContent = "Example Query System data ...";
  567. systemDataTable = QueryDataClient.Instance.Service.QueryData(systemsql);
  568. int maxRow = 0;
  569. if ((pmDataTable == null || pmDataTable.Rows.Count == 0))
  570. {
  571. if (systemDataTable != null)
  572. {
  573. maxRow = systemDataTable.Rows.Count;
  574. }
  575. }
  576. else if ((systemDataTable == null || systemDataTable.Rows.Count == 0))
  577. {
  578. if (pmDataTable != null)
  579. {
  580. maxRow = pmDataTable.Rows.Count;
  581. }
  582. }
  583. else
  584. {
  585. maxRow = pmDataTable.Rows.Count > systemDataTable.Rows.Count ? systemDataTable.Rows.Count : pmDataTable.Rows.Count;
  586. }
  587. var subColNames = new List<DataColumn>() {
  588. new DataColumn("Step\nStartDate"),
  589. new DataColumn("Step\nStartTime"),
  590. new DataColumn("\tStepID\t "),
  591. new DataColumn("\tStepName\t"),
  592. new DataColumn("SubRecipe\nStepName"),
  593. new DataColumn("SubRecipe\nStepNumber"),
  594. new DataColumn("SubRecipe\nLoopInfo"),
  595. new DataColumn("Temp\nCorrection"),
  596. new DataColumn("\tTempPID\t"),
  597. };
  598. // Create a new workbook and sheet
  599. IWorkbook workbook = new XSSFWorkbook();
  600. ISheet sheet = workbook.CreateSheet("Sheet1");
  601. #region style
  602. ICellStyle cellStyle = workbook.CreateCellStyle();
  603. cellStyle.WrapText = true;
  604. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;//粗线
  605. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;//粗线
  606. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;//粗线
  607. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;//粗线
  608. cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  609. cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
  610. ICellStyle borderCellStyle = workbook.CreateCellStyle();
  611. borderCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;//粗线
  612. borderCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;//粗线
  613. borderCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;//粗线
  614. borderCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;//粗线
  615. IFont font = workbook.CreateFont();
  616. borderCellStyle.SetFont(font);
  617. borderCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  618. borderCellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
  619. #endregion
  620. int rowIndex = 4;
  621. int cellIndex = 0;
  622. List<string> headers = new List<string>();
  623. if (!firstHeader)
  624. {
  625. firstHeader = true;
  626. var systemColNames = systemDataTable?.Columns.Cast<DataColumn>().Where(x => x.ColumnName != "internaltimestamp").Select(x =>
  627. {
  628. if (_processProcessDetailAttributeDict.ContainsKey(x.ColumnName))
  629. {
  630. var colAttributeName = "ColName";
  631. if (!_processProcessDetailAttributeDict[x.ColumnName].ContainsKey(colAttributeName))
  632. {
  633. colAttributeName = "DisplayName";
  634. }
  635. var tempStr = _processProcessDetailAttributeDict[x.ColumnName].ContainsKey("DisplayName") && !string.IsNullOrEmpty(_processProcessDetailAttributeDict[x.ColumnName]["DisplayName"]) ? _processProcessDetailAttributeDict[x.ColumnName]["DisplayName"] : x.ColumnName;
  636. headers.Add(tempStr.EndsWith("Enable") ? tempStr.Replace("Valve.", "") : tempStr);
  637. return string.IsNullOrEmpty(_processProcessDetailAttributeDict[x.ColumnName][colAttributeName]) ? x.ColumnName : _processProcessDetailAttributeDict[x.ColumnName][colAttributeName];
  638. }
  639. headers.Add(x.ColumnName.EndsWith("Enable") ? x.ColumnName.Replace("Valve.", "") : x.ColumnName);
  640. return x.ColumnName;
  641. });
  642. var pmColNames = pmDataTable?.Columns.Cast<DataColumn>().Where(x => x.ColumnName != "internaltimestamp").Select(x =>
  643. {
  644. if (_processProcessDetailAttributeDict.ContainsKey(x.ColumnName))
  645. {
  646. var colAttributeName = "ColName";
  647. if (!_processProcessDetailAttributeDict[x.ColumnName].ContainsKey(colAttributeName))
  648. {
  649. colAttributeName = "DisplayName";
  650. }
  651. var tempStr = _processProcessDetailAttributeDict[x.ColumnName].ContainsKey("DisplayName") && !string.IsNullOrEmpty(_processProcessDetailAttributeDict[x.ColumnName]["DisplayName"]) ? _processProcessDetailAttributeDict[x.ColumnName]["DisplayName"] : x.ColumnName;
  652. headers.Add(tempStr.EndsWith("Enable") ? tempStr.Replace("Valve.", "") : tempStr);
  653. return string.IsNullOrEmpty(_processProcessDetailAttributeDict[x.ColumnName][colAttributeName]) ? x.ColumnName : _processProcessDetailAttributeDict[x.ColumnName][colAttributeName];
  654. }
  655. headers.Add(x.ColumnName.EndsWith("Enable") ? x.ColumnName.Replace("Valve.", "") : x.ColumnName);
  656. return x.ColumnName;
  657. });
  658. // Create header row
  659. IRow headerRow = sheet.CreateRow(rowIndex++);
  660. cellIndex = 1;
  661. headerRow.HeightInPoints = 35;
  662. foreach (var subCol in subColNames)
  663. {
  664. ICell cell = headerRow.CreateCell(cellIndex++);
  665. string headerText = subCol.ColumnName.Replace("(", "\n(");
  666. cell.SetCellValue(headerText);
  667. cell.CellStyle = cellStyle;
  668. sheet.SetColumnWidth(cell.ColumnIndex, subCol.ColumnName.Length * 256);
  669. }
  670. foreach (var sysCol in systemColNames ?? new string[0])
  671. {
  672. ICell cell = headerRow.CreateCell(cellIndex++);
  673. string headerText = sysCol.Replace("(", "\n(");
  674. cell.SetCellValue(headerText);
  675. cell.CellStyle = cellStyle;
  676. sheet.SetColumnWidth(cell.ColumnIndex, sysCol.Length * 256);
  677. }
  678. foreach (var pmCol in pmColNames ?? new string[0])
  679. {
  680. ICell cell = headerRow.CreateCell(cellIndex++);
  681. string headerText = pmCol.Replace("(", "\n(");
  682. cell.SetCellValue(headerText);
  683. cell.CellStyle = cellStyle;
  684. sheet.SetColumnWidth(cell.ColumnIndex, pmCol.Length * 256);
  685. }
  686. }
  687. Dictionary<string, string> keyValuePairs = new Dictionary<string, string>()
  688. {
  689. { "Recipe Info",recipeInfo.RecipeName},
  690. { "Recipe StartTime",recipeInfo.ProcessStartTime.ToString("yyyy-MM-dd HH:mm:ss")},
  691. { "Recipe EndTime",recipeInfo.ProcessEndTime.ToString("yyyy-MM-dd HH:mm:ss")},
  692. };
  693. rowIndex = 0;
  694. cellIndex = 0;
  695. IRow dictRow = sheet.CreateRow(rowIndex);
  696. dictRow.HeightInPoints = 35;
  697. foreach (var kvp in keyValuePairs)
  698. {
  699. ICell keyCell = dictRow.CreateCell(cellIndex++);
  700. keyCell.SetCellValue(kvp.Key);
  701. keyCell.CellStyle = cellStyle;
  702. }
  703. rowIndex = 1;
  704. cellIndex = 0;
  705. dictRow = sheet.CreateRow(rowIndex);
  706. dictRow.HeightInPoints = 35;
  707. foreach (var kvp in keyValuePairs)
  708. {
  709. ICell keyCell = dictRow.CreateCell(cellIndex++);
  710. keyCell.SetCellValue(kvp.Value);
  711. keyCell.CellStyle = cellStyle;
  712. //sheet.AutoSizeColumn(cellIndex);
  713. sheet.SetColumnWidth(cellIndex - 1, kvp.Value.Length * 256);
  714. }
  715. int columnIndex = subColNames.Count + 1;
  716. rowIndex = 5;
  717. for (int i = 0; i < maxRow; i++)
  718. {
  719. IRow dataRow = sheet.CreateRow(rowIndex++);
  720. dataRow.HeightInPoints = 25;
  721. var pmRow = pmDataTable != null && pmDataTable.Rows.Count > 0 ? pmDataTable.Rows[i] : null;
  722. var systemRow = systemDataTable != null && systemDataTable.Rows.Count > 0 ? systemDataTable.Rows[i] : null;
  723. DateTime dateTimeKey = new DateTime(systemRow != null ? (long)systemRow[0] : (long)pmRow[0]);
  724. var tempStepInfo = _stepInfo.OrderByDescending(x => x.StartTime).Where(x => x.StartTime <= dateTimeKey).FirstOrDefault();
  725. if (tempStepInfo != null)
  726. {
  727. stepID = tempStepInfo.StepNo;
  728. stepName = tempStepInfo.StepName;
  729. subRecipeStepName = tempStepInfo.SubRecipeStepName;
  730. subRecipeStepNumber = tempStepInfo.SubRecipeStepNumber;
  731. subRecipeLoopInfo = !string.IsNullOrEmpty(tempStepInfo.SubRecipeLoopInfo) ? tempStepInfo.SubRecipeLoopInfo.Replace("/", "|") : tempStepInfo.SubRecipeLoopInfo;
  732. tempCorrection = !string.IsNullOrEmpty(tempStepInfo.TempCorrection) ? tempStepInfo.TempCorrection : "";
  733. tempPid = !string.IsNullOrEmpty(tempStepInfo.TempPid) ? tempStepInfo.TempPid : "";
  734. }
  735. cellIndex = 1;
  736. dataRow.CreateCell(cellIndex++).SetCellValue(dateTimeKey.ToString("yyyy/MM/dd"));
  737. dataRow.CreateCell(cellIndex++).SetCellValue(dateTimeKey.ToString("HH:mm:ss.f"));
  738. dataRow.CreateCell(cellIndex++).SetCellValue(stepID);
  739. dataRow.CreateCell(cellIndex++).SetCellValue(stepName);
  740. dataRow.CreateCell(cellIndex++).SetCellValue(subRecipeStepName);
  741. dataRow.CreateCell(cellIndex++).SetCellValue(subRecipeStepNumber);
  742. dataRow.CreateCell(cellIndex++).SetCellValue(subRecipeLoopInfo);
  743. dataRow.CreateCell(cellIndex++).SetCellValue(tempCorrection);
  744. dataRow.CreateCell(cellIndex++).SetCellValue(tempPid);
  745. if (pmRow == null && systemRow != null)
  746. {
  747. for (int j = 1; j < systemRow.ItemArray.Length; j++)
  748. {
  749. ICell cell = dataRow.CreateCell(cellIndex++);
  750. cell.SetCellValue(systemRow[j].ToString());
  751. cell.CellStyle = cellStyle;
  752. }
  753. for (int j = 0; j < (pmDataTable?.Columns.Count ?? 0); j++)
  754. {
  755. ICell cell = dataRow.CreateCell(cellIndex++);
  756. cell.SetCellValue("");
  757. cell.CellStyle = cellStyle;
  758. }
  759. }
  760. else if (pmRow != null && systemRow == null)
  761. {
  762. for (int j = 0; j < (systemDataTable?.Columns?.Count ?? 0); j++)
  763. {
  764. ICell cell = dataRow.CreateCell(cellIndex++);
  765. cell.SetCellValue("");
  766. cell.CellStyle = cellStyle;
  767. }
  768. for (int j = 1; j < pmRow.ItemArray.Length; j++)
  769. {
  770. ICell cell = dataRow.CreateCell(cellIndex++);
  771. if ((headers.Count > cellIndex - 1 - columnIndex) && headers[cellIndex - 1 - columnIndex].StartsWith("Valve."))//TiN需求164
  772. cell.SetCellValue(pmRow[j].ToString() == bool.TrueString ? "Open" : "Close");
  773. else cell.SetCellValue(pmRow[j].ToString());
  774. cell.CellStyle = cellStyle;
  775. }
  776. }
  777. else if (systemDataTable != null)
  778. {
  779. for (int j = 1; j < systemRow.ItemArray.Length; j++)
  780. {
  781. ICell cell = dataRow.CreateCell(cellIndex++);
  782. cell.SetCellValue(systemRow[j].ToString());
  783. cell.CellStyle = cellStyle;
  784. }
  785. for (int j = 1; j < pmRow.ItemArray.Length; j++)
  786. {
  787. ICell cell = dataRow.CreateCell(cellIndex++);
  788. if ((headers.Count > cellIndex - 1 - columnIndex) && headers[cellIndex - 1 - columnIndex].StartsWith("Valve."))
  789. cell.SetCellValue(pmRow[j].ToString() == bool.TrueString ? "Open" : "Close");
  790. else cell.SetCellValue(pmRow[j].ToString());
  791. cell.CellStyle = cellStyle;
  792. }
  793. }
  794. }
  795. // Write the output to a file
  796. using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
  797. {
  798. workbook.Write(file);
  799. }
  800. }
  801. static string CheckAndReplace(string input)
  802. {
  803. if (input.StartsWith("PM1"))
  804. {
  805. return input.Substring(4);
  806. }
  807. if (input.StartsWith("System"))
  808. {
  809. return input.Substring(7);
  810. }
  811. return input;
  812. }
  813. /// <summary>
  814. /// 取消查询。
  815. /// </summary>
  816. public void CancelQuery()
  817. {
  818. Task.Run(() =>
  819. {
  820. if (_cancellationTokenSource?.Token.CanBeCanceled == true)
  821. {
  822. _cancellationTokenSource.Cancel();
  823. }
  824. Thread.Sleep(100);
  825. //_progQueryUpdate.Report(new ProgressUpdatingEventArgs(100, 100, ""));
  826. //_progChartSuspendUpdating.Report(false);
  827. });
  828. }
  829. }
  830. }