using AR;
using COMM;
using System;
using System.Drawing;
using Project.StateMachine;
using System.Windows.Forms;

namespace Project
{
    public partial class fMain
    {



        void BlinkGridViewItem(arFrame.Control.GridView ctl, int row, int col, int value1, int value2)
        {
            var curValue = ctl.getValue(row, col);
            ctl.setValue(row, col, (byte)(curValue == value1 ? value2 : value1)); // 
        }

        void BlinkLabel(arCtl.arLabel ctl, bool Statue
            , Color onColor1, Color onColor2, Color ofColor1, Color ofColor2,
            String onText = "", String OffText = "")
        {
            if (Statue == false)
            {
                ctl.BackColor2 = ofColor2;
                ctl.BackColor = ofColor1;
                if (OffText != "" && ctl.Text != OffText) ctl.Text = OffText;
            }
            else
            {
                if (onText != "" && ctl.Text != onText) ctl.Text = onText;
                //깜박인다
                if (ctl.BackColor2 == Color.DimGray)
                {
                    ctl.BackColor = onColor1;
                    ctl.BackColor2 = onColor2;
                }
                else
                {
                    ctl.BackColor2 = Color.DimGray;
                    ctl.BackColor = Color.FromArgb(100, 100, 100);
                }
            }

        }

