using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Formats.Asn1;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Drawing.Imaging;
using PackingControlSystem.lib;
using Microsoft.VisualBasic.ApplicationServices;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.VisualBasic.Logging;
using excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Linq.Expressions;
using System.Net.NetworkInformation;



namespace PackingControlSystem
{
    public partial class frmReportOK : Form
    {
        private List<List<string>> Settings = new List<List<string>>();
        DataTable dtHistory = new DataTable();
        DataTable dtHistorySelect = new DataTable();
        DataTable dtFRMQRKANBANSelect = new DataTable();
        DataTable dtPartSelect = new DataTable();
        Microsoft.Office.Interop.Excel.Application excel;
        Microsoft.Office.Interop.Excel.Workbook excelworkBook;
        Microsoft.Office.Interop.Excel.Worksheet excelSheet;
        Microsoft.Office.Interop.Excel.Range excelCellrange;
        private string userName = string.Empty;
        private System.Windows.Forms.ToolStripStatusLabel PLCStatus;
        private System.Windows.Forms.ToolStripStatusLabel TRWaiting;
        public string strIP = string.Empty;
        public string strPort = string.Empty;
        public bool blTUse = false;
        public bool blCSPUse = false;
        public bool blCDUse = false;
        public bool blReInputUse = false;
        DataTable dtSetting = new DataTable();
        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 strPCKBScan = string.Empty;
        public string strPartNo = string.Empty;
        public string strPartId = string.Empty;
        public string strPartName = string.Empty;
        public string strQPack = string.Empty;
        public string strSerialSelect = string.Empty;
        public static bool blChangeOKtoNG = false;
        public static string strMSG = string.Empty;
        public static string strUserQC = string.Empty;
        public string strProcessNo = string.Empty;
        public static bool blDeleteKanban = false;
        public string strStartDate = string.Empty;
        public string strEndDate = string.Empty;
        public string strUNITQRScan = string.Empty;
        public string strLR = string.Empty;
        public string strModel = string.Empty;

        public string strPartID = string.Empty;
        public string strModelShow = string.Empty;
        public string strCode = string.Empty;
        public string strCustomerPartName = string.Empty;
        public string strCustomerPartNO = string.Empty;
        public string strDaySet = string.Empty;
        public string strCustomerID = string.Empty;
        public string strQRLength = string.Empty;
        public string strLocation = string.Empty;
        public string strModelStart = string.Empty;
        public string strModelLength = string.Empty;
        public string strDetail = string.Empty;
        public string strDateStart = string.Empty;
        public string strDateLength = string.Empty;
        public string strSIDE = string.Empty;
        public string strType = string.Empty;
        public string strWet = string.Empty;
        public string strQRKanban = string.Empty;

        public frmReportOK(string systemUserName, ToolStripStatusLabel pLCStatus, System.Windows.Forms.ToolStripStatusLabel tssTRWaiting)
        {
            InitializeComponent();
            userName = systemUserName;
            PLCStatus = pLCStatus;
            TRWaiting = tssTRWaiting;
        }

        private void frmReportOK_Load(object sender, EventArgs e)
        {
            List<string> tmp = null;
            dgvReportOK.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            //listBox1.HorizontalScrollbar = true;
            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

            setStart();

            loadTableSettingPLC();

            //loadTable();
        }
        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 setStart()
        {
            txtPartID.Text = string.Empty;
            txtPartNO.Text = string.Empty;
            txtCustomerPartID.Text = string.Empty;
            txtCustomerPartNO.Text = string.Empty;
            txtKBSerial.Text = string.Empty;
            txtPartSerial.Text = string.Empty;
            dtpProductStart.Text = "01/01/2022";
            //dtpProductTo.Text = DateTime.Now.ToString("dd/MM/yyyy");
            dtpProductTo.Value = DateTime.Now;
            dtpPrintStart.Text = "01/01/2022";
            //dtpPrintTo.Text = DateTime.Now.ToString("dd/MM/yyyy");
            dtpPrintTo.Value = DateTime.Now;
            dgvReportOK.DataSource = DBNull.Value;
            blChangeOKtoNG = false;
            strUserQC = string.Empty;
            blDeleteKanban = false;
        }

        private void loadTable()
        {
            dtHistorySelect = new DataTable();
            clsUtil_MSSQL.GetDataFromTBHistoryOKSelect(RtnDbCon(), "TT_KANBAN_H", ref dtHistorySelect, Convert.ToInt32(dtpProductStart.Value.ToString("yyyyMMdd")), Convert.ToInt32(dtpProductTo.Value.ToString("yyyyMMdd")), Convert.ToInt32(dtpPrintStart.Value.ToString("yyyyMMdd")), Convert.ToInt32(dtpPrintTo.Value.ToString("yyyyMMdd")), txtPartID.Text, txtPartNO.Text, txtCustomerPartID.Text, txtCustomerPartNO.Text, txtKBSerial.Text, txtPartSerial.Text);
            dgvReportOK.DataSource = dtHistorySelect;
            dgvReportOK.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            //dgvReportOK.RowHeadersWidth = 70;

            for (int i = 0; i < dgvReportOK.Rows.Count; i++)
            {
                if (i % 2 == 0)
                {

                    dgvReportOK.Rows[i].DefaultCellStyle.BackColor = Color.WhiteSmoke;

                }
                else
                {


                }

            }

        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            loadTable();
            Cursor = Cursors.Default;
        }



