using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Fsm;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using Aitex.Core.Utilities;
using MECF.Framework.Common.Device.LinMot;
using MECF.Framework.Common.Equipment;
using MECF.Framework.Common.ToolLayout;
using MECF.Framework.Common.WaferHolder;
using CyberX8_Core;
using CyberX8_RT.Devices.LinMot;
using CyberX8_RT.Devices.Prewet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xaml.Schema;
using MECF.Framework.Common.SubstrateTrackings;
using MECF.Framework.Common.Persistent.Prewet;
using MECF.Framework.Common.RecipeCenter;
using Aitex.Core.RT.RecipeCenter;
using System.Timers;
using Aitex.Core.RT.Routine;
using System.Windows.Markup;
using CyberX8_RT.Dispatch;
using MECF.Framework.Common.Jobs;
namespace CyberX8_RT.Modules.Prewet
{
    public class PrewetEntity : Entity, IEntity, IModuleEntity
    {
        #region 常量 
        private const string AUTO = "Auto";
        private const string MANUAL = "Manual";
        private const string DISABLED = "Disabled";
        private const string ENGINEERING = "Engineering";
        private const string PRODUCTION = "Production";
        #endregion
        #region 内部变量
        /// 
        /// LintMot Axis
        /// 
        private LinMotAxis _linmotAxis;
        /// 
        /// prepare to trans
        /// 
        private PrepareToTransferRoutine _prepareToTransferRoutine;
        /// 
        /// Initialize routine
        /// 
        private PrewetInitializeRoutine _initializeRoutine;
        /// 
        /// Linmot Wet Scan Routine
        /// 
        private PrewetLinmotScanWetRoutine _linmotWetScanRoutine;
        /// 
        /// Manual模式下Cycle run 
        /// 
        private CycleManualProcessRecipeRoutine _cycleManualProcessRoutine;
        /// 
        /// delay keepwet routine
        /// 
        private PrewetDelayKeepwetRoutine _delayKeepwetRoutine;
        /// 
        /// prewet Keepwet routine
        /// 
        private PrewetKeepWetRoutine _prewetKeepWetRoutine;
        /// 
        /// 执行前的状态
        /// 
        private string _preExecuteState;
        /// 
        /// Cycle次数
        /// 
        private int _cycle = 0;
        /// 
        /// 已经完成的Cycle次数
        /// 
        private int _achievedCycle = 0;
        /// 
        /// linmot设备数据
        /// 
        private LinMotDeviceData _linMotDeviveData = new LinMotDeviceData();
        /// 
        /// LinmotName
        /// 
        private string _linmotName;
        /// 
        /// PrewetDevice
        /// 
        private PrewetDevice _prewetDevice;
        /// 
        /// 工艺当前执行小步骤
        /// 
        private string _currentStateMachine = "Init";
        /// 
        /// 工艺当前执行大步骤
        /// 
        private string _currentStatus = "Init";
        /// 
        /// 持久化对象
        /// 
        private PrewetPersistentValue _persistentValue;
        /// 
        /// 当前Recipe
        /// 
        private PwtRecipe _currentRecipe;
        /// 
        /// recipe时长
        /// 
        private int _recipeTime;
        /// 
        /// keepwet倒计时
        /// 
        private int _keepwetCountDown;
        /// 
        /// run recipe start time
        /// 
        private DateTime _runRecipeStartTime;
        /// 
        ///  run recipe complete time
        /// 
        private DateTime _runRecipeCompleteTime;
        /// 
        /// 是否Retry
        /// 
        private bool _isRetry = false;
        #endregion
        #region 属性
        /// 
        /// 模块名称
        /// 
        public ModuleName Module { get; private set; }
        /// 
        /// 初始化状态
        /// 
        public bool IsInit { get { return fsm.State == (int)PrewetState.Init; } }
        /// 
        /// 空闲状态
        /// 
        public bool IsIdle { get { return fsm.State == (int)PrewetState.Idle; } }
        /// 
        /// 是否发生错误
        /// 
        public bool IsError { get { return fsm.State == (int)PrewetState.Error; } }
        /// 
        /// 是否正在作业
        /// 
        public bool IsBusy { get { return fsm.State>(int)PrewetState.Idle; } }
        /// 
        /// 是否初始化完成
        /// 
        public bool IsInitialized { get { return fsm.State >= (int)PrewetState.Initialized; } }
        /// 
        /// 是否禁用
        /// 
        public bool IsDisable { get { return _persistentValue == null || _persistentValue.OperatingMode == DISABLED; } }
        /// 
        /// 自动模式
        /// 
        public bool IsAuto { get { return _persistentValue != null && _persistentValue.OperatingMode == AUTO; } }
        /// 
        /// 自动模式
        /// 
        public bool IsManual { get { return _persistentValue != null && _persistentValue.OperatingMode == MANUAL; } }
        /// 
        /// 是否为工程模式
        /// 
        public bool IsEngineering { get { return _persistentValue != null && _persistentValue.RecipeOperatingMode == ENGINEERING; } }
        /// 
        /// 是否为产品模式
        /// 
        public bool IsProduction { get { return _persistentValue != null && _persistentValue.RecipeOperatingMode == PRODUCTION; } }
        /// 
        /// WaferHolder信息
        /// 
        public WaferHolderInfo WaferHolderInfo { get { return WaferHolderManager.Instance.GetWaferHolder(Module.ToString()); } }
        /// 
        /// 当前状态机状态
        /// 
        public int State { get { return fsm.State; } }
        /// 
        /// recipe时长
        /// 
        public int RecipeTime { get { return _recipeTime; } }
        #endregion
        /// 
        /// 构造函数
        /// 
        public PrewetEntity(ModuleName moduleName) 
        {
            this.Module = moduleName;
            _prewetDevice = DEVICE.GetDevice(Module.ToString());
            WaferManager.Instance.SubscribeLocation(Module, 2);
            InitialFsm();
        }
        /// 
        /// 初始化
        /// 
        /// 
        protected override bool Init()
        {
            InitializeParameter();
            InitialDATA();
            InitializeRoutine();
            InitialOperation();
            //InitialStateMachine();
            return true;
        }
        /// 
        /// 中止
        /// 
        protected override void Term()
        {
        }
        /// 初始化状态机
        /// 
        private void InitialFsm()
        {
            fsm = new StateMachine(Module.ToString(), (int)PrewetState.Init, 20);
            fsm.EnableRepeatedMsg(true);
            AnyStateTransition(PrewetMsg.Error, ErrorSolution, PrewetState.Error);
            AnyStateTransition(PrewetMsg.ReturnInit, NullFunc, PrewetState.Init);
            AnyStateTransition(PrewetMsg.ReturnIdle, NullFunc, PrewetState.Idle);
         
            Transition(PrewetState.Error, PrewetMsg.ResumeError, (param) => { return true; }, PrewetState.Init);
            //Initialize
            AnyStateTransition(PrewetMsg.Initialize, InitializeAll, PrewetState.Initializing);
            Transition(PrewetState.Initializing, FSM_MSG.TIMER, InitializeAllTimeout, PrewetState.Idle);
            
            //LinmotWetScan
            Transition(PrewetState.Idle, PrewetMsg.LinmotScanWet, LinmotScanWet, PrewetState.Linmot_Scanning);
            Transition(PrewetState.Linmot_Scanning, FSM_MSG.TIMER, LinmotScanTimeout, PrewetState.Idle);
            //Kepwet
            Transition(PrewetState.Idle, PrewetMsg.KeepWet, KeepWet, PrewetState.KeepWeting);
            Transition(PrewetState.KeepWeting, FSM_MSG.TIMER, KeepWetMonitor, PrewetState.Idle);
            Transition(PrewetState.Idle, PrewetMsg.DelayKeepwet, DelayKeepwet, PrewetState.DelayKeepweting);
            Transition(PrewetState.DelayKeepwetComplete, PrewetMsg.DelayKeepwet, DelayKeepwet, PrewetState.DelayKeepweting);
            Transition(PrewetState.RunRecipeComplete, PrewetMsg.DelayKeepwet, DelayKeepwet, PrewetState.DelayKeepweting);
            Transition(PrewetState.DelayKeepweting, FSM_MSG.TIMER, DelayKeepwetMonitor, PrewetState.DelayKeepwetComplete);
            //PrepareToTransfer
            Transition(PrewetState.Idle, PrewetMsg.PrepareToTransfer, PrepareToTransfer, PrewetState.PrepareToTransfering);
            Transition(PrewetState.PrepareToTransfering, FSM_MSG.TIMER, PrepareToTransferTimeout, PrewetState.Idle); 
            //PrepareToPlace
            Transition(PrewetState.Idle, PrewetMsg.PrepareToPlace, PrepareToTransfer, PrewetState.PreparingToPlace);
            Transition(PrewetState.PreparingToPlace, FSM_MSG.TIMER, PrepareToTransferTimeout, PrewetState.WaitForPlace);
            //PrepareToPick
            Transition(PrewetState.DelayKeepweting, PrewetMsg.PrepareToPick, PrepareToTransfer, PrewetState.PreparingToPick);
            Transition(PrewetState.RunRecipeComplete, PrewetMsg.PrepareToPick, PrepareToTransfer, PrewetState.PreparingToPick);
            Transition(PrewetState.DelayKeepwetComplete, PrewetMsg.PrepareToPick, PrepareToTransfer, PrewetState.PreparingToPick);
            Transition(PrewetState.Idle, PrewetMsg.PrepareToPick, PrepareToTransfer, PrewetState.PreparingToPick);
            Transition(PrewetState.PreparingToPick, FSM_MSG.TIMER, PrepareToTransferTimeout, PrewetState.WaitForPick);
            Transition(PrewetState.WaitForPick, PrewetMsg.PickComplete, NullFunc, PrewetState.Idle);
            //RunRecipe
            Transition(PrewetState.Idle, PrewetMsg.RunRecipe, CycleManualProcess, PrewetState.RunReciping);
            Transition(PrewetState.WaitForPlace, PrewetMsg.RunRecipe, CycleManualProcess, PrewetState.RunReciping);
            Transition(PrewetState.RunReciping, FSM_MSG.TIMER, CycleManualMonitor, PrewetState.RunRecipeComplete);
            //Cycle Manual Process
            Transition(PrewetState.Idle, PrewetMsg.CycleProcessRecipe, CycleManualProcess, PrewetState.CycleManualProcessing);
            Transition(PrewetState.CycleManualProcessing, FSM_MSG.TIMER, CycleManualMonitor, PrewetState.Idle);
            
            //Abort
            Transition(PrewetState.CycleManualProcessing, PrewetMsg.Abort, CycleManualAbort, PrewetState.Abort);
            //Enter Init
            Transition(PrewetState.Idle, PrewetMsg.Init, NullFunc, PrewetState.Init);
            EnumLoop.ForEach((item) => { fsm.MapState((int)item, item.ToString()); });
            EnumLoop.ForEach((item) => { fsm.MapMessage((int)item, item.ToString()); });
        }
        /// 
        /// 初始化参数
        /// 
        private void InitializeParameter()
        {
            _persistentValue = PrewetPersistentManager.Instance.GetPrewetPersistentValue(Module.ToString());
            if (_persistentValue == null)
            {
                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module.ToString(), "Persistent Value Object is not exist");
            }
            _keepwetCountDown = 0;
        }
        /// 
        /// 初始化数据
        /// 
        private void InitialDATA()
        {
            PrewetItem prewetItem = PrewetItemManager.Instance.GetPrewetItem(Module.ToString());
            if (prewetItem!=null)
            {
                _linmotAxis = DEVICE.GetDevice(prewetItem.LinmotID);
                string LinmotDeviceName = _linmotName = _linmotAxis.DeviceID;
                LinMotDevice linMotDevice = LinMotDeviceConfigManager.Instance.GetLinMotDevice(LinmotDeviceName);
                if (linMotDevice != null)
                {
                    _linMotDeviveData = linMotDevice.LinMotDeviceData;
                }
            }
            InitializeSvid();
            DATA.Subscribe($"{Module}.FsmState", () => ((PrewetState)fsm.State).ToString(), SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.WaferHolder", () => WaferHolderInfo, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.AchievedCycle", () => _achievedCycle, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.GetKeepWetLimit", () => fsm.State==(int)PrewetState.DelayKeepweting?Math.Max(_keepwetCountDown-_delayKeepwetRoutine.ElapsedMilliseconds/1000,0):0 , SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.IsInit", () => IsInit, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.IsIdle", () => IsIdle, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.IsError", () => IsError, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.IsBusy", () => IsBusy, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.IsDisable", () => IsDisable, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.LinmotDeviceData", () => _linMotDeviveData, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.LinmotName", () => _linmotName, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.CurrentStateMachine", () => _currentStateMachine, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.CurrentStatus", () => _currentStatus, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.CurrentRecipe", () => _currentRecipe != null ? _currentRecipe.Ppid : "", SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.Linmot.ID", () => _linmotAxis.Module, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.Linmot.IsMotorOn", () => _linmotAxis.IsMotorOn, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.Linmot.IsError", () => _linmotAxis.IsError, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.Linmot.IsSwitchOn", () => _linmotAxis.IsSwitchOn, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.Linmot.ErrorCode", () => _linmotAxis.ErrorCode, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.Linmot.CurrentPosition", () => _linmotAxis.CurrentPosition, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.Linmot.ScanCount", () => _linmotAxis.ScanCount, SubscriptionAttribute.FLAG.IgnoreSaveDB);
        }
        /// 
        /// 初始化SVID
        /// 
        private void InitializeSvid()
        {
            DATA.Subscribe($"{Module}.State", () => ((PrewetState)fsm.State).ToString(), SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.LotID", () => WaferHolderInfo?.LotId, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.WSID", () => WaferHolderInfo?.Id, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.LSAID", () => WaferHolderInfo?.CrsAId, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.LSBID", () => WaferHolderInfo?.CrsBId, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.ModuleRecipe", () => _currentRecipe?.Ppid, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.SequenceRecipe", () => WaferHolderInfo?.SequenceId, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.WaferAID", () => WaferHolderInfo?.WaferAId, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.WaferBID", () => WaferHolderInfo?.WaferBId, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.TotalTime", () => _recipeTime, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.TimeRemain", () => _recipeTime != 0 ? (_recipeTime - Math.Round((double)_cycleManualProcessRoutine.ElapsedMilliseconds / 1000, 0)) : 0, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.Task", () => WaferHolderInfo?.CurrentControlJobId, SubscriptionAttribute.FLAG.IgnoreSaveDB);
            DATA.Subscribe($"{Module}.OperatingMode", () => _persistentValue != null ? _persistentValue.OperatingMode : "None", SubscriptionAttribute.FLAG.IgnoreSaveDB);
        }
        /// 
        /// 初始化操作
        /// 
        protected void InitialOperation()
        {
            OP.Subscribe($"{Module}.InitializeAll", (cmd, args) => { return CheckToPostMessage(eEvent.ERR_PREWET,Module.ToString(),(int)PrewetMsg.Initialize); });
            OP.Subscribe($"{Module}.Abort", (cmd, args) => { return CheckToPostMessage(eEvent.ERR_PREWET,Module.ToString(),(int)PrewetMsg.Abort); });
            OP.Subscribe($"{Module}.LimotScanWet", (cmd, args) => { return CheckToPostMessage(eEvent.ERR_PREWET, Module.ToString(), (int)PrewetMsg.LinmotScanWet, args); });
            OP.Subscribe($"{Module}.KeepWet", (cmd, args) => { return CheckToPostMessage(eEvent.ERR_PREWET, Module.ToString(), (int)PrewetMsg.KeepWet, args); });
            OP.Subscribe($"{Module}.PrepareToTransfer", (cmd, args) => { return CheckToPostMessage(eEvent.ERR_PREWET, Module.ToString(), (int)PrewetMsg.PrepareToTransfer); });
            OP.Subscribe($"{Module}.ManualProcessRecipe", (cmd, args) => { return CheckToPostMessage(eEvent.ERR_PREWET, Module.ToString(), (int)PrewetMsg.ProcessRecipe,args); });
            OP.Subscribe($"{Module}.CycleManualProcessRecipe", (cmd, args) => 
            {
                PwtRecipe recipe = RecipeFileManager.Instance.LoadGenericityRecipe(args[0].ToString());
                if (recipe == null)
                {
                    LOG.WriteLog(eEvent.ERR_PREWET, Module.ToString(), $"{args[0]} recipe is null");
                    return false;
                }
                object[] objects = new object[args.Length];
                objects[0] = recipe;
                for (int i = 1; i < args.Length; i++)
                {
                    objects[i] = args[i];
                }
                return CheckToPostMessage(eEvent.ERR_PREWET, Module.ToString(), (int)PrewetMsg.CycleProcessRecipe,objects); 
            });
           
        }
        /// 
        /// EnterInit
        /// 
        public void EnterInit()
        {
            if ((PrewetState)fsm.State != PrewetState.Idle) return;
            else
            {
                CheckToPostMessage(eEvent.ERR_PREWET, Module.ToString(), (int)PrewetMsg.Init);
            }
        }
        /// 
        /// 初始化Routine
        /// 
        private void InitializeRoutine()
        {
            _prepareToTransferRoutine = new PrepareToTransferRoutine(Module.ToString(), _linmotAxis);
            _initializeRoutine=new PrewetInitializeRoutine(Module.ToString(), _linmotAxis);
            _linmotWetScanRoutine=new PrewetLinmotScanWetRoutine(Module.ToString(), _linmotAxis);
            _cycleManualProcessRoutine = new CycleManualProcessRecipeRoutine(Module.ToString(), _linmotAxis);
            _delayKeepwetRoutine=new PrewetDelayKeepwetRoutine(Module.ToString(),_linmotAxis);
            _prewetKeepWetRoutine = new PrewetKeepWetRoutine(Module.ToString(), _linmotAxis);
        }
        /// 
        /// 初始化状态机
        /// 
        private void InitialStateMachine()
        {
            //_keepwetStateMachine = new PrewetKeepWetStateMachine(Module.ToString(),_linmotAxis);
            //_keepwetStateMachine.Initialize();
        }
        private bool ErrorSolution(object[] param)
        {
            bool result = _prewetDevice.PumpValveClose();
            if (!result)
            {
                LOG.WriteLog(eEvent.ERR_PREWET,Module.ToString(), "Close Pump Valve error");
            }
            return true;
        }
        #region Initialize
        /// 
        /// Initialize
        /// 
        /// 
        /// 
        private bool InitializeAll(object[] param)
        {
            if (fsm.State == (int)PrewetState.Initializing)
            {
                LOG.WriteLog(eEvent.WARN_PREWET, Module.ToString(), "state is Initializing,cannot do initialize");
                return false;
            }
            return _initializeRoutine.Start() == RState.Running;
        }
        /// 
        /// Initialize 监控
        /// 
        /// 
        /// 
        private bool InitializeAllTimeout(object[] param)
        {
            RState ret = _initializeRoutine.Monitor();
            _currentStateMachine = _initializeRoutine.CurrentStateMachine;
            _currentStatus = "initializing";
            if (ret == RState.Failed || ret == RState.Timeout)
            {
                PostMsg(PrewetMsg.Error);
                _currentStateMachine = "Error";
                _currentStatus = "Error";
                return false;
            }
            bool result = ret == RState.End;
            if (result)
            {
                _currentStateMachine = "Idle";
                _currentStatus = "Idle";
            }
            return result;
        }
        #endregion
        #region Linmot scan wet
        /// 
        /// Initialize
        /// 
        /// 
        /// 
        private bool LinmotScanWet(object[] param)
        {
            _preExecuteState = ((PrewetState)fsm.State).ToString();
            return _linmotWetScanRoutine.Start(param) == RState.Running;
        }
        /// 
        /// LinmotScan 监控
        /// 
        /// 
        /// 
        private bool LinmotScanTimeout(object[] param)
        {
            RState ret = _linmotWetScanRoutine.Monitor();
            if (ret == RState.Failed || ret == RState.Timeout)
            {
                PostReturnPreState();
                _currentStateMachine = "Error";
                _currentStatus = "Error";
                return false;
            }
            return ret == RState.End;
        }
        #endregion
        #region Keep wet
        /// 
        /// Keep Wet
        /// 
        /// 
        /// 
        private bool KeepWet(object[] param) 
        {
            _preExecuteState = ((PrewetState)fsm.State).ToString();
            return _prewetKeepWetRoutine.Start() == RState.Running;
        }
        /// 
        /// Keep Wet Monitor
        /// 
        /// 
        /// 
        private bool KeepWetMonitor(object[] param) 
        {
            RState ret = _prewetKeepWetRoutine.Monitor();
            if(ret==RState.End)
            {
                return true;
            }
            else if(ret==RState.Failed||ret==RState.Timeout)
            {
                PostReturnPreState();
                return false;
            }
            return false;
        }
        /// 
        /// Delay Keepwet
        /// 
        /// 
        /// 
        private bool DelayKeepwet(object[] param)
        {
            _preExecuteState = ((PrewetState)fsm.State).ToString();
            _keepwetCountDown = SC.GetValue("Prewet.IdleKeepwetPauseBetweenScanSeconds");
            return _delayKeepwetRoutine.Start() == RState.Running;
        }
        /// 
        /// Delay Keepwet 监控
        /// 
        /// 
        /// 
        private bool DelayKeepwetMonitor(object[] param)
        {
            RState ret = _delayKeepwetRoutine.Monitor();
            if(ret==RState.End)
            {
                return true;
            }
            else if(ret==RState.Failed||ret==RState.Timeout)
            {
                PostMsg(PrewetMsg.Error);
                return false;
            }
            return false;
        }
        #endregion
        #region PrepareToTransfer
        /// 
        /// PrepareToTransfer
        /// 
        /// 
        /// 
        private bool PrepareToTransfer(object[] param)
        {
            bool isNeedStopLinmot = true;
            if (fsm.State == (int)PrewetState.DelayKeepweting)
            {
                _delayKeepwetRoutine.Abort();
                isNeedStopLinmot = false;
            }
            _preExecuteState = ((PrewetState)fsm.State).ToString();
            return _prepareToTransferRoutine.Start(isNeedStopLinmot) == RState.Running;
        }
        /// 
        /// PrepareToTransfer 监控
        /// 
        /// 
        /// 
        private bool PrepareToTransferTimeout(object[] param)
        {
            RState ret = _prepareToTransferRoutine.Monitor();
            if (ret == RState.Failed || ret == RState.Timeout)
            {
                PostReturnPreState();
                _currentStateMachine = "Error";
                _currentStatus = "Error";
                return false;
            }
            return ret == RState.End;
        }
        #endregion
        #region Manual Process
        private bool CycleManualProcess(object[] param)
        {
            PwtRecipe recipe = param[0] as PwtRecipe;
            _cycle = (int)param[1];
            
            bool result = _cycleManualProcessRoutine.Start(param) == RState.Running;
            if(result)
            {
                _isRetry = false;
                if (CellItemRecipeTimeManager.Instance.ContainRecipe(recipe.Ppid))
                {
                    _recipeTime = _cycle * CellItemRecipeTimeManager.Instance.GetRecipeTotalTime(recipe.Ppid);
                }
                else
                {
                    _recipeTime = 0;
                }
                _currentRecipe = recipe;
                _runRecipeStartTime = DateTime.Now;
                if (WaferHolderInfo != null && _currentRecipe != null)
                {
                    FaModuleNotifier.Instance.NotifyWaferShuttleRecipeStart(WaferHolderInfo, _currentRecipe.Ppid);
                }
            }
            return result;
        }
        private bool CycleManualMonitor(object[] param)
        {
            RState state = _cycleManualProcessRoutine.Monitor();
            _currentStatus = _cycleManualProcessRoutine.CurrentStatus;
            _currentStateMachine = _cycleManualProcessRoutine.CurrentStateMachine;
            if (state == RState.Failed || state == RState.Timeout)
            {
                PostMsg(PrewetMsg.Error);
                _currentStateMachine = "Error";
                _currentStatus = "Error";
                _runRecipeCompleteTime = DateTime.Now;
                _cycleManualProcessRoutine.PrewetLotTrackHeaderDatas.ProcessTime = (_runRecipeCompleteTime - _runRecipeStartTime).TotalSeconds.ToString("F2");
                //导出lotTrack数据
                PrewetLotTrackUtil.ExportPrewetLotTrack(Module.ToString(), _cycleManualProcessRoutine.PrewetLotTrackDatas,
                    _cycleManualProcessRoutine.PrewetLotTrackHeaderDatas, IsAuto, _isRetry);
                if (WaferHolderInfo != null && _currentRecipe != null)
                {
                    FaModuleNotifier.Instance.NotifyWaferShuttleRecipeFailed(WaferHolderInfo, _currentRecipe.Ppid);
                }
                return false;
            }
            _achievedCycle = _cycleManualProcessRoutine.GetAchievedCycle();
            bool result = state == RState.End;
            if (result)
            {
                double elapsedMilliseconds = _cycleManualProcessRoutine.ElapsedMilliseconds;
                int recipeTime = (int)Math.Floor(elapsedMilliseconds / _cycle/ 1000);
                CellItemRecipeTimeManager.Instance.UpdateRecipeTime(_currentRecipe.Ppid, recipeTime);
                _runRecipeCompleteTime = DateTime.Now;
                _cycleManualProcessRoutine.PrewetLotTrackHeaderDatas.ProcessTime = (_runRecipeCompleteTime - _runRecipeStartTime).TotalSeconds.ToString("F2");
                //导出lotTrack数据
                PrewetLotTrackUtil.ExportPrewetLotTrack(Module.ToString(), _cycleManualProcessRoutine.PrewetLotTrackDatas,
                    _cycleManualProcessRoutine.PrewetLotTrackHeaderDatas, IsAuto, _isRetry);
                if (WaferHolderInfo != null && _currentRecipe != null)
                {
                    FaModuleNotifier.Instance.NotifyWaferShuttleRecipeEnd(WaferHolderInfo, _currentRecipe.Ppid, recipeTime);
                }
            }
            return result;
        }
        private bool CycleManualAbort(object[] param)
        {
            _cycleManualProcessRoutine.Abort();
            _currentStateMachine = "Abort";
            _currentStatus = "Abort";
            _runRecipeCompleteTime = DateTime.Now;
            _cycleManualProcessRoutine.PrewetLotTrackHeaderDatas.ProcessTime = (_runRecipeCompleteTime - _runRecipeStartTime).TotalSeconds.ToString("F2");
            //导出lotTrack数据
            PrewetLotTrackUtil.ExportPrewetLotTrack(Module.ToString(), _cycleManualProcessRoutine.PrewetLotTrackDatas,
                _cycleManualProcessRoutine.PrewetLotTrackHeaderDatas, IsAuto, _isRetry);
            return true;
        }
        #endregion
        /// 
        /// 返回上一状态
        /// 
        private void PostReturnPreState()
        {
            if (_preExecuteState == PrewetState.Init.ToString())
            {
                PostMsg(PrewetMsg.ReturnInit);
            }
            else if (_preExecuteState != PrewetState.Init.ToString())
            {
                PostMsg(PrewetMsg.ReturnIdle);
            }
        }
        #region IEntity接口模块(unused)
        public bool Check(int msg, out string reason, params object[] args)
        {
            throw new NotImplementedException();
        }
        public bool CheckAcked(int msg)
        {
            throw new NotImplementedException();
        }
        public int Invoke(string function, params object[] args)
        {
            switch (function)
            {
                case "HomeAll":
                    if (IsIdle)
                    {
                        return (int)FSM_MSG.NONE;
                    }
                    if (CheckToPostMessage(eEvent.ERR_PREWET, Module.ToString(), (int)PrewetMsg.Initialize))
                    {
                        return (int)PrewetMsg.Initialize;
                    }
                    else
                    {
                        return (int)FSM_MSG.NONE;
                    }
            }
            return (int)FSM_MSG.NONE;
        }
        #endregion
    }
    public enum PrewetMsg
    {
        Error,
        Abort,
        ResumeError,
        Initialize,
        LinmotScanWet,
        KeepWet,
        DelayKeepwet,
        PrepareToPlace,
        PrepareToPick,
        PrepareToTransfer,
        ReturnInit,
        ReturnIdle,
        ProcessRecipe,
        CycleProcessRecipe,
        RunRecipe,
        PickComplete,
        Init
    }
}