MainWindowViewModel.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. using Basler.Pylon;
  2. using CSScriptLib;
  3. using NPOI.SS.Formula.Functions;
  4. using NPOI.XSSF.Streaming.Values;
  5. using Prism.Commands;
  6. using Prism.Events;
  7. using Prism.Ioc;
  8. using Prism.Mvvm;
  9. using Prism.Regions;
  10. using Prism.Services.Dialogs;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Collections.ObjectModel;
  14. using System.Globalization;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Windows;
  21. using System.Windows.Controls;
  22. using System.Windows.Controls.Primitives;
  23. using System.Windows.Media;
  24. using Team.FFFeederService.Interfaces;
  25. using TeamAAS_VP;
  26. using TeamAAS_VP.Controls;
  27. using TeamAAS_VP.Core;
  28. using TeamAAS_VP.Data;
  29. using TeamAAS_VP.Enums;
  30. using TeamAAS_VP.Events;
  31. using TeamAAS_VP.Interfaces;
  32. using TeamAAS_VP.Models;
  33. using TeamAAS_VP.Resources.Languages;
  34. using TeamAAS_VP.Services;
  35. using TeamAAS_VP.Views;
  36. using TeamAAS_VP.Views.User;
  37. using WPFLocalizeExtension.Engine;
  38. using static MaterialDesignThemes.Wpf.Theme.ToolBar;
  39. namespace TeamAAS_VP.ViewModels
  40. {
  41. public class MainWindowViewModel : BindableBase
  42. {
  43. IRegionManager _regionManager;
  44. IRegionNavigationService _regionNavigationService;
  45. IContainerProvider _container;
  46. IDialogService _dialogService;
  47. IEventAggregator _eventAggregator;
  48. IConfigService _configService;
  49. IRobotService _robotService;
  50. ICameraService _cameraService;
  51. IFeederService _feederService;
  52. IPlcService _plcService;
  53. IProductService _productService;
  54. ICalibrationService _calibrationService;
  55. ISystemDatabaseService _systemDatabaseService;
  56. IDatabaseInitializer _databaseInitializer;
  57. ShiftWatcherService _shiftWatcherService;
  58. private Management management;
  59. private Guid CurrentTime;
  60. private Guid RunTime;
  61. private DateTime StartTime;
  62. private Guid currentUser;
  63. Timer timer;
  64. private bool _loginShowing;
  65. #region 属性
  66. private string _CompanyTitle;
  67. public string CompanyTitle
  68. {
  69. get { return _CompanyTitle; }
  70. set { SetProperty(ref _CompanyTitle, value); }
  71. }
  72. private string _AppVersion;
  73. public string AppVersion
  74. {
  75. get { return _AppVersion; }
  76. set { SetProperty(ref _AppVersion, value); }
  77. }
  78. private int _NavigationIndex = 0;
  79. public int NavigationIndex
  80. {
  81. get { return _NavigationIndex; }
  82. set { SetProperty(ref _NavigationIndex, value); }
  83. }
  84. private ObservableCollection<StatusInfo> _Status;
  85. public ObservableCollection<StatusInfo> Status
  86. {
  87. get { return _Status; }
  88. set { SetProperty(ref _Status, value); }
  89. }
  90. private string _MyTitle;
  91. public string MyTitle
  92. {
  93. get { return _MyTitle; }
  94. set { SetProperty(ref _MyTitle, value); }
  95. }
  96. #endregion
  97. #region 命令
  98. private DelegateCommand<string> _NavigationCommand;
  99. public DelegateCommand<string> NavigationCommand
  100. {
  101. get { return _NavigationCommand; }
  102. set { _NavigationCommand = value; }
  103. }
  104. public DelegateCommand LoadedCommand { get; set; }
  105. public DelegateCommand ClosedCommand { get; set; }
  106. #endregion
  107. #region 事件
  108. #endregion
  109. public MainWindowViewModel(IRegionManager regionManager, IEventAggregator ea, IRegionNavigationService regionNavigationService, IContainerProvider container, IDialogService dialogService,
  110. IConfigService configService, IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService, IProductService productService,
  111. ICalibrationService calibrationService, ISystemDatabaseService systemDatabaseService, IDatabaseInitializer databaseInitializer, ShiftWatcherService shiftWatcherService)
  112. {
  113. _regionManager = regionManager;
  114. _regionNavigationService = regionNavigationService;
  115. _container = container;
  116. _dialogService = dialogService;
  117. _eventAggregator = ea;
  118. _configService = configService;
  119. _robotService = robotService;
  120. _cameraService = cameraService;
  121. _feederService = feederService;
  122. _plcService = plcService;
  123. _productService = productService;
  124. _calibrationService = calibrationService;
  125. _systemDatabaseService = systemDatabaseService;
  126. _databaseInitializer = databaseInitializer;
  127. _shiftWatcherService = shiftWatcherService;
  128. //订阅权限登录事件
  129. _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
  130. management = _container.Resolve<Management>();
  131. NavigationCommand = new DelegateCommand<string>(NavigationVoid);
  132. LoadedCommand = new DelegateCommand(OnLoad);
  133. ClosedCommand = new DelegateCommand(OnClose);
  134. Status = management.Status;
  135. }
  136. #region 方法
  137. //上一次导航的名称
  138. string lastNavigationName = string.Empty;
  139. private void NavigationVoid(string obj)
  140. {
  141. if (!string.IsNullOrEmpty(lastNavigationName))
  142. {
  143. if (lastNavigationName == obj)
  144. {
  145. return;
  146. }
  147. }
  148. lastNavigationName = obj;
  149. switch (obj)
  150. {
  151. case "Home":
  152. _regionManager.RequestNavigate("MainRegionContext", "HomeView");
  153. NavigationIndex = 0;
  154. _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
  155. break;
  156. case "Products":
  157. _regionManager.RequestNavigate("MainRegionContext", "ProductsView");
  158. NavigationIndex = 1;
  159. _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
  160. break;
  161. case "Debug":
  162. _regionManager.RequestNavigate("MainRegionContext", "DebugView");
  163. NavigationIndex = 2;
  164. _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
  165. break;
  166. case "Setting":
  167. _regionManager.RequestNavigate("MainRegionContext", "SettingView");
  168. NavigationIndex = 3;
  169. _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
  170. break;
  171. case "Calib":
  172. _regionManager.RequestNavigate("MainRegionContext", "CalibrationView");
  173. NavigationIndex = 5;
  174. _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
  175. break;
  176. case "Statistics":
  177. _regionManager.RequestNavigate("MainRegionContext", "StatisticsView");
  178. NavigationIndex = 6;
  179. _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
  180. break;
  181. case "User":
  182. _regionManager.RequestNavigate("MainRegionContext", "UserView");
  183. NavigationIndex = 7;
  184. _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
  185. break;
  186. default:
  187. break;
  188. }
  189. }
  190. private async void OnLoad()
  191. {
  192. // 设置标题和版本号
  193. var systemconfig = _configService.GetSystemConfiguration();
  194. MyTitle = systemconfig.Title;
  195. CompanyTitle = systemconfig.CompanyTitle;
  196. AppVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
  197. systemconfig.SoftwareVersion = AppVersion;
  198. _configService.SaveSystemConfiguration(systemconfig);
  199. // 设置语言
  200. //#region 设置语言
  201. //var currentlanguage = _configService.GetSystemConfiguration().CurrentLanguage;
  202. //_configService.SetCurrentLanguage(currentlanguage);
  203. //#endregion
  204. SendTaskMessage(Lang.软件启动, MessageLevel.Info);
  205. StartTime = DateTime.Now;
  206. _regionManager.RequestNavigate("MainRegionContext", "HomeView");
  207. double max = 14;
  208. double curvalue = 0;
  209. currentUser = Guid.NewGuid();
  210. Status.Add(new StatusInfo(currentUser, $"{Lang.当前用户}:{_systemDatabaseService.GetCurrentUser().UserName}[{_systemDatabaseService.GetCurrentUser().userPart.ToString()}]", new SolidColorBrush(Colors.White)));
  211. var _ = Application.Current.Dispatcher.BeginInvoke(new Action(() => { _dialogService.ShowDialog("UProgressBar", rst => { }); }));
  212. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  213. {
  214. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.初始化数据库}...", Value = curvalue });
  215. }));
  216. // 2. 加载校准
  217. _calibrationService.LoadAll();
  218. //-------------------SETP 1: 初始化数据库-----------------------------------------------------------------------
  219. await Task.Delay(200);
  220. //初始化数据库
  221. DatabaseHelper.InitDatabase();
  222. SendTaskMessage($"{Lang.数据库读取完成}!", MessageLevel.Info);
  223. curvalue += 1;
  224. //
  225. await management.ReadConfig();
  226. //-------------------SETP 2: 初始化Feeder-----------------------------------------------------------------------
  227. curvalue += 1;
  228. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  229. {
  230. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化Feeder}...", Value = curvalue });
  231. }));
  232. await management.InitFeeders();
  233. //-------------------SETP 3: 初始化PLC-----------------------------------------------------------------------
  234. curvalue += 1;
  235. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  236. {
  237. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化PLC}...", Value = curvalue });
  238. }));
  239. await management.InitPlc();
  240. //-------------------SETP 4: 初始化Robot-----------------------------------------------------------------------
  241. curvalue += 1;
  242. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  243. {
  244. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化机器人}...", Value = curvalue });
  245. }));
  246. await management.InitRobots();
  247. //-------------------SETP 5: 初始化Camera-----------------------------------------------------------------------
  248. curvalue += 1;
  249. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  250. {
  251. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化相机}...", Value = curvalue });
  252. }));
  253. await management.InitCameras();
  254. //-------------------SETP 6: 初始化光源控制器-----------------------------------------------------------------------
  255. curvalue += 1;
  256. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  257. {
  258. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化光源控制器}...", Value = curvalue });
  259. }));
  260. await management.InitLightControllers();
  261. //-------------------SETP 7: 初始化电批-----------------------------------------------------------------------
  262. curvalue += 1;
  263. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  264. {
  265. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = Lang.正在连接电批, Value = curvalue });
  266. }));
  267. await management.InitScrewDriver();
  268. //-------------------SETP 8: 加载所有产品-----------------------------------------------------------------------
  269. curvalue += 1;
  270. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  271. {
  272. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.加载所有产品}...", Value = curvalue });
  273. }));
  274. await _productService.InitializeAsync();
  275. //-------------------SETP 9: 开启服务器监听-----------------------------------------------------------------------
  276. curvalue += 1;
  277. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  278. {
  279. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.开启服务器监听}...", Value = curvalue });
  280. }));
  281. management.InitBgTcp();
  282. //-------------------SETP 10: 开启Modbus Tcp-----------------------------------------------------------------------
  283. curvalue += 1;
  284. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  285. {
  286. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在开启}Modbus TCP Slave...", Value = curvalue });
  287. }));
  288. management.InitModbusTcp();
  289. //-------------------SETP 11: 开启后台脚本-----------------------------------------------------------------------
  290. curvalue += 1;
  291. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  292. {
  293. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在开启后台脚本}...", Value = curvalue });
  294. }));
  295. management.InitBackgroundcript();
  296. //-------------------SETP 12: 开启扭力测量仪-----------------------------------------------------------------------
  297. curvalue += 1;
  298. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  299. {
  300. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在开启}...", Value = curvalue });
  301. }));
  302. await management.InitSignal();
  303. //-------------------SETP 13: 开启生产排班检测-----------------------------------------------------------------------
  304. // 订阅班次切换事件,强制在UI线程执行(这样可以安全Hide/Show主窗口和弹窗)
  305. //_eventAggregator.GetEvent<WorkShiftChangedNotification>().Subscribe(OnShiftChanged, ThreadOption.UIThread);
  306. //_shiftWatcherService.Start();
  307. //当前日期
  308. CurrentTime = Guid.NewGuid();
  309. Status.Add(new StatusInfo(CurrentTime, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), new SolidColorBrush(Colors.White)));
  310. //当前运行时长
  311. RunTime = Guid.NewGuid();
  312. var run = (DateTime.Now - StartTime);
  313. string formattedTime = string.Format(Lang.已运行时长, (int)run.TotalDays, run.Hours, run.Minutes, run.Seconds);
  314. Status.Add(new StatusInfo(RunTime, formattedTime, new SolidColorBrush(Colors.White)));
  315. timer = new Timer(DoTime, null, 1000, 1000);
  316. curvalue += 1;
  317. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  318. {
  319. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在加载产品}...", Value = curvalue });
  320. }));
  321. Guid productid = _configService.GetSystemConfiguration().LastOpenedProductId;
  322. if (productid != Guid.Empty)
  323. {
  324. _productService.LoadProduct(productid);
  325. _productService.SetCurrentProduct(productid);
  326. await management.WritePositionToPlcAsync();
  327. }
  328. var homeviewmodel = _container.Resolve<HomeViewModel>();
  329. homeviewmodel.OnNavigatedTo(null);
  330. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  331. {
  332. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.完成}", Value = -1 });
  333. }));
  334. }
  335. private void OnClose()
  336. {
  337. }
  338. private void SendTaskMessage(string msg, MessageLevel level)
  339. {
  340. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  341. }
  342. private void DoTime(object state)
  343. {
  344. //当前日期
  345. var c = Status.FirstOrDefault(b => b.ID == CurrentTime);
  346. c.Message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  347. //当前运行时长
  348. var d = Status.FirstOrDefault(b => b.ID == RunTime);
  349. var run = (DateTime.Now - StartTime);
  350. d.Message = string.Format(Lang.已运行时长, (int)run.TotalDays, run.Hours, run.Minutes, run.Seconds);
  351. }
  352. public void Stop()
  353. {
  354. timer?.Dispose();
  355. timer = null;
  356. }
  357. private void LoginChange(Models.User user)
  358. {
  359. var us = Status.FirstOrDefault(u => u.ID == currentUser);
  360. if (us != null)
  361. {
  362. us.Message = $"{Lang.当前用户}:{_systemDatabaseService.GetCurrentUser().UserName}[{_systemDatabaseService.GetCurrentUser().userPart.ToString()}]";
  363. }
  364. }
  365. // 班次切换时触发:停流程→隐藏主窗口→弹登录→登录成功恢复
  366. private void OnShiftChanged()
  367. {
  368. if (_loginShowing)
  369. return;
  370. _loginShowing = true;
  371. // 1 隐藏主窗口
  372. var mainWindow = Application.Current.MainWindow;
  373. mainWindow?.Hide();
  374. CardLoginWindow loginWindow = new CardLoginWindow();
  375. loginWindow.Show();
  376. bool? result = loginWindow.ShowDialog();
  377. // 4️⃣ 根据登录结果处理
  378. if (result == true)
  379. {
  380. // 登录成功 → 显示主窗口
  381. mainWindow?.Show();
  382. }
  383. else
  384. {
  385. // 如果你想强制退出可以用:
  386. Application.Current.Shutdown();
  387. }
  388. _loginShowing = false;
  389. }
  390. #endregion
  391. }
  392. }