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.IO.Ports;

namespace vmsnet
{

    public partial class Frm_Config
    {
        fPleaseWait fw;

        /* 작성자: 이재웅, 작성일: 2024-09-24, 작성내용: 유닛의 채널설정 ToolTip 선언 */
        ToolTip[,] tTip = new ToolTip[4, 2];

        public Frm_Config()
        {
            InitializeComponent();
            this.Controls.Clear();
            this.TabControl1.Visible = false;
            //panbg = new Panel();
            //panbg.Dock = DockStyle.Fill;
            fw = new fPleaseWait();
            fw.TopLevel = false;
            fw.Dock = DockStyle.Fill;
            fw.Show();
            //panbg.Controls.Add(fw);
            this.Controls.Add(fw);
            this.Controls.Add(TabControl1);
            this.Controls.Add(StatusStrip1);
            this.Controls.Add(ToolStrip1);

            /* 작성자: 이재웅, 작성일: 2024-10-11, 작성내용: PC에 인가된 통신포트들만 표시 */
            string[] ports = GetAvailablePorts();
            cmb_plcport.Items.Clear();
            cmb_plcport.Items.AddRange(ports);

            /* 작성자: 이재웅, 작성일: 2024-09-24, 작성내용: 유닛의 채널설정 ToolTip 초기화 */
            for (int i = 0; i < tTip.GetLength(0); i++)
                for (int j = 0; j < tTip.GetLength(1); j++)
                    tTip[i, j] = new ToolTip();

            nudPri1.ValueChanged += NumericUpDown_ValueChanged;
            nudPri2.ValueChanged += NumericUpDown_ValueChanged;
            nudSec1.ValueChanged += NumericUpDown_ValueChanged;
            nudSec2.ValueChanged += NumericUpDown_ValueChanged;
            nud3rdp1.ValueChanged += NumericUpDown_ValueChanged;
            nud3rdp2.ValueChanged += NumericUpDown_ValueChanged;
            nud4thp1.ValueChanged += NumericUpDown_ValueChanged;
            nud4thp2.ValueChanged += NumericUpDown_ValueChanged;
        }

        private static string[] GetAvailablePorts()
        {
            return SerialPort.GetPortNames();
        }

        private void NumericUpDown_ValueChanged(object sender, EventArgs e)
        {
            /* 작성자: 이재웅, 작성일: 2024-09-24, 작성내용: 유닛의 채널설정 ToolTip 생성 */
            NumericUpDown nud = (NumericUpDown)sender;

            // NumericUpDown 매핑을 Dictionary로 관리
            Dictionary<NumericUpDown, (int, int)> nudMapping = new Dictionary<NumericUpDown, (int, int)>
            {
                { nudPri1, (0, 0) },
                { nudPri2, (0, 1) },
                { nudSec1, (1, 0) },
                { nudSec2, (1, 1) },
                { nud3rdp1, (2, 0) },
                { nud3rdp2, (2, 1) },
                { nud4thp1, (3, 0) },
                { nud4thp2, (3, 1) }
            };

            // 유닛채널 공통로직
            string unitChannelInfo = $"{nud.Value.ToString("000").Substring(0, 1)}번유닛 {nud.Value.ToString("000").Substring(1, 2)}번 채널\n\n※ 유닛채널수 : 60개";

            // 컨트롤이 매핑에 존재하는지 확인
            if (nudMapping.TryGetValue(nud, out var indices))
            {
                tTip[indices.Item1, indices.Item2].SetToolTip(nud, unitChannelInfo);
            }
        }

        public void Frm_Config_Load(object sender, System.EventArgs e)
        {
            this.Show();
            Application.DoEvents();
            Initializing();
            fw.Visible = false;
            TabControl1.Visible = true;
            toolStripStatusLabel1.Text = PUB.CONFIG.GetDatabasePath();
        }

        #region NEW DATA ROW


