using Aitex.Core.Common;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Equipment;
using MECF.Framework.Common.SubstrateTrackings;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.SMIFs.Fortrend
{
    public class FortrendSMIF : SMIFBase
    {
        private PeriodicJob _monitorJob;

        public FortrendSMIF(string module, XmlElement node, string ioModule = "")
        {
            var attrModule = node.GetAttribute("module");
            Module = string.IsNullOrEmpty(attrModule) ? module : attrModule;
            Name = node.GetAttribute("id");
            Display = node.GetAttribute("display");
            DeviceID = node.GetAttribute("schematicId");

            _diReady = ParseDiNode("diReady", node, ioModule);
            _diPodInPlace = ParseDiNode("diPodInPlace", node, ioModule);
            //暂时无用处
            //_diAlarm = ParseDiNode("diAlarm", node, ioModule);
            //_diReadyToUnload = ParseDiNode("diReadyToUnload", node, ioModule);

            DoUnloadEnable = ParseDoNode("doUnloadEnable", node, ioModule);
            DoStartRun = ParseDoNode("doStartRun", node, ioModule);
            DoPortLock = ParseDoNode("doPodLock", node, ioModule);
            DoLoadEnable = ParseDoNode("doLoadEnable", node, ioModule);
            DoHomeEnable = ParseDoNode("doHomeEnable", node, ioModule);

            if (SC.GetStringValue("System.InchType") == "Inch6")
            {
                _diCassetteExist = ParseDiNode("diCassette6", node, ioModule);
            }
            else
            {
                _diCassetteExist = ParseDiNode("diCassette8", node, ioModule);
            }

            DataSubscribe();

            OpSubscribe();
        }

        public override bool Initialize()
        {
            base.Initialize();

            if (IsInstalled)
            {
                _monitorJob = new PeriodicJob(1000, OnMonitor, $"{Module}Monitior", true);
            }

            return true;
        }

        private void DataSubscribe()
        {
            DATA.Subscribe($"{Module}.Mode", () => Mode);
            DATA.Subscribe($"{Module}.IsSMIFReady", () => IsSMIFReady);
            DATA.Subscribe($"{Module}.IsSMIFAlarm", () => IsSMIFAlarm);
            DATA.Subscribe($"{Module}.IsHomed", () => IsHomed);
            DATA.Subscribe($"{Module}.IsPodPresent", () => IsPodPresent);
            DATA.Subscribe($"{Module}.PortStatus", () => PortStatus);
        }

        private void OpSubscribe()
        {
            OP.Subscribe($"{Module}.SwitchMode", InvokeSwitchMode);
        }

        public override void OnReceived(string receiveMsg)
        {
            //从服务器收到信息
            string msg = receiveMsg.Replace(Delimiter, "");

            if (!msg.StartsWith("FSD"))
                EV.PostInfoLog(Module, $"Receive {msg}");

            if (msg.StartsWith("HCA"))
            {
                string result = msg.Replace("HCA ", "");

                switch (result)
                {
                    case "OK":
                        {
                            
                        }
                        break;

                    case "DENIED":
                        {
                            EV.PostAlarmLog(Module, "Command rejected not recognized or invalid parameter.");
                        }
                        break;

                    case "BUSY":
                        {
                            EV.PostAlarmLog(Module, "Command rejected, PLUS is busy.");
                        }
                        break;

                    case "CANNOT_PERFORM":
                        {
                            EV.PostAlarmLog(Module, "Command rejected, PLUS not in the proper state to perform the The Host command. PLUS is busy, PLUS in alarm status or prepositioning requirements not met.");
                        }
                        break;

                    case "NO_POD":
                        {
                            EV.PostAlarmLog(Module, "Command rejected, no pod has been placed on PLUS port plate.");
                        }
                        break;

                    case "NOT_READY":
                        {
                            EV.PostAlarmLog(Module, "Command rejected, all host ready conditions or interlocks have not been satisfied.");
                        }
                        break;
                }

                IsDone = true;
            }
            else if (msg.StartsWith("AERS"))
            {
                //事件
                string eventMsg = msg.Replace("AERS ", "");
                if (eventMsg == "REACH_HOME")
                {
                    IsHomeDone = true;
                }
                else if (eventMsg == "CMPL_LOAD")
                {
                    IsLoadDone = true;
                }
                else if (eventMsg == "CMPL_UNLOAD")
                {
                    IsUnloadDone = true;
                }
                else if (eventMsg == "CMPL_LOCK")
                {
                    IsLockDone = true;
                }
                else if (eventMsg == "CMPL_UNLOCK")
                {
                    IsUnLockDone = true;
                }
                else if (eventMsg == "AUTO_MODE")
                {
                    Mode = "AUTO";
                    IsSwitchDone = true;
                }
                else if (eventMsg == "MANUAL_MODE")
                {
                    Mode = "MANUAL";
                    IsSwitchDone = true;
                }
                else if (eventMsg.Contains("WAFER_MAPPING_EVT"))
                {
                    //Mapping结果事件
                    string mapping = eventMsg.Replace("WAFER_MAPPING_EVT ", "");
                    ModuleName cassModuleName = Module == "SMIFA" ? ModuleName.CassAL : ModuleName.CassAR;
                    for (int i = 0; i < mapping.Length; i++)
                    {
                        if (int.TryParse(mapping[i].ToString(), out int result))
                        {
                            //先将对应Wafer删除
                            WaferManager.Instance.DeleteWafer(cassModuleName, i);

                            //0-Full Status(未知状态) 1-Wafer Present 2-Empty 4-Cross Slotted
                            switch (result)
                            {
                                case 0:
                                    {
                                        WaferManager.Instance.CreateWafer(cassModuleName, i, WaferStatus.Unknown);
                                    }
                                    break;

                                case 1:
                                    {
                                        WaferManager.Instance.CreateWafer(cassModuleName, i, WaferStatus.Normal);
                                    }
                                    break;

                                case 2:
                                    {
                                        WaferManager.Instance.DeleteWafer(cassModuleName, i);
                                    }
                                    break;

                                case 4:
                                    {
                                        WaferManager.Instance.CreateWafer(cassModuleName, i, WaferStatus.Crossed);
                                    }
                                    break;
                            }

                        }
                    }
                }
            }
            else if (msg.StartsWith("ARS"))
            {
                //报警 ARS XXYY ZZZZZZ(CR)(LF)
                string alarm = msg.Replace("ARS ", "");
                int index = alarm.IndexOf(' ');
                string alarmCode = alarm.Substring(0, index);
                string alarmText = alarm.Substring(index + 1);

                EV.PostAlarmLog(Module, $"{Module} Alarm,Alarm Code is {alarmCode},Alarm Text: {alarmText}");
            }
            //状态查询结果
            else if (msg.StartsWith("FSD"))
            {
                IsDone = true;

                string query = msg.Replace("FSD", "");
                if (int.TryParse(query.Substring(0, 1), out int formCode))
                {
                    if (formCode == 0)
                    {
                        //general status
                        List<string> resultList = msg.Replace("FSD0 ", "").Split(' ').ToList();
                        foreach (string item in resultList)
                        {
                            if (item.StartsWith("MODE"))
                            {
                                Mode = item.Replace("MODE=", "");
                            }
                            //else if (item.StartsWith("READY"))
                            //{
                            //    if (bool.TryParse(item.Replace("READY=", ""), out bool ready))
                            //    {
                            //        IsSMIFReady = ready;
                            //    }
                            //}
                            else if (item.StartsWith("HOME"))
                            {
                                if (bool.TryParse(item.Replace("HOME=", ""), out bool home))
                                {
                                    IsHomed = home;
                                }
                            }
                            //else if (item.StartsWith("PIP"))
                            //{
                            //    if (bool.TryParse(item.Replace("PIP=", ""), out bool isPodPresent))
                            //    {
                            //        IsPodPresent = isPodPresent;
                            //    }
                            //}
                            else if (item.StartsWith("PRTST"))
                            {
                                PortStatus = item.Replace("PRTST=", "");
                            }
                        }
                    }
                    else if (formCode == 1)
                    {
                        //software part number
                    }
                    else if (formCode == 2)
                    {
                        //Cassette map status
                    }
                }
            }
        }

        public override void Reset()
        {
            if (!IsSMIFReady)
            {
                ClearCmdQueue();
                IsDone = true;
                SMIFReset();
            }

            base.Reset();
        }

        public void SMIFReset()
        {
            RemoteCommand("RESET");
        }

        public void Home()
        {
            //if (!DoHomeEnable.SetValue(true, out string reason))
            //{
            //    EV.PostWarningLog(Module, reason);
            //    return;
            //}

            IsHomeDone = false;
            RemoteCommand("HOME");
        }

        private bool InvokeSwitchMode(string arg1, object[] arg2)
        {
            SwitchMode(arg2[0].ToString());

            return true;
        }

        public void SwitchMode(string mode)
        {
            IsSwitchDone = false;
            RemoteCommand(mode);
        }

        public void PortLock()
        {
            IsLockDone = false;
            //RemoteCommand("LOCK");

            if (!DoPortLock.SetValue(true, out string reason))
            {
                EV.PostWarningLog(Module, reason);
                return;
            }
        }

        public void PortUnLock()
        {
            IsUnLockDone = false;
            //RemoteCommand("UNLOCK");

            if (!DoPortLock.SetValue(false, out string reason))
            {
                EV.PostWarningLog(Module, reason);
                return;
            }
        }

        public void Load()
        {
            if (!IsHomed)
            {
                EV.PostAlarmLog(Module, "SMIF has not home!");
                return;
            }

            if (_diCassetteExist.Value)
            {
                EV.PostAlarmLog(Module, "Cassette Exist,can not Load!");
                return;
            }

            IsLoadDone = false;
            //RemoteCommand("LOAD");

            if (!DoStartRun.SetValue(true, out string reason))
            {
                EV.PostWarningLog(Module, reason);
                return;
            }
        }

        public void Unload()
        {
            if (!IsHomed)
            {
                EV.PostAlarmLog(Module, "SMIF has not home!");
                return;
            }

            if (!_diCassetteExist.Value)
            {
                EV.PostAlarmLog(Module, "Cassette not Exist,can not Unload!");
                return;
            }

            IsUnloadDone = false;
            //RemoteCommand("UNLOAD");

            if (!DoStartRun.SetValue(true, out string reason))
            {
                EV.PostWarningLog(Module, reason);
            }
        }

        public void CloseDoStart()
        {
            if (!DoStartRun.SetValue(false, out string reason))
            {
                EV.PostWarningLog(Module, reason);
                return;
            }
        }

        public void QueryState(int code)
        {
            AddActionToQueue($"FSR FC={code}\r\n");
        }

        private bool OnMonitor()
        {
            if (IsConnected && IsDone)
                QueryState(0);

            return true;
        }

        public void Abort()
        {
            ClearCmdQueue();
            IsDone = true;
        }

        //远程命令
        public void RemoteCommand(string command,string param = "")
        {
            if (IsConnected)
            {
                string msg = $"HCS {command}";
                if (!string.IsNullOrEmpty(param))
                {
                    msg += $" {param}";
                }
                msg += "\r\n";

                AddActionToQueue(msg);
            }
        }
    }
}
