HomeViewModel.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. using MahApps.Metro.Controls;
  2. using MaterialDesignThemes.Wpf;
  3. using NPOI.SS.Formula.Functions;
  4. using OxyPlot;
  5. using OxyPlot.Axes;
  6. using OxyPlot.Legends;
  7. using OxyPlot.Series;
  8. using Prism.Commands;
  9. using Prism.Events;
  10. using Prism.Ioc;
  11. using Prism.Mvvm;
  12. using Prism.Regions;
  13. using Prism.Services.Dialogs;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Collections.ObjectModel;
  17. using System.Linq;
  18. using System.Threading.Tasks;
  19. using System.Windows;
  20. using System.Windows.Media;
  21. using TeamAAS_VP;
  22. using TeamAAS_VP.Controls;
  23. using TeamAAS_VP.Core;
  24. using TeamAAS_VP.Data;
  25. using TeamAAS_VP.Enums;
  26. using TeamAAS_VP.Events;
  27. using TeamAAS_VP.Interfaces;
  28. using TeamAAS_VP.Models;
  29. using TeamAAS_VP.Resources.Languages;
  30. using TeamAAS_VP.Services;
  31. using TeamAAS_VP.ViewModels.DebugMod;
  32. using TeamAAS_VP.Views.DebugMod;
  33. using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
  34. namespace TeamAAS_VP.ViewModels
  35. {
  36. public class HomeViewModel : BindableBase, IConfirmNavigationRequest
  37. {
  38. IEventAggregator _eventAggregator;
  39. IContainerProvider _container;
  40. IProductService _productService;
  41. IConfigService _configService;
  42. IRemoteCommandService _remoteCommandService;
  43. ISystemDatabaseService _systemDatabaseService;
  44. IDialogService _dialogService;
  45. #region 属性
  46. private ObservableCollection<TaskMessage> messageQueue=new ObservableCollection<TaskMessage>();
  47. /// <summary>
  48. /// 运行信息队列
  49. /// </summary>
  50. public ObservableCollection<TaskMessage> MessageQueue
  51. {
  52. get { return messageQueue; }
  53. set { SetProperty(ref messageQueue,value); }
  54. }
  55. private ObservableCollection<ProductModel> _ProductList;
  56. public ObservableCollection<ProductModel> ProductList
  57. {
  58. get { return _ProductList; }
  59. set { SetProperty(ref _ProductList, value); }
  60. }
  61. private Management _management;
  62. public Management management
  63. {
  64. get { return _management; }
  65. set { SetProperty(ref _management, value); }
  66. }
  67. private double _CTTotalSeconds;
  68. public double CTTotalSeconds
  69. {
  70. get { return _CTTotalSeconds; }
  71. set { SetProperty(ref _CTTotalSeconds, value); }
  72. }
  73. private ProductModel _SelectProduct;
  74. public ProductModel SelectProduct
  75. {
  76. get { return _SelectProduct; }
  77. set { SetProperty(ref _SelectProduct,value); }
  78. }
  79. private bool CanLoad
  80. {
  81. get
  82. {
  83. if (SelectProduct!=null && IsLoadProduct)
  84. {
  85. return true;
  86. }
  87. else
  88. {
  89. return false;
  90. }
  91. }
  92. }
  93. private bool _IsLoadProduct = true;
  94. public bool IsLoadProduct
  95. {
  96. get { return _IsLoadProduct; }
  97. set { SetProperty(ref _IsLoadProduct, value); }
  98. }
  99. private bool _isCanExecute = true;
  100. public bool isCanExecute
  101. {
  102. get { return _isCanExecute; }
  103. set { SetProperty(ref _isCanExecute, value); }
  104. }
  105. private ProductModel _CurrentProduct;
  106. public ProductModel CurrentProduct
  107. {
  108. get { return _CurrentProduct; }
  109. set { SetProperty(ref _CurrentProduct, value); }
  110. }
  111. private PlotModel _LockCurvePlotModel;
  112. /// <summary>
  113. /// 锁付曲线
  114. /// </summary>
  115. public PlotModel LockCurvePlotModel
  116. {
  117. get { return _LockCurvePlotModel; }
  118. set { SetProperty(ref _LockCurvePlotModel, value); }
  119. }
  120. private ObservableCollection<LockResult> _LockResults = new ObservableCollection<LockResult>();
  121. /// <summary>
  122. /// 锁付结果列表
  123. /// </summary>
  124. public ObservableCollection<LockResult> LockResults
  125. {
  126. get { return _LockResults; }
  127. set { SetProperty(ref _LockResults, value); }
  128. }
  129. private bool _IsAllowEdit = false;
  130. public bool IsAllowEdit
  131. {
  132. get { return _IsAllowEdit; }
  133. set { SetProperty(ref _IsAllowEdit, value); }
  134. }
  135. #endregion
  136. #region 命令
  137. public DelegateCommand LoadedCommand { get; set; }
  138. private DelegateCommand<ProductModel> _LoadProductCommand;
  139. public DelegateCommand<ProductModel> LoadProductCommand =>
  140. _LoadProductCommand ?? (_LoadProductCommand = new DelegateCommand<ProductModel>(ExecuteLoadProductCommand).ObservesCanExecute(()=> CanLoad).ObservesProperty(()=> SelectProduct).ObservesProperty(()=> IsLoadProduct));
  141. private DelegateCommand _ResetCounterCommand;
  142. public DelegateCommand ResetCounterCommand =>
  143. _ResetCounterCommand ?? (_ResetCounterCommand = new DelegateCommand(ExecuteResetCounterCommand).ObservesCanExecute(() => DoCondition).ObservesProperty(()=>isCanExecute));
  144. private bool DoCondition
  145. {
  146. get { return isCanExecute; }
  147. }
  148. private DelegateCommand<string> _CopyCommand;
  149. public DelegateCommand<string> CopyCommand =>
  150. _CopyCommand ?? (_CopyCommand = new DelegateCommand<string>(ExecuteCopyCommand));
  151. private DelegateCommand _TorqueInspectionCommand;
  152. public DelegateCommand TorqueInspectionCommand =>
  153. _TorqueInspectionCommand ?? (_TorqueInspectionCommand = new DelegateCommand(ExecuteTorqueInspectionCommand));
  154. private DelegateCommand _NozzleCounterResetCommand;
  155. public DelegateCommand NozzleCounterResetCommand =>
  156. _NozzleCounterResetCommand ?? (_NozzleCounterResetCommand = new DelegateCommand(ExecuteNozzleCounterResetCommand));
  157. private DelegateCommand _SetAlarmValueCommand;
  158. public DelegateCommand SetAlarmValueCommand =>
  159. _SetAlarmValueCommand ?? (_SetAlarmValueCommand = new DelegateCommand(ExecuteSetAlarmValueCommand));
  160. #endregion
  161. #region 事件
  162. #endregion
  163. public HomeViewModel(IEventAggregator ea, IContainerProvider container, IProductService productService, IConfigService configService, IRemoteCommandService remoteCommandService
  164. , ISystemDatabaseService systemDatabaseService,IDialogService dialogService)
  165. {
  166. _eventAggregator = ea;
  167. _container = container;
  168. _dialogService = dialogService;
  169. _productService = productService;
  170. LoadedCommand = new DelegateCommand(OnLoad);
  171. _eventAggregator.GetEvent<TaskMessageNotification>().Subscribe(AddMessageInvoke);
  172. //订阅权限登录事件
  173. _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
  174. management = _container.Resolve<Management>();
  175. _configService = configService;
  176. _productService.OnProductChanged += _productService_OnProductChanged;
  177. _remoteCommandService = remoteCommandService;
  178. _remoteCommandService.CycleTimingTicked += _remoteCommandService_CycleTimingTicked;
  179. _systemDatabaseService = systemDatabaseService;
  180. _eventAggregator.GetEvent<LockFinishNotification>().Subscribe(OnLockFinish);
  181. }
  182. private void _remoteCommandService_CycleTimingTicked(object sender, TimeSpan e)
  183. {
  184. try
  185. {
  186. if (App.Current!=null)
  187. {
  188. App.Current.Invoke(() =>
  189. {
  190. CTTotalSeconds = e.TotalSeconds;
  191. });
  192. }
  193. }
  194. catch (Exception)
  195. {
  196. }
  197. }
  198. #region 方法
  199. bool isFirst=true;
  200. private void OnLoad()
  201. {
  202. if (!isFirst)
  203. {
  204. return;
  205. }
  206. InitLockCurvePlotModel();
  207. isFirst = false;
  208. if (_systemDatabaseService.GetCurrentUser().userPart == Enums.UserPart.Operator)
  209. {
  210. IsAllowEdit = false;
  211. }
  212. else
  213. {
  214. IsAllowEdit = true;
  215. }
  216. }
  217. async void ExecuteLoadProductCommand(ProductModel product)
  218. {
  219. if (product == null) return;
  220. var view = new ShowMessage(Lang.是否加载产品, $"{Lang.加载产品}:{product.Name}?");
  221. //show the dialog
  222. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  223. if (result != null && result is bool)
  224. {
  225. if (((bool)result))
  226. {
  227. IsLoadProduct = false;
  228. var waiting = new WaitingControl();
  229. //show the dialog
  230. var task = DialogHost.Show(waiting, "RootDialog", null, null, null);
  231. await _productService.LoadProductAsync(product.ID);
  232. _productService.SetCurrentProduct(product.ID);
  233. await management.WritePositionToPlcAsync();
  234. if (DialogHost.IsDialogOpen("RootDialog"))
  235. {
  236. DialogHost.Close("RootDialog");
  237. }
  238. await task;
  239. //DatabaseHelper.AddLoadProductRecord(product.ID, product.Name, false);
  240. IsLoadProduct = true;
  241. }
  242. }
  243. }
  244. void ExecuteCopyCommand(string textToCopy)
  245. {
  246. Clipboard.SetText(textToCopy);
  247. }
  248. void ExecuteTorqueInspectionCommand()
  249. {
  250. _dialogService.ShowDialog("TorqueCheck", rst =>
  251. {
  252. //对话框关闭之后的回调函数,可以在这解析结果。
  253. ButtonResult result1 = rst.Result;
  254. if (result1 == ButtonResult.OK)
  255. {
  256. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  257. }
  258. });
  259. }
  260. /// <summary>
  261. /// 添加消息至消息队列
  262. /// </summary>
  263. /// <param name="msg"></param>
  264. /// <param name="color"></param>
  265. public void AddMessage(string msg, Color color)
  266. {
  267. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  268. try
  269. {
  270. MessageQueue.Add(new TaskMessage()
  271. {
  272. DT = DateTime.Now,
  273. Message = msg,
  274. FontColol = new SolidColorBrush(color)
  275. });
  276. LogHelper.WriteLogInfo(msg);
  277. }
  278. catch (Exception)
  279. {
  280. }
  281. }));
  282. }
  283. /// <summary>
  284. /// 添加消息至消息队列
  285. /// </summary>
  286. /// <param name="msg"></param>
  287. /// <param name="color"></param>
  288. public void AddMessage(string msg, MessageLevel level)
  289. {
  290. MessageStruct messageStruct = new MessageStruct() { Message = msg, level = level };
  291. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  292. AddMessage(messageStruct);
  293. }));
  294. }
  295. /// <summary>
  296. /// 添加消息至消息队列
  297. /// </summary>
  298. /// <param name="messageStruct"></param>
  299. public void AddMessage(MessageStruct messageStruct)
  300. {
  301. try
  302. {
  303. if (MessageQueue.Count >= 20)
  304. {
  305. MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
  306. }
  307. Color color = Colors.Black;
  308. switch (messageStruct.level)
  309. {
  310. case MessageLevel.Info:
  311. color = Colors.Black;
  312. break;
  313. case MessageLevel.Debug:
  314. color = Colors.Green;
  315. break;
  316. case MessageLevel.Alarm:
  317. color = Colors.Orange;
  318. break;
  319. case MessageLevel.Error:
  320. color = Colors.Red;
  321. break;
  322. }
  323. MessageQueue.Add(new TaskMessage()
  324. {
  325. DT = DateTime.Now,
  326. Message = messageStruct.Message,
  327. FontColol = new SolidColorBrush(color)
  328. });
  329. LogHelper.WriteLogInfo(messageStruct.Message);
  330. }
  331. catch (Exception)
  332. {
  333. }
  334. }
  335. public void AddMessageInvoke(MessageStruct messageStruct)
  336. {
  337. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  338. AddMessage(messageStruct);
  339. }));
  340. }
  341. private void LoginChange(Models.User user)
  342. {
  343. if (user.userPart == Enums.UserPart.Operator)
  344. {
  345. IsAllowEdit = false;
  346. }
  347. else
  348. {
  349. IsAllowEdit = true;
  350. }
  351. }
  352. /// <summary>
  353. /// 重置计数
  354. /// </summary>
  355. async void ExecuteResetCounterCommand()
  356. {
  357. if (management.CurrentProduct == null) return;
  358. var view = new ShowMessage(Lang.计数清零, Lang.是否重置当前产品的计数);
  359. //show the dialog
  360. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  361. if (result != null && result is bool)
  362. {
  363. if (((bool)result))
  364. {
  365. isCanExecute = false;
  366. await _systemDatabaseService.ResetProductionAsync(management.CurrentProduct.Name);
  367. isCanExecute = true;
  368. }
  369. }
  370. }
  371. //初始化曲线图
  372. private void InitLockCurvePlotModel()
  373. {
  374. var model = new PlotModel { Title = "锁付曲线", TitleFontSize = 16};
  375. // 设置图例
  376. var legend = new Legend
  377. {
  378. LegendPosition = LegendPosition.TopRight,
  379. LegendPlacement = LegendPlacement.Outside,
  380. LegendOrientation = LegendOrientation.Vertical,
  381. LegendBorderThickness = 0
  382. };
  383. model.Legends.Add(legend);
  384. // 设置X轴
  385. var xAxis = new LinearAxis
  386. {
  387. Key="X",
  388. Position = AxisPosition.Bottom,
  389. Title = "角度 (°)",
  390. Minimum = 0,
  391. MajorGridlineStyle = LineStyle.Solid,
  392. MinorGridlineStyle = LineStyle.Dot
  393. };
  394. model.Axes.Add(xAxis);
  395. // 设置Y轴
  396. var yAxis = new LinearAxis
  397. {
  398. Key = "Y",
  399. Position = AxisPosition.Left,
  400. Title = "力矩 (kgf)",
  401. MajorGridlineStyle = LineStyle.Solid,
  402. MinorGridlineStyle = LineStyle.Dot
  403. };
  404. model.Axes.Add(yAxis);
  405. // 添加示例数据系列
  406. var series = new LineSeries
  407. {
  408. Title = "锁付力矩曲线",
  409. StrokeThickness = 2,
  410. MarkerSize = 3,
  411. MarkerType = MarkerType.Circle,
  412. CanTrackerInterpolatePoints = false,
  413. };
  414. model.Series.Add(series);
  415. LockCurvePlotModel = model;
  416. }
  417. /// <summary>
  418. /// 螺丝锁付完成时调用
  419. /// </summary>
  420. /// <param name="result"></param>
  421. /// <exception cref="NotImplementedException"></exception>
  422. private void OnLockFinish(LockResult result)
  423. {
  424. //如果当前螺丝编号为1,则清除之前的结果
  425. if (result.Number == 1)
  426. {
  427. LockResults.Clear();
  428. }
  429. LockResults.Add(result);
  430. //更新曲线图
  431. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  432. var series = LockCurvePlotModel.Series[0] as LineSeries;
  433. //var yaxis = LockCurvePlotModel.Axes.FirstOrDefault(p=>p.Key=="Y");
  434. //yaxis.Maximum = result.TargetTorque;
  435. series.Points.Clear();
  436. foreach (var waveData in result.WaveDatas)
  437. {
  438. series.Points.Add(new OxyPlot.DataPoint(waveData.LockAngle, waveData.Torque));
  439. }
  440. LockCurvePlotModel.InvalidatePlot(true);
  441. }));
  442. }
  443. void ExecuteSetAlarmValueCommand()
  444. {
  445. _dialogService.ShowDialog("SetAlarmValue", rst =>
  446. {
  447. //对话框关闭之后的回调函数,可以在这解析结果。
  448. ButtonResult result1 = rst.Result;
  449. if (result1 == ButtonResult.OK)
  450. {
  451. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  452. }
  453. });
  454. }
  455. void ExecuteNozzleCounterResetCommand()
  456. {
  457. management.NumStatistics.NozzleNum = 0;
  458. management.NumStatistics.HeaderNum = 0;
  459. FileHelper.WriteJsonFile(management.NumStatistics, FilePath.NumberStatisticsPath);
  460. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  461. }
  462. #endregion
  463. #region 继承
  464. /// <summary>
  465. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  466. /// </summary>
  467. /// <param name="navigationContext"></param>
  468. /// <param name="continuationCallback"></param>
  469. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  470. {
  471. continuationCallback(true);
  472. }
  473. /// <summary>
  474. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  475. /// </summary>
  476. /// <param name="navigationContext"></param>
  477. /// <exception cref="NotImplementedException"></exception>
  478. public async void OnNavigatedTo(NavigationContext navigationContext)
  479. {
  480. try
  481. {
  482. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  483. }
  484. catch (Exception ex)
  485. {
  486. LogHelper.WriteLogError("主界面界面进入时出错!", ex);
  487. }
  488. }
  489. /// <summary>
  490. /// 是否允许导航到此视图模型。
  491. /// </summary>
  492. /// <param name="navigationContext"></param>
  493. /// <returns></returns>
  494. public bool IsNavigationTarget(NavigationContext navigationContext)
  495. {
  496. return true;
  497. }
  498. /// <summary>
  499. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  500. /// </summary>
  501. /// <param name="navigationContext"></param>
  502. public void OnNavigatedFrom(NavigationContext navigationContext)
  503. {
  504. }
  505. #endregion
  506. private void _productService_OnProductChanged(ProductModel obj)
  507. {
  508. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  509. CurrentProduct = obj;
  510. }));
  511. }
  512. }
  513. }