        private void newrow_window(object sender, System.Data.DataTableNewRowEventArgs e)
        {
            var maxnum = this.DocumentElement1.WIN.Any() ? this.DocumentElement1.WIN.Max(t => t.IDX) : 0;
            e.Row["IDX"] = maxnum + 1;
            e.Row["USE"] = 0;
            e.Row["TITLE"] = $"Win{maxnum + 1}";
            e.Row["MATRIX"] = "1*2";
            e.Row["ALAMH"] = "5";
            e.Row["ALAML"] = "0";
        }
        private void newrow_group(object sender, System.Data.DataTableNewRowEventArgs e)
        {
            var maxnum = this.DocumentElement1.GRP.Any() ? this.DocumentElement1.GRP.Max(t => t.IDX) : 0;
            e.Row["IDX"] = maxnum + 1;
            e.Row["USE"] = 0;
            e.Row["WINDOW"] = "1";
            e.Row["TITLE"] = "";
            e.Row["MATRIX"] = "1*1";
            e.Row["POS"] = "0/0";
            e.Row["SPAN"] = "1/1";
            e.Row["FONT"] = "나눔고딕,8,1";
            e.Row["ALAMH"] = "5";
            e.Row["ALAML"] = "0";
            e.Row["AUTOH"] = "1";
            e.Row["AUTOL"] = "1";
            e.Row["KADEVICE"] = "";
            e.Row["ALAMTYPE"] = "";
            e.Row["NBOFF"] = "0";
            e.Row["NBSEQ"] = "0";
        }
        private void newrow_device(object sender, System.Data.DataTableNewRowEventArgs e)
        {
            var maxnum = this.DocumentElement1.DEVICE.Any() ? this.DocumentElement1.DEVICE.Max(t => t.IDX) : -1;
            e.Row["IDX"] = maxnum + 1;
            e.Row["USE"] = 0;
            e.Row["TITLE"] = "";
            e.Row["IP"] = "";
            e.Row["CHCOUNT"] = "";
            e.Row["KACOMMAND"] = "";
            e.Row["CHCOMMAND"] = "";
            e.Row["SNCOMMAND"] = "";
        }
        private void newrow_channel(object sender, System.Data.DataTableNewRowEventArgs e)
        {
            var maxnum = this.DocumentElement1.CHANNEL.Any() ? this.DocumentElement1.CHANNEL.Max(t => t.IDX) : 0;
            e.Row["IDX"] = maxnum + 1;
            e.Row["USE"] = 1;
            e.Row["DECPOS"] = 3;
            e.Row["UNIT"] = "V";
        }

        #endregion

        private void Initializing()
        { // 설정파일 : Setting.xml

            int retcnt = 0;
            this.DS.Tables["machine"].Clear();
            this.DS.Tables["alamtype"].Clear();
            this.DS.Tables["group"].Clear();

            //데이터는 로컬데이터로 복제해서 사용 240809
            this.DocumentElement1.Clear();//.DEVICE.Clear();
            this.DocumentElement1.Merge(PUB.DS);
            this.DocumentElement1.AcceptChanges();

            this.chk_savebinary.Checked = PUB.CONFIG.binarysave;
            this.chk_synctime.Checked = PUB.CONFIG.synctime;
            this.tb_savepath.Text = PUB.CONFIG.databasefolder;
            this.chk_lsb.Checked = PUB.CONFIG.lsb;
            this.tb_trashper.Text = PUB.CONFIG.trashper.ToString();
            this.tb_saveterm.Text = PUB.CONFIG.saveterm.ToString();
            this.chk_2nddata.Checked = PUB.CONFIG.seconddata;
            this.chk_3rdData.Checked = PUB.CONFIG.thirddata;
            this.chk_4thData.Checked = PUB.CONFIG.getdata4;
            this.chk_sound.Checked = PUB.CONFIG.sound;
            this.tb_viewsize.Text = PUB.CONFIG.viewSize.ToString();
            this.tb_plcidx.Value = PUB.CONFIG.plc_addr;
            this.cmb_plcport.Text = PUB.CONFIG.plc_port;    //this.tb_plcport.Text = PUB.CONFIG.plc_port;
            this.chkEnableKA.Checked = PUB.CONFIG.EnableKA;

            this.tb_div.Text = PUB.CONFIG.datadiv.ToString();
            this.chk_nb.Checked = PUB.CONFIG.nullbalnce;
            this.chk_sumab.Checked = PUB.CONFIG.Sumab;
            this.chk_alplc.Checked = PUB.CONFIG.alamplc;

            /* 작성자: 이재웅, 작성일: 2024-09-24, 작성내용: 유닛의 채널설정 ToolTip 생성 */
            nudPri1.Value = PUB.CONFIG.meas_pri1;
            nudPri2.Value = PUB.CONFIG.meas_pri2;
            nudSec1.Value = PUB.CONFIG.meas_sec1;
            nudSec2.Value = PUB.CONFIG.meas_sec2;
            nud3rdp1.Value = PUB.CONFIG.meas_3rd1;
            nud3rdp2.Value = PUB.CONFIG.meas_3rd2;
            nud4thp1.Value = PUB.CONFIG.meas_4th1;
            nud4thp2.Value = PUB.CONFIG.meas_4th2;
            nudMaxCH.Value = PUB.CONFIG.MaxChCount;
            nudLimit.Value = (decimal)PUB.CONFIG.threadlimit;
            tb_sangho.Text = PUB.CONFIG.sangho;
            tb_tel.Text = PUB.CONFIG.tel;

            DocumentElement1.DEVICE.TableNewRow += newrow_device;

            ////장치목록으로 DEVICEID를 생성한다.
            DS.Tables["machine"].Clear();
            DS.Tables["kadevice"].Clear();
            int idx = 0;
            foreach (var Dr in DocumentElement1.DEVICE.Where(t => t.USE == 1).OrderBy(t => t.IDX))
            {
                var NAME = Dr.TITLE;
                var UNITCH = Dr.CHCOUNT;
                foreach (var UC in UNITCH.Split(",".ToCharArray()))
                {
                    var ucbuffer = UC.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
                    var unit = int.Parse(ucbuffer[0]);// System.Convert.ToInt32(UC.Split("*".ToCharArray())[0]);
                    var ch = int.Parse(ucbuffer[1]);// System.Convert.ToInt32(UC.Split("*".ToCharArray())[1]);
                    for (int i = 1; i <= ch; i++)
                    {
                        idx++;
                        this.DS.Tables["machine"].Rows.Add(new string[] { "[#" + idx.ToString("000") + "]" + NAME + "-" + unit.ToString("0") + i.ToString("00"), (Dr["IDX"] + "," + System.Convert.ToString(unit) + "," + System.Convert.ToString(i)) });
                        this.DS.Tables["kadevice"].Rows.Add(new string[] { "[#" + idx.ToString("000") + "]" + NAME + "-" + unit.ToString("0") + i.ToString("00"), (Dr["IDX"] + "," + System.Convert.ToString(unit) + "," + System.Convert.ToString(i)) });
                    }
                }
            }


            ////알람타입목록생성
            DataRow DR2 = this.DS.Tables["alamtype"].NewRow();
            DR2["title"] = "그룹알람";
            DR2["value"] = "0";
            this.DS.Tables["alamtype"].Rows.Add(DR2);
            DR2 = this.DS.Tables["alamtype"].NewRow();
            DR2["title"] = "자동알람";
            DR2["value"] = "1";
            this.DS.Tables["alamtype"].Rows.Add(DR2);
            DR2 = this.DS.Tables["alamtype"].NewRow();
            DR2["title"] = "개별알람";
            DR2["value"] = "2";
            this.DS.Tables["alamtype"].Rows.Add(DR2);
            DR2 = this.DS.Tables["alamtype"].NewRow();
            DR2["title"] = "개별알람자동";
            DR2["value"] = "3";
            this.DS.Tables["alamtype"].Rows.Add(DR2);
            DR2 = this.DS.Tables["alamtype"].NewRow();
            DR2["title"] = "사용안함";
            DR2["value"] = "4";
            this.DS.Tables["alamtype"].Rows.Add(DR2);
            this.DS.Tables["alamtype"].AcceptChanges();


            retcnt = this.DocumentElement1.WIN.Count; // DAWIN.Fill(DTWIN) '//테이블에 데이터를 채운다.
            this.DocumentElement1.WIN.TableNewRow += newrow_window;

            ////WINDOWS목록을 생성
            DS.Tables["window"].Clear();
            foreach (var dr in this.DocumentElement1.WIN.OrderBy(t => t.IDX))
            {
                string NAME = dr.TITLE;
                this.DS.Tables["window"].Rows.Add(new string[] { NAME, dr.IDX.ToString() });
            }
            DS.Tables["window"].AcceptChanges();

            this.DocumentElement1.GRP.TableNewRow += newrow_group;

            this.DS.Tables["group"].Rows.Clear();
            foreach (var Dr in DocumentElement1.GRP.Where(t => t.USE == 1))
            {
                var GIDX = Dr.IDX;// System.Convert.ToInt32(Dr["IDX"]);
                var WIDX = Dr.WINDOW;// System.Convert.ToInt32(Dr["WINDOW"]);
                var GNAME = Dr.TITLE;// System.Convert.ToString(Dr["TITLE"]);
                var WNAME = PUBC.GetWindowName(WIDX); // DBC.GetScalar("select TITLE from WIN where IDX=" & WIDX)
                var NAME = $"{WNAME}-{GNAME}";
                this.DS.Tables["group"].Rows.Add(new string[] { NAME, $"{GIDX}" });
            }
            this.DS.Tables["group"].AcceptChanges();

            this.DocumentElement1.CHANNEL.TableNewRow += newrow_channel;

            this.DocumentElement1.AcceptChanges();
            DS.AcceptChanges();

            this.dv_device.AutoResizeColumns();
            this.dv_channel.AutoResizeColumns();
            this.dv_grp.AutoResizeColumns();
            this.dv_win.AutoResizeColumns();
        }

