using MainShell.Common;
using MainShell.Alarm;
using MainShell.Process;
using MainShell.Recipe.Models;
using MW.WorkFlow;
using StyletIoC;
using System.Threading.Tasks;
using System.Windows;

namespace MainShell.Manual.Model
{
    public abstract class OperateViewModelBase : CameraBaseViewModel
    {
        private const int WorkflowFaultAlarmId = 20000;

        [Inject]
        public WorkflowRunner Runner { get; set; }

        [Inject]
        public AlarmOperate AlarmOperate { get; set; }


        public virtual async Task StopProcess()
        {
            await Runner.StopAsync();
        }

        protected async Task<WorkflowRunCompletedEventArgs> RunManualActivityAsync(IActivity activity, WorkflowContext context, bool showSuccessDialog = true)
        {
            var result = await Runner.RunActivityWithResultAsync(activity, context);
            ShowWorkflowResultDialog(result, context, activity != null ? activity.Name : null, showSuccessDialog);
            return result;
        }

        protected bool IsWorkflowCompleted(WorkflowRunCompletedEventArgs result)
        {
            return result != null && result.FinalState == WorkflowState.Completed;
        }

        private void ShowWorkflowResultDialog(WorkflowRunCompletedEventArgs result, WorkflowContext context, string activityName, bool showSuccessDialog)
        {
            if (result == null)
            {
                return;
            }

            CommonUti.RunOnUi(() =>
            {
                switch (result.FinalState)
                {
                    case WorkflowState.Faulted:
                        ShowWorkflowFaultAlarm(result, context, activityName);
                        break;
                    case WorkflowState.Canceled:
                        MwMessageBox.Show("流程已取消！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        break;
                    case WorkflowState.Completed:
                        if (showSuccessDialog)
                        {
                            MwMessageBox.Show("流程执行成功。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        break;
                }
            });
        }

        private void ShowWorkflowFaultAlarm(WorkflowRunCompletedEventArgs result, WorkflowContext context, string activityName)
        {
            if (AlarmOperate == null)
            {
                MwMessageBox.Show("流程执行过程中发生异常！", result.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            AlarmOperate.Alert(WorkflowFaultAlarmId);
        }
    }
}
