using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.DataFormats;
using System.Printing;
using System.Management;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using PackingControlSystem.lib;
using System.Net.NetworkInformation;
using System.Net;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using System.Threading.Channels;
using System.Net.Sockets;

namespace PackingControlSystem
{
    public partial class frmMain : Form
    {
        public string systemUserName = string.Empty;
        public string printerName = string.Empty;
        public string systemPermission = string.Empty;
        private List<List<string>> Settings = new List<List<string>>();
        DataTable dtSetting = new DataTable();
        DataTable dtFRMQRKANBANSelectFinish = new DataTable();
        DataTable dtFRMQRKANBANSelectHold = new DataTable();
        public string strKanban = string.Empty;
        public static bool blCancelKanban = false;
        DataTable dtFRMQRKANBANSelect = new DataTable();
        DataTable dtFRMQRKANBANSelectFinishTop = new DataTable();
        public string strCreateDate = string.Empty;
        public string strPLCOKNG = string.Empty;
        public string strPLCError = string.Empty;
        public string strPLCDuplicate = string.Empty;
        public string strPLCSerial = string.Empty;
        public string strResult1 = string.Empty;
        public string strResult2 = string.Empty;
        public string strResult3 = string.Empty;
        public string strIP = string.Empty;
        public string strPort = string.Empty;
        public bool blTUse = false;
        public bool blCSPUse = false;
        public bool blCDUse = false;
        public string strProcessNo = string.Empty;

        public frmMain(string systemUserName, string systemPermission)
        {
            InitializeComponent();
            this.systemUserName = systemUserName;
            this.systemPermission = systemPermission;
        }


        private void partInformationToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmPart newMDIChildPart = new frmPart(systemUserName);
            newMDIChildPart.MdiParent = this;
            newMDIChildPart.Show();
        }

        private void tsmScanKanban_Click(object sender, EventArgs e)
        {


            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmPacking newMDIChildPacking = new frmPacking(systemUserName, printerName, tssLabelStatus, tssPLCStatus, tssTRWaiting);
            newMDIChildPacking.MdiParent = this;
            newMDIChildPacking.Show();


        }