        public void ToolStripButton1_Click(System.Object sender, System.EventArgs e)
        { // √ 저장, Setting.xml(설정파일)

            this.Validate();

            this.dv_device.EndEdit();
            this.dv_channel.EndEdit();
            this.dv_grp.EndEdit();
            this.dv_win.EndEdit();

            this.bs_device.EndEdit();
            this.bs_channel.EndEdit();
            this.bs_group.EndEdit();
            this.bs_normal.EndEdit();
            this.bs_win.EndEdit();


            if (nudPri1.Value < 1 || nudPri2.Value < 1)
            {
                UTIL.MsgE("Primary Data Range 값을 입력하세요");
                nudPri1.Focus();
                return;
            }

            if (chk_2nddata.Checked)
            {
                if (nudSec1.Value < 1 || nudSec2.Value < 1)
                {
                    UTIL.MsgE("Sencodary Data Range 값을 입력하세요");
                    nudSec1.Focus();
                    return;
                }
            }

            //// 3rd, 4th Data Range 설정은 필요할 경우 나중에 추가 계획

            if (this.nudLimit.Value < 500)
            {
                UTIL.MsgE("데이터 요청 주기는 500ms 이상 입력되어야 합니다");
                nudLimit.Focus();
                return;
            }

            //데이터베이스적용
            PUB.DS.Clear();
            PUB.DS.Merge(this.DocumentElement1);
            PUB.DS.AcceptChanges();

            PUB.CONFIG.meas_pri1 = (short)nudPri1.Value;
            PUB.CONFIG.meas_pri2 = (short)nudPri2.Value;
            PUB.CONFIG.meas_sec1 = (short)nudSec1.Value;
            PUB.CONFIG.meas_sec2 = (short)nudSec2.Value;
            PUB.CONFIG.meas_3rd1 = (short)nud3rdp1.Value;
            PUB.CONFIG.meas_3rd2 = (short)nud3rdp2.Value;
            PUB.CONFIG.meas_4th1 = (short)nud4thp1.Value;
            PUB.CONFIG.meas_4th2 = (short)nud4thp2.Value;
            PUB.CONFIG.MaxChCount = (int)nudMaxCH.Value;

            PUB.CONFIG.binarysave = this.chk_savebinary.Checked;
            PUB.CONFIG.synctime = this.chk_synctime.Checked;
            PUB.CONFIG.databasefolder = this.tb_savepath.Text;
            PUB.CONFIG.lsb = this.chk_lsb.Checked;
            PUB.CONFIG.trashper = short.Parse(this.tb_trashper.Text);
            PUB.CONFIG.saveterm = short.Parse(this.tb_saveterm.Text);
            PUB.CONFIG.seconddata = this.chk_2nddata.Checked;
            PUB.CONFIG.thirddata = this.chk_3rdData.Checked;
            PUB.CONFIG.getdata4 = this.chk_4thData.Checked;

            PUB.CONFIG.sound = chk_sound.Checked;
            PUB.CONFIG.viewSize = tb_viewsize.Text.toInt();
            PUB.CONFIG.nullbalnce = chk_nb.Checked;
            if (this.tb_div.Text.IsNumeric() == false) this.tb_div.Text = "1";
            PUB.CONFIG.datadiv = System.Convert.ToInt32(this.tb_div.Text);
            PUB.CONFIG.Sumab = chk_sumab.Checked;
            PUB.CONFIG.plc_port = cmb_plcport.Text;     //PUB.CONFIG.plc_port = tb_plcport.Text;
            PUB.CONFIG.plc_addr = (int)tb_plcidx.Value;
            PUB.CONFIG.alamplc = chk_alplc.Checked;
            PUB.CONFIG.EnableKA = chkEnableKA.Checked;
            PUB.CONFIG.threadlimit = (int)nudLimit.Value;
            PUB.CONFIG.sangho = tb_sangho.Text;
            PUB.CONFIG.tel = tb_tel.Text;

            ////실제파일에 저장한다.
            PUB.CONFIG.Save();


            ////설정정보를 가져온다.
            string[] BackTables = new string[] { "DEVICE", "GRP", "NORMAL", "WIN", "VIEWGROUP", "CHANNEL" };
            foreach (string tabname in BackTables)
            {
                PUB.DS.Tables[tabname].AcceptChanges();
                System.IO.FileInfo fn = new System.IO.FileInfo(PUB.CONFIG.GetDatabasePath() + "\\Database\\Config\\" + tabname + ".xml");
                if (fn.Directory.Exists == false)
                {
                    fn.Directory.Create();
                }
                PUB.DS.Tables[tabname].WriteXml(fn.FullName, XmlWriteMode.IgnoreSchema);
            }

            try
            {
                var fi = new System.IO.FileInfo("window1.dat");
                fi.Delete();
            }
            catch (Exception)
            {

            }
            try
            {
                var fi = new System.IO.FileInfo("window2.dat");
                fi.Delete();
            }
            catch (Exception)
            {

            }

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        public void dv_grp_DataError(object sender, System.Windows.Forms.DataGridViewDataErrorEventArgs e)
        {

        }

        public void dv_channel_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            if (dv_channel.Columns[e.ColumnIndex].HeaderText == "색상코드")
            {
                string nowcolor = dv_channel.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (string.IsNullOrEmpty(nowcolor))
                {
                    nowcolor = System.Convert.ToString(0);
                }
                ColorDialog C = new ColorDialog();
                C.Color = System.Drawing.Color.FromArgb(System.Convert.ToInt32(nowcolor));
                if (C.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }
                dv_channel.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = C.Color.ToArgb().ToString();
                dv_channel.Refresh();
            }
        }



