using Bro.Common.Factory;
using Bro.Common.Helper;
using Bro.Common.Interface;
using Bro.UI.Model;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Media;
namespace Bro.UI.ViewModel
{
///
/// This class contains properties that the main View can data bind to.
///
/// See http://www.mvvmlight.net
///
///
public class MainViewModel : ViewModelBase
{
#region IDialogService
public IDialogCoordinator Dialog
{
get
{
return SimpleIoc.Default.GetInstance("Main");
}
}
#endregion
#region Login
private string _welcomeTitle = string.Empty;
public string WelcomeTitle
{
get
{
return _welcomeTitle;
}
set
{
Set(ref _welcomeTitle, value);
}
}
private string userName = "";
public string UserName
{
get => userName;
set => Set(ref userName, value);
}
#endregion
public MainViewModel(LoginInfo info)
{
InitialCmmd();
Initial();
if (!string.IsNullOrWhiteSpace(info.ProductionCode))
{
CurrentCode = info.ProductionCode;
}
if (!string.IsNullOrWhiteSpace(info.UserName))
{
UserName = info.UserName;
}
LogList.CollectionChanged += LogList_CollectionChanged;
}
private void Initial()
{
WelcomeTitle = ConfigurationManager.AppSettings["Title"];
if (string.IsNullOrWhiteSpace(WelcomeTitle))
{
WelcomeTitle = "T047";
}
WelcomeTitle += " V" + Assembly.GetExecutingAssembly().GetName().Version.ToString();
CodesSource = SettingHelper.GetProductionCodes();
//if (CodesSource == null || CodesSource.Count == 0)
//{
// CodesSource = new List() { "Default" };
//}
//CurrentCode = CodesSource[0];
}
#region ProductionCode
private List codeSource = new List();
public List CodesSource
{
get => codeSource;
set => Set(ref codeSource, value);
}
private string currentCode = "";
public string CurrentCode
{
get => currentCode;
set
{
if (currentCode != value)
{
Set(ref currentCode, value);
LoadProdution(value);
//ProcessOperation(LoadProdution, "Loading", "Load Failed");
}
}
}
private bool isProcessStopped = true;
public bool IsProcessStopped
{
get => isProcessStopped;
set => Set(ref isProcessStopped, value);
}
#endregion
#region Process
public IProcess ProcessControl { get; set; }
string _processCode = "";
private List deviceList = null;
public List DeviceList
{
get => deviceList;
set => Set(ref deviceList, value);
}
private void LoadProcessCode()
{
var systemProcessCodes = ProcessFactory.GetProcessCodes();
var avaiableProcessCodes = SettingHelper.GetProcessCodes();
List pCodes = new List();
if (avaiableProcessCodes.Count > 0)
{
pCodes = avaiableProcessCodes.Intersect(systemProcessCodes).ToList();
}
else
{
pCodes = systemProcessCodes;
}
if (!(pCodes.Count == 1 && pCodes[0] == ""))
{
pCodes.Remove("");
}
_processCode = pCodes[0];
}
private void LoadProdution(string productionCode)
{
LoadProcessCode();
if (productionCode == "Default")
{
productionCode = "";
}
ProcessControl = ProcessFactory.CreateStationProcess(_processCode, productionCode, out string msg);
if (!string.IsNullOrWhiteSpace(msg))
{
throw new ProcessException($"Process创建失败,{msg}", null, ExceptionLevel.Fatal);
}
ProcessControl.InitialProcess();
//SimpleIoc.Default.Unregister("ProcessControl");
//SimpleIoc.Default.Register(() => ProcessControl, "ProcessControl", true);
SimpleIoc.Default.Unregister();
SimpleIoc.Default.Register(() =>
{
RunningViewModel vm = new RunningViewModel(ProcessControl);
return vm;
}, true);
SimpleIoc.Default.Unregister();
SimpleIoc.Default.Register(() =>
{
InformationViewModel vm = new InformationViewModel(ProcessControl);
return vm;
}, true);
Messenger.Default.Send("", "ProcessDone");
ProcessControl.OnProcessStateChanged -= OnProcessStateChanged;
ProcessControl.OnProcessStateChanged += OnProcessStateChanged;
ProcessControl.OnLog -= OnProcessLog;
ProcessControl.OnLog += OnProcessLog;
//using (var scope = GlobalVar.Container.BeginLifetimeScope())
//{
// DeviceList = scope.Resolve>();
//}
DeviceList = ProcessControl.DeviceCollection;
LogList.Clear();
}
private void LoadProdution()
{
LoadProdution(CurrentCode);
}
private void OnProcessStateChanged(EnumHelper.DeviceState state)
{
IsProcessStopped = (state != EnumHelper.DeviceState.DSOpen);
}
#endregion
#region Operation
public RelayCommand Cmmd_Run { get; set; }
public RelayCommand Cmmd_Stop { get; set; }
public RelayCommand Cmmd_Load { get; set; }
private void InitialCmmd()
{
Cmmd_Run = new RelayCommand(OnCmmdRun);
Cmmd_Stop = new RelayCommand(OnCmmdStop);
Cmmd_Load = new RelayCommand(OnCmmdLoad);
}
private async void OnCmmdLoad()
{
await ProcessOperation(ProcessControl.InitialProcess, "Loading", "Load Failed");
}
private async void OnCmmdStop()
{
await ProcessOperation(ProcessControl.Close, "Stopping", "Stop Failed");
}
//int i = 0;
private async void OnCmmdRun()
{
await ProcessOperation(ProcessControl.Open, "Starting", "Start Failed");
//SimpleIoc.Default.GetInstance().Images[0].Shapes.Add(new Bro.Common.ImageCanvas.Shapes.ComplexPointIndicator()
//{
// PointInfo = new Bro.Common.Model.ComplexPoint()
// {
// ImagePoint = new Bro.Common.Model.DirectionAidPoint() { X = 300 + i * 200, Y = 300 + i * 200 },
// PlatPoint = new Bro.Common.Model.DirectionAidPoint() { X = 300, Y = 200, IsAvailable = false, },
// },
// Angle = 30,
// Index = 10,
//});
//i++;
}
private async Task ProcessOperation(Action action, string desc, string errorHint)
{
var controller = await Dialog.ShowProgressAsync(this, desc, $"Process is {desc}...");
controller.SetProgressBarForegroundBrush(new SolidColorBrush(Color.FromRgb(10, 22, 33)));
controller.SetIndeterminate();
await Task.Run(() =>
{
action.Invoke();
//Thread.Sleep(1000);
}).ContinueWith((t) =>
{
controller.CloseAsync();
if (t.Exception != null)
{
Dialog.ShowMessageAsync(this, errorHint, t.Exception.GetExceptionMessage());
}
});
}
#endregion
#region Log
private ObservableCollection logList = new ObservableCollection();
public ObservableCollection LogList
{
get => logList;
set => Set(ref logList, value);
}
private void LogList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
RaisePropertyChanged("LogList");
}
private async void OnProcessLog(DateTime logTime, string prefix, string msg)
{
await Task.Run(() =>
{
string log = logTime.ToString("HH:mm:ss.fff") + "\t" + prefix;
if (!string.IsNullOrWhiteSpace(msg))
{
log += ("\r\n" + msg);
}
App.Current.Dispatcher.Invoke(() =>
{
LogList.Add(log);
if (LogList.Count > 200)
{
//LogList = new ObservableCollection(LogList.Skip(100));
//LogList.CollectionChanged += LogList_CollectionChanged;
int i = 100;
while (i > 0)
{
LogList.RemoveAt(0);
i--;
}
}
});
});
}
#endregion
public override void Cleanup()
{
base.Cleanup();
if (ProcessControl.ProcessState == EnumHelper.DeviceState.DSOpen)
{
ProcessControl.Close();
}
}
}
}