using System.Collections.Generic;
using System;
using System.Drawing;
using System.Diagnostics;
using System.Data;
using System.Collections;
using System.Windows.Forms;
using AR;
using System.Linq;
using vmsnet;
using System.Windows.Forms.DataVisualization.Charting;

namespace vmsnet
{
    public partial class Frm_Sub
    {
        public HMI.DispCtrl DispCtrl1;
        public bool poweroff = false;

        //DataTable CHDATA;
        bool Init = false;
        private HMI.BarCtrl BarCtrl1 = null;
        readonly ScottPlot.WinForms.FormsPlot formsPlot1;
        ScottPlot.Plottables.Scatter[] Streamer1;

        List<float>[] dataVolt = null;
        List<double>[] dataTime = null;

        short voltlimit = 0;
        short timelimit = 10;

        /// <summary>
        /// 1부터시작하는 채널의 번호입니다.(인덱스가 아님)
        /// 채널선택화면에서 선택된 채널 번호만 들어있다.
        /// docuementElement1 에는 모든 그룹/채널 정보가 들어있다
        /// </summary>
        List<int> selectchlist = new List<int>();

        public Frm_Sub()
        {
            // 이 호출은 디자이너에 필요합니다.
            InitializeComponent();

            #region "InitializeComponent HMI - userControl"
            PUB.CONFIG.opensubwindow = true;
            this.DispCtrl1 = new HMI.DispCtrl();
            this.DispCtrl1.init = false;
            this.DispCtrl1.BorderColor = System.Drawing.Color.Gray;
            this.DispCtrl1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.DispCtrl1.Font = new System.Drawing.Font("맑은 고딕", (float)(12.0F), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
            this.DispCtrl1.Font_Grouptitle = new System.Drawing.Font("Microsoft Sans Serif", (float)(14.25F), System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, System.Convert.ToByte(129));
            this.DispCtrl1.Font_Grouptitle_Color = System.Drawing.Color.Red;
            this.DispCtrl1.Font_Header = new System.Drawing.Font("Microsoft Sans Serif", (float)(9.75F), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, System.Convert.ToByte(129));
            this.DispCtrl1.Font_Header_Color = System.Drawing.Color.Yellow;
            this.DispCtrl1.FullScreen = true;
            this.DispCtrl1.init = true;
            this.DispCtrl1.initmsg = "initializing...";
            this.DispCtrl1.Location = new System.Drawing.Point(3, 3);
            this.DispCtrl1.Message_Warning = "";
            this.DispCtrl1.Name = "DispCtrl1";
            this.DispCtrl1.Padding = new System.Windows.Forms.Padding(3);
            this.TableLayoutPanel1.SetRowSpan(this.DispCtrl1, 3);
            this.DispCtrl1.ShowIndex = -1;
            this.DispCtrl1.Size = new System.Drawing.Size(774, 699);
            this.DispCtrl1.TabIndex = 3;
            this.DispCtrl1.Times = null;
            this.DispCtrl1.Values = null;
            this.DispCtrl1.OnAlamChange += DispCtrl1_OnAlamChangeL;
            this.DispCtrl1.OnChangedShowIndex += DispCtrl1_OnChangedShowIndex;
            this.DispCtrl1.OnClickCell += DispCtrl1_OnClickCell;
            this.DispCtrl1.OnClickGroup += DispCtrl1_OnClickGroup;
            this.DispCtrl1.OnClickPrint += DispCtrl1_OnClickPrint;
            this.DispCtrl1.OnNotifyData += DispCtrl1_OnNotifyData;
            this.DispCtrl1.OnSetNullbalance += DispCtrl1_OnSetNullbalance;
            this.DispCtrl1.RaiseAlarm += DispCtrl1_RaiseAlarm;
            this.TableLayoutPanel1.Controls.Add(this.DispCtrl1, 0, 0);


            formsPlot1 = new ScottPlot.WinForms.FormsPlot() { Dock = DockStyle.Fill };
            formsPlot1.MouseDown += FormsPlot1_MouseDown;
            formsPlot1.MouseUp += FormsPlot1_MouseUp;
            formsPlot1.MouseMove += FormsPlot1_MouseMove;

            CrossHair = formsPlot1.Plot.Add.Crosshair(0, 0);
            CrossHair.TextColor = ScottPlot.Colors.White;
            CrossHair.TextBackgroundColor = CrossHair.HorizontalLine.Color;

            formsPlot1.Plot.YLabel("VOLTAGE");
            formsPlot1.Plot.XLabel("COUNT");

            formsPlot1.Plot.ShowLegend();
            formsPlot1.Plot.Axes.DateTimeTicksBottom();
            formsPlot1.Plot.Axes.ContinuouslyAutoscale = true;
            formsPlot1.Plot.RenderManager.RenderStarting += (s1, e1) =>
            {
                ScottPlot.Tick[] ticks = formsPlot1.Plot.Axes.Bottom.TickGenerator.Ticks;
                for (int i = 0; i < ticks.Length; i++)
                {
                    DateTime dt = DateTime.FromOADate(ticks[i].Position);
                    string label = $"{dt:yy-MM-dd\nHH:mm:ss}";
                    ticks[i] = new ScottPlot.Tick(ticks[i].Position, label);
                }
            };

            this.TableLayoutPanel1.Controls.Add(this.formsPlot1, 1, 1);

            this.BarCtrl1 = new HMI.BarCtrl();
            this.BarCtrl1.BackColor = System.Drawing.Color.White;
            this.BarCtrl1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.BarCtrl1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.BarCtrl1.Font = new System.Drawing.Font("맑은 고딕", (float)(12.0F), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
            this.BarCtrl1.Location = new System.Drawing.Point(783, 373);
            this.BarCtrl1.Name = "BarCtrl1";
            this.BarCtrl1.Show_DebugMsg = false;
            this.BarCtrl1.Size = new System.Drawing.Size(775, 329);
            this.BarCtrl1.TabIndex = 6;
            this.TableLayoutPanel1.Controls.Add(this.BarCtrl1, 1, 2);

            Streamer1 = new ScottPlot.Plottables.Scatter[0]; //최대10개로한다
            dataVolt = new List<float>[0];
            dataTime = new List<double>[0];
            #endregion

            PUB.RemoteCommandEvent += Pub_RemoteCommandEvent;
        }

        #region "scott plot mouse event"
        ScottPlot.Plottables.Crosshair CrossHair;
        ScottPlot.Plottables.VerticalLine[] CursorLine;
        private ScottPlot.Plottables.AxisLine GetLineUnderMouse(float x, float y)
        {
            ScottPlot.CoordinateRect rect = formsPlot1.Plot.GetCoordinateRect(x, y, radius: 10);

            foreach (var axLine in formsPlot1.Plot.GetPlottables<ScottPlot.Plottables.AxisLine>().Reverse())
            {
                if (axLine.IsUnderMouse(rect))
                    return axLine;
            }

            return null;
        }


        private void FormsPlot1_MouseDown(object sender, MouseEventArgs e)
        {
            var lineUnderMouse = GetLineUnderMouse(e.X, e.Y);
            if (lineUnderMouse != null)
            {
                PlottableBeingDragged = lineUnderMouse;
                formsPlot1.Interaction.Disable(); // disable panning while dragging
            }
        }

        private void FormsPlot1_MouseUp(object sender, MouseEventArgs e)
        {
            PlottableBeingDragged = null;
            formsPlot1.Interaction.Enable(); // enable panning again
            formsPlot1.Refresh();
        }
        ScottPlot.Plottables.AxisLine PlottableBeingDragged = null;
        private void FormsPlot1_MouseMove(object sender, MouseEventArgs e)
        {

            //update cross line
            ScottPlot.Pixel mousePixel = new ScottPlot.Pixel(e.X, e.Y);
            ScottPlot.Coordinates mouseCoordinates = formsPlot1.Plot.GetCoordinates(mousePixel);
            if (mouseCoordinates.X is double.NaN || mouseCoordinates.Y is double.NaN ||
                mouseCoordinates.X is double.PositiveInfinity || mouseCoordinates.Y is double.PositiveInfinity ||
                mouseCoordinates.X is double.NegativeInfinity || mouseCoordinates.Y is double.NegativeInfinity)
            {
                return;
            }

            if (CrossHair != null)
            {
                CrossHair.Position = mouseCoordinates;
                var time = DateTime.FromOADate(mouseCoordinates.X);

                CrossHair.VerticalLine.Text = $"{time:yy-MM-dd\nHH:mm:ss}";
                CrossHair.HorizontalLine.Text = $"{mouseCoordinates.Y:N2}v";

                if (formsPlot1.InvokeRequired)
                    formsPlot1.Invoke(new Action(() => formsPlot1.Refresh()));
                else
                    formsPlot1.Refresh();
            }




            // this rectangle is the area around the mouse in coordinate units
            ScottPlot.CoordinateRect rect = formsPlot1.Plot.GetCoordinateRect(e.X, e.Y, radius: 10);

            if (PlottableBeingDragged is null)
            {
                // set cursor based on what's beneath the plottable
                var lineUnderMouse = GetLineUnderMouse(e.X, e.Y);
                if (lineUnderMouse is null) Cursor = Cursors.Default;
                else if (lineUnderMouse.IsDraggable && lineUnderMouse is ScottPlot.Plottables.VerticalLine) Cursor = Cursors.SizeWE;
                else if (lineUnderMouse.IsDraggable && lineUnderMouse is ScottPlot.Plottables.HorizontalLine) Cursor = Cursors.SizeNS;
            }
            else
            {
                // update the position of the plottable being dragged
                if (PlottableBeingDragged is ScottPlot.Plottables.HorizontalLine hl)
                {
                    hl.Y = rect.VerticalCenter;
                    hl.Text = $"{hl.Y:0.00}v";
                }
                else if (PlottableBeingDragged is ScottPlot.Plottables.VerticalLine vl)
                {
                    vl.X = rect.HorizontalCenter;
                    var time = DateTime.FromOADate(vl.X);
                    //vl.Text = $"{vl.X:0.00}";
                    vl.Text = $"{time:yy-MM-dd\nHH:mm:ss}";
                }
                formsPlot1.Refresh();
            }
        }
        #endregion

        delegate void Pub_RemoteCommandEventHandler(object sender, RemoteCommand e);
        private void Pub_RemoteCommandEvent(object sender, RemoteCommand e)
        {
            if (e.Command == rCommand.StateMessage)
            {
                if (this.InvokeRequired)
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        lb_status.Text = e.Data.ToString();
                        lb_status.Invalidate();
                    }));
                }
                else
                {
                    lb_status.Text = e.Data.ToString();
                    lb_status.Invalidate();
                }
            }
            else if (e.Command == rCommand.SaveGroupClass)
            {
                var fi1 = new System.IO.FileInfo("window2.grp");
                PUB.SaveGroupClass(DispCtrl1.GROUPS, fi1);
            }
            else if (e.Command == rCommand.DAQConnected)
            {

            }
            else if (e.Command == rCommand.DAQDisconnected)
            {

            }
            else if (e.Command == rCommand.RefreshChart)
            {
                REFRESHCHART(false);
            }
            else if (e.Command == rCommand.ValueUpdate)
            {
                //전체화면모드에서는 실시간데이터를 표시하지 않는다.
                if (DispCtrl1.FullScreen == false)
                {
                    //스트리머,데이터,선택된 채널 정보가 있어야 업데이트 가능하다
                    if (e.Data != null && this.Streamer1 != null && this.selectchlist.Any())
                    {
                        var data = e.Data as List<NotifyData>;

                        //선택된 채널의 정보만 사용
                        var recvdatas = data.Where(t => selectchlist.Contains(t.chno)).Select(t => t);
                        if (recvdatas.Any() == false) return; //대상채널데이터가 없다.


                        //받은데이터를 화면에 추가한다.
                        foreach (var newdata in recvdatas)
                        {
                            var ch = newdata.chno - 1;
                            var val = newdata.value;
                            var time = newdata.time;

                            //자료가없거나 스트리머가 없는 경우
                            if (ch >= this.Streamer1.Length || this.Streamer1[ch] == null) continue;


                            float value = 0;
                            if (PUB.CONFIG.datadiv != 0 && PUB.CONFIG.datadiv != 1)
                                value = (newdata.value) / PUB.CONFIG.datadiv;
                            else
                                value = (newdata.value);

                            //채널정보를 통해서 소수점위치와 옾셋값을 가져온다
                            value = (float)(value / Math.Pow(10, newdata.decpos));

                            //최종옵셋
                            value += newdata.offset;

                            //데이터 추가
                            if (this.Streamer1[ch].IsVisible)
                            {
                                var v_time = DateTime.Parse(time);
                                this.dataTime[ch].Add(v_time.ToOADate());
                                this.dataVolt[ch].Add(value);

                                var mintime = DateTime.FromOADate(dataTime[ch].First());
                                var maxtime = DateTime.FromOADate(dataTime[ch].Last());
                                var ts = (maxtime - mintime);
                                if (ts.TotalMinutes >= this.timelimit)
                                {
                                    //10개지운다
                                    if (dataTime[ch].Count > 10)
                                    {
                                        dataTime[ch].RemoveRange(0, 10);
                                        dataVolt[ch].RemoveRange(0, 10);
                                    }

                                }

                            }
                        }
                        this.BeginInvoke(new Action(() =>
                        {
                            this.formsPlot1.Refresh();
                        }));
                    }
                    this.BarCtrl1.Invalidate();
                }
            }
            else PUB.ProcessDisplayControl(this.DispCtrl1, e.Command, e.Data);
        }

        public void Frm_Main_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            this.DispCtrl1.OnAlamChange -= DispCtrl1_OnAlamChangeL;
            this.DispCtrl1.OnChangedShowIndex -= DispCtrl1_OnChangedShowIndex;
            this.DispCtrl1.OnClickCell -= DispCtrl1_OnClickCell;
            this.DispCtrl1.OnClickGroup -= DispCtrl1_OnClickGroup;
            this.DispCtrl1.OnClickPrint -= DispCtrl1_OnClickPrint;
            this.DispCtrl1.OnNotifyData -= DispCtrl1_OnNotifyData;
            this.DispCtrl1.OnSetNullbalance -= DispCtrl1_OnSetNullbalance;
            this.DispCtrl1.RaiseAlarm -= DispCtrl1_RaiseAlarm;
            PUB.RemoteCommandEvent -= Pub_RemoteCommandEvent;
            formsPlot1.MouseDown -= FormsPlot1_MouseDown;
            formsPlot1.MouseUp -= FormsPlot1_MouseUp;
            formsPlot1.MouseMove -= FormsPlot1_MouseMove;


            PUB.CONFIG.opensubwindow = false;
            PUB.CONFIG.win2pos = this.Left.ToString() + "," + this.Top.ToString();
            PUB.CONFIG.Save();

        }

        public void Frm_Sub_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F9:
                    this.ShowPrint();
                    break;
            }
        }

        public void Frm_Main_Load(object sender, System.EventArgs e)
        {
            //display logo
            if (System.IO.File.Exists("logo.jpg"))
                this.bt_logo.Image = Image.FromFile("logo.jpg");
            else this.bt_logo.Visible = false;

            this.DispCtrl1.init = false;
            MakeTempDatabase();
            this.Show();
            Application.DoEvents();

            REFRESHCHART();
            Refresh_전해조목록();
            //PUB.subWindow = this.DispCtrl1.GROUPS;

            //this.bt_config.Enabled = true;
            //this.bt_tview.Enabled = true;
            this.bt_tviewr.Enabled = true;
            //this.bt_alamhistory.Enabled = true;
            //this.bt_alamsetup.Enabled = true;
            this.bt_save.Enabled = true;
            //this.bt_print.Enabled = true;
            DispCtrl1.FullScreen = true; ////전체보기
            TableLayoutPanel1.ColumnStyles[1].Width = 0;

            PUB.log.Add(AR.Log.ETYPE.STARTUP, "프로그램시작-초기화완료(SUB)");
            Init = true;

            this.Timer1.Enabled = true;
            this.Timer1.Start();
        }
        public void MakeTempDatabase()
        {
            this.documentElement1.Clear();
            this.documentElement1.GRP.Merge(PUB.DS.GRP);
            this.documentElement1.CHANNEL.Merge(PUB.DS.CHANNEL);
            this.documentElement1.AcceptChanges();
            this.ds1.Clear();
            this.ds1.AcceptChanges();
        }
        public void REFRESHCHART(bool renew = false)
        {

            this.DispCtrl1.init = false;
            this.DispCtrl1.SuspendLayout();
            this.DispCtrl1.initpercent = 1;
            this.DispCtrl1.initmsg = "Crate Sub Window";
            this.DispCtrl1._raise_alarm = false;
            this.DispCtrl1._raise_alarm_pre = false;
            this.DispCtrl1.datadiv = PUB.CONFIG.datadiv;
            this.DispCtrl1.NullbalanceRealValue = PUB.CONFIG.nullbalnce;
            this.DispCtrl1.Sumab = PUB.CONFIG.Sumab;
            this.DispCtrl1.EnableKA = PUB.CONFIG.EnableKA;

            this.DispCtrl1.FONT_NB = PUB.GetFontFromStr(PUB.DESIGN.font_nb);
            this.DispCtrl1.FONT_CV = PUB.GetFontFromStr(PUB.DESIGN.font_cellvalue);
            this.DispCtrl1.FONT_CN = PUB.GetFontFromStr(PUB.DESIGN.font_cellname);
            this.DispCtrl1.Font_Header = PUB.GetFontFromStr(PUB.DESIGN.font_summary);
            this.DispCtrl1.FONT_CT = PUB.GetFontFromStr(PUB.DESIGN.font_celltitle);
            this.DispCtrl1.FONT_AV = PUB.GetFontFromStr(PUB.DESIGN.font_alarmvalue);
            this.DispCtrl1.FONT_KA = PUB.GetFontFromStr(PUB.DESIGN.font_kaValue);
            this.DispCtrl1.FONT_KU = PUB.GetFontFromStr(PUB.DESIGN.font_kaUnit);

            DispCtrl1_RaiseAlarm(false);

            var dtwin = PUB.DS.WIN.Where(t => t.IDX == 2).FirstOrDefault();//
            HMI.CWINDOW Win = new HMI.CWINDOW();
            if (dtwin != null)
            {
                Win.MATRIX = dtwin.MATRIX;//  System.Convert.ToString(dtwin["MATRIX"]);
                Win.이름 = dtwin.TITLE;// System.Convert.ToString(dtwin["TITLE"]);
            }
            else
            {
                Win.MATRIX = "1*1";
                Win.이름 = "NoData";
            }

            Win.IDX = 2;// System.Convert.ToInt32("2");
            this.DispCtrl1.WINDOW = Win;

            UpdateWindowStatus();

            var infofile = new System.IO.FileInfo("window2.grp");
            bool makeinfo = true;
            if (infofile.Exists)
            {
                ////복원처리
                //MsgBox("직렬시작")
                System.IO.FileStream fs = new System.IO.FileStream(infofile.FullName, System.IO.FileMode.Open);
                var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                try
                {
                    var Groups = (HMI.CGROUP[])(bf.Deserialize(fs));
                    PUB.SubGroup = Groups;
                    makeinfo = false;
                }
                catch (Exception)
                {
                    makeinfo = true;
                    //MsgBox(ex.Message.ToString)
                }
                fs.Close();
            }

         
            if (!makeinfo && !renew)
            {
                foreach (var g in this.DispCtrl1.GROUPS)
                {
                    foreach (var gi in g.Items)
                    {
                        gi.활성화 = false;
                        gi._onalamh = false;
                        gi._onalaml = false;
                        gi._onalamover = false;
                        gi._p_onalamh = false;
                        gi._p_onalaml = false;
                        gi._p_onalamover = false;
                        gi.mtime = "";
                    }
                }
            }
            else
            {
                this.DispCtrl1.initpercent = 0;
                this.DispCtrl1.initmsg = "Init Group";

                var DReaders = PUB.DS.GRP.Where(t => t.USE == 1 && t.WINDOW == 2);
                var GroupCount = DReaders.Count();
                //DispCtrl1.ResizeGroup(GroupCount);
                int GIDX = 0;
                HMI.CGROUP[] GroupItems = new HMI.CGROUP[GroupCount];

                foreach (var DReader in DReaders)
                {

                    ////empty error check
                    if (DReader.TITLE == "") DReader.TITLE = "Unknown";
                    if (DReader.MATRIX == "") DReader.MATRIX = "1*1";
                    if (DReader.POS == "") DReader.POS = "0/0";
                    if (DReader.SPAN == "") DReader.SPAN = "1/1";
                    if (DReader.FONT == "") DReader.FONT = "나눔고딕,8,1";
                    if (DReader.ALAMTYPE == "") DReader.ALAMTYPE = "MANUAL";

                    this.DispCtrl1.initmsg = $"Create Group #{DReader.TITLE}";
                    this.DispCtrl1.initpercent = System.Convert.ToInt32((double)(100 * (GIDX + 1)) / GroupCount);

                    string Fontinfo = DReader.FONT;
                    string fontname = System.Convert.ToString(Fontinfo.Split(",".ToCharArray())[0]);
                    int fontsize = System.Convert.ToInt32(Fontinfo.Split(",".ToCharArray())[1]);
                    int fontstyle = 0;
                    try
                    {
                        fontstyle = System.Convert.ToInt32(Fontinfo.Split(",".ToCharArray())[2]);
                    }
                    catch (Exception)
                    {
                        fontstyle = 0;
                    }
                    FontStyle FS = (FontStyle)fontstyle;
                    HMI.CGROUP G1 = new HMI.CGROUP();
                    G1.셀글꼴 = new Font(fontname, fontsize, FS);

                    string spaninfo = DReader.SPAN;
                    string posinfo = DReader.POS;

                    G1.아이템배열 = DReader.MATRIX;
                    G1.이름 = DReader.TITLE;
                    G1.줄병합 = System.Convert.ToInt32(spaninfo.Split("/".ToCharArray())[0]);
                    G1.열병합 = System.Convert.ToInt32(spaninfo.Split("/".ToCharArray())[1]);
                    G1.줄번호 = System.Convert.ToInt32(posinfo.Split("/".ToCharArray())[0]);
                    G1.열번호 = System.Convert.ToInt32(posinfo.Split("/".ToCharArray())[1]);
                    G1.WIDX = DReader.WINDOW; //("WINDOW") '//지정된 윈도우 일련번호
                    G1.IDX = DReader.IDX; //("IDX") '//이그룹의 일련번호
                    G1._ampidx = DReader.KADEVICE; //("KADEVICE")
                    G1.AlarmType = DReader.ALAMTYPE; //("ALAMTYPE")
                    G1._null_itemseq = (short)DReader.NBSEQ; //("NBSEQ")
                    G1.NullBalanceOffset = DReader.NBOFF; //("NBOFF")

                    if (G1._ampidx != "")
                    {
                        string gg1 = System.Convert.ToString(G1._ampidx.Split(",".ToCharArray())[0]);
                        string ggU = System.Convert.ToString(G1._ampidx.Split(",".ToCharArray())[1]);
                        string gg2 = System.Convert.ToString(G1._ampidx.Split(",".ToCharArray())[2]);

                        ////디바이스를 열어서 순서대로 한다.
                        var DTDEV = PUB.DS.DEVICE.Where(t => t.USE == 1).OrderBy(t => t.IDX);
                        short DTDEVIDX = 0;
                        short deviceidx = -1;
                        foreach (var DRdev in DTDEV)
                        {
                            if (DRdev.IDX.ToString() == gg1)
                            {
                                deviceidx = DTDEVIDX;
                                break;
                            }
                            DTDEVIDX++;
                        }
                        if (deviceidx != -1)
                        {
                            G1._ampunit = "KA";
                            G1._ampdecpos = (short)0;
                            G1._ampidx = deviceidx + "," + G1._ampidx.Split(",".ToCharArray())[1] + "," + gg2;
                        }
                        else
                        {
                            G1._ampunit = "NONE";
                            G1._ampdecpos = (short)0;
                        }
                    }
                    else
                    {
                        G1._ampunit = "NONE";
                        G1._ampdecpos = (short)0;
                    }

                    //Totalsize += G1.RowCount * G1.ColumnCount;

                    G1.HIGH = DReader.ALAMH; //("ALAMH")
                    G1.LOW = DReader.ALAML; //("ALAML")
                    G1.UP = DReader.AUTOH; //("AUTOH")
                                           //G1.DOWN = DReader("AUTOH")
                    G1.AlarmType = DReader.ALAMTYPE; //("ALAMTYPE")
                    G1.nbh = DReader.NBH; //("NBH")
                                          //G1.nbhh = DReader("NBHH")
                    G1.nbl = DReader.NBL; //("NBL")
                                          //G1.nbll = DReader("NBLL")

                    string maxname = "";
                    string maxalam = "";
                    string alamstr = "";
                    HMI.CITEM[] G1item = new HMI.CITEM[(G1.RowCount * G1.ColumnCount) - 1 + 1];

                    ////연결된셀의정보(해당 그룹에 속해있는 아이템)
                    var DTChannels = PUB.DS.CHANNEL.Where(t => t.GIDX == G1.IDX).OrderBy(t => t.IDX);//

                    ////initialzing....
                    for (int i = 0; i <= G1item.GetUpperBound(0); i++)
                    {
                        this.DispCtrl1.initpercent = System.Convert.ToInt32((double)((i + 1) * 100) / G1item.Length);
                        if ((this.DispCtrl1.initpercent) % 25 == 0)
                        {
                            this.DispCtrl1.Refresh();
                        }
                        //Me.DispCtrl1.initmsg = GIDX + 1 & "번째 그룹설정중(아이템:" & (i + 1).ToString & ")"

                        ////셀정보를 가져온다
                        DocumentElement.CHANNELRow DrChannel = null;
                        HMI.CITEM gi = new HMI.CITEM();
                        gi.seq = (short)i;

                        if (DTChannels.Any() && i < DTChannels.Count())
                            DrChannel = DTChannels.ElementAt(i);// [i]; ////이데이터가 채널정보에 없다.

                        string MACHINE = "";
                        if (DrChannel == null)
                        {
                            gi.알람형태 = COMM.EALAMTYPE.사용안함;
                            gi.idx = (short)1;
                            gi.alamh = 0;
                            gi.alaml = 0;
                            gi.aalamh = 0;
                            gi.aalaml = 0;
                            gi.이름 = "";
                            gi.enable = false;
                            gi.사용 = false;
                            gi.idx_ch = (short)(-1);
                            gi.idx_dev = (short)(-1);
                            gi.idx_unit = (short)(-1);
                            gi.활성화 = false;
                            gi.c_color = Color.Black;
                            gi.unit = "";
                            gi.decpos = (short)0;
                            MACHINE = "";
                        }
                        else
                        {
                            gi.알람형태 = (COMM.EALAMTYPE)DrChannel.ALAMTYPE;// ["ALAMTYPE"];
                            gi.idx = DrChannel.IDX;// ["IDX"]; ////채널의 고유인덱스
                            gi.alamh = 0;
                            gi.alaml = 0;
                            gi.aalamh = 0;
                            gi.aalaml = 0;
                            gi.alamv = -999;
                            gi.활성화 = false;
                            gi.unit = DrChannel.UNIT;
                            gi.decpos = DrChannel.DECPOS;
                            gi.c_color = System.Drawing.Color.FromArgb(DrChannel.COLOR);

                            if ((gi.알람형태 == COMM.EALAMTYPE.개별알람) || (gi.알람형태 == COMM.EALAMTYPE.개별알람자동)) ////직접입력이므로 데이터베이스를 사용한다.
                            {
                                gi.alamh = DrChannel.ALAMH;
                                gi.alaml = DrChannel.ALAML;
                                gi.aalamh = DrChannel.AUTOH;
                                gi.aalaml = DrChannel.AUTOL;
                            }
                            else if (gi.알람형태 == COMM.EALAMTYPE.사용안함)
                            {
                                gi.alamh = -999;
                                gi.alaml = -999;
                                gi.aalamh = -999;
                                gi.aalaml = -999;
                            }
                            else if (gi.알람형태 == COMM.EALAMTYPE.그룹설정을따름)
                            {
                                gi.alamh = G1.HIGH;
                                gi.alaml = G1.LOW;
                                gi.aalamh = G1.UP;
                                gi.aalaml = G1.UP;
                            }
                            gi.이름 = DrChannel.TITLE;
                            gi.사용 = DrChannel.ENABLE == 1;

                            MACHINE = DrChannel["MACHINE"].ToString().Trim();
                        }


                        if (!string.IsNullOrEmpty(MACHINE)) ////장비정보가 있다면
                        {
                            int DEVIDX = int.Parse(MACHINE.Split(",".ToCharArray())[0]);
                            int UNITNO = int.Parse(MACHINE.Split(",".ToCharArray())[1]);
                            int CHNO = int.Parse(MACHINE.Split(",".ToCharArray())[2]);

                            ////디바이스를 열어서 순서대로 한다.
                            var DTDEV = PUB.DS.DEVICE.Where(t => t.USE == 1).OrderBy(t => t.IDX);//
                            short DTDEVIDX = 0;
                            short deviceidx = -1;
                            foreach (var DRdev in DTDEV)
                            {
                                if (DRdev.IDX == DEVIDX)
                                {
                                    deviceidx = DTDEVIDX;
                                    break;
                                }
                                DTDEVIDX++;
                            }
                            gi.idx_dev = deviceidx;
                            gi.idx_ch = (short)(CHNO - 1);
                            gi.idx_unit = (short)UNITNO;
                            gi.활성화 = false;
                        }
                        else
                        {
                            gi.idx_dev = (short)(-1);
                            gi.idx_ch = (short)(-1);
                            gi.idx_unit = (short)(-1);
                            gi.사용 = false;
                            gi.활성화 = false;
                        }

                        alamstr = $"↑{gi.HIGH} ↓{gi.LOW}";
                        if (gi.이름.Length > maxname.Length)
                        {
                            maxname = gi.이름;
                        }
                        if (alamstr.Length > maxalam.Length)
                        {
                            maxalam = alamstr;
                        }

                        G1item[i] = gi;
                    }

                    G1.maxcellname = maxname;
                    G1.maxcellvalue = "10.000";
                    G1.maxcellalam = "88.8.88";

                    G1.Items = G1item;

                    GroupItems[GIDX] = G1;//.GROUPS[GIDX] = G1;
                    GIDX++;
                }

                PUB.SubGroup = GroupItems;
                PUB.SaveGroupClass(PUB.SubGroup, infofile);
            }

            //set UI Control
            this.DispCtrl1.GROUPS = PUB.SubGroup;

            PUB.StatusMSG("Ready...");
            this.DispCtrl1.initmsg = "Complete";
            this.DispCtrl1.init = true;
            this.DispCtrl1.Values = PUB.Values;
            this.DispCtrl1.Times = PUB.Times;
            //Me.DispCtrl1.WINDOW.restarttime = CONFIG.Restart
            this.DispCtrl1.SmallSize = System.Convert.ToInt32(PUB.CONFIG.viewSize);
            this.DispCtrl1.FullScreen = true;
            this.DispCtrl1.Refresh();
            this.DispCtrl1.ResumeLayout();
            this.Refresh();

            TableLayoutPanel1.ColumnStyles[1].Width = System.Convert.ToSingle(DispCtrl1.FullScreen ? (object)0 : PUB.CONFIG.maintv_winsize);

            formsPlot1.Plot.Clear();
            CrossHair = formsPlot1.Plot.Add.Crosshair(0, 0);
            CrossHair.TextColor = ScottPlot.Colors.White;
            CrossHair.TextBackgroundColor = CrossHair.HorizontalLine.Color;
            formsPlot1.Refresh();

            //make kaindex
            PUB.KA2_IndexList.Clear();
            PUB.KA2_SUM = 0f;
            var GroupRows2 = PUB.DS.GRP.Where(t => t.USE == 1 && t.WINDOW == 2).OrderBy(t => t.TITLE);//
            foreach (var GDr in GroupRows2)
            {
                if (GDr.KADEVICE.isEmpty()) continue;

                var _ampidx = GDr.KADEVICE; // DReader("KADEVICE")

                var gg1 = GDr.KADEVICE.Split(",".ToCharArray())[0].toInt(); //device
                var ggU = GDr.KADEVICE.Split(",".ToCharArray())[1].toInt();
                var gg2 = GDr.KADEVICE.Split(",".ToCharArray())[2].toInt();

                ////디바이스를 열어서 순서대로 한다.
                var DTDEV = PUB.DS.DEVICE.Where(t => t.USE == 1).OrderBy(t => t.IDX);//
                short DTDEVIDX = 0;
                short deviceidx = (-1);
                foreach (DocumentElement.DEVICERow DRdev in DTDEV)
                {
                    if (DRdev.IDX == gg1)
                    {
                        deviceidx = DTDEVIDX;
                        break;
                    }
                    DTDEVIDX++;
                }
                if (deviceidx != -1) PUB.KA2_IndexList.Add($"{deviceidx},{ggU},{gg2}");
            }


        }




        public void DispCtrl1_OnClickCell(HMI.CITEM idx, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                using (var f = new Frm_Cell(idx))
                    f.ShowDialog();
            }
            else if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                using (var f = new Setting.fDesignSetting())
                {
                    if (f.ShowDialog() == DialogResult.OK)
                    {
                        PUB.RaiseRemoteCommandEvent(rCommand.RefreshChart);
                    }

                }
                // Me.ContextMenuStrip1.Show()
                //Me.ContextMenuStrip1.SetBounds(e.Location.X + DispCtrl1.Left, e.Location.Y + DispCtrl1.Top, 100, 100)
            }
        }

        public void DispCtrl1_OnClickGroup(HMI.CGROUP idx, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                Frm_Grp F = new Frm_Grp(idx);
                F.ShowDialog();

                var infofile = new System.IO.FileInfo("window2.grp");
                PUB.SaveGroupClass(PUB.SubGroup, infofile);
                // REFRESHCHART()
            }
        }

        private void bt_window_Click(System.Object sender, System.EventArgs e)
        {
            Frm_Win F = new Frm_Win(this.DispCtrl1.WINDOW);
            F.ShowDialog();
            UpdateWindowStatus();
        }

        private void UpdateWindowStatus()
        {
            //Me.bt_window.Text = Me.DispCtrl1.WINDOW.이름 & "(윈도우속성)"
        }

        private void DispCtrl1_OnAlamChangeL(int ch, COMM.EALAMRAISETYPE raisetype, COMM.EALAMTYPE atype, string AM, float value, float maxvalue, float minvalue)
        {
            TimeSpan ts = DateTime.Now - PUB.StartupTime;
            if (ts.TotalSeconds < 7) return;

            bool rlt = PUB.Alarm.InsertData(DateTime.Now, ch, raisetype, value, atype, maxvalue, minvalue, AM, "");
            PUB.log.Add(AR.Log.ETYPE.NORMAL, "알람이 발생되었습니다(ch=" + ch.ToString() + ",type=" + raisetype.ToString() + ", value=" + value.ToString() + ", min=:" + minvalue.ToString() + ",max=" + maxvalue.ToString() + ",atype=" + atype.ToString() + " ,am=" + AM);
        }

        public void DispCtrl1_OnSetNullbalance(HMI.CGROUP grp, float value)
        {
            if (!PUBC.UpdateNullBalanceOffset(grp.IDX, value))
            {
                UTIL.MsgE("Null Balance 값 저장실패");
            }
        }

        public void Timer1_Tick(System.Object sender, System.EventArgs e)
        {
            DispCtrl1.MonitorOn = PUB.sm.Step == COMM.ESMStep.RUN;
            lb_lasttime.Text = $"Last Time : {PUB.lasttime}";
            this.DispCtrl1.Invalidate();
        }

        public void DispCtrl1_RaiseAlarm(bool On)
        {
            PUB.Set_Sound(On, false);
            lb_alarm.ForeColor = On ? Color.Red : Color.Gray;
        }

        public void DispCtrl1_OnClickPrint(HMI.CGROUP idx)
        {
            PUB.printgrp = idx;
            this.PrintGroup.DefaultPageSettings.Landscape = false;
            this.PPreviewDialog.ShowDialog();
        }

        public void PrintDocument1_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            ////출력그룹이 있야한다.
            if (ReferenceEquals(PUB.printgrp, null))
            {
                UTIL.MsgE("선택된 그룹이 없으므로 출력을 할 수 없습니다");
                return;
            }

            ////graphics capsule
            Point margin = new Point(30, 30);
            Graphics G = e.Graphics;
            SizeF pagesize = new SizeF(PrintGroup.DefaultPageSettings.PaperSize.Width - (margin.X * 2), PrintGroup.DefaultPageSettings.PaperSize.Height - (margin.Y * 2));

            Rectangle windowRect = new Rectangle(margin.X, margin.Y, System.Convert.ToInt32(pagesize.Width), System.Convert.ToInt32(pagesize.Height));
            ////G.DrawRectangle(Pens.Red, windowRect)
            ////G.DrawString(pagesize.ToString, Me.Font, Brushes.Red, margin.X, margin.Y)

            ////데이텅영역
            Rectangle DataRect = new Rectangle(margin.X, margin.Y * 2, System.Convert.ToInt32(pagesize.Width), System.Convert.ToInt32(pagesize.Height - margin.Y * 2));
            ////G.DrawRectangle(Pens.Blue, DataRect)
            ////G.DrawString(DataRect.ToString, Me.Font, Brushes.Blue, DataRect.Left, DataRect.Top)

            ////출력일시표시
            string title = "출력일시 : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Font titlefont = new Font("돋움", 10, FontStyle.Bold);
            SizeF fontsize = G.MeasureString(title, titlefont);
            float Y = DataRect.Top + DataRect.Height + 10;
            float X = margin.X + DataRect.Width - fontsize.Width;
            G.DrawString(title, titlefont, Brushes.Black, X, Y); ////가운데정렬 해서 출력

            title = "[" + PUB.CONFIG.sangho + "] Cell Voltage Monitoring System";
            fontsize = G.MeasureString(title, titlefont);
            X = margin.X;
            G.DrawString(title, titlefont, Brushes.Black, X, Y); ////가운데정렬 해서 출력

            //Dim bottommargin As Integer = 50
            //Dim WindowRect As RectangleF = New RectangleF(30, Y, pagesize.Width * 0.7, pagesize.Height - Y - bottommargin)
            //Dim ChartRect As RectangleF = New RectangleF(WindowRect.Left + 50, WindowRect.Top + 50, WindowRect.Width - (50 * 2), WindowRect.Height - (50 * 2))

            //'Dim 상호명 As String = DBC.GetScalar("select SANGHO from NORMAL")
            //Dim 상호font As New Font("나눔고딕", 18, FontStyle.Bold)
            //Dim 상호size As SizeF = G.MeasureString(상호명, 상호font)
            //G.DrawString(상호명, 상호font, Brushes.Black, WindowRect.Left, WindowRect.Top - 상호size.Height - 10)

            //Y += 상호size.Height

            SizeF itemsize = new SizeF(DataRect.Width, DataRect.Height);

            ////이미지생성해서 그린다.
            this.DispCtrl1.DrawGroup(G, PUB.printgrp, new Point(0, 0), itemsize, DataRect, 0, 0, true, true);
            G.DrawRectangle(Pens.Gray, DataRect);


            G.Dispose();
        }
        private void ShowPrint()
        {

            this.PrintWin.DefaultPageSettings.Landscape = true;
            this.PrintPreViewWin.ShowDialog();
        }
        public void PrintWin_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {

            ////현재윈도우를 화면으로 출력

            ////graphics capsule
            Point margin = new Point(30, 30);
            Graphics G = e.Graphics;
            SizeF pagesize = new SizeF(PrintGroup.DefaultPageSettings.PaperSize.Height - (margin.X * 2), PrintGroup.DefaultPageSettings.PaperSize.Width - (margin.Y * 2));
            Rectangle windowRect = new Rectangle(margin.X, margin.Y, System.Convert.ToInt32(pagesize.Width), System.Convert.ToInt32(pagesize.Height));
            Rectangle DataRect = new Rectangle(margin.X, margin.Y * 2, System.Convert.ToInt32(pagesize.Width), System.Convert.ToInt32(pagesize.Height - margin.Y * 2));

            ////출력일시표시
            string title = "출력일시 : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Font titlefont = new Font("돋움", 10, FontStyle.Bold);
            SizeF fontsize = G.MeasureString(title, titlefont);
            float Y = DataRect.Top + DataRect.Height + 10;
            float X = margin.X + DataRect.Width - fontsize.Width;
            G.DrawString(title, titlefont, Brushes.Black, X, Y); ////가운데정렬 해서 출력

            title = "[" + PUB.CONFIG.sangho + "] Cell Voltage Monitoring System";
            fontsize = G.MeasureString(title, titlefont);
            X = margin.X;
            G.DrawString(title, titlefont, Brushes.Black, X, Y); ////가운데정렬 해서 출력

            SizeF itemsize = new SizeF((float)((double)DataRect.Width / this.DispCtrl1.WINDOW.CoulumnCount), (float)((double)DataRect.Height / this.DispCtrl1.WINDOW.RowCount));

            foreach (HMI.CGROUP Grp in this.DispCtrl1.GROUPS)
            {
                this.DispCtrl1.DrawGroup(G, Grp, new Point(0, 0), itemsize, DataRect, Grp.열번호, Grp.줄번호, true, true);
            }
            G.DrawRectangle(Pens.Gray, DataRect);
            G.Dispose();
        }


        public void cmb_group_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmb_tanks.SelectedIndex < 0) return;

            /* 작성자: 이재웅, 작성일: 2024-11-22, 내용: 차트/Scatter/Volt/Time 초기화 */
            this.formsPlot1.Plot.Clear();
            this.Streamer1 = new ScottPlot.Plottables.Scatter[0];
            this.dataVolt = new List<float>[0];
            this.dataTime = new List<double>[0];
            /**********************************************************************/

            Console.WriteLine("개별 index = " + this.cmb_tanks.SelectedIndex.ToString());
            this.DispCtrl1.ShowIndex = this.cmb_tanks.SelectedIndex;
            this.DispCtrl1.Refresh();

            //현재등록된 목록을 모두 삭제
            this.ds1.channel.Clear();
            this.formsPlot1.Plot.Remove<ScottPlot.Plottables.DataStreamer>();   //데이터스트림삭제
            this.formsPlot1.Refresh();

            var grpName = cmb_tanks.Text.Substring(4).Trim();
            var grpNo = int.Parse(cmb_tanks.Text.Substring(1, 2));

            var grpdr = this.documentElement1.GRP.Where(t => t.TITLE.Equals(grpName)).FirstOrDefault();
            if (grpdr == null) return;

            var chlist = this.documentElement1.CHANNEL.Where(t => t.GIDX == grpdr.IDX);
            if (chlist.Any() == false) return;


            // 미리저장된 목록을 확인한다.
            var chstr = "";
            if (grpNo == 0) chstr = PUB.CONFIG.grp0chlist;
            else if (grpNo == 1) chstr = PUB.CONFIG.grp1chlist;
            else if (grpNo == 2) chstr = PUB.CONFIG.grp2chlist;
            else if (grpNo == 3) chstr = PUB.CONFIG.grp3chlist;
            else if (grpNo == 4) chstr = PUB.CONFIG.grp4chlist;
            else if (grpNo == 5) chstr = PUB.CONFIG.grp5chlist;
            else if (grpNo == 6) chstr = PUB.CONFIG.grp6chlist;
            else if (grpNo == 7) chstr = PUB.CONFIG.grp7chlist;
            else if (grpNo == 8) chstr = PUB.CONFIG.grp8chlist;
            else if (grpNo == 9) chstr = PUB.CONFIG.grp9chlist;

            var chbuf = chstr.Split((char[])(new[] { ',' }), StringSplitOptions.RemoveEmptyEntries);


            //목록은 추가하지만 스트립을 추가하지 않으니 최초 선택시에는 데이터가 나오지 않는다.
            //사용자는 채널 선택을 사용해야 데이터가 보인다.
            this.ds1.channel.Clear();
            this.selectchlist.Clear();
            foreach (var dr in chlist)
            {
                var newdr = ds1.channel.NewchannelRow();
                newdr.idx = dr.IDX;
                newdr.use = chbuf.Contains(dr.IDX.ToString()) ? true : false;
                newdr.c1 = "";
                newdr.c2 = "";
                newdr.cname = dr.TITLE;
                newdr.cc = dr.COLOR;

                /* 작성자: 이재웅, 작성일: 2024-12-09, 내용: '개별보기' 상태에서 전해조 그룹 변경 時 자동으로 선택된 전해조 채널 보이기 */
                if (newdr.use)
                {
                    int idx = dr.IDX;
                    //지정된 플롯의 표시여부를 변경한다.
                    if (this.Streamer1.Length < idx)
                    {
                        Array.Resize(ref Streamer1, idx);
                        Array.Resize(ref dataVolt, idx);
                        Array.Resize(ref dataTime, idx);
                    }

                    if (dataTime[idx - 1] == null) dataTime[idx - 1] = new List<double>();
                    if (dataVolt[idx - 1] == null) dataVolt[idx - 1] = new List<float>();
                    if (Streamer1[idx - 1] == null) Streamer1[idx - 1] = formsPlot1.Plot.Add.ScatterPoints(dataTime[idx - 1], dataVolt[idx - 1]);

                    Streamer1[idx - 1].LineWidth = 1;
                    Streamer1[idx - 1].MarkerSize = 0;
                    /* 작성자: 이재웅, 작성일: 2024-11-27, 내용: 변경한 셀이름으로 차트범례 표시 */
                    Streamer1[idx - 1].LegendText = newdr.cname; //$"CH{idx}";
                    Streamer1[idx - 1].IsVisible = true;
                    selectchlist.Add(idx);    //선택채널에 추가한다.
                }
                /************************************************************************/

                ds1.channel.AddchannelRow(newdr);
            }
            ds1.channel.AcceptChanges();
            formsPlot1.Refresh();

        }

        public void Refresh_전해조목록()
        {
            this.cmb_tanks.Items.Clear();
            var itemlist = DispCtrl1.GROUPS.Select(t => $"[{t.IDX:00}] {t.이름}").ToArray();
            if (itemlist == null)
            {
                UTIL.MsgE("선택가능한 목록이 없습니다");
                return;
            }
            this.cmb_tanks.Items.AddRange(itemlist);
        }

        public void DispCtrl1_OnChangedShowIndex(int index)
        {
            ////개별표시일때 표시되는 인덱스가 바뀐경우에 처리해야할 사항
            ////트렌드뷰가 해당 데이터를 표시할 수 있도록 설정을 변경해줘야한다.
            //If Not Init Then Return

            if (DispCtrl1.FullScreen || DispCtrl1.GROUPS == null) return;
            HMI.CGROUP Grp = DispCtrl1.GROUPS[index];

            this.BarCtrl1.Group = Grp;
            this.BarCtrl1.bMakeBarRect = true;
        }


        /// <summary>
        /// 트렌드뷰갱신용으로 사용할 이벤트임
        /// </summary>
        /// <remarks></remarks>
        public void DispCtrl1_OnNotifyData(DateTime Currenttime)
        {
           
        }

        private void bt_fullscreen_Click(object sender, EventArgs e)
        { // 전체보기/개별보기
            DispCtrl1.FullScreen = !DispCtrl1.FullScreen;
            DispCtrl1.bMakeRect = true;

            if (DispCtrl1.FullScreen)
            {
                bt_fullscreen.Text = "개별보기";
            }
            else
            {
                this.formsPlot1.Plot.Clear();
                CrossHair = formsPlot1.Plot.Add.Crosshair(0, 0);
                CrossHair.TextColor = ScottPlot.Colors.White;
                CrossHair.TextBackgroundColor = CrossHair.HorizontalLine.Color;
                this.Streamer1 = new ScottPlot.Plottables.Scatter[0];
                this.dataVolt = new List<float>[0];
                this.dataTime = new List<double>[0];
                this.formsPlot1.Refresh();

                bt_fullscreen.Text = "전체보기";
                Refresh_전해조목록();

                //0번 전해조 선택
                if (this.cmb_tanks.Items.Count > 0) this.cmb_tanks.SelectedIndex = 0;

                var grpName = cmb_tanks.Text.Substring(4).Trim();
                var grpNo = int.Parse(cmb_tanks.Text.Substring(1, 2));

                //현재선택된 그룹의 채널목록을 추출해야한다.
                if (grpName.isEmpty() == false)
                {
                    var drGrp = documentElement1.GRP.Where(t => t.TITLE == grpName).FirstOrDefault();
                    if (drGrp != null)
                    {
                        //채널목록을 확인한다.
                        var chrows = documentElement1.CHANNEL.Where(t => t.GIDX == drGrp.IDX);
                        if (chrows.Any() == true)
                        {
                            var uselist = ds1.channel.Where(t => t.IsuseNull() == false && t.use == true).ToList();

                            this.formsPlot1.Plot.Remove<ScottPlot.Plottables.DataStreamer>();   //데이터스트림삭제
                            this.formsPlot1.Refresh();
                            this.selectchlist.Clear();

                            if (uselist != null && uselist.Any() == true)
                            {
                                foreach (var item in uselist)
                                {
                                    int idx = item.idx;

                                    //지정된 플롯의 표시여부를 변경한다.
                                    if (this.Streamer1.Length < idx)
                                    {
                                        Array.Resize(ref Streamer1, idx);
                                        Array.Resize(ref dataVolt, idx);
                                        Array.Resize(ref dataTime, idx);
                                    }

                                    if (dataTime[idx - 1] == null) dataTime[idx - 1] = new List<double>();
                                    if (dataVolt[idx - 1] == null) dataVolt[idx - 1] = new List<float>();
                                    if (Streamer1[idx - 1] == null) Streamer1[idx - 1] = formsPlot1.Plot.Add.ScatterPoints(dataTime[idx - 1], dataVolt[idx - 1]);

                                    Streamer1[idx - 1].LineWidth = 1;
                                    Streamer1[idx - 1].MarkerSize = 0;
                                    /* 작성자: 이재웅, 작성일: 2024-11-27, 내용: 변경한 셀이름으로 차트범례 표시 */
                                    Streamer1[idx - 1].LegendText = item.cname; //$"CH{idx}";
                                    Streamer1[idx - 1].IsVisible = true;
                                    selectchlist.Add(idx);    //선택채널에 추가한다.
                                }
                            }

                            if (CrossHair == null)
                            {
                                CrossHair = formsPlot1.Plot.Add.Crosshair(0, 0);
                                CrossHair.TextColor = ScottPlot.Colors.White;
                                CrossHair.TextBackgroundColor = CrossHair.HorizontalLine.Color;
                            }

                            formsPlot1.Plot.Axes.ContinuouslyAutoscale = true;
                            this.formsPlot1.Refresh();
                        }
                    }
                }
            }

            DispCtrl1.Invalidate();
            TableLayoutPanel1.ColumnStyles[1].Width = DispCtrl1.FullScreen ? 0f : (PUB.CONFIG.maintv_winsize);

        }

        private void btMonitorOn_Click(object sender, EventArgs e)
        {
            PUB.RunMonitor();
        }

        private void ToolStripButton2_Click(object sender, EventArgs e)
        {
            PUB.log.Add(AR.Log.ETYPE.NORMAL, "소리끄기실행");
            PUB.Set_Sound(false, true); ////disable sound from user
            PUB.Set_Sound(false, false); ////disable sound from user 보조화면도 소리를 끈다.

            if (PUB.CONFIG.alamplc && PUB.masterk.IsOpen())
            {
                if (PUB.masterk.isValid)
                {
                    if (PUB.masterk.SetOutput(PUB.CONFIG.plc_addr, false))
                    {
                        PUB.log.Add("소리끄기기능에서 PLC도 끔");
                    }
                }
                else
                {
                    PUB.log.Add("ERROR", "plc상태가 유효하지 않습니다 OFF실패");
                }
            }
        }

        private void bt_logo_Click(object sender, EventArgs e)
        {
            UTIL.RunExplorer(UTIL.CurrentPath);
        }

        Frm_trend_Real frm_trend_realtime;
        private void bt_tviewr_Click(object sender, EventArgs e)
        {
            if (frm_trend_realtime == null || frm_trend_realtime.IsDisposed)
                frm_trend_realtime = new Frm_trend_Real(this.DispCtrl1);

            frm_trend_realtime.Show();

            if (frm_trend_realtime.WindowState == FormWindowState.Minimized)
                frm_trend_realtime.WindowState = FormWindowState.Normal;
            else if (frm_trend_realtime.Visible == false)
                frm_trend_realtime.Visible = true;

            frm_trend_realtime.Activate();
        }

        private void bt_save_Click(object sender, EventArgs e)
        {
            var buf = new System.Text.StringBuilder();
            var bufdata = new System.Text.StringBuilder();

            foreach (HMI.CGROUP g in this.DispCtrl1.GROUPS)
            {
                buf.Append(g.이름);

                string lasttime = "";
                System.Text.StringBuilder valuebuffer = new System.Text.StringBuilder();
                foreach (HMI.CITEM gi in g.Items)
                {
                    if (string.IsNullOrEmpty(lasttime))
                    {
                        lasttime = gi.측정시간;
                    }
                    buf.Append("," + gi.이름);
                    valuebuffer.Append("," + gi.측정값);
                }
                buf.Append("\r\n");
                buf.Append(lasttime);
                buf.Append(valuebuffer.ToString());
                buf.Append("\r\n");
                buf.Append("\r\n");
            }

            //if (PUB.CONFIG.opensubwindow && PUB.subgroup != null)
            //{
            //    foreach (HMI.CGROUP g in PUB.subgroup)
            //    {
            //        buf.Append(g.이름);

            //        string lasttime = "";
            //        var valuebuffer = new System.Text.StringBuilder();
            //        foreach (HMI.CITEM gi in g.Items)
            //        {
            //            if (string.IsNullOrEmpty(lasttime))
            //            {
            //                lasttime = gi.측정시간;
            //            }
            //            buf.Append("," + gi.이름);
            //            valuebuffer.Append("," + gi.측정값);
            //        }
            //        buf.Append("\r\n");
            //        buf.Append(lasttime);
            //        buf.Append(valuebuffer.ToString());

            //        buf.Append("\r\n");
            //        buf.Append("\r\n");
            //    }
            //}

            try
            {
                var fn = UTIL.MakePath(UTIL.CurrentPath, "current_sub.csv");
                System.IO.File.WriteAllText(fn, buf.ToString(), System.Text.Encoding.Default);
                PUB.log.Add(AR.Log.ETYPE.NORMAL, "Save Current(SUB) Data CsV");
                UTIL.RunExplorer(fn);
            }
            catch (Exception ex)
            {
                UTIL.MsgE($"현재데이터 저장실패\r\n{ex.Message}");
                PUB.log.Add(AR.Log.ETYPE.ERROR, "현재데이터(SUB) 저장실패:" + ex.Message.ToString());
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        { // 채널선택
            var grpName = cmb_tanks.Text.Substring(4).Trim();
            var grpNo = int.Parse(cmb_tanks.Text.Substring(1, 2));

            //현재선택된 그룹의 채널목록을 추출해야한다.
            if (grpName.isEmpty())
            {
                UTIL.MsgE("채널 그룹을 선택하세요");
                return;
            }

            var drGrp = documentElement1.GRP.Where(t => t.TITLE == grpName).FirstOrDefault();
            if (drGrp == null)
            {
                UTIL.MsgE("선택된 채널 그룹 정보가 없습니다");
                return;
            }

            //채널목록을 확인한다.
            var chrows = documentElement1.CHANNEL.Where(t => t.GIDX == drGrp.IDX);
            if (chrows.Any() == false)
            {
                UTIL.MsgE("해당 그룹에 등록된 채널정보가 없습니다");
                return;
            }

            //현재 등록된 채널정보를 토대로 데이터를 선택한다
            using (var f = new Frm_SelectCH(ds1.channel))
            {
                if (f.ShowDialog() == DialogResult.OK)
                {
                    //현재등록된 목록을 모두 삭제
                    this.formsPlot1.Plot.Remove<ScottPlot.Plottables.DataStreamer>();   //데이터스트림삭제
                    this.formsPlot1.Refresh();
                    this.selectchlist.Clear();

                    //기존에 선택된 자료 선택하제
                    foreach (var item in ds1.channel.Where(t => t.use))
                    {
                        item.use = false;
                    }
                    ds1.channel.AcceptChanges();

                    foreach (ListViewItem item in f.CheckedListBox1.Items)
                    {
                        int idx = int.Parse(item.Tag.ToString()); //.SubItems(0).Text)

                        //지정된 플롯의 표시여부를 변경한다.
                        if (this.Streamer1.Length < idx)
                        {
                            Array.Resize(ref Streamer1, idx);
                            Array.Resize(ref dataVolt, idx);
                            Array.Resize(ref dataTime, idx);
                        }

                        if (dataTime[idx - 1] == null) dataTime[idx - 1] = new List<double>();
                        if (dataVolt[idx - 1] == null) dataVolt[idx - 1] = new List<float>();
                        /* 작성자: 이재웅, 작성일: 2024-11-11, 작성내용: sub 화면만 '개별보기' 채널 중복생성 오류 주석처리 
                         *
                         * if (Streamer1[idx - 1] != null) this.Streamer1[idx - 1] = null; // 주화면(FMain.cs)에는 없는 행 !!!
                         */
                        if (Streamer1[idx - 1] == null) Streamer1[idx - 1] = this.formsPlot1.Plot.Add.ScatterPoints(dataTime[idx - 1], dataVolt[idx - 1]);  //이재웅, 2024-10-17

                        Streamer1[idx - 1].LineWidth = 1;
                        Streamer1[idx - 1].MarkerSize = 0;
                        /* 작성자: 이재웅, 작성일: 2024-11-27, 내용: 변경한 셀이름으로 차트범례 표시 */
                        Streamer1[idx - 1].LegendText = item.Text; //$"CH{idx}";
                        Streamer1[idx - 1].IsVisible = item.Checked;

                        var dr = ds1.channel.Where(t => t.idx == idx).FirstOrDefault();
                        if (dr != null)
                        {
                            dr.use = item.Checked;
                            dr.EndEdit();
                        }
                        if (item.Checked) selectchlist.Add(idx);    //선택채널에 추가한다.
                    }
                    //ds1.channel.AcceptChanges();  //이재웅, 2024-10-17


                    //사용자목록에 저장한다
                    string chstr = string.Join(",", selectchlist.ToArray());
                    if (grpNo == 0) PUB.CONFIG.grp0chlist = chstr;
                    else if (grpNo == 1) PUB.CONFIG.grp1chlist = chstr;
                    else if (grpNo == 2) PUB.CONFIG.grp2chlist = chstr;
                    else if (grpNo == 3) PUB.CONFIG.grp3chlist = chstr;
                    else if (grpNo == 4) PUB.CONFIG.grp4chlist = chstr;
                    else if (grpNo == 5) PUB.CONFIG.grp5chlist = chstr;
                    else if (grpNo == 6) PUB.CONFIG.grp6chlist = chstr;
                    else if (grpNo == 7) PUB.CONFIG.grp7chlist = chstr;
                    else if (grpNo == 8) PUB.CONFIG.grp8chlist = chstr;
                    else if (grpNo == 9) PUB.CONFIG.grp9chlist = chstr;

                    PUB.CONFIG.Save();

                    if (CrossHair == null)
                    {
                        CrossHair = formsPlot1.Plot.Add.Crosshair(0, 0);
                        CrossHair.TextColor = ScottPlot.Colors.White;
                        CrossHair.TextBackgroundColor = CrossHair.HorizontalLine.Color;
                    }

                    formsPlot1.Plot.Axes.ContinuouslyAutoscale = true;
                    this.formsPlot1.Refresh();
                }

            }

        }
    }

}