        public void dv_channel_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
        {

            string Color = System.Convert.ToString(dv_channel.Rows[e.RowIndex].Cells["C_COLOR"].Value);
            bool enable = System.Convert.ToBoolean(dv_channel.Rows[e.RowIndex].Cells["C_ENABLE"].Value);
            if (enable == false)
            {
                dv_channel.Rows[e.RowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                dv_channel.Rows[e.RowIndex].DefaultCellStyle.ForeColor = System.Drawing.Color.Gray;
            }
            else
            {
                dv_channel.Rows[e.RowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Empty;
                dv_channel.Rows[e.RowIndex].DefaultCellStyle.ForeColor = System.Drawing.Color.Black;

                if (!string.IsNullOrEmpty(Color) && Color.IsNumeric())
                {
                    dv_channel.Rows[e.RowIndex].Cells[2].Style.BackColor = System.Drawing.Color.FromArgb(System.Convert.ToInt32(Color));
                    dv_channel.Rows[e.RowIndex].Cells[1].Style.BackColor = System.Drawing.Color.FromArgb(System.Convert.ToInt32(Color));
                }
            }


        }

        public void dv_channel_DataError(object sender, System.Windows.Forms.DataGridViewDataErrorEventArgs e)
        {

        }

        public void ToolStripButton15_Click(System.Object sender, System.EventArgs e)
        {
            if (UTIL.MsgQ("현재 목록을 재구성하시겠습니까?\r\n기존의 목록정보는 삭제됩니다") != DialogResult.Yes) return;

            this.dv_channel.SuspendLayout();
            this.dv_channel.Visible = false;

            ////현재모든채널을삭제한다.
            this.DocumentElement1.CHANNEL.Clear();
            this.DocumentElement1.CHANNEL.AcceptChanges();

            ////재구성 방법 :  각 장비마다 1개의 그룹을 생성
            ////그룹내 서브그룹의 해당 그룹의 채널수 / 2
            var Dt = this.DocumentElement1.GRP.Where(t => t.USE == 1).OrderBy(t => t.IDX).ToList();
            int IDX = 0;
            int coloridx = 0;

            List<Color> Colormap = new List<Color>(0);
            Colormap.Add(Color.Indigo);
            Colormap.Add(Color.Red);
            Colormap.Add(Color.SeaGreen);
            Colormap.Add(Color.Violet);
            Colormap.Add(Color.Goldenrod);
            Colormap.Add(Color.RosyBrown);
            Colormap.Add(Color.LightCoral);
            Colormap.Add(Color.SpringGreen);
            Colormap.Add(Color.Yellow);
            Colormap.Add(Color.Orchid);
            Colormap.Add(Color.OrangeRed);
            Colormap.Add(Color.CadetBlue);
            Colormap.Add(Color.Lime);
            Colormap.Add(Color.OliveDrab);
            Colormap.Add(Color.Aqua);
            Colormap.Add(Color.SaddleBrown);
            Colormap.Add(Color.Tomato);
            Colormap.Add(Color.DarkSlateBlue);
            Colormap.Add(Color.Green);
            Colormap.Add(Color.Teal);
            Colormap.Add(Color.DarkSlateGray);
            Colormap.Add(Color.RoyalBlue);
            Colormap.Add(Color.DarkKhaki);
            Colormap.Add(Color.DarkMagenta);
            Colormap.Add(Color.Orange);
            Colormap.Add(Color.LawnGreen);
            Colormap.Add(Color.SlateGray);
            Colormap.Add(Color.DarkOrange);
            Colormap.Add(Color.Blue);
            Colormap.Add(Color.Firebrick);
            Colormap.Add(Color.DarkBlue);
            Colormap.Add(Color.Sienna);
            Colormap.Add(Color.DimGray);
            Colormap.Add(Color.SandyBrown);
            Colormap.Add(Color.DodgerBlue);
            Colormap.Add(Color.Magenta);
            Colormap.Add(Color.SkyBlue);
            Colormap.Add(Color.Chocolate);
            Colormap.Add(Color.LemonChiffon);
            Colormap.Add(Color.Crimson);
            Colormap.Add(Color.DeepSkyBlue);

            this.prb.Minimum = 0;
            this.prb.Value = 0;

            //그룹설정의 아이템배열값을 가지고 전체 채널을 우선 생성한다
            //IDX와 그룹번호를 우선 생성한다.
            Dictionary<int, int> grpinfo = new Dictionary<int, int>();

            foreach (DocumentElement.GRPRow Dr in Dt)
            {
                string Matrix = Dr.MATRIX.Trim();//.["matrix"].ToString().Trim();
                Matrix = Matrix.Replace("*", "x").Replace("X", "x").Replace("/", "x").Replace("-", "x");

                var matbuf = Matrix.Split("x".ToCharArray());
                if (int.TryParse(matbuf[0], out int rowcount) == false)
                {
                    UTIL.MsgE($"{Dr.TITLE} 의 Matrix 입력값이 올바르지 않습니다\n값:{Dr.MATRIX}\n" +
                        "Matrix 값은 50*4 형태로 입력하세요");
                    return;
                }
                if (int.TryParse(matbuf[1], out int colcount) == false)
                {
                    UTIL.MsgE($"{Dr.TITLE} 의 Matrix 입력값이 올바르지 않습니다\n값:{Dr.MATRIX}\n" +
                        "Matrix 값은 50*4 형태로 입력하세요");
                    return;
                }

                //전체채널 수량을 체크
                this.prb.Maximum = rowcount * colcount;
                this.prb.Value = 0;
                // workmsg(rowcount * colcount)

                lbMsg.Text = $"{Dr.TITLE} 생성 중({prb.Maximum}건)";
                ////아이템갯수만큼 돈다.
                for (int i = 0; i <= (colcount * rowcount - 1); i++)
                {
                    this.prb.Value++;
                    grpinfo.Add(IDX + 1, Dr.IDX);
                    IDX++;
                }
                Application.DoEvents();
            }
            Application.DoEvents();

            ////장치의 데이터를 맵핑시킨다.
            ////모든장치목록을 갱신합니다. 순서대로 맵핑시킨다.

            //데이터삭제
            int cindex = 0;
            IDX = 0;
            coloridx = 0;
            bool idxerr = false;
            var DTD = this.DocumentElement1.DEVICE.Where(t => t.USE == 1).OrderBy(t => t.IDX);
            foreach (var DRD in DTD)
            {
                var DeviceID = DRD.IDX;
                var UNITCH = DRD.CHCOUNT.Split(','); // DRD("CHCOUNT")
                foreach (string UC in UNITCH)
                {
                    var ucBuf = UC.Split('*');
                    int unit = int.Parse(ucBuf[0]); ////sub unit no
                    int ch = int.Parse(ucBuf[1]); ////channel no

                    this.prb.Value = 0;
                    this.prb.Maximum = ch;
                    this.lbMsg.Text = $"{DRD.TITLE}/{unit}:{ch}";
                    Application.DoEvents();


                    for (int i = 1; i <= ch; i++)   //채널은 1번부터 시작한다.
                    {
                        //this.prb.Value++;
                        if (grpinfo.ContainsKey(IDX + 1) == false)
                        {
                            //해당키는 더이상 속하지 않는다.
                            UTIL.MsgE($"번호 {IDX + 1}은 사용자 그룹에 속하지 않는 번호이므로 생성하지 않습니다");
                            idxerr = true;
                            break;
                        }

                        var newdr = this.DocumentElement1.CHANNEL.NewCHANNELRow();
                        newdr.IDX = IDX + 1;// ["IDX"] = IDX + 1;
                        newdr.TITLE = $"#{(IDX + 1):000}";
                        newdr.ENABLE = DRD.USE;
                        newdr.GIDX = grpinfo[IDX + 1];// Dr.IDX; ////이셀의 그룹인덱스
                        newdr.MACHINE = $"{DeviceID},{unit},{i}";

                        newdr.IDX_M = DeviceID;
                        newdr.IDX_U = unit;
                        newdr.IDX_C = i - 1;

                        newdr.ALAMTYPE = 0; ////기본알람은그룹알람으로
                        newdr.ALAMH = 0;
                        newdr.ALAML = 0;
                        newdr.DECPOS = 3;
                        newdr.UNIT = "V";

                        short mok = (short)(Math.Floor((double)coloridx / Colormap.Count));
                        short namu = (short)(coloridx % Colormap.Count);
                        Color C = Colormap[namu];
                        newdr.COLOR = C.ToArgb();
                        this.DocumentElement1.CHANNEL.Rows.Add(newdr);

                        IDX++;
                        cindex++;
                        coloridx++;
                    }
                    if (idxerr) break;
                }
                if (idxerr) break;
            }

            this.dv_channel.ResumeLayout();
            this.dv_channel.Visible = true;
            //this.bn_channel.Visible = true;
            Application.DoEvents();
        }

        private void ToolStripButton2_Click(System.Object sender, System.EventArgs e)
        {
            bool retval = false;
            foreach (GM10 d in PUB.DAQ)
            {
                if (UTIL.MsgQ("다음 장치를 재구성하시겠습니까?" + "\r\n" + "장치명:" + d.title) != DialogResult.Yes) return;

                bool Result = d.Reconstrction();
                if (Result)
                {
                    retval = true;
                }
            }
            if (retval)
            {
                UTIL.MsgI("프로그램을 다시 시작 하세요");
            }
        }

        public void DV_WIN_CellContentClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {

        }

        public void DV_WIN_DataError(object sender, System.Windows.Forms.DataGridViewDataErrorEventArgs e)
        {

        }


        public void 장치구조재구성ToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            DataRowView drv = this.bs_device.Current as DataRowView;
            if (drv == null) return;
            var drDev = drv.Row as DocumentElement.DEVICERow;
            if (drDev == null) return;


            GM10 M = new GM10(drDev.IP, drDev.PORT, "title", "", 99);
            if (!M.Connect().Result)
            {
                UTIL.MsgE("장치를 연결할 수 없습니다" + "\r\n" + "장치의 전원및 연결상태를 확인하세요");
                return;
            }
            bool retval = M.Reconstrction();
            if (retval)
            {
                UTIL.MsgI("장치구조재구성 완료" + "\r\n" + "프로그램을 재시작하세요");
            }
            else
            {
                UTIL.MsgE("장치구조재구성 실패");
            }
        }

        public void 장치자동설정ToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            DataRowView drv = this.bs_device.Current as DataRowView;
            if (drv == null) return;
            var drDev = drv.Row as DocumentElement.DEVICERow;
            if (drDev == null) return;

            GM10 M = new GM10(drDev.IP, drDev.PORT, "title", "", System.Convert.ToInt32(drv["IDX"]));
            if (!M.Connect().Result)
            {
                UTIL.MsgE("장치를 연결할 수 없습니다" + "\r\n" + "장치의 전원및 연결상태를 확인하세요");
                return;
            }

            string kadevicestr = "";
            foreach (DataRow dr in this.DocumentElement1.GRP.Rows)
            {
                string kd = dr["KADEVICE"].ToString();
                if (kd.Trim() == "")
                {
                    continue;
                }
                if (string.IsNullOrEmpty(kadevicestr))
                {
                    kadevicestr = kd;
                }
                else
                {
                    kadevicestr += "/" + kd;
                }
            }

            bool retval = M.ReSetting(kadevicestr, System.Convert.ToString(drv["SNCOMMAND"]), System.Convert.ToString(drv["KACOMMAND"]), System.Convert.ToString(drv["CHCOMMAND"]));
            if (retval)
            {
                UTIL.MsgI("장치자동설정 완료" + "\r\n" + "프로그램을 재시작하세요");
            }
            else
            {
                UTIL.MsgE("장치자동설정 실패");
            }
        }

