HomeViewModel.cs 18 KB

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