        Boolean displayOn = false;
        private void tmDisplay_Tick(object sender, EventArgs e)
        {
            if (displayOn == false) displayOn = true;
            else
            {
                PUB.log.AddAT("Display Timer Overlab");// Console.WriteLine("display overlab");
                return;
            }

            if (PUB.sm.Step > eSMStep.INIT &&
                panTopMenu.Enabled == false) panTopMenu.Enabled = true;

            //배터리정보표시
            var bmsinfo = PUB.BMS.BMSInformation;
            lbBat.VLevel = bmsinfo.rsoc;
            lbBat.Volt = bmsinfo.packVoltage;
            lbBat.MaxA = bmsinfo.fullCapacity;
            lbBat.CurA = bmsinfo.remainingCapacity;
            lbBat.IsOpen = PUB.BMS.IsOpen;

            //쓰레드로인해서 메인에서 진행하게한다. SPS는 메인쓰레드에서 진행 됨
            //팝을 제거 혹은 표시하는 기능
            if (PUB.popup.needShow) PUB.popup.showMessage();
            else if (PUB.popup.needClose) PUB.popup.Visible = false; // .setVision(false)();

            //자동 리부트 코드 실행 (230710)
            var chargeon = VAR.BOOL[eVarBool.FLAG_CHARGEONA] || VAR.BOOL[eVarBool.FLAG_CHARGEONM];
            if (PUB.sm.Step == eSMStep.RUN & PUB.sm.RunStep == ERunStep.READY && chargeon == false &&
                PUB.setting.AutoRebootTimeStart.isEmpty() == false && startuptime.Year != 1982 &&
                PUB.Automodeonreboot == false && PUB.setting.SetAutoModeOn == false && PUB.AutRebootAlreay == false)
            {
                var strbuf = PUB.setting.AutoRebootTimeStart.Split('~');
                if (strbuf.Length == 2)
                {
                    strbuf[0] = strbuf[0].Trim();
                    strbuf[1] = strbuf[1].Trim();

                    var btimes = DateTime.TryParse(DateTime.Now.ToString("yyyy-MM-dd ") + strbuf[0], out DateTime TimeS);
                    var btimee = DateTime.TryParse(DateTime.Now.ToString("yyyy-MM-dd ") + strbuf[1], out DateTime TimeE);

                    //이미 재부팅을 했는지 확인한다
                    if (PUB.setting.AutoRebootTimeStart.isEmpty() == false)
                    {
                        if (DateTime.TryParse(PUB.setting.AutoRebootTimeStart, out DateTime RebootLast))
                        {
                            //지정된 시간내에서 재부팅이 되었다
                            if (RebootLast >= TimeS.AddMinutes(-1) && RebootLast <= TimeE.AddMinutes(1))
                            {
                                //재부팅이 완료됨
                                PUB.log.Add($"이미 재부팅을 진행 했습니다");
                                PUB.AutRebootAlreay = true;
                            }
                        }
                    }

                    if (PUB.AutRebootAlreay == false && btimes && btimee && TimeS <= TimeE && DateTime.Now >= TimeS && DateTime.Now <= TimeE)   //둘다시간조건에 맞아야한다
                    {
                        //기록을 남긴다.(확인용)
                        EEMStatus.AddStatusSQL(eSMStep.IDLE, $"자동재부팅실행({strbuf[0]}~{strbuf[1]})", DateTime.Now, true);

                        //자동모드도 해제 해준다(다른 일이 발생하지 않도록)
                        VAR.BOOL[eVarBool.FLAG_AUTORUN] = false;
                        PUB.AGV.AGVCharge(PUB.setting.ChargerID, false);
                        PUB.AGV.AGVMoveStop("autoreboot");
                        PUB.sm.SetNewStep(eSMStep.IDLE);

                        if (System.Diagnostics.Debugger.IsAttached == false)
                        {
                            PUB.Speak(Lang.자동재부팅을실행합니다);
                            PUB.SystemReboot(5, true);
                        }
                        else PUB.setting.SetAutoModeOn = true;

                    }
                }
            }

            //자동실행-230710 - 프로그램이 켜진 후 5분안에만 동작한다
            if (startuptime.Year != 1982 && PUB.setting.SetAutoModeOn && PUB.sm.Step == eSMStep.IDLE && PUB.Automodeonreboot == false)
            {
                if (VAR.BOOL[eVarBool.FLAG_AUTORUN] == true)    //이미 자동상태라면
                {
                    //이미 켜져있으니 처리하지 않는다
                    PUB.setting.SetAutoModeOn = false;
                    PUB.setting.Save();
                }
                else
                {
                    var tsStartup = DateTime.Now - startuptime;
                    if (tsStartup.TotalMinutes < 3)
                    {
                        if (tsStartup.TotalSeconds > 10) //5초이전에는동작하지 말자
                        {
                            PUB.log.Add($"자동 오토런 실행");
                            func_sw_start(false);
                            PUB.setting.SetAutoModeOn = false;
                            PUB.setting.Save();
                        }
                    }
                    else
                    {
                        //5분을 넘어선 데이터는 쓸모없다 폐기
                        PUB.setting.SetAutoModeOn = false;
                        PUB.setting.Save();
                    }
                }

            }



            lbTime.Text = PUB.sm.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss");

            //자동충전중이다(프로그램에 의해 충전이 진행된 상태)
            if (VAR.BOOL[eVarBool.FLAG_CHARGEONA] == true || VAR.BOOL[eVarBool.FLAG_CHARGEONM] == true)
            {
                lbStStep.Text = VAR.BOOL[eVarBool.FLAG_CHARGEONA] ? "자동충전" : "수동충전";
                lbIDLE.ProgressForeColor = Color.Tomato;
                if (lbIDLE.ProgressEnable == false)
                    lbIDLE.ProgressEnable = true;

                //lbIDLE.ForeColor = Color.Gold;
                lbIDLE.ProgressForeColor = Color.Gold;

                if (PUB.sm.Step != eSMStep.RUN)
                {
                    var tsIdle = VAR.TIME.RUN(eVarTime.ChargeStart);
                    lbIDLE.ProgressMax = 100;// PUB.setting.ChargeMaxLevel;
                    lbIDLE.ProgressMin = 0;
                    lbIDLE.Text = $"{PUB.BMS.BMSInformation.rsoc}%";
                    lbIDLE.ProgressValue = (float)PUB.BMS.BMSInformation.rsoc;
                }
                else
                {
                    //if (PUB.setting.ChargeMaxTime < 1)
                    //{/
                    var tsIdle = VAR.TIME.RUN(eVarTime.ChargeStart);
                    lbIDLE.ProgressMax = PUB.setting.ChargeMaxLevel;
                    lbIDLE.ProgressMin = 0;
                    lbIDLE.Text = $"({PUB.BMS.BMSInformation.rsoc}/{PUB.setting.ChargeMaxLevel})%";
                    lbIDLE.ProgressValue = (float)PUB.BMS.BMSInformation.rsoc;
                    //}
                    //else
                    //{
                    //    var tsIdle = VAR.TIME.RUN(eVarTime.ChargeStart);
                    //    lbIDLE.ProgressMax = PUB.setting.ChargeMaxTime;
                    //    lbIDLE.ProgressMin = 0;
                    //    lbIDLE.Text = string.Format("{0:N0}/{1} 초 충전 중", tsIdle.TotalSeconds, PUB.setting.ChargeMaxTime);
                    //    lbIDLE.ProgressValue = (float)tsIdle.TotalSeconds;
                    //}

                }


            }
            else
            {
                TimeSpan timerun;
                if (PUB.sm.Step == eSMStep.RUN)
                {
                    if (PUB.sm.RunStep == ERunStep.READY)
                    {
                        //대기시간
                        lbStStep.Text = "대기중";
                        timerun = VAR.TIME.RUN(eVarTime.ReadyStart);
                    }
                    else
                    {
                        //가동시간
                        lbStStep.Text = "가동중";
                        timerun = VAR.TIME.RUN(eVarTime.RunStart);
                    }
                }
                else
                {
                    lbStStep.Text = "장비멈춤";
                    timerun = VAR.TIME.RUN(eVarTime.IdleStart);
                }
                lbIDLE.Text = string.Format("{0}일 {1}시 {2}분 {3}초", timerun.Days, timerun.Hours, timerun.Minutes, timerun.Seconds);
                if (lbIDLE.ProgressEnable == true)
                    lbIDLE.ProgressEnable = false;
            }

            //hw접속상태 표시
            MenuAGV.BackColor = PUB.AGV.IsValid ? Color.FromArgb(40, 40, 40) : Color.Brown;
            MenuBMS.BackColor = PUB.BMS.IsValid ? Color.FromArgb(40, 40, 40) : Color.Brown;
            MenuMAN.BackColor = PUB.AGV.IsValid ? Color.FromArgb(40, 40, 40) : Color.Brown;


            btChargeA.Enabled = !VAR.BOOL[eVarBool.FLAG_CHARGEONM];
            btHome.Enabled = btChargeA.Enabled;
            btAutoRun.Enabled = btChargeA.Enabled;

            var bCharge =
                (PUB.sm.RunStep == ERunStep.GOCHARGE || PUB.sm.RunStep == ERunStep.CHARGECHECK || VAR.BOOL[eVarBool.FLAG_CHARGEONA] == true);

            //가동, 목적지가 충전기라면 홈 이동이다
            var bHome = PUB.sm.Step == eSMStep.RUN && (PUB.sm.RunStep == ERunStep.GOHOME);
            //var bChargeM = PUB.flag.get(EFlag.FLAG_CHARGEONM);
            var bAuto = VAR.BOOL[eVarBool.FLAG_AUTORUN];
            //if(batu)

            var bChargeM = VAR.BOOL[eVarBool.FLAG_CHARGEONM];
            if (btHome.Enabled == false)
            {
                btHome.BackColor2 = Color.Gray;
                btHome.BackColor = Color.DimGray;
            }
            else BlinkLabel(this.btHome, bHome, Color.Aqua, Color.Teal, Color.Aqua, Color.Teal, "홈\n취소", "홈\n이동");
            if (btChargeA.Enabled == false)
            {
                btChargeA.BackColor2 = Color.Gray;
                btChargeA.BackColor = Color.DimGray;
            }
            else
            {
                //충전가능요건이라면 해당 시간을 표시해준다.
                BlinkLabel(this.btChargeA, bCharge, Color.LightSalmon, Color.Tomato, Color.LightSalmon, Color.Tomato, "자동충전취소", "자동충전\n실행(" + PUB.counter.CountChargeA.ToString() + ")");
            }
            BlinkLabel(this.btChargeM, bChargeM, Color.LightSalmon, Color.Tomato, Color.LightSalmon, Color.Tomato, "수동충전취소", "수동충전\n실행(" + PUB.counter.CountChargeM.ToString() + ")");
            //BlinkLabel(this.btChargeM, bChargeM, Color.LightSalmon, Color.Tomato, "수동충전취소", "수동충전\n실행(" + Pub.counter.CountChargeM.ToString() + ")");
            if (btAutoRun.Enabled == false)
            {
                btAutoRun.BackColor2 = Color.Gray;
                btAutoRun.BackColor = Color.DimGray;
            }
            else BlinkLabel(this.btAutoRun, bAuto == false, Color.DarkMagenta, Color.BlueViolet, Color.Lime, Color.Green, "수동\n조작중", "자동\n실행중");

            //상태 표시
            Update_SSStatus();

            //IO상태(상단줄) 표시
            Update_IOStatus();

            //display mesasge
            Update_StatusMessage();

            //음악 on/off 처리
            Update_Music();

            //HWState.Invalidate();
            SSInfo.Invalidate();
            IOState.Invalidate();

            #region retgion"1분 time 루틴"
            var ts = DateTime.Now - tm1minute;
            if (ts.TotalMinutes >= 1)
            {
                //리셋카운트
                _AutoResetCount();

                //상태를 DB에 저장한다. 230314
                var tsrun = VAR.TIME.RUN(eVarTime.StatusReporttime);
                if (tsrun.TotalSeconds >= PUB.setting.StatusInterval) EEMStatus.UpdateStatusSQL(PUB.sm.Step, _extrun: true);

                tm1minute = DateTime.Now;
            }
            #endregion

            #region retgion"5분 time 루틴"
            ts = DateTime.Now - tm5minute;
            if (ts.TotalMinutes >= 5)
            {
                //남은디스크확인
                CheckFreeSpace();

                //사용기록 업데이트
                PUB.CheckNRegister5(Application.ProductName, "chi", Application.ProductVersion, PUB.setting.MCID, PUB.setting.AGV_ADDRESS);
                tm5minute = DateTime.Now;
            }
            #endregion

            //wat.Stop();
            //Console.WriteLine("disp time : " + wat.ElapsedMilliseconds.ToString() + "ms");
            displayOn = false;
        }