        public void ToolStripMenuItem1_Click(System.Object sender, System.EventArgs e)
        {
            DataRowView drv = this.bs_channel.Current as DataRowView;
            if (ReferenceEquals(drv, null))
            {
                return;
            }

            string MACHINE = System.Convert.ToString(drv["MACHINE"]);
            string idx = System.Convert.ToString(drv["IDX"]);

            var offset = UTIL.InputBox("변경할 장치ID를 입력하세요(0,0,1,45) DEVID,UNITID,STARTCH,ACCNUM", "0,0,1,45");
            if (offset.Item1 == false) return;

            short dev = System.Convert.ToInt16(offset.Item2.Split(",".ToCharArray())[0]);
            short unit = System.Convert.ToInt16(offset.Item2.Split(",".ToCharArray())[1]);
            short se = System.Convert.ToInt16(offset.Item2.Split(",".ToCharArray())[2]);
            short ae = System.Convert.ToInt16(offset.Item2.Split(",".ToCharArray())[3]);

            short acc = (short)0;

            this.prb.Minimum = 0;
            this.prb.Maximum = Math.Min(System.Convert.ToInt32(double.Parse(idx) + se), this.DocumentElement1.CHANNEL.Rows.Count);
            this.prb.Value = 0;

            this.dv_channel.SuspendLayout();

            //1,1,20,반복갯수
            for (int i = int.Parse(idx); i <= Math.Min(System.Convert.ToInt32(double.Parse(idx) + ae), this.DocumentElement1.CHANNEL.Rows.Count); i++)
            {
                this.prb.Value++;
                Application.DoEvents();
                if (acc > ae)
                {
                    break; ////반복횟수를 넘기면 빠져나간다.
                }
                try
                {
                    this.DocumentElement1.CHANNEL.Rows[i - 1]["MACHINE"] = dev + "," + System.Convert.ToString(unit) + "," + (se + acc).ToString();
                }
                catch (Exception)
                {

                }
                acc++;
            }

            this.dv_channel.ResumeLayout();
            this.dv_channel.Refresh();

        }

