using System;
using System.Collections.Generic;
using System.Threading;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.SCCore;
using MECF.Framework.Common.CommonData;
using MECF.Framework.Common.Equipment;
using MECF.Framework.Common.SubstrateTrackings;

namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Robots.HwinRobot
{
    public class HwinRobotB : HwinRobot
    {
        public HwinRobotB(string module, string name, string endof = "\r\n") : base(module, name)
        {
            OP.Subscribe($"{Module}.SetPosition", (string cmd, object[] args) =>
            {
                MoveInfo = new RobotMoveInfo()
                {
                    Action = RobotAction.Picking,
                    ArmTarget = RobotArm.ArmA,
                    BladeTarget = "ArmA." + args[0].ToString(),
                };
                return true;
            });
            ModuleAssociateStationDic = new Dictionary<string, string>()
            {
                {$"{ModuleName.LoadLock }", "B" },
                {$"{ModuleName.CassBL}", "A"},
                {$"{ModuleName.LoadLock }.Pick", "C" },
                {$"{ModuleName.LoadLock }.Place", "B" },
            };
        }
        public override void NoteActionCompleted()
        {
            //Blade1Target = ModuleName.System;
            //Blade2Target = ModuleName.System;
            CheckToPostMessage((int)RobotMsg.ActionDone);
        }


        #region Command Functions

        public override void RobotPickB(object[] args)
        {
            if (args.Length >= 2)
            {
                _lstHandler.Clear();
                lock (_locker)
                {
                    _lstHandler.AddLast(new HwinRobotBGETBHandler(this, args[0].ToString(), Convert.ToInt32(args[1])));
                }
            }
        }

        public override void RobotPlaceB(object[] args)
        {
            if (args.Length >= 2)
            {
                _lstHandler.Clear();
                lock (_locker)
                {
                    _lstHandler.AddLast(new HwinRobotBPUTBHandler(this, args[0].ToString(), Convert.ToInt32(args[1])));
                }
            }
        }

        public override void SetWaferData(string data)
        {
            //0:未扫片 1:有 2:没有  3:斜放 4:两片 5:薄片
            string errorMessage = "";
            int waferCount = 1;
            if (CurrentInteractModule == ModuleName.CassBL)
            {
                waferCount = 8;
            }

            if (data.Length == 25)//Wafer Cassette
            {
                for (int i = 0; i < waferCount; i++)
                {
                    string waferStatue = data.Substring(i, 1);
                    if (waferStatue == "1")
                    {
                        if (!WaferManager.Instance.CheckHasTray(CurrentInteractModule, i))
                        {
                            WaferManager.Instance.CreateTray(CurrentInteractModule, i);
                        }
                    }
                    else if (waferStatue == "0" || waferStatue == "X")
                    {
                        if (WaferManager.Instance.CheckHasTray(CurrentInteractModule, i))
                        {
                            WaferManager.Instance.DeleteWafer(CurrentInteractModule, i);
                        }
                    }
                    else
                    {
                        if (!WaferManager.Instance.CheckHasTray(CurrentInteractModule, i))
                        {
                            WaferManager.Instance.CreateTray(CurrentInteractModule, i,Aitex.Core.Common.TrayStatus.Crossed);
                        }
                        errorMessage += $"slot {i + 1} has crossed wafer!" + "\r\n";
                    }
                }
            }
            else if (data.Length == 1)
            {
                if (data == "0")
                {
                    if (!WaferManager.Instance.CheckHasTray(ModuleHelper.Converter(Module), 0))
                    {
                        WaferManager.Instance.CreateTray(ModuleHelper.Converter(Module), 0);
                    }
                }
                else if (data == "1")
                {
                    if (WaferManager.Instance.CheckHasTray(ModuleHelper.Converter(Module), 0))
                    {
                        WaferManager.Instance.DeleteWafer(ModuleHelper.Converter(Module), 0);
                    }
                }
            }
            if (!String.IsNullOrEmpty(errorMessage))
            {
                EV.PostWarningLog(Module, $"Module {CurrentInteractModule} {errorMessage}");
            }
        }
      
        //internal override bool ParseErrData(string response)
        //{
        //    try
        //    {
        //        var errs = new HiwinRobotAggregatedErrors(response).AggregateErrorMessages;

        //        if (errs != null)
        //        {
        //            foreach (var err in errs)
        //            {
        //                EV.PostWarningLog(Module, err);
        //            }
        //        }

        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        return true;
        //    }
        //}

        public override void InputA()
        {
            _lstHandler.Clear();
            lock (_locker)
            {
                _lstHandler.AddLast(new HwinRobotBINPUTHandler(this));
            }
        }

        public override void RobotRsr()
        {
            _lstHandler.Clear();
            lock (_locker)
            {
                _lstHandler.AddLast(new HwinRobotBRSRHandler(this));
            }
        }
        public override void RobotConnectHomeAll()
        {
            IsBusy = false;
            base.Connection.ForceClear();
            _lstHandler.Clear();
            lock (_locker)
            {
                _lstHandler.AddLast(new HwinRobotRespHandler(this));
                _lstHandler.AddLast(new HwinRobotRemsHandler(this));
                _lstHandler.AddLast(new HwinRobotSVONHandler(this));
                _lstHandler.AddLast(new HwinRobotHomeHandler(this, _scMotionTimeout.IntValue));
                _lstHandler.AddLast(new HwinRobotBOPTClosePHandler(this));
                _lstHandler.AddLast(new HwinRobotBINPUTHandler(this));
                _lstHandler.AddLast(new HwinRobotBOPTPHandler(this));
            }
        }
        #endregion
        #region Note Functions
        public void ContineHome()
        {
            fAbort(null);
            _lstHandler.AddLast(new HwinRobotHomeHandler(this, _scHomeTimeout.IntValue));

        }

      
        public override bool ReadParameter(object[] param)
        {
            IsBusy = true;
            return CheckToPostMessage((int)RobotMsg.ReadData, param);
        }
        protected override bool fStartMapWafer(object[] param)
        {
            try
            {
                if (param.Length >= 1)
                {

                    lock (_locker)
                    {
                        _lstHandler.AddLast(new HwinRobotMapHandler(this, param[0].ToString(), _scMotionTimeout.IntValue));
                        _lstHandler.AddLast(new HwinRobotBRSRHandler(this, _scMotionTimeout.IntValue));
                        _lstHandler.AddLast(new HwinRobotHomeHandler(this, _scMotionTimeout.IntValue));
                    }
                }
            }
            catch (Exception ex)
            {
                LOG.Write(ex);
                return false;
            }

            return true;
        }

        protected override bool fStartPlaceWafer(object[] param)
        {
            try
            {
                //arm, station, slot
                if (param.Length >= 3)
                {

                    lock (_locker)
                    {
                        if (param[1].ToString() == ModuleName.LoadLock.ToString())
                        {
                            /* 1.打开夹爪
                             * 2.取盘位置低位
                             * 3.抬升托盘
                             */
                            int _rDistance = SC.GetValue<int>("TrayRobot.PlaceRMoveDistance");

                            _lstHandler.AddLast(new HwinRobotBOPTPHandler(this, _scMotionTimeout.IntValue));
                            _lstHandler.AddLast(new HwinRobotMTCSPHandler(this, $"{param[1].ToString()}", "Place", _scMotionTimeout.IntValue));
                            _lstHandler.AddLast(new HwinRobotMOVRPHandler(this, _rDistance, _scMotionTimeout.IntValue));
                            _lstHandler.AddLast(new HwinRobotRETHHandler(this, _scMotionTimeout.IntValue));
                            //_lstHandler.AddLast(new HwinRobotBOPTClosePHandler(this, _scMotionTimeout.IntValue));
                        }
                        else
                        {
                            _lstHandler.AddLast(new HwinRobotBPUTBHandler(this, param[1].ToString(), Convert.ToInt32(param[2]), _scMotionTimeout.IntValue));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LOG.Write(ex);
                return false;
            }

            return true;
        }

        //(module, slot)
        protected override bool fStartPickWafer(object[] param)
        {
            try
            {
                //Load 高位B,Load 低位C

                //arm, station, slot
                if (param.Length >= 3)
                {
                    lock (_locker)
                    {
                        if (param[1].ToString() == ModuleName.LoadLock.ToString())
                        {
                            /* 1.打开夹爪
                             * 2.取盘位置低位
                             * 3.抬升托盘
                             * 4.收回
                             */
                            int _rDistance = SC.GetValue<int>("TrayRobot.PickRMoveDistance");

                            _lstHandler.AddLast(new HwinRobotBOPTPHandler(this,  _scMotionTimeout.IntValue));
                            _lstHandler.AddLast(new HwinRobotMTCSPHandler(this, $"{param[1].ToString()}", "Pick", _scMotionTimeout.IntValue));
                            _lstHandler.AddLast(new HwinRobotMOVRGHandler(this, _rDistance, _scMotionTimeout.IntValue)); 
                            _lstHandler.AddLast(new HwinRobotRETHHandler(this, _scMotionTimeout.IntValue));
                            _lstHandler.AddLast(new HwinRobotBOPTClosePHandler(this, _scMotionTimeout.IntValue));

                        }
                        else
                        {
                            string str = $"{param[1]}  {Convert.ToInt32(param[2])}";
                            _lstHandler.AddLast(new HwinRobotBGETBHandler(this, param[1].ToString(), Convert.ToInt32(param[2]), _scMotionTimeout.IntValue));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LOG.Write(ex);
                return false;
            }

            return true;
        }

        protected override bool fPlaceComplete(object[] param)
        {
            IsBusy = false;
            return true;
        }

        protected override bool fPickComplete(object[] param)
        {
            IsBusy = false;
            return true;
        }

       

        protected override bool fReset(object[] param)
        {
            _trigError.RST = true;

            Connection.SetCommunicationError(false, "");
            _trigCommunicationError.RST = true;

            _trigRetryConnect.RST = true;
            if (_isAlarm)
            {
                lock (_locker)
                {
                    //_lstHandler.AddLast(new HwinRobotBResetHandler(this));
                }

                Thread.Sleep(100);
                CheckToPostMessage((int)RobotMsg.ActionDone);
            }

            IsBusy = false;

            return true;
        }

       

       
        //[module][slot]
        protected override bool fStartExtendForPick(object[] param)
        {
            try
            {
                //if (param.Length >= 2)
                //{

                //    lock (_locker)
                //    {
                //        _lstHandler.AddLast(new HwinRobotBGETSPHandler(this, param[0].ToString(), Convert.ToInt32(param[1]), 1, _scMotionTimeout.IntValue));
                //        _lstHandler.AddLast(new HwinRobotBGETSPHandler(this, param[0].ToString(), Convert.ToInt32(param[1]), 2, _scMotionTimeout.IntValue));
                //    }
                //}
            }
            catch (Exception ex)
            {
                LOG.Write(ex);
                return false;
            }

            return true;
        }

        protected override bool fStartExtendForPlace(object[] param)
        {
            try
            {
                //if (param.Length >= 2)
                //{

                //    lock (_locker)
                //    {
                //        _lstHandler.AddLast(new HwinRobotBPUTSPHandler(this, param[0].ToString(), Convert.ToInt32(param[1]), 1, _scMotionTimeout.IntValue));
                //        _lstHandler.AddLast(new HwinRobotBPUTSPHandler(this, param[0].ToString(), Convert.ToInt32(param[1]), 2, _scMotionTimeout.IntValue));
                //    }
                //}
            }
            catch (Exception ex)
            {
                LOG.Write(ex);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 开始从Pick处缩回
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        protected override bool fStartRetractFromPick(object[] param)
        {
            try
            {
                //if (param.Length >= 2)
                //{

                //    lock (_locker)
                //    {
                //        _lstHandler.AddLast(new HwinRobotBGETSPHandler(this, param[0].ToString(), Convert.ToInt32(param[1]), 3, _scMotionTimeout.IntValue));
                //        _lstHandler.AddLast(new HwinRobotBGETSPHandler(this, param[0].ToString(), Convert.ToInt32(param[1]), 4, _scMotionTimeout.IntValue));
                //    }
                //}
            }
            catch (Exception ex)
            {
                LOG.Write(ex);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 开始从Place处缩回
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        protected override bool fStartRetractFromPlace(object[] param)
        {
            try
            {
                //if (param.Length >= 2)
                //{
                //    lock (_locker)
                //    {
                //        _lstHandler.AddLast(new HwinRobotBPUTSPHandler(this, param[0].ToString(), Convert.ToInt32(param[1]), 3, _scMotionTimeout.IntValue));
                //        _lstHandler.AddLast(new HwinRobotBPUTSPHandler(this, param[0].ToString(), Convert.ToInt32(param[1]), 4, _scMotionTimeout.IntValue));
                //    }
                //}
            }
            catch (Exception ex)
            {
                LOG.Write(ex);
                return false;
            }

            return true;
        }

        

       
        #endregion
    }
}
