using Basler.Pylon; using CSScriptLib; using NPOI.SS.Formula.Functions; using NPOI.XSSF.Streaming.Values; using Prism.Commands; using Prism.Events; using Prism.Ioc; using Prism.Mvvm; using Prism.Regions; using Prism.Services.Dialogs; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; using Team.FFFeederService.Interfaces; using TeamAAS_VP; using TeamAAS_VP.Controls; using TeamAAS_VP.Core; using TeamAAS_VP.Data; using TeamAAS_VP.Enums; using TeamAAS_VP.Events; using TeamAAS_VP.Interfaces; using TeamAAS_VP.Models; using TeamAAS_VP.Resources.Languages; using TeamAAS_VP.Services; using TeamAAS_VP.Views; using TeamAAS_VP.Views.User; using WPFLocalizeExtension.Engine; using static MaterialDesignThemes.Wpf.Theme.ToolBar; namespace TeamAAS_VP.ViewModels { public class MainWindowViewModel : BindableBase { IRegionManager _regionManager; IRegionNavigationService _regionNavigationService; IContainerProvider _container; IDialogService _dialogService; IEventAggregator _eventAggregator; IConfigService _configService; IRobotService _robotService; ICameraService _cameraService; IFeederService _feederService; IPlcService _plcService; IProductService _productService; ICalibrationService _calibrationService; ISystemDatabaseService _systemDatabaseService; IDatabaseInitializer _databaseInitializer; ShiftWatcherService _shiftWatcherService; private Management management; private Guid CurrentTime; private Guid RunTime; private DateTime StartTime; private Guid currentUser; Timer timer; private bool _loginShowing; #region 属性 private string _CompanyTitle; public string CompanyTitle { get { return _CompanyTitle; } set { SetProperty(ref _CompanyTitle, value); } } private string _AppVersion; public string AppVersion { get { return _AppVersion; } set { SetProperty(ref _AppVersion, value); } } private int _NavigationIndex = 0; public int NavigationIndex { get { return _NavigationIndex; } set { SetProperty(ref _NavigationIndex, value); } } private ObservableCollection _Status; public ObservableCollection Status { get { return _Status; } set { SetProperty(ref _Status, value); } } private string _MyTitle; public string MyTitle { get { return _MyTitle; } set { SetProperty(ref _MyTitle, value); } } #endregion #region 命令 private DelegateCommand _NavigationCommand; public DelegateCommand NavigationCommand { get { return _NavigationCommand; } set { _NavigationCommand = value; } } public DelegateCommand LoadedCommand { get; set; } public DelegateCommand ClosedCommand { get; set; } #endregion #region 事件 #endregion public MainWindowViewModel(IRegionManager regionManager, IEventAggregator ea, IRegionNavigationService regionNavigationService, IContainerProvider container, IDialogService dialogService, IConfigService configService, IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService, IProductService productService, ICalibrationService calibrationService, ISystemDatabaseService systemDatabaseService, IDatabaseInitializer databaseInitializer, ShiftWatcherService shiftWatcherService) { _regionManager = regionManager; _regionNavigationService = regionNavigationService; _container = container; _dialogService = dialogService; _eventAggregator = ea; _configService = configService; _robotService = robotService; _cameraService = cameraService; _feederService = feederService; _plcService = plcService; _productService = productService; _calibrationService = calibrationService; _systemDatabaseService = systemDatabaseService; _databaseInitializer = databaseInitializer; _shiftWatcherService = shiftWatcherService; //订阅权限登录事件 _eventAggregator.GetEvent().Subscribe(LoginChange); management = _container.Resolve(); NavigationCommand = new DelegateCommand(NavigationVoid); LoadedCommand = new DelegateCommand(OnLoad); ClosedCommand = new DelegateCommand(OnClose); Status = management.Status; } #region 方法 //上一次导航的名称 string lastNavigationName = string.Empty; private void NavigationVoid(string obj) { if (!string.IsNullOrEmpty(lastNavigationName)) { if (lastNavigationName == obj) { return; } } lastNavigationName = obj; switch (obj) { case "Home": _regionManager.RequestNavigate("MainRegionContext", "HomeView"); NavigationIndex = 0; _eventAggregator.GetEvent().Publish(NavigationIndex); break; case "Products": _regionManager.RequestNavigate("MainRegionContext", "ProductsView"); NavigationIndex = 1; _eventAggregator.GetEvent().Publish(NavigationIndex); break; case "Debug": _regionManager.RequestNavigate("MainRegionContext", "DebugView"); NavigationIndex = 2; _eventAggregator.GetEvent().Publish(NavigationIndex); break; case "Setting": _regionManager.RequestNavigate("MainRegionContext", "SettingView"); NavigationIndex = 3; _eventAggregator.GetEvent().Publish(NavigationIndex); break; case "Calib": _regionManager.RequestNavigate("MainRegionContext", "CalibrationView"); NavigationIndex = 5; _eventAggregator.GetEvent().Publish(NavigationIndex); break; case "Statistics": _regionManager.RequestNavigate("MainRegionContext", "StatisticsView"); NavigationIndex = 6; _eventAggregator.GetEvent().Publish(NavigationIndex); break; case "User": _regionManager.RequestNavigate("MainRegionContext", "UserView"); NavigationIndex = 7; _eventAggregator.GetEvent().Publish(NavigationIndex); break; default: break; } } private async void OnLoad() { // 设置标题和版本号 var systemconfig = _configService.GetSystemConfiguration(); MyTitle = systemconfig.Title; CompanyTitle = systemconfig.CompanyTitle; AppVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); systemconfig.SoftwareVersion = AppVersion; _configService.SaveSystemConfiguration(systemconfig); // 设置语言 //#region 设置语言 //var currentlanguage = _configService.GetSystemConfiguration().CurrentLanguage; //_configService.SetCurrentLanguage(currentlanguage); //#endregion SendTaskMessage(Lang.软件启动, MessageLevel.Info); StartTime = DateTime.Now; _regionManager.RequestNavigate("MainRegionContext", "HomeView"); double max = 14; double curvalue = 0; currentUser = Guid.NewGuid(); Status.Add(new StatusInfo(currentUser, $"{Lang.当前用户}:{_systemDatabaseService.GetCurrentUser().UserName}[{_systemDatabaseService.GetCurrentUser().userPart.ToString()}]", new SolidColorBrush(Colors.White))); var _ = Application.Current.Dispatcher.BeginInvoke(new Action(() => { _dialogService.ShowDialog("UProgressBar", rst => { }); })); _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.初始化数据库}...", Value = curvalue }); })); // 2. 加载校准 _calibrationService.LoadAll(); //-------------------SETP 1: 初始化数据库----------------------------------------------------------------------- await Task.Delay(200); //初始化数据库 DatabaseHelper.InitDatabase(); SendTaskMessage($"{Lang.数据库读取完成}!", MessageLevel.Info); curvalue += 1; // await management.ReadConfig(); //-------------------SETP 2: 初始化Feeder----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化Feeder}...", Value = curvalue }); })); await management.InitFeeders(); //-------------------SETP 3: 初始化PLC----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化PLC}...", Value = curvalue }); })); await management.InitPlc(); //-------------------SETP 4: 初始化Robot----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化机器人}...", Value = curvalue }); })); await management.InitRobots(); //-------------------SETP 5: 初始化Camera----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化相机}...", Value = curvalue }); })); await management.InitCameras(); //-------------------SETP 6: 初始化光源控制器----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化光源控制器}...", Value = curvalue }); })); await management.InitLightControllers(); //-------------------SETP 7: 初始化电批----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = Lang.正在连接电批, Value = curvalue }); })); await management.InitScrewDriver(); //-------------------SETP 8: 加载所有产品----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.加载所有产品}...", Value = curvalue }); })); await _productService.InitializeAsync(); //-------------------SETP 9: 开启服务器监听----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.开启服务器监听}...", Value = curvalue }); })); management.InitBgTcp(); //-------------------SETP 10: 开启Modbus Tcp----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在开启}Modbus TCP Slave...", Value = curvalue }); })); management.InitModbusTcp(); //-------------------SETP 11: 开启后台脚本----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在开启后台脚本}...", Value = curvalue }); })); management.InitBackgroundcript(); //-------------------SETP 12: 开启扭力测量仪----------------------------------------------------------------------- curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在开启}...", Value = curvalue }); })); await management.InitSignal(); //-------------------SETP 13: 开启生产排班检测----------------------------------------------------------------------- // 订阅班次切换事件,强制在UI线程执行(这样可以安全Hide/Show主窗口和弹窗) //_eventAggregator.GetEvent().Subscribe(OnShiftChanged, ThreadOption.UIThread); //_shiftWatcherService.Start(); //当前日期 CurrentTime = Guid.NewGuid(); Status.Add(new StatusInfo(CurrentTime, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), new SolidColorBrush(Colors.White))); //当前运行时长 RunTime = Guid.NewGuid(); var run = (DateTime.Now - StartTime); string formattedTime = string.Format(Lang.已运行时长, (int)run.TotalDays, run.Hours, run.Minutes, run.Seconds); Status.Add(new StatusInfo(RunTime, formattedTime, new SolidColorBrush(Colors.White))); timer = new Timer(DoTime, null, 1000, 1000); curvalue += 1; _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在加载产品}...", Value = curvalue }); })); Guid productid = _configService.GetSystemConfiguration().LastOpenedProductId; if (productid != Guid.Empty) { await _productService.LoadProductAsync(productid); _productService.SetCurrentProduct(productid); await management.WritePositionToPlcAsync(); } var homeviewmodel = _container.Resolve(); homeviewmodel.OnNavigatedTo(null); _ = App.Current.Dispatcher.BeginInvoke(new Action(() => { _eventAggregator.GetEvent().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.完成}", Value = -1 }); })); } private void OnClose() { } private void SendTaskMessage(string msg, MessageLevel level) { _eventAggregator.GetEvent().Publish(new Models.MessageStruct() { Message = msg, level = level }); } private void DoTime(object state) { //当前日期 var c = Status.FirstOrDefault(b => b.ID == CurrentTime); c.Message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //当前运行时长 var d = Status.FirstOrDefault(b => b.ID == RunTime); var run = (DateTime.Now - StartTime); d.Message = string.Format(Lang.已运行时长, (int)run.TotalDays, run.Hours, run.Minutes, run.Seconds); } public void Stop() { timer?.Dispose(); timer = null; } private void LoginChange(Models.User user) { var us = Status.FirstOrDefault(u => u.ID == currentUser); if (us != null) { us.Message = $"{Lang.当前用户}:{_systemDatabaseService.GetCurrentUser().UserName}[{_systemDatabaseService.GetCurrentUser().userPart.ToString()}]"; } } // 班次切换时触发:停流程→隐藏主窗口→弹登录→登录成功恢复 private void OnShiftChanged() { if (_loginShowing) return; _loginShowing = true; // 1 隐藏主窗口 var mainWindow = Application.Current.MainWindow; mainWindow?.Hide(); CardLoginWindow loginWindow = new CardLoginWindow(); loginWindow.Show(); bool? result = loginWindow.ShowDialog(); // 4️⃣ 根据登录结果处理 if (result == true) { // 登录成功 → 显示主窗口 mainWindow?.Show(); } else { // 如果你想强制退出可以用: Application.Current.Shutdown(); } _loginShowing = false; } #endregion } }