        public void ToolStrip1_ItemClicked(System.Object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
        {

        }

        public void bt_editcell_Click(System.Object sender, System.EventArgs e)
        {
            DataRowView drv = this.bs_channel.Current as DataRowView;
            if (ReferenceEquals(drv, null))
            {
                return;
            }

            string MACHINE = System.Convert.ToString(drv["MACHINE"]);
            string idx = System.Convert.ToString(drv["IDX"]);
            var offset = UTIL.InputBox("이름규칙을 입력하세요" + "\r\n" + "앞문자,시작번호,끝번호", "A,1,500");
            if (offset.Item1 == false) return;

            string sc = System.Convert.ToString(offset.Item2.Split(",".ToCharArray())[0]);
            short ss = System.Convert.ToInt16(offset.Item2.Split(",".ToCharArray())[1]);
            short se = System.Convert.ToInt16(offset.Item2.Split(",".ToCharArray())[2]);

            this.prb.Minimum = 0;
            this.prb.Maximum = System.Convert.ToInt32(this.DocumentElement1.CHANNEL.Rows.Count - double.Parse(idx));
            this.prb.Value = 0;

            for (int i = int.Parse(idx); i <= this.DocumentElement1.CHANNEL.Rows.Count; i++)
            {
                if (this.prb.Value < this.prb.Maximum)
                {
                    this.prb.Value++;
                }
                try
                {
                    if (ss > se)
                    {
                        goto endOfForLoop;
                    }
                    this.DocumentElement1.CHANNEL.Rows[i - 1]["TITLE"] = sc + ss.ToString("000"); //// ""  '// Me.DTCHANNEL.Rows(i - 1 + CInt(offset))("MACHINE")
                    ss++;
                }
                catch (Exception)
                {

                }
            }
        endOfForLoop:
            1.GetHashCode(); //VBConversions note: C# requires an executable line here, so a dummy line was added.
        }

        public void 그룹ID변경ToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            DataRowView drv = this.bs_channel.Current as DataRowView;
            if (ReferenceEquals(drv, null))
            {
                return;
            }

            string MACHINE = System.Convert.ToString(drv["MACHINE"]);
            string idx = System.Convert.ToString(drv["IDX"]);
            var offset = UTIL.InputBox("그룹규칙을 입력하세요" + "\r\n" + "시작번호,반복갯수", "1,160");
            if (offset.Item1 == false) return;

            short ss = System.Convert.ToInt16(offset.Item2.Split(",".ToCharArray())[0]);
            short se = System.Convert.ToInt16(offset.Item2.Split(",".ToCharArray())[1]);
            short acc = (short)0;

            this.prb.Minimum = 0;
            this.prb.Maximum = System.Convert.ToInt32(this.DocumentElement1.CHANNEL.Rows.Count - double.Parse(idx));
            this.prb.Value = 0;

            for (int i = int.Parse(idx); i <= this.DocumentElement1.CHANNEL.Rows.Count; i++)
            {
                if (this.prb.Value < this.prb.Maximum)
                {
                    this.prb.Value++;
                }
                try
                {
                    if (acc > se)
                    {
                        return;
                    }
                    this.DocumentElement1.CHANNEL.Rows[i - 1]["GIDX"] = ss; //// ""  '// Me.DTCHANNEL.Rows(i - 1 + CInt(offset))("MACHINE")
                    acc++;
                }
                catch (Exception)
                {

                }
            }
        }