        private void tsmReprintKanban_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmReprintKanban newMDIChildReprintKanban = new frmReprintKanban(systemUserName, printerName, tssLabelStatus);
            newMDIChildReprintKanban.MdiParent = this;
            newMDIChildReprintKanban.Show();
        }

        private void userInformationToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmUser newMDIChildUser = new frmUser(systemUserName);
            newMDIChildUser.MdiParent = this;
            newMDIChildUser.Show();
        }

        private void customerInformationToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmCustomer newMDIChildCustomer = new frmCustomer(systemUserName);
            newMDIChildCustomer.MdiParent = this;
            newMDIChildCustomer.Show();
        }

        private void tsmReportOK_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmReportOK newMDIChildReportOK = new frmReportOK(systemUserName, tssPLCStatus, tssTRWaiting);
            newMDIChildReportOK.MdiParent = this;
            newMDIChildReportOK.Show();
        }

        private void tsmReportNG_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmReportNG newMDIChildReportNG = new frmReportNG();
            newMDIChildReportNG.MdiParent = this;
            newMDIChildReportNG.Show();
        }

        private void tsmReportReturn_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmReportReturn newMDIChildReportReturn = new frmReportReturn();
            newMDIChildReportReturn.MdiParent = this;
            newMDIChildReportReturn.Show();
        }

        private void tsmSettingLabel_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmSettingLabel newMDIChildSettingLabel = new frmSettingLabel(systemUserName);
            newMDIChildSettingLabel.MdiParent = this;
            newMDIChildSettingLabel.Show();
        }

        private void tsmAbout_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmAbout newMDIChildAbout = new frmAbout();
            newMDIChildAbout.MdiParent = this;
            newMDIChildAbout.Show();
        }

        private void tsbScanPacking_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmPacking newMDIChildPacking = new frmPacking(systemUserName, printerName, tssLabelStatus, tssPLCStatus, tssTRWaiting);

            newMDIChildPacking.MdiParent = this;
            newMDIChildPacking.Show();
        }

        private void tsbReportOK_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmReportOK newMDIChildReportOK = new frmReportOK(systemUserName, tssPLCStatus, tssTRWaiting);
            newMDIChildReportOK.MdiParent = this;
            newMDIChildReportOK.Show();
        }

        private void tsbReportNG_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmReportNG newMDIChildReportNG = new frmReportNG();
            newMDIChildReportNG.MdiParent = this;
            newMDIChildReportNG.Show();
        }

        private void tsbReprintKanban_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmReprintKanban newMDIChildReprintKanban = new frmReprintKanban(systemUserName, printerName, tssLabelStatus);
            newMDIChildReprintKanban.MdiParent = this;
            newMDIChildReprintKanban.Show();
        }

        private void tsbClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.Text = "Packing Control System (1 Way  KB Print) " + "Version " + Application.ProductVersion;

            blCancelKanban = false;
            strCreateDate = string.Empty;
            Cursor = Cursors.WaitCursor;
            if ((systemPermission == "ADMINISTRATOR"))
            {
                informationToolStripMenuItem1.Enabled = true;
                reportToolStripMenuItem1.Enabled = true;
                settingToolStripMenuItem.Enabled = true;
                tsmReprintKanban.Enabled = true;
                tsbReportOK.Enabled = true;
                tsbReportNG.Enabled = true;
                tsbReprintKanban.Enabled = true;
            }
            else if ((systemPermission == "LEADER") || (systemPermission == "QA"))
            {
                informationToolStripMenuItem1.Enabled = false;
                reportToolStripMenuItem1.Enabled = true;
                settingToolStripMenuItem.Enabled = false;
                tsmReprintKanban.Enabled = true;
                tsbReportOK.Enabled = true;
                tsbReportNG.Enabled = true;
                tsbReprintKanban.Enabled = true;
            }
            else
            {
                informationToolStripMenuItem1.Enabled = false;
                reportToolStripMenuItem1.Enabled = false;
                settingToolStripMenuItem.Enabled = false;
                tsmReprintKanban.Enabled = false;
                tsbReportOK.Enabled = false;
                tsbReportNG.Enabled = false;
                tsbReprintKanban.Enabled = false;
            }

            tssLabelDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            tssLabelTime.Text = DateTime.Now.ToString("HH:mm:ss");
            tssLabelUser.Text = this.systemUserName;
            tssTRWaiting.Text = string.Empty;
            timer1.Enabled = true;

            List<string> tmp = null;
            Settings = new List<List<string>>();
            tmp = null;
            using (var csv = new CsvReader(System.IO.Directory.GetCurrentDirectory() + "\\Settings.csv"))
            {
                while ((tmp = csv.ReadRow()) != null)
                {
                    Settings.Add(tmp);

                }

            }//using end

            //printerName = "TSC TTP-247";
            printerName = this.Settings[1][0];

            tssLabelStatus.Text = printerName;
            tssPLCStatus.Text = string.Empty;
            bool IsOffline = false;
            bool IsFound = false;
            ManagementObjectSearcher searcher = new
            ManagementObjectSearcher("SELECT * FROM Win32_Printer where Name='" + printerName + "'");
            foreach (ManagementObject printer in searcher.Get())
            {
                IsOffline = (bool)printer["WorkOffline"];
                IsFound = true;
            }
            if ((IsOffline) || (IsFound == false))
            {
                tssLabelStatus.BackColor = Color.Red;

            }
            else
            {
                tssLabelStatus.BackColor = Color.LightGreen;

            }

            loadTable();

            if (PingPLC() == true)
            {
                tssPLCStatus.BackColor = Color.LightGreen;
            }
            else
            {
                tssPLCStatus.BackColor = Color.Red;
            }

            if (tssPLCStatus.BackColor == Color.LightGreen)
            {
                ForcedSetLive();
            }

            Cursor = Cursors.Default;

        }

        public string RtnDbCon()
        {
            return "Data Source=" + this.Settings[0][0] + ";Initial Catalog=" + this.Settings[0][1] + ";User Id=sa;Password=" + this.Settings[0][2] + ";";

        }

        private void loadTable()
        {
            dtSetting = new DataTable();
            clsUtil_MSSQL.GetDataFromTBsettingPLC(RtnDbCon(), "TM_SETTING_PLC", ref dtSetting);

            strIP = string.Empty;
            strPort = "8501";
            blTUse = false;
            blCSPUse = false;
            blCDUse = false;
            strProcessNo = string.Empty;

            if (dtSetting.Rows.Count > 0)
            {
                tssPLCStatus.Text = dtSetting.Rows[0][0].ToString();
                strIP = dtSetting.Rows[0][0].ToString();
                strPort = dtSetting.Rows[0][1].ToString();
                blTUse = Convert.ToBoolean(dtSetting.Rows[0][2].ToString());
                blCSPUse = Convert.ToBoolean(dtSetting.Rows[0][3].ToString());
                blCDUse = Convert.ToBoolean(dtSetting.Rows[0][4].ToString());
                strProcessNo = dtSetting.Rows[0][5].ToString();
            }
            if ((strPort == null) || (strPort == string.Empty))
            {
                strPort = "8501";
            }

        }

        private void ForcedSetLive()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;
            System.Threading.Thread.Sleep(50);

            ExeCommandPLC("ST" + (char)_cmd01 + "MR1305" + (char)_cmd02, "ForcedSet");
        }

        public bool PingPLC()
        {
            Ping ping = new Ping();

            PingReply pingStatus = ping.Send(IPAddress.Parse(strIP));

            if (pingStatus.Status == IPStatus.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy == false)
            {
                backgroundWorker1.RunWorkerAsync();
            }

            if (backgroundWorker2.IsBusy == false)
            {
                backgroundWorker2.RunWorkerAsync();
            }

            if (backgroundWorker3.IsBusy == false)
            {
                backgroundWorker3.RunWorkerAsync();
            }

            if (backgroundWorker6.IsBusy == false)
            {
                backgroundWorker6.RunWorkerAsync();
            }

            if (backgroundWorker7.IsBusy == false)
            {
                backgroundWorker7.RunWorkerAsync();
            }

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            tssLabelDate.Text = DateTime.Now.ToString("dd/MM/yyyy");

        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {

            tssLabelTime.Text = DateTime.Now.ToString("HH:mm:ss");

        }

        private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
        {
            tssLabelStatus.Text = printerName;
            bool IsOffline = false;
            bool IsFound = false;
            ManagementObjectSearcher searcher = new
            ManagementObjectSearcher("SELECT * FROM Win32_Printer where Name='" + printerName + "'");
            foreach (ManagementObject printer in searcher.Get())
            {
                IsOffline = (bool)printer["WorkOffline"];
                IsFound = true;
            }
            if ((IsOffline) || (IsFound == false))
            {
                tssLabelStatus.BackColor = Color.Red;
            }
            else
            {
                tssLabelStatus.BackColor = Color.LightGreen;
            }

            //if (tssLabelStatus.BackColor == Color.Red)
            //{
            //    tssLabelStatus.BackColor = Color.LightGreen;
            //}
            //else
            //{
            //    tssLabelStatus.BackColor = Color.Red;
            //}

        }

        private void settingPLCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null)
                ActiveMdiChild.Close();

            frmSettingPLC newMDIChildSettingPLC = new frmSettingPLC(systemUserName);
            newMDIChildSettingPLC.MdiParent = this;
            newMDIChildSettingPLC.Show();
        }

        private void backgroundWorker6_DoWork(object sender, DoWorkEventArgs e)
        {
            loadTable();

            if (PingPLC() == true)
            {
                tssPLCStatus.BackColor = Color.LightGreen;
            }
            else
            {
                tssPLCStatus.BackColor = Color.Red;
            }
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void tsbCancelKanban_Click(object sender, EventArgs e)
        {


            dtFRMQRKANBANSelectFinish = new DataTable();
            clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Finish(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelectFinish, string.Empty);
            if (dtFRMQRKANBANSelectFinish is not null)
            {
                if (dtFRMQRKANBANSelectFinish.Rows.Count > 0)
                {
                    if ((dtFRMQRKANBANSelectFinish.Rows[0][1].ToString() == "Packing") || (dtFRMQRKANBANSelectFinish.Rows[0][1].ToString() == "Printed"))
                    {
                        strKanban = dtFRMQRKANBANSelectFinish.Rows[0][0].ToString();

                        frmCancelKanban frm = new frmCancelKanban(strKanban, "ยกเลิก Kanban", "ADMINISTRATOR");
                        frm.ShowDialog();

                        if (blCancelKanban == true)
                        {
                            strCreateDate = dtFRMQRKANBANSelectFinish.Rows[0][3].ToString();

                            dtFRMQRKANBANSelect = new DataTable();
                            clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Cancel(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, strKanban, strCreateDate);

                            if (dtFRMQRKANBANSelect is not null)
                            {
                                if (dtFRMQRKANBANSelect.Rows.Count > 0)
                                {
                                    for (int i = 0; i < dtFRMQRKANBANSelect.Rows.Count; i++)
                                    {
                                        clsUtil_MSSQL.updateCancelKanban(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                                        this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                        DateTime.Now.ToString("HHmmss"));

                                        clsUtil_MSSQL.updateCancelQRScan(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                                        this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                        DateTime.Now.ToString("HHmmss"));
                                    }
                                }
                            }

                            //clsUtil_MSSQL.updateCancelKanban(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelectFinish.Rows[0][2].ToString()),
                            //this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                            //DateTime.Now.ToString("HHmmss"));

                            //clsUtil_MSSQL.updateCancelQRScan(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelectFinish.Rows[0][2].ToString()),
                            //this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                            //DateTime.Now.ToString("HHmmss"));

                            WriteReSetLHRH();

                            if (ActiveMdiChild != null)
                                ActiveMdiChild.Close();

                            MessageBox.Show(this, "Cancel Kanban เรียบร้อย",
                                               "Packing Control System (1 Way  KB Print)", MessageBoxButtons.OK,
                                               MessageBoxIcon.Information,
                                               MessageBoxDefaultButton.Button1, 0);
                        }

                    }
                    else if (dtFRMQRKANBANSelectFinish.Rows[0][1].ToString() == "Finish")
                    {
                        strKanban = dtFRMQRKANBANSelectFinish.Rows[0][0].ToString();

                        dtFRMQRKANBANSelectFinishTop = new DataTable();
                        clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Finish_Top(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelectFinishTop, strKanban);

                        if (dtFRMQRKANBANSelectFinishTop is not null)
                        {
                            if (dtFRMQRKANBANSelectFinishTop.Rows.Count > 0)
                            {
                                if ((dtFRMQRKANBANSelectFinishTop.Rows[0][1].ToString() == "Packing") || (dtFRMQRKANBANSelectFinishTop.Rows[0][1].ToString() == "Printed"))
                                {
                                    strKanban = dtFRMQRKANBANSelectFinishTop.Rows[0][0].ToString();

                                    frmCancelKanban frm = new frmCancelKanban(strKanban, "ยกเลิก Kanban", "ADMINISTRATOR");
                                    frm.ShowDialog();

                                    if (blCancelKanban == true)
                                    {
                                        strCreateDate = dtFRMQRKANBANSelectFinishTop.Rows[0][3].ToString();

                                        dtFRMQRKANBANSelect = new DataTable();
                                        clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Cancel(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, strKanban, strCreateDate);

                                        if (dtFRMQRKANBANSelect is not null)
                                        {
                                            if (dtFRMQRKANBANSelect.Rows.Count > 0)
                                            {
                                                for (int i = 0; i < dtFRMQRKANBANSelect.Rows.Count; i++)
                                                {
                                                    clsUtil_MSSQL.updateCancelKanban(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                                                    this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                                    DateTime.Now.ToString("HHmmss"));

                                                    clsUtil_MSSQL.updateCancelQRScan(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                                                    this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                                    DateTime.Now.ToString("HHmmss"));
                                                }
                                            }
                                        }

                                        //clsUtil_MSSQL.updateCancelKanban(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelectFinish.Rows[0][2].ToString()),
                                        //this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                        //DateTime.Now.ToString("HHmmss"));

                                        //clsUtil_MSSQL.updateCancelQRScan(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelectFinish.Rows[0][2].ToString()),
                                        //this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                        //DateTime.Now.ToString("HHmmss"));

                                        MessageBox.Show(this, "Cancel Kanban เรียบร้อย",
                                                           "Packing Control System (1 Way  KB Print)", MessageBoxButtons.OK,
                                                           MessageBoxIcon.Information,
                                                           MessageBoxDefaultButton.Button1, 0);

                                        
                                    }
                                }

                            }

                        }
                        else
                        {
                            MessageBox.Show(this, "ไม่มี Kanban ที่ยัง Packing ไม่เสร็จ",
                                           "Production window", MessageBoxButtons.OK,
                                           MessageBoxIcon.Warning,
                                           MessageBoxDefaultButton.Button1, 0);
                        }

                    }
                    else
                    {
                        MessageBox.Show(this, "ไม่มี Kanban ที่ยัง Packing ไม่เสร็จ",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                    }
                }
            }


        }

        private void tsbHoldKanban_Click(object sender, EventArgs e)
        {
            dtFRMQRKANBANSelectHold = new DataTable();
            clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Hold(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelectHold);
            if (dtFRMQRKANBANSelectHold is not null)
            {
                if (dtFRMQRKANBANSelectHold.Rows.Count > 0)
                {
                    strKanban = string.Empty;

                    for (int i = 0; i < dtFRMQRKANBANSelectHold.Rows.Count; i++)
                    {
                        strKanban = strKanban + dtFRMQRKANBANSelectHold.Rows[i][0].ToString() + "\r\n";
                    }

                    DialogResult dialogResult = MessageBox.Show(this, "มี Kanban : \r\n" + strKanban + "ที่ยัง Hold อยู่",
                                       "Production window", MessageBoxButtons.YesNo,
                                   MessageBoxIcon.Question,
                                   MessageBoxDefaultButton.Button1, 0);

                    if (dialogResult == DialogResult.No)
                    {
                        return;
                    }

                    //    MessageBox.Show(this, "มี Kanban : \r\n" + strKanban + "ที่ยัง Hold อยู่",
                    //                   "Production window", MessageBoxButtons.OK,
                    //                   MessageBoxIcon.Warning,
                    //                   MessageBoxDefaultButton.Button1, 0);
                    
                    //return;
                }
            }

            dtFRMQRKANBANSelectFinish = new DataTable();
            clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Status(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelectFinish);
            if (dtFRMQRKANBANSelectFinish is not null)
            {
                if (dtFRMQRKANBANSelectFinish.Rows.Count > 0)
                {
                    if ((dtFRMQRKANBANSelectFinish.Rows[0][1].ToString() == "Packing") || (dtFRMQRKANBANSelectFinish.Rows[0][1].ToString() == "Printed"))
                    {
                        strKanban = dtFRMQRKANBANSelectFinish.Rows[0][0].ToString();

                        frmCancelKanban frm = new frmCancelKanban(strKanban, "หยุด Pack ชั่วคราว", "LEADER");
                        frm.ShowDialog();

                        if (blCancelKanban == true)
                        {
                            strCreateDate = dtFRMQRKANBANSelectFinish.Rows[0][3].ToString();

                            dtFRMQRKANBANSelect = new DataTable();
                            clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Cancel(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, strKanban, strCreateDate);

                            if (dtFRMQRKANBANSelect is not null)
                            {
                                if (dtFRMQRKANBANSelect.Rows.Count > 0)
                                {
                                    for (int i = 0; i < dtFRMQRKANBANSelect.Rows.Count; i++)
                                    {
                                        if (dtFRMQRKANBANSelect.Rows[i][2].ToString() == "Packing")
                                        {
                                            clsUtil_MSSQL.updateCancelKanban(RtnDbCon(), "HoldPacking", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                                        this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                        DateTime.Now.ToString("HHmmss"));

                                            clsUtil_MSSQL.updateCancelQRScan(RtnDbCon(), "HoldPacking", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                                            this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                            DateTime.Now.ToString("HHmmss"));
                                        }
                                        else if (dtFRMQRKANBANSelect.Rows[i][2].ToString() == "Printed")
                                        {
                                            clsUtil_MSSQL.updateCancelKanban(RtnDbCon(), "HoldPrinted", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                                       this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                       DateTime.Now.ToString("HHmmss"));

                                            clsUtil_MSSQL.updateCancelQRScan(RtnDbCon(), "HoldPrinted", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                                            this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                                            DateTime.Now.ToString("HHmmss"));
                                        }

                                    }
                                }
                            }

                            //clsUtil_MSSQL.updateCancelKanban(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelectFinish.Rows[0][2].ToString()),
                            //this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                            //DateTime.Now.ToString("HHmmss"));

                            //clsUtil_MSSQL.updateCancelQRScan(RtnDbCon(), "Cancel", Convert.ToInt32(dtFRMQRKANBANSelectFinish.Rows[0][2].ToString()),
                            //this.systemUserName, DateTime.Now.ToString("yyyyMMdd"),
                            //DateTime.Now.ToString("HHmmss"));

                            WriteReSetLHRH();

                            if (ActiveMdiChild != null)
                                ActiveMdiChild.Close();

                            MessageBox.Show(this, "Hold Kanban เรียบร้อย",
                                               "Packing Control System (1 Way  KB Print)", MessageBoxButtons.OK,
                                               MessageBoxIcon.Information,
                                               MessageBoxDefaultButton.Button1, 0);
                        }

                    }
                    else
                    {
                        MessageBox.Show(this, "ไม่มี Kanban ที่ยัง Packing ไม่เสร็จ",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                    }
                }
                else
                {
                    MessageBox.Show(this, "ไม่มี Kanban ที่ยัง Packing ไม่เสร็จ",
                                   "Production window", MessageBoxButtons.OK,
                                   MessageBoxIcon.Warning,
                                   MessageBoxDefaultButton.Button1, 0);
                }
            }
            else
            {
                MessageBox.Show(this, "ไม่มี Kanban ที่ยัง Packing ไม่เสร็จ",
                               "Production window", MessageBoxButtons.OK,
                               MessageBoxIcon.Warning,
                               MessageBoxDefaultButton.Button1, 0);
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            WriteReSetLHRH();
        }

        private void WriteReSetLHRH()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;

            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("RS" + (char)_cmd01 + "MR1400" + (char)_cmd02, "ForcedSet");

            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("RS" + (char)_cmd01 + "MR1401" + (char)_cmd02, "ForcedSet");
        }

        private void ExeCommandPLC(string _CommandStr, String _CommandType)
        {

            if (tssPLCStatus.BackColor == Color.Red)
            {
                MessageBox.Show(this, "ไม่สามารถเติดต่อ PLC ได้ เนื่องจาก PLC Offline",
                                   "Connect PLC", MessageBoxButtons.OK,
                                   MessageBoxIcon.Error,
                                   MessageBoxDefaultButton.Button1, 0);
                return;
            }

            string textToSend = DateTime.Now.ToString();
            DateTime startSend = DateTime.Now;

            //---create a TCPClient object at the IP and port no.---
            TcpClient client = new TcpClient(strIP, Convert.ToInt32(strPort));
            NetworkStream nwStream = client.GetStream();



            string _command = string.Empty;
            _command = _CommandStr + "\r\n"; // Read Current position


            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(_command);


            //---send the text---
            //Console.WriteLine("Sending : " + textToSend);
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            //---read back the text---
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
            int bytesRead = 0;
            byte _cmd01 = 0x20;

            bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);

            string _returnValue1 = string.Empty;
            //_returnValue1 = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead).Replace("\r\n", string.Empty);
            _returnValue1 = System.Text.Encoding.ASCII.GetString(bytesToRead, 0, bytesRead).Replace("\r\n", string.Empty);
            DateTime endSend = DateTime.Now;
            TimeSpan ts = endSend - startSend;
            if (_CommandType == "DataRead")
            {
                string[] val;
                val = _returnValue1.Split((char)_cmd01);
                int intvalue = 0;
                int intvalue2 = 0;
                char charvalue;
                char charvalue2;
                string serial = string.Empty;

                for (int i = 0; i < val.Length; i++)
                {
                    intvalue = Convert.ToInt32(val[i].Substring(0, 2), 16);
                    intvalue2 = Convert.ToInt32(val[i].Substring(2, 2), 16);

                    charvalue = Convert.ToChar(intvalue);
                    charvalue2 = Convert.ToChar(intvalue2);

                    serial = serial + charvalue.ToString() + charvalue2.ToString();
                }
                strPLCSerial = serial;
                //MessageBox.Show(serial);
            }
            else if (_CommandType == "DataReadOKNG")
            {
                strPLCOKNG = Convert.ToInt32(_returnValue1).ToString();
                //Show(Convert.ToInt32(_returnValue1).ToString() + Environment.NewLine + ts.TotalMilliseconds + " Milliseconds");

            }
            else if (_CommandType == "DataReadError")
            {
                strPLCError = Convert.ToInt32(_returnValue1).ToString();

            }
            else if (_CommandType == "DataReadDuplicate")
            {
                strPLCDuplicate = Convert.ToInt32(_returnValue1).ToString();

            }
            else if ((_CommandType == "ForcedSet") || (_CommandType == "ForcedReset") || (_CommandType == "DataWrite"))
            {
                //MessageBox.Show(_returnValue1.ToString() + Environment.NewLine + ts.TotalMilliseconds + " Milliseconds");
                strResult1 = _returnValue1.ToString();
            }
            else if (_CommandType == "DataWriteOKNG")
            {
                strResult2 = _returnValue1.ToString();
            }
            else if (_CommandType == "DataKanbanWrite")
            {
                //MessageBox.Show(_returnValue1.ToString() + Environment.NewLine + ts.TotalMilliseconds + " Milliseconds");
                strResult3 = _returnValue1.ToString();
            }


            Console.ReadLine();
            client.Close();

        }

        private void backgroundWorker7_DoWork(object sender, DoWorkEventArgs e)
        {
            if (tssPLCStatus.BackColor == Color.LightGreen)
            {
                ForcedSetLive();
            }
        }
    }
}
