using MaterialDesignThemes.Wpf; using Prism.Commands; using Prism.Events; using Prism.Ioc; using Prism.Mvvm; using Prism.Regions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using System.Web.Hosting; using System.Windows; using Team.FFFeederService; using Team.FFFeederService.Interfaces; using TeamAAS_VP; using TeamAAS_VP.Controls; using TeamAAS_VP.Core; using TeamAAS_VP.Enums; using TeamAAS_VP.Events; using TeamAAS_VP.Interfaces; using TeamAAS_VP.Models; using TeamAAS_VP.Models.Feeder; using TeamAAS_VP.Resources.Languages; using TeamAAS_VP.Services; using TeamAAS_VP.Views.Product; using static Org.BouncyCastle.Math.Primes; namespace TeamAAS_VP.ViewModels.DebugMod { public class FeederClearViewModel : BindableBase, IConfirmNavigationRequest { IContainerProvider _container; IEventAggregator _eventAggregator; IConfigService _configService; IFeederService _feederService; IRemoteCommandService _remoteCommandService; ISystemDatabaseService _systemDatabaseService; CancellationTokenSource TokenSource; #region 属性 public Management management { get; set; } private IVoiceCoilMotorFeeder _Feeder; public IVoiceCoilMotorFeeder Feeder { get { return _Feeder; } set { SetProperty(ref _Feeder, value); FeederChangedEvent?.Invoke(value); } } private ObservableCollection _Feeders = new ObservableCollection(); /// /// Feeder参数 /// public ObservableCollection Feeders { get { return _Feeders; } set { SetProperty(ref _Feeders, value); } } private FeederInfo _SelectFeeder; public FeederInfo SelectFeeder { get { return _SelectFeeder; } set { SetProperty(ref _SelectFeeder, value); } } private int _SelectFeederFunctionIndex; /// /// 选择的的Feeder振动功能码索引 /// public int SelectFeederFunctionIndex { get { return _SelectFeederFunctionIndex; } set { SetProperty(ref _SelectFeederFunctionIndex, value); if (value >= 0 && value <= 25) { SelectFeederFunction = (VibrationFunction)value; } else { SelectFeederFunction = VibrationFunction.Delay; } } } private VibrationFunction _SelectFeederFunction; /// /// 选中的feeder振动功能码 /// public VibrationFunction SelectFeederFunction { get { return _SelectFeederFunction; } set { SetProperty(ref _SelectFeederFunction, value); } } private FeederClearWork _SelelctFeederClearWork; /// /// 选中的Feeder清料任务 /// public FeederClearWork SelelctFeederClearWork { get { return _SelelctFeederClearWork; } set { SetProperty(ref _SelelctFeederClearWork, value); if (value != null) { SelectFeeder = Feeders.FirstOrDefault(p => p.Id == value.FeederId); } else { SelectFeeder = null; } } } private ObservableCollection _AllTasks; /// /// 全局任务列表(用于任务管理) /// public ObservableCollection AllTasks { get { return _AllTasks; } set { SetProperty(ref _AllTasks, value); } } #endregion #region 命令 private DelegateCommand _LoadedCommand; public DelegateCommand LoadedCommand => _LoadedCommand ?? (_LoadedCommand = new DelegateCommand(ExecuteLoadedCommand)); private DelegateCommand _SaveClearTaskCommand; public DelegateCommand SaveClearTaskCommand => _SaveClearTaskCommand ?? (_SaveClearTaskCommand = new DelegateCommand(ExecuteSaveClearTaskCommandName, (sender) => { return SelelctFeederClearWork != null; }).ObservesProperty(() => SelelctFeederClearWork)); private DelegateCommand _AddFunctionCommand; public DelegateCommand AddFunctionCommand => _AddFunctionCommand ?? (_AddFunctionCommand = new DelegateCommand(ExecuteAddFunctionCommand)); private DelegateCommand _RemoveFunctionCommand; public DelegateCommand RemoveFunctionCommand => _RemoveFunctionCommand ?? (_RemoveFunctionCommand = new DelegateCommand(ExecuteRemoveFunctionCommand)); private DelegateCommand _AddClearTaskCommand; public DelegateCommand AddClearTaskCommand => _AddClearTaskCommand ?? (_AddClearTaskCommand = new DelegateCommand(ExecuteAddClearTaskCommand)); private DelegateCommand _RemoveClearTaskCommand; public DelegateCommand RemoveClearTaskCommand => _RemoveClearTaskCommand ?? (_RemoveClearTaskCommand = new DelegateCommand(ExecuteRemoveClearTaskCommand, CanExecuteRemoveClearTaskCommand).ObservesProperty(() => SelelctFeederClearWork)); private DelegateCommand _StartSelectedCommand; public DelegateCommand StartSelectedCommand => _StartSelectedCommand ?? (_StartSelectedCommand = new DelegateCommand(ExecuteStartSelectedCommand, CanExecuteStartSelectedCommand).ObservesProperty(() => SelelctFeederClearWork)); #endregion #region 事件 public event Action FeederChangedEvent; #endregion public FeederClearViewModel(IContainerProvider container, IEventAggregator ea,IConfigService configService,IFeederService feederService, IRemoteCommandService remoteCommandService, ISystemDatabaseService systemDatabaseService) { _container = container; _eventAggregator = ea; _configService = configService; _feederService = feederService; _remoteCommandService = remoteCommandService; _systemDatabaseService = systemDatabaseService; //订阅权限登录事件 _eventAggregator.GetEvent().Subscribe(LoginChange); } #region 方法 void ExecuteLoadedCommand() { try { if (_systemDatabaseService.GetCurrentUser().userPart == Enums.UserPart.Operator) { IsAllowEdit = false; } else { IsAllowEdit = true; } } catch (Exception) { } } // helper wrapper to get feeders from config service (protect null) private IEnumerable _config_service_GetAllFeeders() { try { return _configService.GetAllFeeders(); } catch { return new List(); } } /// /// 保存清料任务 /// /// async void ExecuteSaveClearTaskCommandName(object feeder) { try { if (SelectFeeder == null) { return; } if (SelelctFeederClearWork == null) { return; } // ensure FeederId is assigned to the task SelelctFeederClearWork.FeederId = SelectFeeder.Id; SelelctFeederClearWork.FeederName = SelectFeeder.FeederName; // attempt to fetch live feeder for parameter binding if (Feeder == null) { Feeder = _feederService.GetFeeder(SelectFeeder.Id); } if (Feeder != null && Feeder.IsConnected) { foreach (var item in SelelctFeederClearWork.FeederWorks.FeederWorkList) { if (item.Function == VibrationFunction.Delay) continue; var paramCollection = await Feeder.GetShakeGroupValueAsync((int)item.Function); item.SingleAction = paramCollection; } } _configService.AddOrUpdateClearanceTask(SelelctFeederClearWork); MessageBox.Show(Lang.完成); } catch (Exception ex) { LogHelper.WriteLogError("Feeder清料界面保存振动任务时出错!", ex); MessageBox.Show(ex.Message); } } /// /// 增加振动盘振动任务 /// async void ExecuteAddFunctionCommand() { try { if (SelectFeeder == null) { return; } if (SelelctFeederClearWork == null) { return; } if (SelectFeederFunction == VibrationFunction.Delay) { var view = new AddProduct() { Title = $"{Lang.添加动作}:", Item = $"{Lang.持续时长}(ms)" }; //show the dialog var result = await DialogHost.Show(view, "RootDialog", null, null, null); if (result != null && !string.IsNullOrEmpty(result.ToString()) && int.TryParse(result.ToString(), out int time)) { SelelctFeederClearWork.FeederWorks.Add(new FeederWork() { Step = SelelctFeederClearWork.FeederWorks.Count, Function = SelectFeederFunction, Duration = time }); } } else { var view = new AddProduct() { Title = $"{Lang.添加动作}:", Item = $"{Lang.持续时长}(ms)" }; //show the dialog var result = await DialogHost.Show(view, "RootDialog", null, null, null); if (result != null && !string.IsNullOrEmpty(result.ToString()) && int.TryParse(result.ToString(), out int time)) { if (Feeder != null && Feeder.IsConnected) { var paramCollection = await Feeder.GetShakeGroupValueAsync((int)SelectFeederFunction); SelelctFeederClearWork.FeederWorks.Add(new FeederWork() { Step = SelelctFeederClearWork.FeederWorks.Count, Function = SelectFeederFunction, Duration = time, SingleAction = paramCollection }); } else { SelelctFeederClearWork.FeederWorks.Add(new FeederWork() { Step = SelelctFeederClearWork.FeederWorks.Count, Function = SelectFeederFunction, Duration = time }); } } } } catch (Exception ex) { LogHelper.WriteLogError("Feeder清料界面增加振动盘任务时出错!", ex); MessageBox.Show(ex.Message); } } /// /// 移除振动盘振动任务 /// /// void ExecuteRemoveFunctionCommand(object index) { try { if (SelectFeeder == null) { return; } if (SelelctFeederClearWork == null) { return; } if (SelelctFeederClearWork.FeederWorks == null || SelelctFeederClearWork.FeederWorks.FeederWorkList == null) { return; } if ((int)index < 0) return; SelelctFeederClearWork.FeederWorks.FeederWorkList.RemoveAt((int)index); } catch (Exception ex) { LogHelper.WriteLogError("Feeder清料界面移除振动盘任务时出错!", ex); MessageBox.Show(ex.Message); } } /// /// 增加清料任务 /// /// async void ExecuteAddClearTaskCommand(object feeder) { try { var view = new AddProduct() { Title = $"{Lang.创建清料任务}:", Item = "Name" }; //show the dialog var result = await DialogHost.Show(view, "RootDialog", null, null, null); if (result != null && !string.IsNullOrEmpty(result.ToString())) { if (!FileHelper.CheckFileName(result.ToString())) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = Lang.输入的名称不符合文件名命名规则, Duration = 1 }); return; } // create new task and attach to selected feeder if any var newTask = new FeederClearWork() { Name = result.ToString(), CreateTime = DateTime.Now, BackOutput = VibrationFunction.A, BeforeScript = false, BeforeOutput = VibrationFunction.A, BackScript = false, ClearCount = 1, FeederWorks = new FeederWorks(), VibrationCount = 1, }; newTask.FeederWorks.FeederWorkList = new ObservableCollection(); newTask.TaskCode=_configService.GetAllClearanceTasks().Select(t=>t.TaskCode).DefaultIfEmpty(0).Max()+1; newTask.FeederId=_configService.GetAllFeeders().FirstOrDefault()?.Id??Guid.Empty; newTask.FeederName = _configService.GetAllFeeders().FirstOrDefault()?.FeederName??string.Empty; _configService.AddOrUpdateClearanceTask(newTask); AllTasks=new ObservableCollection(_configService.GetAllClearanceTasks()); SelelctFeederClearWork = AllTasks.FirstOrDefault(p=>p.Id==newTask.Id); } } catch (Exception ex) { LogHelper.WriteLogError("Feeder清料-新建任务时出错", ex); MessageBox.Show(ex.Message); } } /// /// 移除清料任务 /// /// void ExecuteRemoveClearTaskCommand(object feeder) { try { if (SelelctFeederClearWork == null) return; if (MessageBox.Show(Lang.是否移除清料任务, Lang.移除清料任务, MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK) { return; } _configService.RemoveClearanceTask(SelelctFeederClearWork.Id); AllTasks = new ObservableCollection(_configService.GetAllClearanceTasks()); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 }); } catch (Exception ex) { LogHelper.WriteLogError("Feeder清料-移除任务时出错", ex); MessageBox.Show(ex.Message); } } private bool CanExecuteRemoveClearTaskCommand(object arg) { return SelelctFeederClearWork != null; } /// /// 执行选中任务 /// async void ExecuteStartSelectedCommand() { try { if (SelelctFeederClearWork==null) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "请选择至少一个任务", Duration = 2 }); return; } TokenSource = new CancellationTokenSource(); var view = new WaitingPage(); //show the dialog var _= DialogHost.Show(view, "RootDialog", null, ExtendedClosingEventHandler, ExtendedClosedEventHandler); bool result = await _remoteCommandService.ExecuteClearMaterialTaskAsync(SelelctFeederClearWork.TaskCode, TokenSource.Token); if (DialogHost.IsDialogOpen("RootDialog")) { TokenSource = null; DialogHost.Close("RootDialog"); if (!result) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "任务执行失败,请检查设备连接状态", Duration = 2 }); return; } MessageBox.Show(Lang.完成); } else { TokenSource = null; } } catch (Exception ex) { LogHelper.WriteLogError("启动任务时出错", ex); MessageBox.Show(ex.Message); } } private bool CanExecuteStartSelectedCommand() { return SelelctFeederClearWork != null; } private void ExtendedClosingEventHandler(object sender, DialogClosingEventArgs eventArgs) { if (TokenSource!=null) { TokenSource.Cancel(); } } private void ExtendedClosedEventHandler(object sender, DialogClosedEventArgs eventArgs) { } #endregion #region 继承 /// /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。 /// /// /// public void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) { continuationCallback(true); } /// /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。 /// /// /// public async void OnNavigatedTo(NavigationContext navigationContext) { try { // load centralized flat task list var allTasks = _configService.GetAllClearanceTasks(); // expose for task management UI AllTasks = new ObservableCollection(allTasks); Feeders = new ObservableCollection(_config_service_GetAllFeeders()); } catch (Exception) { } } /// /// 是否允许导航到此视图模型。 /// /// /// public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } /// /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。 /// /// public void OnNavigatedFrom(NavigationContext navigationContext) { } #endregion private bool _IsAllowEdit = false; public bool IsAllowEdit { get { return _IsAllowEdit; } set { SetProperty(ref _IsAllowEdit, value); } } private void LoginChange(Models.User user) { if (user.userPart == Enums.UserPart.Operator) { IsAllowEdit = false; } else { IsAllowEdit = true; } } } }