        public void DECPOS변경ToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            DataRowView drv = this.bs_channel.Current as DataRowView;
            if (ReferenceEquals(drv, null))
            {
                return;
            }

            string MACHINE = System.Convert.ToString(drv["MACHINE"]);
            string idx = System.Convert.ToString(drv["IDX"]);
            var offset = UTIL.InputBox("DECPOS를 입력하세요", "3");
            if (offset.Item1 == false) return;

            //Dim ss As Short = offset.Split(",")(0)
            //Dim se As Short = offset.Split(",")(1)
            //Dim acc As Short = 0

            this.prb.Minimum = 0;
            this.prb.Maximum = System.Convert.ToInt32(this.DocumentElement1.CHANNEL.Rows.Count - double.Parse(idx));
            this.prb.Value = 0;

            for (int i = int.Parse(idx); i <= this.DocumentElement1.CHANNEL.Rows.Count; i++)
            {
                if (this.prb.Value < this.prb.Maximum)
                {
                    this.prb.Value++;
                }
                this.DocumentElement1.CHANNEL.Rows[i - 1]["DECPOS"] = offset; //// ""  '// Me.DTCHANNEL.Rows(i - 1 + CInt(offset))("MACHINE")
            }
        }

        public void UNIT변경ToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
        {
            DataRowView drv = this.bs_channel.Current as DataRowView;
            if (ReferenceEquals(drv, null))
            {
                return;
            }

            string MACHINE = System.Convert.ToString(drv["MACHINE"]);
            string idx = System.Convert.ToString(drv["IDX"]);
            var offset = UTIL.InputBox("UNIT를 입력하세요", "V");
            if (offset.Item1 == false) return;


            //Dim ss As Short = offset.Split(",")(0)
            //Dim se As Short = offset.Split(",")(1)
            //Dim acc As Short = 0

            this.prb.Minimum = 0;
            this.prb.Maximum = System.Convert.ToInt32(this.DocumentElement1.CHANNEL.Rows.Count - double.Parse(idx));
            this.prb.Value = 0;

            for (int i = int.Parse(idx); i <= this.DocumentElement1.CHANNEL.Rows.Count; i++)
            {
                if (this.prb.Value < this.prb.Maximum)
                {
                    this.prb.Value++;
                }
                this.DocumentElement1.CHANNEL.Rows[i - 1]["UNIT"] = offset; //// ""  '// Me.DTCHANNEL.Rows(i - 1 + CInt(offset))("MACHINE")
            }
        }