        void Update_Count()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new System.Windows.Forms.MethodInvoker(Update_Count), null);
            }
            else
            {
                lbCntDN.Text = PUB.counter.CountDn.ToString();
                lbCNtUP.Text = PUB.counter.CountUp.ToString();
                lbCntQA.Text = PUB.counter.CountQA.ToString();
                lbCntQC.Text = PUB.counter.CountQC.ToString();
                // lbCntPk.Text = PUB.counter.CountQa2.ToString();
            }

        }
        void Update_IOStatus()
        {
            int inputrow = 0;
            int inputcol = 0;

            ////비상정지는 깜박임으로 알려준다
            if (VAR.BOOL[eVarBool.EMERGENCY]) BlinkGridViewItem(IOState, inputrow, inputcol++, 2, 0);
            else IOState.setValue(inputrow, inputcol++, 0);

            IOState.setTitle(inputrow, inputcol, "DIR:" + PUB.AGV.data.Direction.ToString()); IOState.setValue(inputrow, inputcol++, 0);
            IOState.setTitle(inputrow, inputcol, "MOV:" + PUB.AGV.data.Sts.ToString()); IOState.setValue(inputrow, inputcol++, 0);
            IOState.setTitle(inputrow, inputcol, "SPD:" + PUB.AGV.data.Speed.ToString()); IOState.setValue(inputrow, inputcol++, 0);
            IOState.setTitle(inputrow, inputcol, $"PBS:{PUB.AGV.data.guidesensor}"); IOState.setValue(inputrow, inputcol++, 0);

            if (PUB.AGV.data.TagNo < 0)
            {
                IOState.setTitle(inputrow, inputcol, "(TAG)"); IOState.setValue(inputrow, inputcol++, 0);
            }
            else
            {
                IOState.setTitle(inputrow, inputcol, "T" + PUB.AGV.data.TagNo.ToString()); IOState.setValue(inputrow, inputcol++, 0);
            }
            if (PUB.AGV.data.CallNo < 0)
            {
                IOState.setTitle(inputrow, inputcol, "(CAL)");
                IOState.setValue(inputrow, inputcol++, 0);
            }
            else
            {
                IOState.setTitle(inputrow, inputcol, "CAL:" + PUB.AGV.data.CallNo.ToString());
                IOState.setValue(inputrow, inputcol++, 0);
            }

            IOState.setTitle(inputrow, inputcol, "RUN"); IOState.setValue(inputrow, inputcol++, (PUB.AGV.system1.agv_run ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "MARK"); IOState.setValue(inputrow, inputcol++, (VAR.BOOL[eVarBool.MARK_SENSOR] ? 1 :  0));
            IOState.setTitle(inputrow, inputcol, "CHG"); IOState.setValue(inputrow, inputcol++, (PUB.AGV.system1.Battery_charging ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "ITM"); IOState.setValue(inputrow, inputcol++, (VAR.BOOL[eVarBool.ITEMON] ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, $"DS{PUB.AGV.data.Distance}"); IOState.setValue(inputrow, inputcol++, (PUB.AGV.data.Distance > 0 ? 1 : 0));
            IOState.Invalidate();
        }

        /// <summary>
        /// 가동중 40% 미만에서는 배터리 경고 메세지를 추가한다(리더)
        /// </summary>
        void Update_BatteryWarnSpeak()
        {
            if (PUB.BMS == null || PUB.BMS.BMSInformation.rsoc > 40) return;

            //가동중이거나 수동모드에서는 메세지 알림한다
            if (PUB.AGV.system1.agv_run || VAR.BOOL[eVarBool.FLAG_AUTORUN] == false)
            {
                var timeoutsec = 15;
                if (PUB.BMS.IsValid == false) timeoutsec = 30;

                var tswarnmsg = VAR.TIME.RUN(eVarTime.BatWarnTime);
                if (tswarnmsg.TotalSeconds >= timeoutsec)
                {
                    if (VAR.BOOL[eVarBool.FLAG_CHARGEONM] == false && VAR.BOOL[eVarBool.FLAG_CHARGEONA] == false)
                    {
                        if (PUB.BMS.IsValid == false)
                        {
                            PUB.Speak(Lang.배터리통신에문제가있습니다);
                        }
                        else
                        {
                            if (VAR.BOOL[eVarBool.FLAG_AUTORUN] == false)
                                PUB.Speak(Lang.충전이필요합니다자동모드로전환하세요);
                            else
                                PUB.Speak(Lang.충전이필요합니다);
                        }
                    }
                    else
                    {
                        //충전중이므로 메세지처리를 하지 않는다
                    }


                    VAR.TIME.Update(eVarTime.BatWarnTime);
                }
            }
        }

        /// <summary>
        /// 가동중일때 음악이 나오게 한다
        /// </summary>
        void Update_Music()
        {
            if (PUB.mplayer == null) return;
            if (PUB.mplayer != null && !string.IsNullOrEmpty(PUB.mplayer.SoundLocation) && PUB.bPlayMusic)
            {
                if (PUB.AGV.system1.agv_run == false)
                {
                    if (PUB.bPlayMusic)
                    {
                        PUB.mplayer.Stop();
                        PUB.bPlayMusic = false;
                    }

                }
            }
            else if (PUB.setting.Enable_Music && PUB.mplayer != null && !string.IsNullOrEmpty(PUB.mplayer.SoundLocation))
            {
                if (PUB.AGV.system1.agv_run == true)
                {
                    if (PUB.bPlayMusic == false)
                    {
                        PUB.mplayer.Play();
                        PUB.bPlayMusic = true;
                    }
                }
            }
        }

        void Update_SSStatus()
        {
            if (PUB.sm.IsThreadRun) SSInfo.setValue(0, 0, 0);
            else SSInfo.setValue(0, 0, 2);

            var runspeed = PUB.sm.RunSpeed.TotalMilliseconds;
            SSInfo.setTitle(0, 0, $"{PUB.sm.Step}\n{runspeed:N1} ms");

            if (runspeed > 9)
                SSInfo.setValue(0, 0, 2);
            else if (runspeed > 4)
                SSInfo.setValue(0, 0, 3);
            else
                SSInfo.setValue(0, 0, 0);


            SSInfo.setTitle(1, 0, string.Format("{0}({1})", PUB.sm.RunStep, PUB.sm.RunStepSeq));
            if (PUB.sm.Step == eSMStep.RUN)
                SSInfo.setTitle(1, 1, string.Format("{0:N1} sec", PUB.sm.GetRunSteptime.TotalSeconds));
            else
                SSInfo.setTitle(1, 1, "--");

        }

        /// <summary>
        /// 환경설정에따른 카운트를 리셋처리한다. 171128
        /// </summary>
        void _AutoResetCount()
        {
            if (PUB.setting.datetime_Check_1 && PUB.setting.datetime_Reset_1 != "") //오전
            {
                try
                {
                    DateTime SetTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + PUB.setting.datetime_Reset_1 + ":00");
                    DateTime LastClearTime = PUB.counter.CountReset;

                    //현재 시간이 클리어대상 시간보다 크고, 마지막으로 클리어한 시간이 지정시간보다 작아야함
                    if (DateTime.Now > SetTime && LastClearTime < SetTime)
                    {
                        PUB.log.AddI("Count Reset #1");
                        PUB.counter.CountClear();
                    }
                }
                catch { }
            }

            if (PUB.setting.datetime_Check_2 && PUB.setting.datetime_Reset_2 != "") //오후
            {
                try
                {
                    DateTime SetTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + PUB.setting.datetime_Reset_2 + ":00");
                    DateTime LastClearTime = PUB.counter.CountReset;

                    //현재 시간이 클리어대상 시간보다 크고, 마지막으로 클리어한 시간이 지정시간보다 작아야함
                    if (DateTime.Now > SetTime && LastClearTime < SetTime)
                    {
                        PUB.log.AddI("Count Reset #2");
                        PUB.counter.CountClear();
                    }
                }
                catch { }
            }
        }

        DateTime tm1minute = DateTime.Now.AddDays(-1);
        DateTime tm5minute = DateTime.Now;

        void UpdateProgressStatus(double value, double max, string title)
        {
            UpdateProgressStatus((float)value, (float)max, title);
        }

        void UpdateProgressStatus(float value, float max, string title = "")
        {
            if (PUB.Result.SMSG_ProgressEnable == false) PUB.Result.SMSG_ProgressEnable = true;
            if (PUB.Result.SMSG_ProgressMax != max) PUB.Result.SMSG_ProgressMax = max;
            if (PUB.Result.SMSG_ProgressValue != value)
            {
                if (value < max) PUB.Result.SMSG_ProgressValue = value;
                else PUB.Result.SMSG_ProgressValue = max;
            }
            if (PUB.Result.SMSG_ProgressForeColor != Color.White)
                PUB.Result.SMSG_ProgressForeColor = Color.White;

            if (title != "")
                if (VAR.STR[eVarString.StatusMessage].Equals(title) == false) VAR.STR[eVarString.StatusMessage] = title;
        }

        void UpdateStatusMessage(string dispmsg, Color fcolor, Color shadow)
        {
            UpdateStatusMessage(dispmsg, Color.DimGray, Color.Gray, fcolor, shadow);
        }

        void UpdateStatusMessage(string dispmsg, Color bColor, Color bColor2, Color fcolor, Color shadow, Boolean blank = false)
        {

            //if (lbMsg.ProgressEnable == true) lbMsg.ProgressEnable = false;
            if (dispmsg != VAR.STR[eVarString.StatusMessage] || PUB.Result.SMSG_ForeColor != fcolor ||
                PUB.Result.SMSG_ShadowColor != shadow
                || (PUB.Result.SMSG_BackColor != bColor && PUB.Result.SMSG_BackColor2 != bColor))
            {
                PUB.Result.SMSG_BackColor = bColor;
                PUB.Result.SMSG_BackColor2 = bColor2;
                PUB.Result.SMSG_ForeColor = fcolor;
                PUB.Result.SMSG_ShadowColor = shadow;
                VAR.STR[eVarString.StatusMessage] = dispmsg;
                if (blank) PUB.Result.SMSG_Tag = "BLANK";
                else PUB.Result.SMSG_Tag = null;
                //PUB.Result.UpdateStatusMessage();
            }
        }


        void Update_StatusMessage()
        {
            //최우선 점검 사항 표시
            if (PUB.sm.Step > eSMStep.INIT)
            {
                //오류가 있다면 오류를 표시해준다.
                if (PUB.AGV.IsOpen == false )
                {
                    UpdateStatusMessage("AGV 연결실패", Color.Tomato, Color.Black);
                }
                else if(PUB.AGV.IsValid==false)
                {
                    UpdateStatusMessage("AGV 통신상태 불량", Color.Tomato, Color.Black);
                }
                else if (PUB.AGV.error.Emergency)
                {
                    if (PUB.AGV.error.runerror_by_no_magent_line)
                    {
                        UpdateStatusMessage("마그넷이 감지 되지 않습니다", Color.Tomato, Color.Black);
                    }
                    else
                    {
                        UpdateStatusMessage("비상 정지", Color.Tomato, Color.Black);
                    }
                }
                else if (PUB.BMS != null || PUB.BMS.IsOpen==false)
                {
                    UpdateStatusMessage("BMS가 연결되지 않았습니다", Color.Tomato, Color.Black);
                }
                else if (PUB.BMS != null || PUB.BMS.IsValid == false)
                {
                    UpdateStatusMessage("BMS 통신상태 불량", Color.Tomato, Color.Black);
                }
                //else if (PUB.PLC.IsOpen == false)
                //{
                //    UpdateStatusMessage(Lang.PLC연결실패, Color.Tomato, Color.Black);
                //}
                //else if (PUB.PLC.IsValid == false)
                //{
                //    UpdateStatusMessage(Lang.PLC통신실패, Color.Tomato, Color.Black);
                //}
                else if (VAR.BOOL[eVarBool.FLAG_CHARGEONA] == true)
                {
                    //남은 충전시간 계산
                    string msg = string.Empty;
                    if (PUB.BMS.BMSInformation.rsoc < PUB.setting.ChargeEmergencyLevel)
                    {
                        msg = $"충전 진행 중(이동 불가)\n저전압으로 인해 사용이 불가 합니다";
                    }
                    else
                    {
                        var remaintime = VAR.TIME.RUN(eVarTime.ChargeStart);
                        var remainsec = PUB.setting.ChargeMaxTime - remaintime.TotalSeconds;
                        msg = "충전 진행 중 (이동 불가) " + remainsec.ToString("N0") + "초 후 충전이 자동 OFF 됩니다";
                    }
                    UpdateStatusMessage(msg, Color.Orange, Color.Black);
                }
                else if (VAR.BOOL[eVarBool.FLAG_CHARGEONM] == true)// PUB.flag.get(EFlag.FLAG_CHARGEONM) == true)
                {
                    UpdateStatusMessage("충전(수동) 진행 중 (이동 불가)", Color.Orange, Color.Black);
                }
                else if (PUB.AGV.IsOpen == false)
                {
                    UpdateStatusMessage(Lang.AGV연결실패, Color.Tomato, Color.Black);
                }
                else
                {
                    if (PUB.sm.Step == eSMStep.IDLE)
                    {
                        if (PUB.AGV.system1.agv_run)
                        {
                            if (PUB.AGV.system1.stop_by_front_detect)
                                UpdateStatusMessage("장애물로 인한 일시 정지", Color.SkyBlue, Color.Black);
                            else
                                UpdateStatusMessage("AGV 이동 중", Color.SkyBlue, Color.Black);
                        }
                        else if (PUB.AGV.error.Emergency)
                        {
                            if (PUB.AGV.error.runerror_by_no_magent_line)
                            {
                                UpdateStatusMessage("비상 정지 : 마그넷 라인이 감지 안됨", Color.SkyBlue, Color.Black);
                            }
                            else
                            {
                                UpdateStatusMessage("비상 정지", Color.SkyBlue, Color.Black);
                            }
                        }
                        else
                        {
                            var smg = "(작업을 시작 하려면 [AUTO]로 전환 하세요)";
                            UpdateStatusMessage(smg, Color.SkyBlue, Color.Black);
                        }
                    }
                    else if (PUB.sm.Step == eSMStep.RUN)
                    {

                        string stMsg;
                        if (PUB.AGV.system1.stop_by_front_detect)//.GetValueI(arDev.FakePLC.DIName.PINI_LIDAR_STOP))
                            stMsg = Lang.전방에물체가감지되었습니다;
                        //else if (PUB.PLC.GetValueI(arDev.FakePLC.DIName.PINI_EMG))
                        //    stMsg = Lang.비상정지신호가감지되었습니다;
                        else if (PUB.AGV.signal1.front_gate_out == true)
                            stMsg = Lang.선로를이탈했습니다;
                        else if (PUB.AGV.error.runerror_by_no_magent_line)
                            stMsg = "마그네틱 라인을 벗어났습니다";
                        else
                        {
                            stMsg = "자동 대기";
                            if (PUB.setting.Enable_AutoCharge)
                            {
                                var tsIdle = VAR.TIME.RUN(eVarTime.ReadyStart);
                                var remainTry = (int)(PUB.setting.ChargeRetryTerm - tsIdle.TotalSeconds);
                                var progMax = PUB.setting.ChargeRetryTerm;
                                stMsg += " / (" + remainTry.ToString() + ") 초 후 충전을 시작 합니다";
                                UpdateProgressStatus(tsIdle.TotalSeconds, progMax, "");
                            }
                            else
                            {
                                stMsg += "(자동충전 해제됨)";
                            }
                        }

                        UpdateStatusMessage(stMsg, Color.SkyBlue, Color.Black);
                        //자동 충전 대기상태를 프로그레시브로 표시한다


                        if (PUB.AGV.system1.stop_by_front_detect == true)
                        {
                            UpdateStatusMessage("이동 방향 근접거리 물체 감지(이동 불가 - 일시정지)", Color.Tomato, Color.Black);
                        }
                        else if (VAR.BOOL[eVarBool.OVERLOAD] == true)
                        {
                            UpdateStatusMessage("오버로드 감지(안전커버를 확인하세요)", Color.Tomato, Color.Black);
                        }
                        else if (PUB.AGV.error.runerror_by_no_magent_line)
                        {
                            UpdateStatusMessage("마그네틱 라인을 벗어 났습니다", Color.Black, Color.White);
                        }
                        else
                        {
                            if (VAR.BOOL[eVarBool.WAIT_COVER_DOWN] == true)
                            {
                                UpdateStatusMessage(Lang.안전커버를내려주세요, Color.Lime, Color.Black);
                            }
                            else if (VAR.BOOL[eVarBool.WAIT_COVER_UP] == true)
                            {
                                UpdateStatusMessage(Lang.안전커버를올려주세요, Color.Lime, Color.Black);
                            }
                            else
                            {
                                if (PUB.sm.RunStep == ERunStep.BUFFER_IN)
                                {
                                    if (PUB.sm.RunStepSeq == 1)
                                    {
                                        UpdateStatusMessage(String.Format("하차 이동 전 (현재 위치 검색)", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                    }
                                    else UpdateStatusMessage(String.Format("하차 이동 중 ({0})", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                }
                                else if (PUB.sm.RunStep == ERunStep.BUFFER_OUT)
                                {
                                    if (PUB.sm.RunStepSeq == 1)
                                    {
                                        UpdateStatusMessage(String.Format("상차 이동 전 (현재 위치 검색)", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                    }
                                    else UpdateStatusMessage(String.Format("상차 이동 중 ({0})", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                }
                                else if (PUB.sm.RunStep == ERunStep.LOADER_IN)
                                {
                                     UpdateStatusMessage(String.Format("로더 진입 중 ({0})", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                }
                                else if (PUB.sm.RunStep == ERunStep.LOADER_OUT)
                                {
                                     UpdateStatusMessage(String.Format("로더 배출 중 ({0})", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                }
                                else if (PUB.sm.RunStep == ERunStep.UNLOADER_IN)
                                {
                                     UpdateStatusMessage(String.Format("언로더 진입 중 ({0})", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                }
                                else if (PUB.sm.RunStep == ERunStep.UNLOADER_OUT)
                                {
                                     UpdateStatusMessage(String.Format("언로더 배출 중 ({0})", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                }
                                else if (PUB.sm.RunStep == ERunStep.CLEANER_IN)
                                {
                                     UpdateStatusMessage(String.Format("클리너 진입 중 ({0})", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                }
                                else if (PUB.sm.RunStep == ERunStep.CLEANER_OUT)
                                {
                                     UpdateStatusMessage(String.Format("클리너 배출 중 ({0})", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                }
                                else if (PUB.sm.RunStep == ERunStep.GOCHARGE)
                                {
                                    if (PUB.Result.result_message.isEmpty() == true)
                                    {
                                        UpdateStatusMessage(String.Format("충전기로 이동 중"), Color.Lime, Color.Black);
                                    }
                                    else
                                    {
                                        if (PUB.Result.result_progressmax > 0)
                                            UpdateProgressStatus(PUB.Result.result_progressvalue, PUB.Result.result_progressmax, PUB.Result.result_message);
                                        else
                                            UpdateStatusMessage(PUB.Result.result_message, Color.Lime, Color.Black);
                                    }
                                }
                                else if (PUB.sm.RunStep == ERunStep.CHARGECHECK)
                                {
                                    if (PUB.Result.result_message.isEmpty() == true)
                                    {
                                        UpdateStatusMessage(String.Format("충전기 작동 확인 중"), Color.Lime, Color.Black);
                                    }
                                    else
                                    {
                                        if (PUB.Result.result_progressmax > 0)
                                            UpdateProgressStatus(PUB.Result.result_progressvalue, PUB.Result.result_progressmax, PUB.Result.result_message);
                                        else
                                            UpdateStatusMessage(PUB.Result.result_message, Color.Lime, Color.Black);
                                    }
                                }
                                else if (PUB.sm.RunStep == ERunStep.GOHOME)
                                {
                                    UpdateStatusMessage(String.Format("홈(QC) 이동 중", PUB.Result.TargetPos), Color.Lime, Color.Black);
                                }
                                else
                                {
                                    //충전준비상태라면 관련 정보를 표시한다 230117
                                    if (VAR.BOOL[eVarBool.CHARGE_READY])
                                    {
                                        var sec = VAR.I32[eVarInt32.ChargeWaitSec];
                                        UpdateStatusMessage($"{sec} 초 후 충전이 시작 됩니다", Color.Lime, Color.Black);
                                    }
                                    else
                                    {
                                        var msg = $"대기상태(현재위치:{PUB.Result.CurrentPos}/대상위치:{PUB.Result.TargetPos})";
                                        if (PUB.setting.Enable_AutoCharge) msg += "(자동충전:ON)";
                                        else msg += "(자동충전:OFF)";
                                        UpdateStatusMessage(msg, Color.Lime, Color.Black);
                                    }

                                    //UpdateStatusMessage(String.Format("--", Pub.Result.TargetPos), Color.White, Color.Black);
                                }
                            }
                        }


                    }
                    else if (PUB.sm.Step == eSMStep.ERROR)
                    {
                        UpdateStatusMessage("오류 발생", Color.Red, Color.Black);
                    }
                    else if (PUB.sm.Step == eSMStep.PAUSE)
                    {
                        UpdateStatusMessage("정지 됨", Color.Tomato, Color.Black);
                    }
                    else if (PUB.sm.Step == eSMStep.FINISH)
                    {
                        UpdateStatusMessage("작업 완료", Color.Lime, Color.Black);
                    }
                    else if (PUB.sm.bPause == true)
                    {
                        UpdateStatusMessage("[START]를 누르면 시작 됩니다", Color.Yellow, Color.Black);
                    }
                    else
                    {
                        string msg = "진행 중";
                        UpdateStatusMessage(msg, Color.Lime, Color.Black);
                    }
                }


            }
        }
    }
}