        private void btnExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel File|*.xls";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string ext = System.IO.Path.GetExtension(sfd.FileName);
                switch (ext)
                {
                    case ".xls":
                        Cursor = Cursors.WaitCursor;
                        WriteToExcel(dtHistorySelect, sfd.FileName);
                        Cursor = Cursors.Default;
                        break;
                }
            }
        }


        private void WriteToExcel(System.Data.DataTable dt, string location)
        {


            //instantiate excel objects (application, workbook, worksheets)
            excel.Application XlObj = new excel.Application();
            XlObj.Visible = false;
            excel._Workbook WbObj = (excel.Workbook)(XlObj.Workbooks.Add(""));
            excel._Worksheet WsObj = (excel.Worksheet)WbObj.ActiveSheet;



            //run through datatable and assign cells to values of datatable
            try
            {
                int row = 1; int col = 1;
                foreach (DataColumn column in dt.Columns)
                {
                    //adding columns
                    WsObj.Cells[row, col] = column.ColumnName;

                    WsObj.Cells[1, col].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);

                    col++;
                }
                //reset column and row variables
                col = 1;
                row++;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //adding data
                    foreach (var cell in dt.Rows[i].ItemArray)
                    {
                        WsObj.Cells[row, col] = cell;
                        //WsObj.Columns[6].NumberFormat = "@";
                        //WsObj.Columns[8].NumberFormat = "@";
                        //WsObj.Columns[9].NumberFormat = "@";
                        //WsObj.Columns[12].NumberFormat = "@";
                        //WsObj.Columns[13].NumberFormat = "@";
                        //WsObj.Columns[14].NumberFormat = "@";
                        //WsObj.Columns[15].NumberFormat = "@";
                        //WsObj.Columns[16].NumberFormat = "@";
                        col++;
                    }
                    col = 1;
                    row++;
                }
                WsObj.Columns.AutoFit();
                WbObj.SaveAs(location);
            }
            catch (COMException x)
            {
                //ErrorHandler.Handle(x);
            }
            catch (Exception ex)
            {
                //ErrorHandler.Handle(ex);
            }
            finally
            {
                WbObj.Close();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvReportOK_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvReportOK_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

        }

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

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

        }

        private void dgvReportOK_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowindex = dgvReportOK.CurrentRow.Index;
            this.strSerialSelect = dgvReportOK[15, rowindex].Value.ToString();
            strUNITQRScan = string.Empty;
            string strModel = dgvReportOK[18, rowindex].Value.ToString();
            string strLR = dgvReportOK[19, rowindex].Value.ToString();
            string strMaxSerial = dgvReportOK[7, rowindex].Value.ToString();

            if (strSerialSelect != string.Empty)
            {
                ReSendSerialSet();

                frmNGManual frm = new frmNGManual(strSerialSelect);
                frm.ShowDialog();

                if (blChangeOKtoNG == true)
                {
                    //ReSendSerialSet();

                    //DateTime StartDate = DateTime.Now;
                    //DateTime EndDate = DateTime.Now;
                    //Double total_days = (EndDate - StartDate).TotalDays;
                    //Double total_days = 0;

                    strPCKBScan = dgvReportOK[20, rowindex].Value.ToString();
                    strPartNo = dgvReportOK[2, rowindex].Value.ToString();
                    strPartId = dgvReportOK[0, rowindex].Value.ToString();
                    strPartName = dgvReportOK[1, rowindex].Value.ToString();
                    strQPack = dgvReportOK[6, rowindex].Value.ToString().Replace(".00", "");

                    //----------Search Part Information--------------
                    dtPartSelect = new DataTable();
                    clsUtil_MSSQL.GetDataFromTBPartNoSelect(RtnDbCon(), "TM_PARTS", ref dtPartSelect, strPartNo);
                    if (dtPartSelect is not null)
                    {
                        if (dtPartSelect.Rows.Count > 0)
                        {
                            strPartID = dtPartSelect.Rows[0][1].ToString();
                            strModelShow = dtPartSelect.Rows[0][2].ToString();
                            strCode = dtPartSelect.Rows[0][3].ToString();
                            strPartName = dtPartSelect.Rows[0][4].ToString();
                            strCustomerPartName = dtPartSelect.Rows[0][5].ToString();
                            strPartNo = dtPartSelect.Rows[0][6].ToString();
                            strCustomerPartNO = dtPartSelect.Rows[0][7].ToString();
                            strQPack = dtPartSelect.Rows[0][8].ToString().Replace(".00", "");
                            strDaySet = dtPartSelect.Rows[0][10].ToString().Replace(".00", "");
                            strCustomerID = dtPartSelect.Rows[0][13].ToString();
                            strQRLength = dtPartSelect.Rows[0][12].ToString();
                            strLocation = dtPartSelect.Rows[0][21].ToString();
                            strModelStart = dtPartSelect.Rows[0][23].ToString();
                            strModelLength = dtPartSelect.Rows[0][24].ToString();
                            strDetail = dtPartSelect.Rows[0][25].ToString();
                            strDateStart = dtPartSelect.Rows[0][26].ToString();
                            strDateLength = dtPartSelect.Rows[0][27].ToString();
                            strSIDE = dtPartSelect.Rows[0][30].ToString();
                            strType = dtPartSelect.Rows[0][31].ToString();
                            strWet = dtPartSelect.Rows[0][32].ToString();
                        }
                    }

                    //clsUtil_MSSQL.insertHistoryLog(RtnDbCon(), strPCKBScan, strPartNo, strPartId, strPartNo,
                    //strPartName, Convert.ToInt32(strQPack), 0, "kg", DateTime.Now.ToString("MMM dd yyyy hh:mmtt"),
                    //DateTime.Now.ToString("MMM dd yyyy hh:mmtt"), 0.00, strUserQC, DateTime.Now.ToString("yyyyMMdd"),
                    //DateTime.Now.ToString("HHmmss"), "NG", strMSG, "STAGE2", Environment.MachineName, "");

                    //clsUtil_MSSQL.updateHoldQRScan(RtnDbCon(), "NG", strSerialSelect,
                    //                    userName, DateTime.Now.ToString("yyyyMMdd"),
                    //                    DateTime.Now.ToString("HHmmss"));

                    //strUNITQRScan = strSerialSelect.Substring(0, 19) + " "
                    //+ DateTime.Now.ToString("yyyyMMdd")
                    //+ DateTime.Now.ToString("HHmmss") + strModel + strLR + "160 ";

                    for (int i = 4; i > strProcessNo.Length; i--)
                    {
                        strProcessNo = strProcessNo + " ";
                    }

                    //-------Data Send to PLC--------
                    strUNITQRScan = strSerialSelect.Substring(0, 19) + " "
                        + DateTime.Now.ToString("yyyyMMdd")
                    //+ DateTime.Now.ToString("HHmmss") + strModel + strLR + "160 ";
                    + DateTime.Now.ToString("HHmmss") + strModel + strLR + strProcessNo;



                    if (PLCStatus.BackColor == Color.LightGreen)
                    {
                        if (blTUse == true)
                        {
                            DataWrite(strUNITQRScan, strUNITQRScan.Length, "3");
                            DataKanbanWrite(strMaxSerial, strMaxSerial.Length);
                            WriteSignalSet();

                            if (strResult1 != "OK" || strResult2 != "OK" || strResult3 != "OK")
                            {
                                MessageBox.Show(this, "เขียนข้อมูลใน PLC ไม่ได้",
                                                   "Production window", MessageBoxButtons.OK,
                                                   MessageBoxIcon.Warning,
                                                   MessageBoxDefaultButton.Button1, 0);


                                return;
                            }

                            ReadSignalSet();
                        }
                    }

                    if (PLCStatus.BackColor == Color.LightGreen)
                    {
                        if (blCSPUse == true)
                        {
                            if (DataRead() == false)
                            {
                                return;
                            }

                            if (strPLCError == "2")
                            {
                                NGShow("Traceability ข้อมูลผิดปกติ", strSerialSelect);
                                ReadSignalSet();
                                return;
                            }
                            else if (strPLCError != "1")
                            {

                                MessageBox.Show(this, "ข้อมูลจาก PLC ผิดปกติ",
                                                   "Production window", MessageBoxButtons.OK,
                                                   MessageBoxIcon.Warning,
                                                   MessageBoxDefaultButton.Button1, 0);
                                ReadSignalSet();
                                return;
                            }
                            if (strPLCOKNG == "2")
                            {
                                NGShow("Traceability ชิ้นงานข้าม Process", strSerialSelect);
                                ReadSignalSet();
                                return;
                            }
                            else if (strPLCOKNG != "1")
                            {

                                MessageBox.Show(this, "ข้อมูลจาก PLC ผิดปกติ",
                                                   "Production window", MessageBoxButtons.OK,
                                                   MessageBoxIcon.Warning,
                                                   MessageBoxDefaultButton.Button1, 0);
                                ReadSignalSet();
                                return;
                            }
                            if (blCDUse == true)
                            {
                                if (strPLCDuplicate == "2")
                                {
                                    NGShow("Traceability check Serial ซ้ำ", strSerialSelect);
                                    ReadSignalSet();
                                    return;
                                }
                                else if (strPLCDuplicate != "1")
                                {

                                    MessageBox.Show(this, "ข้อมูลจาก PLC ผิดปกติ",
                                                       "Production window", MessageBoxButtons.OK,
                                                       MessageBoxIcon.Warning,
                                                       MessageBoxDefaultButton.Button1, 0);
                                    ReadSignalSet();
                                    return;
                                }
                            }


                        }
                        else
                        {
                            if (blCDUse == true)
                            {
                                if (DataRead() == false)
                                {
                                    return;
                                }

                                if (strPLCError == "2")
                                {
                                    NGShow("Traceability ข้อมูลผิดปกติ", strSerialSelect);
                                    ReadSignalSet();
                                    return;
                                }
                                else if (strPLCError != "1")
                                {
                                    ReadSignalSet();

                                    MessageBox.Show(this, "ย้อมูลจาก PLC ผิดปกติ",
                                                       "Production window", MessageBoxButtons.OK,
                                                       MessageBoxIcon.Warning,
                                                       MessageBoxDefaultButton.Button1, 0);


                                    return;
                                }

                                if (strPLCDuplicate == "2")
                                {
                                    NGShow("Traceability check Serial ซ้ำ", strSerialSelect);
                                    ReadSignalSet();
                                    return;
                                }
                                else if (strPLCDuplicate != "1")
                                {

                                    MessageBox.Show(this, "ข้อมูลจาก PLC ผิดปกติ",
                                                       "Production window", MessageBoxButtons.OK,
                                                       MessageBoxIcon.Warning,
                                                       MessageBoxDefaultButton.Button1, 0);

                                    ReadSignalSet();
                                    return;
                                }
                            }
                        }

                    }

                    //DataWrite(strUNITQRScan, strUNITQRScan.Length, "3");
                    //WriteSignalSet();


                    //if (strResult1 != "OK" || strResult2 != "OK")
                    //{
                    //    ReadSignalSet();

                    //    MessageBox.Show(this, "เขียนข้อมูลใน PLC ไม่ได้",
                    //                       "Production window", MessageBoxButtons.OK,
                    //                       MessageBoxIcon.Warning,
                    //                       MessageBoxDefaultButton.Button1, 0);


                    //    return;
                    //}


                    //ReadSignalSet();

                    clsUtil_MSSQL.insertHistoryLog(RtnDbCon(), strPCKBScan, strPartNo, strPartId, strPartNo,
                   strPartName, Convert.ToInt32(strQPack), 0, "kg", DateTime.Now.ToString("MMM dd yyyy hh:mmtt"),
                   DateTime.Now.ToString("MMM dd yyyy hh:mmtt"), 0.00, strUserQC, DateTime.Now.ToString("yyyyMMdd"),
                   DateTime.Now.ToString("HHmmss"), "NG", strMSG, "STAGE2", Environment.MachineName, "", strSerialSelect);

                    clsUtil_MSSQL.updateHoldQRScan(RtnDbCon(), "NG", strSerialSelect,
                                        userName, DateTime.Now.ToString("yyyyMMdd"),
                                        DateTime.Now.ToString("HHmmss"));

                    MessageBox.Show(this, "เปลี่ยนข้อมูลสำเร็จ",
                                           "Production window", MessageBoxButtons.OK,
                                           MessageBoxIcon.Information,
                                           MessageBoxDefaultButton.Button1, 0);

                }
                else
                {
                    ForcedSetNoWait();
                }

            }
        }

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

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

        private bool DataRead()
        {
            strPLCSerial = string.Empty;
            strPLCOKNG = string.Empty;
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("RDS" + (char)_cmd01 + "DM2500.H" + (char)_cmd01 + "20" + (char)_cmd02, "DataRead");

            if (strPLCSerial.Substring(0, 19) == strUNITQRScan.Substring(0, 19))
            {
                System.Threading.Thread.Sleep(50);
                ExeCommandPLC("RD" + (char)_cmd01 + "DM2512.U" + (char)_cmd02, "DataReadError");
                System.Threading.Thread.Sleep(50);
                ExeCommandPLC("RD" + (char)_cmd01 + "DM2510.U" + (char)_cmd02, "DataReadOKNG");
                System.Threading.Thread.Sleep(50);
                ExeCommandPLC("RD" + (char)_cmd01 + "DM2511.U" + (char)_cmd02, "DataReadDuplicate");
                //ReadSignalSet();
                return true;
            }
            else
            {
                //System.Threading.Thread.Sleep(50);
                TRWaiting.Text = "Traceability Response Waiting......";
                //lblTRWaiting.Text = "Traceability Response Waiting......";

                var w = new Form() { Size = new Size(0, 0) };
                Task.Delay(TimeSpan.FromSeconds(0.01))
                    .ContinueWith((t) => w.Close(), TaskScheduler.FromCurrentSynchronizationContext());

                MessageBox.Show(w, "Waiting");


                DateTime startSend = DateTime.Now;
                for (int i = 0; i < 1000; i++)
                {
                    System.Threading.Thread.Sleep(50);
                    ExeCommandPLC("RDS" + (char)_cmd01 + "DM2500.H" + (char)_cmd01 + "20" + (char)_cmd02, "DataRead");
                    if (strPLCSerial.Substring(0, 19) == strUNITQRScan.Substring(0, 19))
                    {
                        System.Threading.Thread.Sleep(50);
                        ExeCommandPLC("RD" + (char)_cmd01 + "DM2512.U" + (char)_cmd02, "DataReadError");
                        System.Threading.Thread.Sleep(50);
                        ExeCommandPLC("RD" + (char)_cmd01 + "DM2510.U" + (char)_cmd02, "DataReadOKNG");
                        System.Threading.Thread.Sleep(50);
                        ExeCommandPLC("RD" + (char)_cmd01 + "DM2511.U" + (char)_cmd02, "DataReadDuplicate");
                        //ReadSignalSet();
                        TRWaiting.Text = string.Empty;
                        //lblTRWaiting.Text = string.Empty;
                      
                        return true;

                    }

                    if (i == 50)
                    {

                        DialogResult dialogResult = MessageBox.Show(this, "ท่านต้องการรอ Traceability Response ต่อหรือไม่?",
                                   "Production window", MessageBoxButtons.YesNo,
                                   MessageBoxIcon.Question,
                                   MessageBoxDefaultButton.Button1, 0);

                        if (dialogResult == DialogResult.Yes)
                        {

                            i = 0;
                        }
                        else if (dialogResult == DialogResult.No)
                        {
                            TRWaiting.Text = string.Empty;
                            //lblTRWaiting.Text = string.Empty;
                            return false;
                        }
                    }
                }

                TRWaiting.Text = string.Empty;
                //lblTRWaiting.Text = string.Empty;
                return false;

                //DateTime endSend = DateTime.Now;
                //TimeSpan ts = endSend - startSend;
                //MessageBox.Show(ts.TotalMilliseconds + " Milliseconds");
            }
            //timer2.Enabled = false;

        }

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

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

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

        private string convertScantoDateFormat(string format)
        {
            string strDate = string.Empty;
            string strMonth = string.Empty;
            string strFormat = string.Empty;
            if (format.Length == 4)
            {
                switch (format.Substring(2, 1))
                {
                    case "X":
                        strMonth = "10";
                        break;
                    case "Y":
                        strMonth = "11";
                        break;
                    case "Z":
                        strMonth = "12";
                        break;
                    default:
                        strMonth = "0" + format.Substring(2, 1);
                        break;
                }
                switch (format.Substring(3, 1))
                {
                    case "A":
                        strDate = "10";
                        break;
                    case "B":
                        strDate = "11";
                        break;
                    case "C":
                        strDate = "12";
                        break;
                    case "D":
                        strDate = "13";
                        break;
                    case "E":
                        strDate = "14";
                        break;
                    case "F":
                        strDate = "15";
                        break;
                    case "G":
                        strDate = "16";
                        break;
                    case "H":
                        strDate = "17";
                        break;
                    case "J":
                        strDate = "18";
                        break;
                    case "K":
                        strDate = "19";
                        break;
                    case "L":
                        strDate = "20";
                        break;
                    case "M":
                        strDate = "21";
                        break;
                    case "N":
                        strDate = "22";
                        break;
                    case "P":
                        strDate = "23";
                        break;
                    case "R":
                        strDate = "24";
                        break;
                    case "S":
                        strDate = "25";
                        break;
                    case "T":
                        strDate = "26";
                        break;
                    case "U":
                        strDate = "27";
                        break;
                    case "W":
                        strDate = "28";
                        break;
                    case "X":
                        strDate = "29";
                        break;
                    case "Y":
                        strDate = "30";
                        break;
                    case "Z":
                        strDate = "31";
                        break;
                    default:
                        strDate = "0" + format.Substring(3, 1);
                        break;
                }

                strFormat = "20" + format.Substring(0, 2) + strMonth + strDate;

                return strFormat;

            }
            else if (format.Length == 6)
            {
                return "20" + format;
            }
            else
            {
                return format;
            }

        }

        private void NGShow(string msg, string partserial)
        {
            try
            {

                DateTime StartDate = DateTime.Now;
                DateTime EndDate = DateTime.Now;
                Double total_days = (EndDate - StartDate).TotalDays;
                //String strDryDate = "20" + txtUNITQRScan.Text.Substring(Convert.ToInt32(strDateStart.Replace(".00", "")) - 1, Convert.ToInt32(strDateLength.Replace(".00", "")));
                String strDryDate = convertScantoDateFormat(partserial.Substring(Convert.ToInt32(strDateStart.Replace(".00", "")) - 1, Convert.ToInt32(strDateLength.Replace(".00", ""))));
                String strDryDateFull = strDryDate.Substring(0, 4) + "-" + strDryDate.Substring(4, 2) + "-" + strDryDate.Substring(6, 2);
                DateTime DryDate = Convert.ToDateTime(strDryDateFull);
                DateTime ExpDate = DryDate.AddDays(Convert.ToInt32(strDaySet));

                clsUtil_MSSQL.insertHistoryLog(RtnDbCon(), strQRKanban, strPartNo, strPartID, strPartNo,
                strPartName, Convert.ToInt32(strQPack), 0, "kg", StartDate.ToString("MMM dd yyyy hh:mmtt"),
                EndDate.ToString("MMM dd yyyy hh:mmtt"), total_days, userName, DateTime.Now.ToString("yyyyMMdd"),
                DateTime.Now.ToString("HHmmss"), "NG", msg, "STAGE2", Environment.MachineName, "", partserial);

                frmNG frm = new frmNG(msg);
                frm.ShowDialog();
            }
            catch (Exception)
            {
                //MessageBox.Show(this, "สแกนผิด QR Code",
                //                       "Production window", MessageBoxButtons.OK,
                //                       MessageBoxIcon.Warning,
                //                       MessageBoxDefaultButton.Button1, 0);

                return;
            }
        }

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

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

            //System.Threading.Thread.Sleep(1000);
            //ExeCommandPLC("RS" + (char)_cmd01 + "MR1300" + (char)_cmd02, "ForcedSet");
        }

        private void DataKanbanWrite(String strData, Int32 lenData)
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;

            //byte bytevalue;
            string serial = string.Empty;
            string lenSerial = string.Empty;

            for (int i = 0; i < strData.Length; i++)
            {
                byte[] bytes = Encoding.Default.GetBytes(strData.Substring(i, 1));

                string hexString = BitConverter.ToString(bytes);

                serial = serial + hexString;

                if (((i % 2) != 0) && (i != strData.Length - 1))
                {
                    serial = serial + (char)_cmd01;
                }

            }

            //if ((serial.Length % 2) == 1)
            //{
            //    serial = serial + "20";

            //    lenData = lenData + 1;

            //    lenData = lenData / 2;

            //    lenSerial = lenData.ToString();
            //}
            if ((lenData % 2) == 1)
            {
                serial = serial + "20";

                lenData = lenData + 1;

                lenData = lenData / 2;

                lenSerial = lenData.ToString();
            }
            else
            {
                lenData = lenData / 2;

                lenSerial = lenData.ToString();
            }



            //MessageBox.Show(serial + Environment.NewLine + lenSerial);
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("WRS" + (char)_cmd01 + "DM1524.H" + (char)_cmd01 + lenSerial + (char)_cmd01 + serial + (char)_cmd02, "DataKanbanWrite");

        }

        private void DataWrite(String strData, Int32 lenData, string strOKNG)
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;

            //byte bytevalue;
            string serial = string.Empty;
            string lenSerial = string.Empty;

            for (int i = 0; i < strData.Length; i++)
            {
                byte[] bytes = Encoding.Default.GetBytes(strData.Substring(i, 1));

                string hexString = BitConverter.ToString(bytes);

                serial = serial + hexString;

                if (((i % 2) != 0) && (i != strData.Length - 1))
                {
                    serial = serial + (char)_cmd01;
                }

            }

            //if ((serial.Length % 2) == 1)
            //{
            //    serial = serial + "20";

            //    lenData = lenData + 1;

            //    lenData = lenData / 2;

            //    lenSerial = lenData.ToString();
            //}
            if ((lenData % 2) == 1)
            {
                serial = serial + "20";

                lenData = lenData + 1;

                lenData = lenData / 2;

                lenSerial = lenData.ToString();
            }
            else
            {
                lenData = lenData / 2;

                lenSerial = lenData.ToString();
            }



            //MessageBox.Show(serial + Environment.NewLine + lenSerial);
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("WRS" + (char)_cmd01 + "DM1500.H" + (char)_cmd01 + lenSerial + (char)_cmd01 + serial + (char)_cmd02, "DataWrite");
            //System.Threading.Thread.Sleep(50);
            //ExeCommandPLC("WRS" + (char)_cmd01 + "DM1521.H" + (char)_cmd01 + "2" + (char)_cmd01 + "3136" + (char)_cmd01 + "3020" + (char)_cmd02, "DataWrite");
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("WR" + (char)_cmd01 + "DM1523.U" + (char)_cmd01 + strOKNG + (char)_cmd02, "DataWriteOKNG");

        }

        private void loadTableSettingPLC()
        {
            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;
            blReInputUse = false;

            if (dtSetting.Rows.Count > 0)
            {
                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();
                blReInputUse = Convert.ToBoolean(dtSetting.Rows[0][6].ToString());
            }
            if ((strPort == null) || (strPort == string.Empty))
            {
                strPort = "8501";
            }

            if (PLCStatus.BackColor == Color.LightGreen)
            {
                if (blTUse == true)
                {
                    ForcedSetTU();
                }
                else
                {
                    ForcedResetTU();
                }
                if (blCSPUse == true)
                {
                    ForcedSetCSP();
                }
                else
                {
                    ForcedResetCSP();
                }
                if (blCDUse == true)
                {
                    ForcedSetCD();
                }
                else
                {
                    ForcedResetCD();
                }
                if (blReInputUse == true)
                {
                    ForcedSetReInput();
                }
                else
                {
                    ForcedResetReInput();
                }
            }

        }

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

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

        private void ForcedResetReInput()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("RS" + (char)_cmd01 + "MR1004" + (char)_cmd02, "ForcedReset");
        }

        private void ForcedResetCD()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("RS" + (char)_cmd01 + "MR1002" + (char)_cmd02, "ForcedReset");
        }

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

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

        private void ForcedResetCSP()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("RS" + (char)_cmd01 + "MR1001" + (char)_cmd02, "ForcedReset");
        }

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

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

        private void ForcedResetTU()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("RS" + (char)_cmd01 + "MR1000" + (char)_cmd02, "ForcedReset");
        }

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

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

        private void ExeCommandPLC(string _CommandStr, String _CommandType)
        {

            if (PLCStatus.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 btnClear_Click(object sender, EventArgs e)
        {
            setStart();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            strUNITQRScan = string.Empty;
            strLR = string.Empty;
            strModel = string.Empty;
            strResult1 = string.Empty;
            strResult2 = string.Empty;
            blDeleteKanban = false;
            string strMaxSerial = txtKBSerial.Text;
            if (txtKBSerial.Text == string.Empty)
            {
                MessageBox.Show(this, "กรุณาใส่ 1 WAY Serial ที่จะลบก่อน",
                                       "รายงานการผลิตงาน OK", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }

            ReSendSerialSet();

            frmCancelKanban frm = new frmCancelKanban(txtKBSerial.Text, "ลบ 1 Way Kanban", "ADMINISTRATOR");
            frm.ShowDialog();

            if (blDeleteKanban == true)
            {

                //ReSendSerialSet();

                strStartDate = dtpPrintStart.ToString();

               
                        //--------------Search 1 WAY Serial Kanban---------------- 
                        dtFRMQRKANBANSelect = new DataTable();
                clsUtil_MSSQL.GetDataFromTBHistoryDeleteSelect(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, Convert.ToInt32(dtpProductStart.Value.ToString("yyyyMMdd")), Convert.ToInt32(dtpProductTo.Value.ToString("yyyyMMdd")), Convert.ToInt32(dtpPrintStart.Value.ToString("yyyyMMdd")), Convert.ToInt32(dtpPrintTo.Value.ToString("yyyyMMdd")), txtKBSerial.Text);

                if (dtFRMQRKANBANSelect is not null)
                {
                    if (dtFRMQRKANBANSelect.Rows.Count > 0)
                    {
                       
                        for (int i = 4; i > strProcessNo.Length; i--)
                        {
                            strProcessNo = strProcessNo + " ";
                        }

                        for (int i = 0; i < dtFRMQRKANBANSelect.Rows.Count; i++)
                        {
                            if (i != 0)
                            {
                                ReSendSerialSet();
                                Thread.Sleep(1000);
                            }
                            
                            //----------Search Part Information--------------
                            dtPartSelect = new DataTable();
                            clsUtil_MSSQL.GetDataFromTBPartNoSelect(RtnDbCon(), "TM_PARTS", ref dtPartSelect, dtFRMQRKANBANSelect.Rows[i][3].ToString());
                            if (dtPartSelect is not null)
                            {
                                if (dtPartSelect.Rows.Count > 0)
                                {
                                    strPartID = dtPartSelect.Rows[0][1].ToString();
                                    strModelShow = dtPartSelect.Rows[0][2].ToString();
                                    strCode = dtPartSelect.Rows[0][3].ToString();
                                    strPartName = dtPartSelect.Rows[0][4].ToString();
                                    strCustomerPartName = dtPartSelect.Rows[0][5].ToString();
                                    strPartNo = dtPartSelect.Rows[0][6].ToString();
                                    strCustomerPartNO = dtPartSelect.Rows[0][7].ToString();
                                    strQPack = dtPartSelect.Rows[0][8].ToString().Replace(".00", "");
                                    strDaySet = dtPartSelect.Rows[0][10].ToString().Replace(".00", "");
                                    strCustomerID = dtPartSelect.Rows[0][13].ToString();
                                    strQRLength = dtPartSelect.Rows[0][12].ToString();
                                    strLocation = dtPartSelect.Rows[0][21].ToString();
                                    strModelStart = dtPartSelect.Rows[0][23].ToString();
                                    strModelLength = dtPartSelect.Rows[0][24].ToString();
                                    strDetail = dtPartSelect.Rows[0][25].ToString();
                                    strDateStart = dtPartSelect.Rows[0][26].ToString();
                                    strDateLength = dtPartSelect.Rows[0][27].ToString();
                                    strSIDE = dtPartSelect.Rows[0][30].ToString();
                                    strType = dtPartSelect.Rows[0][31].ToString();
                                    strWet = dtPartSelect.Rows[0][32].ToString();
                                }
                            }

                            strSerialSelect = dtFRMQRKANBANSelect.Rows[i][16].ToString();
                            strModel = dtFRMQRKANBANSelect.Rows[i][19].ToString();
                            strQRKanban = dtFRMQRKANBANSelect.Rows[i][22].ToString();

                            for (int i1 = 0; i1 < 6; i1++)
                            {
                                if (strModel.Length == 6)
                                {
                                    break;
                                }
                                else
                                {
                                    strModel = strModel + " ";
                                }
                            }
                            strLR = " " + dtFRMQRKANBANSelect.Rows[i][20].ToString().Substring(0, 1);

                            //-------Data Send to PLC--------
                            strUNITQRScan = strSerialSelect.Substring(0, 19) + " "
                                + DateTime.Now.ToString("yyyyMMdd")
                            //+ DateTime.Now.ToString("HHmmss") + strModel + strLR + "160 ";
                            + DateTime.Now.ToString("HHmmss") + strModel + strLR + strProcessNo;


                            if (PLCStatus.BackColor == Color.LightGreen)
                            {
                                if (blTUse == true)
                                {
                                    DataWrite(strUNITQRScan, strUNITQRScan.Length, "4");
                                    DataKanbanWrite(strMaxSerial, strMaxSerial.Length);
                                    WriteSignalSet();

                                    if (strResult1 != "OK" || strResult2 != "OK" || strResult3 != "OK")
                                    {
                                        MessageBox.Show(this, "เขียนข้อมูลใน PLC ไม่ได้",
                                                           "Production window", MessageBoxButtons.OK,
                                                           MessageBoxIcon.Warning,
                                                           MessageBoxDefaultButton.Button1, 0);


                                        continue;
                                    }

                                    ReadSignalSet();
                                }
                            }

                            if (PLCStatus.BackColor == Color.LightGreen)
                            {
                                if (blCSPUse == true)
                                {
                                    if (DataRead() == false)
                                    {
                                        continue;
                                    }

                                    if (strPLCError == "2")
                                    {
                                        NGShow("Traceability ข้อมูลผิดปกติ", strSerialSelect);
                                        ReadSignalSet();
                                        //return;
                                        continue;
                                    }
                                    else if (strPLCError != "1")
                                    {

                                        MessageBox.Show(this, "ข้อมูลจาก PLC ผิดปกติ",
                                                           "Production window", MessageBoxButtons.OK,
                                                           MessageBoxIcon.Warning,
                                                           MessageBoxDefaultButton.Button1, 0);
                                        ReadSignalSet();
                                        continue;
                                    }
                                    if (strPLCOKNG == "2")
                                    {
                                        NGShow("Traceability ชิ้นงานข้าม Process", strSerialSelect);
                                        ReadSignalSet();
                                        continue;
                                    }
                                    else if (strPLCOKNG != "1")
                                    {

                                        MessageBox.Show(this, "ข้อมูลจาก PLC ผิดปกติ",
                                                           "Production window", MessageBoxButtons.OK,
                                                           MessageBoxIcon.Warning,
                                                           MessageBoxDefaultButton.Button1, 0);
                                        ReadSignalSet();
                                        continue;
                                    }
                                    if (blCDUse == true)
                                    {
                                        if (strPLCDuplicate == "2")
                                        {
                                            NGShow("Traceability check Serial ซ้ำ", strSerialSelect);
                                            ReadSignalSet();
                                            continue;
                                        }
                                        else if (strPLCDuplicate != "1")
                                        {

                                            MessageBox.Show(this, "ข้อมูลจาก PLC ผิดปกติ",
                                                               "Production window", MessageBoxButtons.OK,
                                                               MessageBoxIcon.Warning,
                                                               MessageBoxDefaultButton.Button1, 0);
                                            ReadSignalSet();
                                            continue;
                                        }
                                    }


                                }
                                else
                                {
                                    if (blCDUse == true)
                                    {
                                        if (DataRead() == false)
                                        {
                                            continue;
                                        }

                                        if (strPLCError == "2")
                                        {
                                            NGShow("Traceability ข้อมูลผิดปกติ", strSerialSelect);
                                            ReadSignalSet();
                                            continue;
                                        }
                                        else if (strPLCError != "1")
                                        {

                                            MessageBox.Show(this, "ข้อมูลจาก PLC ผิดปกติ",
                                                               "Production window", MessageBoxButtons.OK,
                                                               MessageBoxIcon.Warning,
                                                               MessageBoxDefaultButton.Button1, 0);

                                            ReadSignalSet();
                                            continue;
                                        }

                                        if (strPLCDuplicate == "2")
                                        {
                                            NGShow("Traceability check Serial ซ้ำ", strSerialSelect);
                                            ReadSignalSet();
                                            continue;
                                        }
                                        else if (strPLCDuplicate != "1")
                                        {

                                            MessageBox.Show(this, "ข้อมูลจาก PLC ผิดปกติ",
                                                               "Production window", MessageBoxButtons.OK,
                                                               MessageBoxIcon.Warning,
                                                               MessageBoxDefaultButton.Button1, 0);

                                            ReadSignalSet();
                                            continue;
                                        }
                                    }
                                }

                            }
                            
                            //DataWrite(strUNITQRScan, strUNITQRScan.Length, "4");
                            //WriteSignalSet();

                            //if (strResult1 != "OK" || strResult2 != "OK" )
                            //{
                            //    ReadSignalSet();

                            //    MessageBox.Show(this, "เขียนข้อมูลใน PLC ไม่ได้",
                            //                       "Production window", MessageBoxButtons.OK,
                            //                       MessageBoxIcon.Warning,
                            //                       MessageBoxDefaultButton.Button1, 0);


                            //    continue;
                            //}

                            //ReadSignalSet();

                            clsUtil_MSSQL.updateCancelKanban(RtnDbCon(), "Delete", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                            userName, DateTime.Now.ToString("yyyyMMdd"),
                            DateTime.Now.ToString("HHmmss"));

                            clsUtil_MSSQL.updateCancelQRScan(RtnDbCon(), "Delete", Convert.ToInt32(dtFRMQRKANBANSelect.Rows[i][1].ToString()),
                            userName, DateTime.Now.ToString("yyyyMMdd"),
                            DateTime.Now.ToString("HHmmss"));

                            MessageBox.Show(this, "Delete Kanban เรียบร้อย",
                                   "รายงานการผลิตงาน OK", MessageBoxButtons.OK,
                                   MessageBoxIcon.Information,
                                   MessageBoxDefaultButton.Button1, 0);

                            return;

                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "ไม่พบข้อมูล 1 WAY Serial ที่จะลบ",
                                       "รายงานการผลิตงาน OK", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show(this, "ไม่พบข้อมูล 1 WAY Serial ที่จะลบ",
                                   "รายงานการผลิตงาน OK", MessageBoxButtons.OK,
                                   MessageBoxIcon.Warning,
                                   MessageBoxDefaultButton.Button1, 0);
                    return;
                }

                //MessageBox.Show(this, "Delete Kanban ไม่สำเร็จ",
                //                   "รายงานการผลิตงาน OK", MessageBoxButtons.OK,
                //                   MessageBoxIcon.Information,
                //                   MessageBoxDefaultButton.Button1, 0);

            }
            else
            {
                ForcedSetNoWait();
            }

        }
    }
}