        public void Button1_Click(object sender, EventArgs e)
        {
            PUB.masterk.SetOutput((int)tb_plcidx.Value, true);
        }

        public void Button2_Click(object sender, EventArgs e)
        {
            PUB.masterk.SetOutput((int)tb_plcidx.Value, false);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var od = new FolderBrowserDialog();
            od.SelectedPath = this.tb_savepath.Text;
            if (od.ShowDialog() != DialogResult.OK) return;
            tb_savepath.Text = od.SelectedPath;
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            if (UTIL.MsgQ("현재 등록된 장비의 로컬 테스트 IP(127.0.1)로 변경할까요?\n동일 IP로 인해 포트번호는 자동 증가 합니다") != DialogResult.Yes) return;
            var port = 34150;
            foreach (var dr in this.DocumentElement1.DEVICE)
            {
                dr.IP = "127.0.0.1";
                dr.PORT = port++;
            }
            this.DocumentElement1.DEVICE.AcceptChanges();
        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            if (UTIL.MsgQ("현재 등록된 장비의 IP(192.168.0.1) 부터 자동 할당 할까요?") != DialogResult.Yes) return;
            var ip = 1;
            foreach (var dr in this.DocumentElement1.DEVICE)
            {
                dr.IP = $"192.168.0.{ip++}";
                dr.PORT = 34150;
            }
            this.DocumentElement1.DEVICE.AcceptChanges();
        }
    }
}
