using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Formats.Asn1;
using System.Linq;
using System.Text;
//using CsvReadWrite;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Drawing.Imaging;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Microsoft.VisualBasic;
using System.IO;
using PackingControlSystem.lib;
using lib;
using System.Drawing.Drawing2D;
//using System.Drawing.Imaging;
using System.Drawing.Text;
using TheArtOfDev.HtmlRenderer.Core;
using TheArtOfDev.HtmlRenderer.Core.Entities;
//using TheArtOfDev.HtmlRenderer.Core.Utils;
using TheArtOfDev.HtmlRenderer.WinForms.Adapters;
using TheArtOfDev.HtmlRenderer.WinForms.Utilities;
using TheArtOfDev.HtmlRenderer.WinForms;
using System.Reflection.Emit;
using System.Reflection;
using System.Security.Policy;
using TheArtOfDev.HtmlRenderer.Core.Utils;
//using SixLabors.ImageSharp;
using System.Net.Sockets;
using System.Linq.Expressions;
using System.Net.NetworkInformation;
using static System.Windows.Forms.AxHost;

namespace PackingControlSystem
{
    public partial class frmPacking : Form
    {
        private List<List<string>> Settings = new List<List<string>>();
        DataTable dtPart = new DataTable();
        DataTable dtPartSelect = new DataTable();
        private Image returnImage;
        private string partNo = string.Empty;
        private string userName = string.Empty;
        private List<string> serialScan = new List<string>();
        string[] row = new string[4];
        private int rowindex = 0;
        private string strCustomerPartName = string.Empty;
        private string strCustomerPartNO = string.Empty;
        private string strFRMSERIAL = string.Empty;
        DataTable dtTT_KANBAN_HSelect = new DataTable();
        private int rowid = 0;
        DataTable dtFRMQRKANBANSelect = new DataTable();
        DataTable dtFRMQRKANBANSelectFinish = new DataTable();
        DataTable dtFRMQRKANBANSelectPacking = new DataTable();
        DataTable dtFRMQRKANBANSelectFinishHalf = new DataTable();
        DataTable dtSerialSelect = new DataTable();
        private System.Drawing.Printing.PrintDocument printDocument;
        private string printBuffer;
        TextProcessing textProcessing;
        IniFile ini;
        string selected_preset;
        Graphics graphics;
        Rectangle rect = new Rectangle(280, 35, 20, 20);
        SolidBrush redBrush = new SolidBrush(Color.Red);
        Dictionary<String, Preset> presets = new Dictionary<string, Preset>();
        private string printerName;
        DataTable dtCustomerSelect = new DataTable();
        DataTable dtKanbanLSelect = new DataTable();
        private string strCustomerName = string.Empty;
        private string strLocation = string.Empty;
        private string strADSPartNo = string.Empty;
        private string strFGP4 = string.Empty;
        private string strQTYP7 = string.Empty;
        private string strP9 = string.Empty;
        private string strQR = string.Empty;
        private string strSIDE = string.Empty;
        private string strBOX = string.Empty;
        private string strDetail = string.Empty;
        private System.Windows.Forms.ToolStripStatusLabel printerStatus;
        private System.Windows.Forms.ToolStripStatusLabel PLCStatus;
        private System.Windows.Forms.ToolStripStatusLabel TRWaiting;
        DataTable dtSetting = new DataTable();
        DataTable dtMaxSerial = new DataTable();
        DataTable dtFRMQRKANBANSelectHold = new DataTable();
        private Int32 intMaxSerial = 0;
        private string strMaxSerial = string.Empty;
        private string strMaxSerialCut = string.Empty;
        private string strQRLength = string.Empty;
        private string strSerialSelect = string.Empty;
        public static bool blChangeOKtoNG = false;
        public static string strMSG = string.Empty;
        public static string strUserQC = string.Empty;
        private string strModelStart = string.Empty;
        private string strModelLength = string.Empty;
        private string strDateStart = string.Empty;
        private string strDateLength = 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 bool blReInputUse = false;
        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 strUNITQRScan = string.Empty;
        public string strLR = string.Empty;
        public string strModel = string.Empty;
        public string strType = string.Empty;
        public string strWet = string.Empty;
        public static string strScanWet = string.Empty;
        public string strProcessNo = string.Empty;
        public static bool blClearSerial = false;
        public string strComNo = string.Empty;
        public Int32 intRowID = 0;


        private Int32 ModelNameX = 0;
        private Int32 ModelNameY = 0;
        private Int32 ModelNameFS = 0;
        private Int32 CustomerNameX = 0;
        private Int32 CustomerNameY = 0;
        private Int32 CustomerNameFS = 0;
        private Int32 CustomerCodeX = 0;
        private Int32 CustomerCodeY = 0;
        private Int32 CustomerCodeFS = 0;
        private Int32 QtyX = 0;
        private Int32 QtyY = 0;
        private Int32 QtyFS = 0;
        private Int32 UserNameX = 0;
        private Int32 UserNameY = 0;
        private Int32 UserNameFS = 0;
        private Int32 SerialNoX = 0;
        private Int32 SerialNoY = 0;
        private Int32 SerialNoFS = 0;
        private Int32 PartNoX = 0;
        private Int32 PartNoY = 0;
        private Int32 PartNoFS = 0;
        private Int32 CustomerPartNoX = 0;
        private Int32 CustomerPartNoY = 0;
        private Int32 CustomerPartNoFS = 0;
        private Int32 LocationX = 0;
        private Int32 LocationY = 0;
        private Int32 LocationFS = 0;
        private Int32 SIDEX = 0;
        private Int32 SIDEY = 0;
        private Int32 SIDEFS = 0;
        private Int32 DateX = 0;
        private Int32 DateY = 0;
        private Int32 DateFS = 0;
        private Int32 TimeX = 0;
        private Int32 TimeY = 0;
        private Int32 TimeFS = 0;
        private Int32 QRX = 0;
        private Int32 QRY = 0;
        private Int32 QRFS = 0;
        private Int32 DetailX = 0;
        private Int32 DetailY = 0;
        private Int32 DetailFS = 0;

        private string ModelStyle = string.Empty;
        private string CustomerStyle = string.Empty;
        private string LocationStyle = string.Empty;
        private string SIDEStyle = string.Empty;
        private string QTYStyle = string.Empty;
        private string QRStyle = string.Empty;
        private string PartNameStyle = string.Empty;
        private string UserNameStyle = string.Empty;
        private string SerialStyle = string.Empty;
        private string ADSPartNoStyle = string.Empty;
        private string CustomerPartNoStyle = string.Empty;
        private string ScanDateStyle = string.Empty;
        private string ScanTimeStyle = string.Empty;
        private string DetailStyle = string.Empty;

        private Int32 intKanbanID = 0;

        private string strKanbanID = string.Empty;

        public frmPacking(string systemUserName, string printerName, System.Windows.Forms.ToolStripStatusLabel tssLabelStatus, System.Windows.Forms.ToolStripStatusLabel tssPLCStatus, System.Windows.Forms.ToolStripStatusLabel tssTRWaiting)
        {
            InitializeComponent();
            userName = systemUserName;

            // 
            // ThePrintDocument
            // 
            this.printDocument = new System.Drawing.Printing.PrintDocument();
            this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.ThePrintDocument_PrintLabel);

            graphics = base.CreateGraphics();
            graphics.FillEllipse(redBrush, rect);

            // Prepare settings from INI
            ini = new lib.IniFile("config.ini");
            selected_preset = "192.168.1.1"; // ini.Read("default", null);
            loadAllPreset(selected_preset);

            //Initialize text processing
            string input_format = ini.Read("input", selected_preset);
            char delimiter = '|'; // ini.Read("delimiter", null).ToCharArray()[0];
            textProcessing = new TextProcessing(input_format, delimiter);

            this.printerName = printerName;
            printerStatus = tssLabelStatus;
            PLCStatus = tssPLCStatus;
            TRWaiting = tssTRWaiting;

        }

        private void loadAllPreset(string defaultPreset = null)
        {
            bool isFound = false;

            // Flush old settings
            presets.Clear();
            //for (int i = menuPreset.DropDownItems.Count; i > 2; i--)
            //{
            //    menuPreset.DropDownItems.RemoveAt(i - 1);
            //}

            foreach (string preset_id in ini.Read("preset", null).Split(','))
            {
                try
                {
                    // Update menu
                    //ToolStripMenuItem menu = new ToolStripMenuItem(preset_id
                    //    , null, presetSelect_Click);
                    if (preset_id.Equals(defaultPreset))
                    {
                        //menu.Checked = true;
                        isFound = true;

                        //log("Info: preset found, use " + preset_id + " as default preset.");
                        selected_preset = preset_id;

                        // Update printer
                        //searchPrinters(ini.Read("printer", preset_id));
                    }
                    //menuPreset.DropDownItems.Add(menu);

                    // Keep loaded preset settings
                    presets.Add(preset_id,
                        new Preset(
                        preset_id,
                        ini.Read("printer", preset_id),
                        ini.Read("template", preset_id),
                        ini.Read("width", preset_id),
                        ini.Read("height", preset_id),
                        ini.Read("input", preset_id)
                        ));
                }
                catch (Exception e)
                {

                }
            }

            if (defaultPreset != null && !isFound)
            {
                //log("Error: default preset not found!, please choose the new one.");
            }
        }



        private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
                printDocument.PrinterSettings.PrinterName = this.printerName;
                printPreviewDialog1.Document = this.printDocument;
                printPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D;
                printPreviewDialog1.ShowDialog();

                printPreviewDialog1.PrintPreviewControl.Zoom = 200 / 100f;
                (printPreviewDialog1 as Form).WindowState = FormWindowState.Maximized;
            }
            catch (Exception exp)
            {
                System.Console.WriteLine(exp.Message.ToString());
            }
        }

        protected void ThePrintDocument_PrintLabel(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
        {

            SolidBrush myBrush = new SolidBrush(Color.Black);

            Size size = new Size(700, 500);

            //HTML render
            //Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(printBuffer);

            Image image = RenderToImage(printBuffer, size, Color.White, null);


            Rectangle rect = new Rectangle(0, 0, Int32.Parse("700"), Int32.Parse("500"));
            ev.Graphics.DrawImage(image, rect);

            ev.HasMorePages = false;

            myBrush.Dispose();

        }

        public static Image RenderToImage(string html, Size size, Color backgroundColor = new Color(), CssData cssData = null,
            EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad = null, EventHandler<HtmlImageLoadEventArgs> imageLoad = null)
        {
            if (backgroundColor == Color.Transparent)
                throw new ArgumentOutOfRangeException("backgroundColor", "Transparent background in not supported");

            // create the final image to render into
            var image = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb);

            if (!string.IsNullOrEmpty(html))
            {
                // create memory buffer from desktop handle that supports alpha channel
                IntPtr dib;
                var memoryHdc = Win32Utils.CreateMemoryHdc(IntPtr.Zero, image.Width, image.Height, out dib);
                try
                {
                    // create memory buffer graphics to use for HTML rendering
                    using (var memoryGraphics = Graphics.FromHdc(memoryHdc))
                    {
                        memoryGraphics.Clear(backgroundColor != Color.Empty ? backgroundColor : Color.White);

                        // render HTML into the memory buffer
                        RenderHtml(memoryGraphics, html, PointF.Empty, size, cssData, true, stylesheetLoad, imageLoad);
                    }

                    // copy from memory buffer to image
                    CopyBufferToImage(memoryHdc, image);
                }
                finally
                {
                    Win32Utils.ReleaseMemoryHdc(memoryHdc, dib);
                }
            }

            return image;
        }

        private static void CopyBufferToImage(IntPtr memoryHdc, Image image)
        {
            using (var imageGraphics = Graphics.FromImage(image))
            {
                var imgHdc = imageGraphics.GetHdc();
                Win32Utils.BitBlt(imgHdc, 0, 0, image.Width, image.Height, memoryHdc, 0, 0, Win32Utils.BitBltCopy);
                imageGraphics.ReleaseHdc(imgHdc);
            }
        }

        private static SizeF RenderHtml(Graphics g, string html, PointF location, SizeF maxSize, CssData cssData, bool useGdiPlusTextRendering, EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad, EventHandler<HtmlImageLoadEventArgs> imageLoad)
        {
            SizeF actualSize = SizeF.Empty;

            if (!string.IsNullOrEmpty(html))
            {
                using (var container = new HtmlContainer())
                {
                    container.Location = location;
                    container.MaxSize = maxSize;
                    container.AvoidAsyncImagesLoading = true;
                    container.AvoidImagesLateLoading = true;
                    container.UseGdiPlusTextRendering = useGdiPlusTextRendering;

                    if (stylesheetLoad != null)
                        container.StylesheetLoad += stylesheetLoad;
                    if (imageLoad != null)
                        container.ImageLoad += imageLoad;

                    container.SetHtml(html, cssData);
                    container.PerformLayout(g);
                    container.PerformPaint(g);

                    actualSize = container.ActualSize;
                }
            }

            return actualSize;
        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        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 frmPacking_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            if (PLCStatus.BackColor == Color.LightGreen)
            {
                pnlPLC.BackColor = Color.LightGreen;
            }
            else
            {
                pnlPLC.BackColor = Color.Red;
            }

            List<string> tmp = null;
            dgvScanPacking.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

            strComNo = this.Settings[1][2];

            if (strComNo.Length == 1)
            {
                strComNo = "0" + strComNo;
            }

            SettxtStart();

            loadTableSetting();

            loadTableSettingPLC();

            //loadTest();

        }

        private void loadTest()
        {
            btnTestPrint.Visible = true;
            //btnForcedSet.Visible = true;
            //btnForcedReset.Visible = true;
            //btnDataRead.Visible = true;
            //btnDataWrite.Visible = true;
            //txttoHex.Visible = true;
        }

        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 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 SettxtStart()
        {
            lblPartNo.Text = string.Empty;
            lblCustomerID.Text = string.Empty;
            lblCode.Text = string.Empty;
            lblPartID.Text = string.Empty;
            lblPartName.Text = string.Empty;
            lblModelShow.Text = string.Empty;
            lblQPack.Text = "0";
            lblDaySet.Text = string.Empty;
            lblExpireDate.Text = string.Empty;
            strCustomerPartName = string.Empty;
            strCustomerPartNO = string.Empty;
            strFRMSERIAL = string.Empty;
            lblSIDE.Text = string.Empty;
            rowid = 0;
            strPLCOKNG = string.Empty;
            strPLCSerial = string.Empty;
            strResult1 = string.Empty;
            strResult2 = string.Empty;
            strResult3 = string.Empty;
            TableClear();
            TRWaiting.Text = string.Empty;
            lblTRWaiting.Text = string.Empty;
            strBOX = string.Empty;
            lblBox.Text = string.Empty;
            strUserQC = string.Empty;
            blClearSerial = false;
            pbPart.Image = null;
            strScanWet = string.Empty;
        }

        private void SettxtClear()
        {
            lblPartNo.Text = string.Empty;
            lblCustomerID.Text = string.Empty;
            lblCode.Text = string.Empty;
            lblPartID.Text = string.Empty;
            lblPartName.Text = string.Empty;
            lblModelShow.Text = string.Empty;
            lblQPack.Text = "0";
            lblDaySet.Text = string.Empty;
            lblExpireDate.Text = string.Empty;
            strCustomerPartName = string.Empty;
            strCustomerPartNO = string.Empty;
            strFRMSERIAL = string.Empty;
            lblSIDE.Text = string.Empty;
            rowid = 0;
            strPLCOKNG = string.Empty;
            strPLCSerial = string.Empty;
            strResult1 = string.Empty;
            strResult2 = string.Empty;
            strResult3 = string.Empty;
            TRWaiting.Text = string.Empty;
            lblTRWaiting.Text = string.Empty;
            strBOX = string.Empty;
            lblBox.Text = string.Empty;
            strUserQC = string.Empty;
            blClearSerial = false;
            pbPart.Image = null;
            strScanWet = string.Empty;
        }

        private void txtPCKBScan_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtPCKBScan_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void txtPCKBScan_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            string strID = string.Empty;


            // Check if User Presses Enter
            if (e.KeyCode == System.Windows.Forms.Keys.Return)
            {
                // Here: user pressed ENTER key

                txtPCKBScan.Text = txtPCKBScan.Text.ToUpper();

                List<string> tmp;
                tmp = new List<string>();
                tmp = txtPCKBScan.Text.Split("$").ToList();
                Int32 intAllQty = 0;
                Int32 intQtyperBox = 0;



                //ADSMT$13253527$113040-35090$FG$$$6$$0$30/1/2023

                if (tmp.Count < 10)
                {
                    MessageBox.Show(this, "สแกนผิด QR Code",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);

                    txtPCKBScan.Focus();
                    txtPCKBScan.SelectAll();


                    return;
                }

                //if (tmp[0] != "ADSMT")
                //{
                //    MessageBox.Show(this, "สแกนผิด QR Code",
                //                       "Production window", MessageBoxButtons.OK,
                //                       MessageBoxIcon.Warning,
                //                       MessageBoxDefaultButton.Button1, 0);

                //    txtPCKBScan.Focus();
                //    txtPCKBScan.SelectAll();


                //    return;
                //}


                //-------------Select Kanban Packing--------------------
                dtFRMQRKANBANSelectFinish = new DataTable();
                clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_StatusTop1(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelectFinish);
                if (dtFRMQRKANBANSelectFinish is not null)
                {
                    if (dtFRMQRKANBANSelectFinish.Rows.Count > 0)
                    {
                        strKanbanID = dtFRMQRKANBANSelectFinish.Rows[0][2].ToString();
                        if ((dtFRMQRKANBANSelectFinish.Rows[0][1].ToString() == "Packing") || (dtFRMQRKANBANSelectFinish.Rows[0][1].ToString() == "Printed"))
                        {
                            if (dtFRMQRKANBANSelectFinish.Rows[0][0].ToString() != txtPCKBScan.Text)
                            {
                                MessageBox.Show(this, "ให้สแกน Kanban ที่ยัง Packing ไม่เสร็จ",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);

                                txtPCKBScan.Focus();
                                txtPCKBScan.SelectAll();


                                return;
                            }
                        }
                    }
                }

                //-----------Select Kanban Hold----------------
                dtFRMQRKANBANSelectHold = new DataTable();
                clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelectHold(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelectHold, txtPCKBScan.Text);
                if (dtFRMQRKANBANSelectHold is not null)
                {
                    if (dtFRMQRKANBANSelectHold.Rows.Count > 0)
                    {
                        strKanbanID = dtFRMQRKANBANSelectHold.Rows[0][1].ToString();
                        for (int i = 0; i < dtFRMQRKANBANSelectHold.Rows.Count; i++)
                        {
                            if (dtFRMQRKANBANSelectHold.Rows[i][2].ToString() == "HoldPacking")
                            {
                                clsUtil_MSSQL.updatePackingHoldKanban(RtnDbCon(), "Packing",
                                            userName, DateTime.Now.ToString("yyyyMMdd"),
                                            DateTime.Now.ToString("HHmmss"), "HoldPacking", txtPCKBScan.Text);

                                clsUtil_MSSQL.updatePackingHoldQRScan(RtnDbCon(), "",
                                userName, DateTime.Now.ToString("yyyyMMdd"),
                                DateTime.Now.ToString("HHmmss"), "HoldPacking", Convert.ToInt32(strKanbanID));
                            }
                            else if (dtFRMQRKANBANSelectHold.Rows[i][2].ToString() == "HoldPrinted")
                            {
                                clsUtil_MSSQL.updatePackingHoldKanban(RtnDbCon(), "Printed",
                                            userName, DateTime.Now.ToString("yyyyMMdd"),
                                            DateTime.Now.ToString("HHmmss"), "HoldPrinted", txtPCKBScan.Text);

                                clsUtil_MSSQL.updatePackingHoldQRScan(RtnDbCon(), "",
                                userName, DateTime.Now.ToString("yyyyMMdd"),
                                DateTime.Now.ToString("HHmmss"), "HoldPrinted", Convert.ToInt32(strKanbanID));
                            }
                        }
                    }
                }

                //----------Select Kanban Half Day---------------              
                dtFRMQRKANBANSelect = new DataTable();
                //clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, txtPCKBScan.Text);
                clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Temp(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, txtPCKBScan.Text);

                dtFRMQRKANBANSelectFinishHalf = new DataTable();
                clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Finish_Half(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelectFinishHalf, txtPCKBScan.Text);

                strFRMSERIAL = tmp[1];
                strADSPartNo = tmp[2];
                strFGP4 = tmp[3];
                strQTYP7 = tmp[6];
                strP9 = tmp[8];

                intAllQty = Convert.ToInt32(strQTYP7);

                //------------Select Part Information--------------
                dtPartSelect = new DataTable();
                clsUtil_MSSQL.GetDataFromTBPartNoSelect(RtnDbCon(), "TM_PARTS", ref dtPartSelect, tmp[2]);
                if (dtPartSelect is not null)
                {
                    if (dtPartSelect.Rows.Count > 0)
                    {

                        lblPartID.Text = dtPartSelect.Rows[0][1].ToString();
                        lblModelShow.Text = dtPartSelect.Rows[0][2].ToString();
                        //txtModel.Text = dtPartSelect.Rows[0][2].ToString();
                        lblCode.Text = dtPartSelect.Rows[0][3].ToString();
                        lblPartName.Text = dtPartSelect.Rows[0][4].ToString();
                        strCustomerPartName = dtPartSelect.Rows[0][5].ToString();
                        lblPartNo.Text = dtPartSelect.Rows[0][6].ToString();
                        strCustomerPartNO = dtPartSelect.Rows[0][7].ToString();
                        lblQPack.Text = dtPartSelect.Rows[0][8].ToString().Replace(".00", "");
                        //nudCircleTime.Text = dtPartSelect.Rows[0][9].ToString();
                        lblDaySet.Text = dtPartSelect.Rows[0][10].ToString().Replace(".00", "");
                        //nudWetLifeTime.Text = dtPartSelect.Rows[0][11].ToString();
                        lblCustomerID.Text = dtPartSelect.Rows[0][13].ToString();
                        strQRLength = dtPartSelect.Rows[0][12].ToString();
                        //txtLocation.Text = dtPartSelect.Rows[0][21].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();
                        //txtPackaging.Text = dtPartSelect.Rows[0][22].ToString();
                        strSIDE = dtPartSelect.Rows[0][30].ToString();
                        strType = dtPartSelect.Rows[0][31].ToString();
                        strWet = dtPartSelect.Rows[0][32].ToString();
                        lblSIDE.Text = strSIDE;

                        if (strType == "Wet")
                        {
                            frmScanQR2 frm = new frmScanQR2(strWet);
                            frm.ShowDialog();

                            if (strScanWet == string.Empty)
                            {
                                SettxtStart();
                                txtPCKBScan.Text = string.Empty;
                                return;
                            }

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

                            //clsUtil_MSSQL.insertHistoryLog(RtnDbCon(), txtPCKBScan.Text, lblPartNo.Text, lblPartID.Text, lblPartNo.Text,
                            //lblPartName.Text, 0, 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"), "OK", strScanWet, "STAGE1", Environment.MachineName, "ScanQR2");
                        }



                        intQtyperBox = Convert.ToInt32(lblQPack.Text);

                        strBOX = Convert.ToString(intAllQty / intQtyperBox);

                        if (strBOX == "0")
                        {
                            MessageBox.Show(this, "จำนวน Part Serial ทั้งหมดใน Kanban น้อยกว่าจำนวน Part Serial ต่อ Box",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);

                            txtPCKBScan.Focus();
                            txtPCKBScan.SelectAll();


                            return;
                        }

                        dtCustomerSelect = new DataTable();
                        clsUtil_MSSQL.GetDataFromTBCustomerSelect(RtnDbCon(), "TM_CUSTOMER", ref dtCustomerSelect, lblCustomerID.Text);

                        strCustomerName = dtCustomerSelect.Rows[0][2].ToString();



                        pbPart.Image = null;

                        if (dtPartSelect.Rows[0][28] != System.DBNull.Value)
                        {
                            pbPart.Image = byteArrayToImage((byte[])dtPartSelect.Rows[0][28]);
                        }

                        TableShow();

                        for (int i = 0; i < Convert.ToInt32(lblQPack.Text); i++)
                        {
                            row = new string[] { string.Empty, string.Empty, string.Empty, string.Empty };
                            dgvScanPacking.Rows.Add(row);
                        }

                        //loadTableSerial();

                        //-------------------Hide for Customer use Kanban Test-------------------------
                        if (dtFRMQRKANBANSelectFinishHalf.Rows.Count > 0)
                        {
                            NGShowSTAGE1("PC Kanban นี้สแกนครบแล้วในครึ่งวันนี้", "NG: PC Kanban นี้สแกนครบแล้วในครึ่งวันนี้");

                            dgvScanPacking.Rows.Clear();

                            SettxtClear();

                            txtPCKBScan.ReadOnly = false;
                            txtPCKBScan.BackColor = Color.Yellow;
                            txtPCKBScan.Focus();

                            return;
                        }
                        //-----------------------------------------------------------------------------

                        //----------Send PLC SIDE of Part Information-----------
                        if (strSIDE == "LH")
                        {
                            WriteSetLH();
                        }
                        else if (strSIDE == "RH")
                        {
                            WriteSetRH();
                        }
                        //-------------------------------------------------


                        txtPCKBScan.ReadOnly = true;
                        txtPCKBScan.BackColor = Color.YellowGreen;

                        txtUNITQRScan.Focus();

                        lblScan.Text = "Scan UNIT QR Code";


                    }
                    //else if (dtPartSelect.Rows.Count > 1)
                    //{
                    //    frmScanQR2 frm = new frmScanQR2();
                    //    frm.ShowDialog();



                    //}
                    else
                    {
                        //frmScanQR2 frm = new frmScanQR2();
                        //frm.ShowDialog();

                        NGShowSTAGE1("ไม่มี Master Part ในระบบ", "NG: ไม่มี Master Part ในระบบ");

                        return;
                    }

                }
                else
                {
                    //frmScanQR2 frm = new frmScanQR2();
                    //frm.ShowDialog();

                    NGShowSTAGE1("ไม่มี Master Part ในระบบ", "NG: ไม่มี Master Part ในระบบ");

                    return;
                }

                lblBox.Text = dtFRMQRKANBANSelect.Rows.Count.ToString() + " / " + strBOX;

                //-------------------Hide for Customer use Kanban Test-------------------------
                //if (dtFRMQRKANBANSelectFinishHalf.Rows.Count > 0)
                //{
                //    NGShowSTAGE1("PC Kanban นี้สแกนครบแล้วในครึ่งวันนี้", "NG: PC Kanban นี้สแกนครบแล้วในครึ่งวันนี้");

                //    dgvScanPacking.Rows.Clear();

                //    SettxtClear();

                //    txtPCKBScan.ReadOnly = false;
                //    txtPCKBScan.BackColor = Color.Yellow;
                //    txtPCKBScan.Focus();

                //    return;
                //}
                //-----------------------------------------------------------------------------

                strID = string.Empty;

                dtFRMQRKANBANSelectPacking = new DataTable();
                clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Packing(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelectPacking, txtPCKBScan.Text);


                if (dtFRMQRKANBANSelectPacking is not null)
                {
                    if (dtFRMQRKANBANSelectPacking.Rows.Count > 0)
                    {
                        if (dtFRMQRKANBANSelectPacking.Rows[0][2].ToString() == "Packing")
                        {
                            strID = dtFRMQRKANBANSelectPacking.Rows[0][1].ToString();

                        }
                    }
                    else { strID = string.Empty; }

                }
                else
                {
                    strID = string.Empty;
                }

                if (strID != string.Empty)
                {

                    dtKanbanLSelect = new DataTable();
                    clsUtil_MSSQL.GetDataFromTBTT_KANBAN_L_ID(RtnDbCon(), "TT_KANBAN_L", ref dtKanbanLSelect, strID);

                    if (dtKanbanLSelect is not null)
                    {
                        if (dtKanbanLSelect.Rows.Count > 0)
                        {
                            for (int i = 0; i < dtKanbanLSelect.Rows.Count; i++)
                            {
                                dgvScanPacking[0, i].Value = dtKanbanLSelect.Rows[0][0].ToString();
                                dgvScanPacking[1, i].Value = dtKanbanLSelect.Rows[0][1].ToString();
                                dgvScanPacking[2, i].Value = dtKanbanLSelect.Rows[0][2].ToString();
                                dgvScanPacking[3, i].Value = "OK";
                                dgvScanPacking[3, i].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                                dgvScanPacking[3, i].Style.BackColor = Color.LightGreen;
                                                                
                            }
                        }

                    }


                }




            }
            else
            {
                // Here: user did not press ENTER key
            }
        }

        public bool IsNumeric(string value)
        {
            return value.All(char.IsNumber);
        }

        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");
        }

        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            System.Drawing.Bitmap bitmap = null;
            ImageConverter converter = new ImageConverter();
            System.Drawing.Image img =
            (System.Drawing.Image)converter.ConvertFrom(byteArrayIn);
            bitmap = (System.Drawing.Bitmap)img;
            return bitmap;
        }

        private bool CheckConvertScantoMonthFormat(string format)
        {
            switch (format.Substring(2, 1))
            {
                case "X":
                    return true;
                case "Y":
                    return true;
                case "Z":
                    return true;
                case "1":
                    return true;
                case "2":
                    return true;
                case "3":
                    return true;
                case "4":
                    return true;
                case "5":
                    return true;
                case "6":
                    return true;
                case "7":
                    return true;
                case "8":
                    return true;
                case "9":
                    return true;
                default:
                    return false;
            }
        }

        private bool CheckConvertScantoDateFormat(string format)
        {

            if (CheckConvertScantoMonthFormat(format) == false)
            {
                return false;
            }

            switch (format.Substring(3, 1))
            {
                case "A":
                    return true;
                case "B":
                    return true;
                case "C":
                    return true;
                case "D":
                    return true;
                case "E":
                    return true;
                case "F":
                    return true;
                case "G":
                    return true;
                case "H":
                    return true;
                case "J":
                    return true;
                case "K":
                    return true;
                case "L":
                    return true;
                case "M":
                    return true;
                case "N":
                    return true;
                case "P":
                    return true;
                case "R":
                    return true;
                case "S":
                    return true;
                case "T":
                    return true;
                case "U":
                    return true;
                case "W":
                    return true;
                case "X":
                    return true;
                case "Y":
                    return true;
                case "Z":
                    return true;
                case "1":
                    return true;
                case "2":
                    return true;
                case "3":
                    return true;
                case "4":
                    return true;
                case "5":
                    return true;
                case "6":
                    return true;
                case "7":
                    return true;
                case "8":
                    return true;
                case "9":
                    return true;
                default:
                    return false;
            }
        }

        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 txtUNITQRScan_TextChanged(object sender, EventArgs e)
        {

        }


        private void txtUNITQRScan_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            byte _cmd00 = 0x00;
            strUNITQRScan = string.Empty;
            strLR = string.Empty;
            strModel = string.Empty;
            strResult1 = string.Empty;
            strResult2 = string.Empty;
            intRowID = -99;
            // Check if User Presses Enter
            if (e.KeyCode == System.Windows.Forms.Keys.Return)
            {

                //txtUNITQRScan.Text = string.Empty;

                //txtUNITQRScan.Text = "478170CO40233X AFFGG_R";

                //txtUNITQRScan.Text = "478170CO48233XAFFGG";

                txtUNITQRScan.Text = txtUNITQRScan.Text.ToUpper();

                strSerialSelect = txtUNITQRScan.Text;

                if (lblSIDE.Text.Trim() != string.Empty)
                {
                    strLR = " " + lblSIDE.Text.Substring(0, 1);
                }
                else
                {
                    MessageBox.Show(this, "ยังไม่ได้ตั้งค่า SIDE ใน Part Information",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);

                    return;

                }

                strModel = lblCode.Text;

                for (int i = 0; i < 6; i++)
                {
                    if (strModel.Length == 6)
                    {
                        break;
                    }
                    else
                    {
                        strModel = strModel + " ";
                    }
                }


                if (txtUNITQRScan.Text.Length != 19)
                {
                    MessageBox.Show(this, "จำนวนตัวอักษรใน QR Code ไม่เท่ากับ 19 ตัวอักษร",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);

                    txtUNITQRScan.SelectAll();
                    txtUNITQRScan.Focus();

                    return;
                }


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

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

                //strUNITQRScan = txtUNITQRScan.Text.Substring(0, 19) + (char)_cmd00
                //    + 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, "1");
                        DataKanbanWrite(strMaxSerial, strMaxSerial.Length);
                        WriteSignalSet();
                    }
                    else
                    {

                    }

                }

                //DataWrite(strUNITQRScan, strUNITQRScan.Length, "1");


                
                if (strResult1 != "OK" || strResult2 != "OK" || strResult3 != "OK")
                {
                    MessageBox.Show(this, "Write Data PLC Error",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);

                    return;
                }

                
                if (PLCStatus.BackColor == Color.LightGreen)
                {
                    if (blCSPUse == true)
                    {
                        if (DataRead() == false)
                        {
                            txtUNITQRScan.Text = string.Empty;
                            txtUNITQRScan.Focus();
                        }
                        else
                        {
                            MessageBox.Show(convertScantoDateFormat(txtUNITQRScan.Text.Substring(10, 4))
                    + Environment.NewLine + strResult1 + " | " + strResult2 + " | " + strResult3
                     + Environment.NewLine + strPLCSerial.Substring(0, 10) + " | " + strPLCError
                     + " | " + strPLCOKNG + " | " + strPLCDuplicate);
                        }
                    }
                    else
                    {

                    }
                }
                */


                if ((txtUNITQRScan.Text.Substring(Convert.ToInt32(strModelStart) - 1, Convert.ToInt32(strModelLength))
                    == strCustomerPartNO.Replace("-", "")) && (serialSearch(txtUNITQRScan.Text.Trim()) == false))
                {
                    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", "")));
                    if (CheckConvertScantoDateFormat(txtUNITQRScan.Text.Substring(Convert.ToInt32(strDateStart.Replace(".00", "")) - 1, Convert.ToInt32(strDateLength.Replace(".00", "")))) == false)
                    {
                        MessageBox.Show(this, "ข้อมูลวันที่ของ Serial ไม่ถูกต้อง!!!",
                                                   "Production window", MessageBoxButtons.OK,
                                                   MessageBoxIcon.Warning,
                                                   MessageBoxDefaultButton.Button1, 0);

                        txtUNITQRScan.Text = string.Empty;
                        txtUNITQRScan.Focus();

                        return;
                    }
                    String strDryDate = convertScantoDateFormat(txtUNITQRScan.Text.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(lblDaySet.Text));
                    DateOnly StartDateOnly = DateOnly.FromDateTime(StartDate);
                    DateOnly ExpDateOnly = DateOnly.FromDateTime(ExpDate);

                    lblExpireDate.Text = ExpDate.ToString("dd/MM/yyyy");

                    if ((ExpDateOnly < StartDateOnly) && (Convert.ToInt32(lblDaySet.Text) != 0))
                    {

                        DataWrite(strUNITQRScan, strUNITQRScan.Length, "2");
                        WriteSignalSet();
                        NGShow("ชิ้นงานหมดอายุการใช้งานแล้ว", txtUNITQRScan.Text);
                        ReadSignalSet();
                        return;
                    }


                    if (PLCStatus.BackColor == Color.LightGreen)
                    {
                        if (blTUse == true)
                        {
                            SearchRowTable();
                            if (rowindex == 0)
                            {
                                loadSerial();
                            }
                            else
                            {
                                loadSerialLast(txtPCKBScan.Text);
                            }

                            DataWrite(strUNITQRScan, strUNITQRScan.Length, "1");
                            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);

                                txtUNITQRScan.Text = string.Empty;
                                txtUNITQRScan.Focus();

                                return;
                            }


                            if (DataRead() == false)
                            {
                                txtUNITQRScan.Text = string.Empty;
                                txtUNITQRScan.Focus();
                                return;
                            }

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

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

                                ForcedSetNoWait();
                                txtUNITQRScan.Text = string.Empty;
                                txtUNITQRScan.Focus();

                                return;
                            }



                        }
                    }

                    if (PLCStatus.BackColor == Color.LightGreen)
                    {
                        if (blCSPUse == true)
                        {
                            //if (DataRead() == false)
                            //{
                            //    txtUNITQRScan.Text = string.Empty;
                            //    txtUNITQRScan.Focus();
                            //    return;
                            //}

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

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

                            //    txtUNITQRScan.Text = string.Empty;
                            //    txtUNITQRScan.Focus();

                            //    return;
                            //}
                            if (strPLCOKNG == "2")
                            {
                                //DataWrite(strUNITQRScan, strUNITQRScan.Length, "9");


                                NGShow("Traceability ชิ้นงานข้าม Process", txtUNITQRScan.Text);
                                ReadSignalSet();
                                return;
                            }
                            else if (strPLCOKNG != "1")
                            {

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

                                return;
                            }
                            if (blCDUse == true)
                            {
                                if (strPLCDuplicate == "2")
                                {
                                    //DataWrite(strUNITQRScan, strUNITQRScan.Length, "9");

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

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

                                    return;
                                }
                            }


                        }
                        else
                        {
                            if (blCDUse == true)
                            {
                                //if (DataRead() == false)
                                //{
                                //    txtUNITQRScan.Text = string.Empty;
                                //    txtUNITQRScan.Focus();
                                //    return;
                                //}

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

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

                                //    txtUNITQRScan.Text = string.Empty;
                                //    txtUNITQRScan.Focus();

                                //    return;
                                //}

                                if (strPLCDuplicate == "2")
                                {
                                    //DataWrite(strUNITQRScan, strUNITQRScan.Length, "9");
                                    NGShow("Traceability check Serial ซ้ำ", txtUNITQRScan.Text);
                                    ReadSignalSet();
                                    return;
                                }
                                else if (strPLCDuplicate != "1")
                                {

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

                                    return;
                                }
                            }
                        }

                    }

                    ReadSignalSet();

                    WriteSignalOK();

                    clsUtil_MSSQL.insertHistoryLog(RtnDbCon(), txtPCKBScan.Text, lblPartNo.Text, lblPartID.Text, lblPartNo.Text,
                    lblPartName.Text, Convert.ToInt32(lblQPack.Text), 0, "kg", DryDate.ToString("dd/MM/yyyy"),
                    ExpDate.ToString("dd/MM/yyyy"), total_days, userName, DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"), "OK", "", "", Environment.MachineName, "", txtUNITQRScan.Text);

                    dgvScanPacking[0, SearchRowTable()].Value = txtUNITQRScan.Text.Trim();
                    dgvScanPacking[1, rowindex].Value = DryDate.ToString("yyyyMMdd");
                    dgvScanPacking[2, rowindex].Value = ExpDate.ToString("yyyyMMdd");
                    dgvScanPacking[3, rowindex].Value = "OK";
                    dgvScanPacking[3, rowindex].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    dgvScanPacking[3, rowindex].Style.BackColor = Color.LightGreen;

                    //lblExpireDate.Text = string.Empty;

                    //New Function บันทึกตั้งแต่ตอนสแกน Part แรกของกล่อง                   
                    if (rowindex == 0)
                    {

                        loadSerial();

                        string strFinish = string.Empty;
                        strFinish = "Packing";

                        clsUtil_MSSQL.insertTT_KANBAN_H(RtnDbCon(), lblPartNo.Text, lblPartName.Text, lblModelShow.Text, lblCode.Text,
                        lblPartID.Text, lblCustomerID.Text, strCustomerPartNO, strCustomerPartNO, strCustomerPartName,
                        string.Empty, string.Empty, strLocation, string.Empty, string.Empty,
                        Convert.ToInt32(lblQPack.Text), "PCS", strMaxSerial,
                        strQR,
                        strFRMSERIAL, txtPCKBScan.Text, "FG", userName, DateTime.Now.ToString("yyyyMMdd"),
                        DateTime.Now.ToString("HHmmss"), "Y", userName, DateTime.Now.ToString("yyyyMMdd"),
                        DateTime.Now.ToString("HHmmss"), userName, DateTime.Now.ToString("yyyyMMdd"),
                        DateTime.Now.ToString("HHmmss"), "0", strSIDE, strFinish, strScanWet, strDetail, 0, 0);
                    }

                    loadSerialLast(txtPCKBScan.Text);

                    dtTT_KANBAN_HSelect = new DataTable();
                    clsUtil_MSSQL.GetDataFromTBSelectTT_KANBAN_HMaxID(RtnDbCon(), "TT_KANBAN_H", ref dtTT_KANBAN_HSelect);
                    rowid = Convert.ToInt32(dtTT_KANBAN_HSelect.Rows[0][0].ToString());                    

                    clsUtil_MSSQL.insertTT_KANBAN_L(RtnDbCon(), rowid, lblPartNo.Text, lblPartName.Text, lblModelShow.Text, lblCode.Text,
                    lblPartID.Text, string.Empty, strMaxSerial, dgvScanPacking[0, rowindex].Value.ToString(),
                    Convert.ToInt64(dgvScanPacking[1, rowindex].Value.ToString()), dgvScanPacking[2, rowindex].Value.ToString(),
                    "Y", userName, DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"), userName, DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"), string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, 0, 0);


                    dtFRMQRKANBANSelect = new DataTable();
                    //clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, txtPCKBScan.Text);//Use Half Day
                    clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_TempH(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, txtPCKBScan.Text);//Not Use Half Day

                    if (dtFRMQRKANBANSelect.Rows.Count > 0)
                    {
                        lblBox.Text = dtFRMQRKANBANSelect.Rows.Count.ToString() + " / " + strBOX;
                    }
                    else
                    {
                        dtFRMQRKANBANSelect = new DataTable();
                        //clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, txtPCKBScan.Text);//Use Half Day
                        clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect_Temp(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, txtPCKBScan.Text);//Not Use Half Day

                    }

                    lblBox.Text = dtFRMQRKANBANSelect.Rows.Count.ToString() + " / " + strBOX;

                    if (dgvScanPacking.Rows.Count == rowindex + 1)
                    {
                        Cursor = Cursors.WaitCursor;

                        loadSerialLast(txtPCKBScan.Text);

                        int intBox = 0;
                        string strFinish = string.Empty;
                        List<string> tmp;
                        tmp = new List<string>();
                        tmp = lblBox.Text.Split("/").ToList();
                        if (tmp.Count == 2)
                        {
                            intBox = Convert.ToInt32(tmp[1].Trim()) - Convert.ToInt32(tmp[0].Trim());
                        }
                        if (intBox == 0)
                        {
                            strFinish = "Finish";
                            WriteReSetLHRH();
                        }
                        else
                        {
                            //strFinish = "Packing";
                            strFinish = "Printed";
                        }

                        clsUtil_MSSQL.updateFinishKanban(RtnDbCon(), strFinish, strMaxSerial,
                                        userName, DateTime.Now.ToString("yyyyMMdd"),
                                        DateTime.Now.ToString("HHmmss"), txtPCKBScan.Text);

                        //clsUtil_MSSQL.insertTT_KANBAN_H(RtnDbCon(), lblPartNo.Text, lblPartName.Text, lblModelShow.Text, lblCode.Text,
                        //lblPartID.Text, lblCustomerID.Text, strCustomerPartNO, strCustomerPartNO, strCustomerPartName,
                        //string.Empty, string.Empty, strLocation, string.Empty, string.Empty,
                        //Convert.ToInt32(lblQPack.Text), "PCS", strMaxSerial,
                        //strQR,
                        //strFRMSERIAL, txtPCKBScan.Text, "FG", userName, DateTime.Now.ToString("yyyyMMdd"),
                        //DateTime.Now.ToString("HHmmss"), "Y", userName, DateTime.Now.ToString("yyyyMMdd"),
                        //DateTime.Now.ToString("HHmmss"), userName, DateTime.Now.ToString("yyyyMMdd"),
                        //DateTime.Now.ToString("HHmmss"), "0", strSIDE, strFinish, strScanWet, strDetail, 0, 0);

                        //dtTT_KANBAN_HSelect = new DataTable();
                        //clsUtil_MSSQL.GetDataFromTBSelectTT_KANBAN_HMaxID(RtnDbCon(), "TT_KANBAN_H", ref dtTT_KANBAN_HSelect);
                        //rowid = Convert.ToInt32(dtTT_KANBAN_HSelect.Rows[0][0].ToString());

                        //for (int i = 0; i < dgvScanPacking.Rows.Count; i++)
                        //{
                        //    clsUtil_MSSQL.insertTT_KANBAN_L(RtnDbCon(), rowid, lblPartNo.Text, lblPartName.Text, lblModelShow.Text, lblCode.Text,
                        //lblPartID.Text, string.Empty, strMaxSerial, dgvScanPacking[0, i].Value.ToString(),
                        //Convert.ToInt64(dgvScanPacking[1, i].Value.ToString()), dgvScanPacking[2, i].Value.ToString(),
                        //"Y", userName, DateTime.Now.ToString("yyyyMMdd"),
                        //DateTime.Now.ToString("HHmmss"), userName, DateTime.Now.ToString("yyyyMMdd"),
                        //DateTime.Now.ToString("HHmmss"), string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, 0, 0);

                        //}

                        //Print Label
                        printLabelProcess(sender, e);

                        Cursor = Cursors.Default;

                        frmFinishPacking frm = new frmFinishPacking();
                        frm.ShowDialog();

                        dtFRMQRKANBANSelect = new DataTable();
                        clsUtil_MSSQL.GetDataFromTBTT_KANBAN_HSelect(RtnDbCon(), "TT_KANBAN_H", ref dtFRMQRKANBANSelect, txtPCKBScan.Text);


                        //lblBox.Text = dtFRMQRKANBANSelect.Rows.Count.ToString() + " / " + strBOX;//Use Half Day

                        //if (dtFRMQRKANBANSelect.Rows.Count.ToString() == strBOX) //Use Half Day
                        if (strFinish == "Finish")
                        {
                            SettxtStart();

                            dgvScanPacking.Rows.Clear();

                            txtPCKBScan.ReadOnly = false;
                            txtPCKBScan.BackColor = Color.Yellow;

                            txtPCKBScan.Text = string.Empty;
                            txtUNITQRScan.Text = string.Empty;
                            txtPCKBScan.Focus();
                        }
                        else
                        {
                            loadTableSerial();

                            TableShow();

                            for (int i = 0; i < Convert.ToInt32(lblQPack.Text); i++)
                            {
                                row = new string[] { string.Empty, string.Empty, string.Empty, string.Empty };
                                dgvScanPacking.Rows.Add(row);
                            }

                            txtUNITQRScan.Text = string.Empty;
                            txtUNITQRScan.Focus();
                        }



                    }
                    else
                    {
                        frmOK frm = new frmOK();
                        frm.ShowDialog();
                        txtUNITQRScan.Text = string.Empty;
                        txtUNITQRScan.Focus();
                    }



                }
                //else if (txtUNITQRScan.Text.Substring(Convert.ToInt32(strQRLength) - 3, 3) != lblCode.Text)
                else if (txtUNITQRScan.Text.Substring(Convert.ToInt32(strModelStart) - 1, Convert.ToInt32(strModelLength))
                        != strCustomerPartNO.Replace("-", ""))
                {
                    DataWrite(strUNITQRScan, strUNITQRScan.Length, "2");
                    WriteSignalSet();
                    NGShow("Kanban ไม่ตรงกับ Model ที่กำลังแพ็ค", txtUNITQRScan.Text);
                    ReadSignalSet();

                }
                else if (serialSearch(txtUNITQRScan.Text.Trim()) == true)
                {
                    DataWrite(strUNITQRScan, strUNITQRScan.Length, "2");
                    WriteSignalSet();
                    NGShow("QR Code ชิ้นงานนี้เคยสแกนแล้ว", txtUNITQRScan.Text);
                    ReadSignalSet();

                }

            }
            else
            {
                // Here: user did not press ENTER key
            }
        }

        private bool setContentPrintBuffer(string str)
        {
            bool ret = true;
            Dictionary<string, VarObject> vars = textProcessing.ParseInput(str, '|');

            foreach (string key in vars.Keys)
            {
                VarObject v;
                vars.TryGetValue(key, out v);
            }

            //Read template content
            try
            {
                string html = System.IO.File.ReadAllText(ini.Read("template", selected_preset));

                //Process html
                html = TextProcessing.ReplaceVariables(textProcessing, html, ini);

                printBuffer = html;
            }
            catch (Exception e)
            {
                //log("Error: " + e.Message);
                ret = false;

            }

            return ret;
        }



        private bool serialSearch(string serial)
        {
            string searchValue = serial;

            dtSerialSelect = new DataTable();
            clsUtil_MSSQL.GetDataFromTBTT_KANBAN_LSelect(RtnDbCon(), "TT_KANBAN_L", ref dtSerialSelect, serial);
            if (dtSerialSelect is not null)
            {
                if ((dtSerialSelect.Rows.Count > 0) && (blCDUse == true))
                {
                    return true;
                }

            }


            if (dgvScanPacking.Rows.Count == 0)
            {
                return false;
            }

            //dgvScanPacking.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            try
            {
                foreach (DataGridViewRow row in dgvScanPacking.Rows)
                {
                    if (row.Cells[0].Value is null)
                    {
                        return false;
                    }

                    if ((row.Cells[0].Value.ToString().Equals(searchValue)) && (blCDUse == true))
                    {
                        row.Selected = true;
                        return true;
                    }
                }
                return false;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
                return false;
            }
        }

        private int SearchRowTable()
        {

            if (dgvScanPacking.Rows.Count == 0)
            {
                return 0;
            }

            //dgvScanPacking.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            try
            {
                rowindex = 0;

                foreach (DataGridViewRow row in dgvScanPacking.Rows)
                {
                    if (row.Cells[0].Value is null)
                    {
                        return 0;
                    }
                    if (row.Cells[3].Value.ToString().Equals("NG"))
                    {
                        return rowindex;
                    }
                    if (row.Cells[0].Value.ToString().Equals(string.Empty))
                    {
                        return rowindex;
                    }

                    rowindex = rowindex + 1;


                }
                rowindex = 0;
                return 0;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
                rowindex = 0;
                return 0;
            }
        }

        private int SearchRowNGTable(string serial)
        {

            if (dgvScanPacking.Rows.Count == 0)
            {
                return 0;
            }

            //dgvScanPacking.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            try
            {
                if (intRowID != -99)
                {
                    rowindex = intRowID;
                    return rowindex;
                }

                rowindex = 0;

                foreach (DataGridViewRow row in dgvScanPacking.Rows)
                {
                    if (row.Cells[0].Value is null)
                    {
                        return 0;
                    }
                    //if (row.Cells[3].Value.ToString().Equals("NG")
                    //    && row.Cells[0].Value.ToString().Equals(serial))
                    //{
                    //    return rowindex;
                    //}
                    if (row.Cells[3].Value.ToString().Equals("NG"))
                    {
                        return rowindex;
                    }
                    if (row.Cells[0].Value.ToString().Equals(string.Empty))
                    {
                        //this.row = new string[] { string.Empty, string.Empty, string.Empty, string.Empty };
                        //dgvScanPacking.Rows.Add(this.row);
                        return rowindex;
                    }

                    rowindex = rowindex + 1;


                }
                return 0;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
                return 0;
            }
        }

        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(lblDaySet.Text));

                clsUtil_MSSQL.insertHistoryLog(RtnDbCon(), txtPCKBScan.Text, lblPartNo.Text, lblPartID.Text, lblPartNo.Text,
                lblPartName.Text, Convert.ToInt32(lblQPack.Text), 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);

                dgvScanPacking[0, SearchRowNGTable(partserial)].Value = partserial;
                dgvScanPacking[1, rowindex].Value = DryDate.ToString("yyyyMMdd");
                dgvScanPacking[2, rowindex].Value = ExpDate.ToString("yyyyMMdd");
                dgvScanPacking[3, rowindex].Value = "NG";
                dgvScanPacking[3, rowindex].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgvScanPacking[3, rowindex].Style.BackColor = Color.Red;

                //if (dgvScanPacking.RowCount > 0)
                //{
                //    if (dgvScanPacking[3, dgvScanPacking.RowCount].Value.ToString() == "NG")
                //    {
                //        dgvScanPacking.Rows.RemoveAt(dgvScanPacking.RowCount - 1);
                //    }
                //}

                frmNG frm = new frmNG(msg);
                frm.ShowDialog();

                txtUNITQRScan.Text = string.Empty;
                txtUNITQRScan.Focus();
            }
            catch (Exception)
            {
                MessageBox.Show(this, "สแกนผิด QR Code",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);

                txtUNITQRScan.Text = string.Empty;
                txtUNITQRScan.Focus();
                return;
            }
        }

        private void NGShowSTAGE1(string msg, string msgSave)
        {
            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 strDryDateFull = strDryDate.Substring(0, 4) + "-" + strDryDate.Substring(4, 2) + "-" + strDryDate.Substring(6, 2);
            //DateTime DryDate = Convert.ToDateTime(strDryDateFull);
            //DateTime ExpDate = DryDate.AddDays(Convert.ToInt32(lblDaySet.Text));

            clsUtil_MSSQL.insertHistoryLog(RtnDbCon(), txtPCKBScan.Text, string.Empty, string.Empty, string.Empty,
            string.Empty, 0, 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", msgSave, "STAGE1", Environment.MachineName, "", "");

            //dgvScanPacking[0, SearchRowNGTable(txtUNITQRScan.Text.Trim())].Value = txtUNITQRScan.Text.Trim();
            //dgvScanPacking[1, rowindex].Value = DryDate.ToString("yyyyMMdd");
            //dgvScanPacking[2, rowindex].Value = ExpDate.ToString("yyyyMMdd");
            //dgvScanPacking[3, rowindex].Value = "NG";
            //dgvScanPacking[3, rowindex].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //dgvScanPacking[3, rowindex].Style.BackColor = Color.Red;

            //if (dgvScanPacking.RowCount > 0)
            //{
            //    if (dgvScanPacking[3, dgvScanPacking.RowCount].Value.ToString() == "NG")
            //    {
            //        dgvScanPacking.Rows.RemoveAt(dgvScanPacking.RowCount - 1);
            //    }
            //}

            frmNG frm = new frmNG(msg);
            frm.ShowDialog();

            txtPCKBScan.Text = string.Empty;
            txtPCKBScan.Focus();
        }

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

        }

        private void TableShow()
        {
            dgvScanPacking.Rows.Clear();

            dgvScanPacking.ColumnCount = 4;
            dgvScanPacking.Columns[0].Name = "Serial";
            dgvScanPacking.Columns[1].Name = "MFG Date";
            dgvScanPacking.Columns[2].Name = "Expire Date";
            dgvScanPacking.Columns[3].Name = "Status";

            dgvScanPacking.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgvScanPacking.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgvScanPacking.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgvScanPacking.Columns[3].SortMode = DataGridViewColumnSortMode.NotSortable;

            dgvScanPacking.Columns[0].Width = 150;
            dgvScanPacking.Columns[1].Width = 150;
            dgvScanPacking.Columns[2].Width = 150;
            dgvScanPacking.Columns[3].Width = 150;

            dgvScanPacking.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            dgvScanPacking.RowHeadersWidth = 70;

            rowindex = 0;
        }

        private void TableClear()
        {
            dgvScanPacking.ColumnCount = 4;
            dgvScanPacking.Columns[0].Name = "            ";
            dgvScanPacking.Columns[1].Name = "            ";
            dgvScanPacking.Columns[2].Name = "            ";
            dgvScanPacking.Columns[3].Name = "            ";

            dgvScanPacking.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgvScanPacking.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgvScanPacking.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgvScanPacking.Columns[3].SortMode = DataGridViewColumnSortMode.NotSortable;

            //dgvScanPacking.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;


            dgvScanPacking.RowHeadersWidth = 70;
            //dgvScanPacking.Columns[0].Width = 100;
            //dgvScanPacking.Columns[1].Width = 100;
            //dgvScanPacking.Columns[2].Width = 100;
            //dgvScanPacking.Columns[3].Width = 100;


            rowindex = 0;
        }

        private void dgvScanPacking_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // Add row number
            (sender as DataGridView).Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex + 1).ToString();

            int idx = e.RowIndex;
            DataGridViewRow row = dgvScanPacking.Rows[idx];
            row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            row.HeaderCell.Style.BackColor = SystemColors.Control;

            //dgvScanPacking.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            int counter = dgvScanPacking.Rows.Count;

            for (int i = 0; i < counter; i++)
            {
                if (i % 2 == 0)
                {
                    dgvScanPacking.Rows[i].DefaultCellStyle.BackColor = SystemColors.Window;
                }
                else
                {
                    dgvScanPacking.Rows[i].DefaultCellStyle.BackColor = SystemColors.Control;
                }
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            loadSerial();
            printLabelProcess(sender, e);
        }

        private void loadSerial()
        {
            loadTableSetting();

            loadTableSerial();

            strQR = "PCSYS" + "$" + strMaxSerial + "$" + lblPartNo.Text + "$" + strFGP4 + "$" + strCustomerPartNO
                    + "$$" + strQTYP7 + "$$" + strP9 + "$" + DateTime.Now.ToString("yyyyMMdd");
        }

        private void loadSerialLast(string kanban)
        {
            loadTableSetting();

            loadTableSerialLast(kanban);

            strQR = "PCSYS" + "$" + strMaxSerial + "$" + lblPartNo.Text + "$" + strFGP4 + "$" + strCustomerPartNO
                    + "$$" + strQTYP7 + "$$" + strP9 + "$" + DateTime.Now.ToString("yyyyMMdd");
        }

        private void printLabelProcess(object sender, EventArgs e)
        {

            //strSIDE = "LH";

            if (printerStatus.BackColor == Color.LightGreen)
            {

                printLabel(sender, e, "" + "|" + QRStyle + "|" + strQR + "|" +
                CustomerStyle + "|" + strCustomerName + "|" +
                LocationStyle + "|" + strLocation + "|" +
                SIDEStyle + "|" + strSIDE + "|" +
                QTYStyle + "|" + lblQPack.Text + "| " +
                PartNameStyle + "|" + lblPartName.Text + "|" +
                UserNameStyle + "|" + userName + "|" +
                SerialStyle + "|" + strMaxSerial + "|" +
                ADSPartNoStyle + "|" + lblPartNo.Text + "|" +
                CustomerPartNoStyle + "|" + strCustomerPartNO + "|" +
                ScanDateStyle + "|" + ScanTimeStyle + "|" + DateTime.Now.ToString("yyyyMMddHHmmss") + "|" +
                ModelStyle + "|" + lblModelShow.Text + "|" + DetailStyle + "|" + strDetail);

                //printPriviewLabel(sender, e, "" + "|" + QRStyle + "|" + strQR + "|" +
                //CustomerStyle + "|" + strCustomerName + "|" +
                //LocationStyle + "|" + strLocation + "|" +
                //SIDEStyle + "|" + strSIDE + "|" +
                //QTYStyle + "|" + lblQPack.Text + "| " +
                //PartNameStyle + "|" + lblPartName.Text + "|" +
                //UserNameStyle + "|" + userName + "|" +
                //SerialStyle + "|" + strMaxSerial + "|" +
                //ADSPartNoStyle + "|" + lblPartNo.Text + "|" +
                //CustomerPartNoStyle + "|" + strCustomerPartNO + "|" +
                //ScanDateStyle + "|" + ScanTimeStyle + "|" + DateTime.Now.ToString("yyyyMMddHHmmss") + "|" +
                //ModelStyle + "|" + lblModelShow.Text + "|" + DetailStyle + "|" + strDetail);


            }
            else
            {
                MessageBox.Show(this, "ไม่สามารถเพิมพ์ได้ เนื่องจาก Printer Offline",
                                   "Print Label", MessageBoxButtons.OK,
                                   MessageBoxIcon.Error,
                                   MessageBoxDefaultButton.Button1, 0);

                printPriviewLabel(sender, e, "" + "|" + QRStyle + "|" + strQR + "|" +
                                    CustomerStyle + "|" + strCustomerName + "|" +
                                    LocationStyle + "|" + strLocation + "|" +
                                    SIDEStyle + "|" + strSIDE + "|" +
                                    QTYStyle + "|" + lblQPack.Text + "| " +
                                    PartNameStyle + "|" + lblPartName.Text + "|" +
                                    UserNameStyle + "|" + userName + "|" +
                                    SerialStyle + "|" + strMaxSerial + "|" +
                                    ADSPartNoStyle + "|" + lblPartNo.Text + "|" +
                                    CustomerPartNoStyle + "|" + strCustomerPartNO + "|" +
                                    ScanDateStyle + "|" + ScanTimeStyle + "|" + DateTime.Now.ToString("yyyyMMddHHmmss") + "|" +
                                    ModelStyle + "|" + lblModelShow.Text + "|" + DetailStyle + "|" + strDetail);

            }
        }

        private void loadTableSetting()
        {
            dtSetting = new DataTable();
            clsUtil_MSSQL.GetDataFromTBsetting(RtnDbCon(), "TM_SETTING", ref dtSetting);

            //Customer Code -> ADS Part No

            if (dtSetting.Rows.Count > 0)
            {
                ModelNameX = Convert.ToInt32(dtSetting.Rows[0][1].ToString());
                ModelNameY = Convert.ToInt32(dtSetting.Rows[0][2].ToString());
                ModelNameFS = Convert.ToInt32(dtSetting.Rows[0][3].ToString());
                //position: absolute; display: block; margin - top:1px; margin - left:140px; font - size: 38px; font - weight: bold; font color: white;
                ModelStyle = "position: absolute; display: block; margin-top:" + ModelNameY + "px; margin-left:" + ModelNameX + "px;font-size: " + ModelNameFS + "px; font-weight: bold;  font color: white;";

                CustomerNameX = Convert.ToInt32(dtSetting.Rows[0][4].ToString());
                CustomerNameY = Convert.ToInt32(dtSetting.Rows[0][5].ToString());
                CustomerNameFS = Convert.ToInt32(dtSetting.Rows[0][6].ToString());
                //< span style = "position: absolute; display: block; margin-top:10px; margin-left:240px;font-size: 32px; font-weight: bold; " >${ Customer}</ span >
                CustomerStyle = "position: absolute; display: block; margin-top:" + CustomerNameY + "px; margin-left:" + CustomerNameX + "px;font-size: " + CustomerNameFS + "px; font-weight: bold; ";

                CustomerCodeX = Convert.ToInt32(dtSetting.Rows[0][7].ToString());
                CustomerCodeY = Convert.ToInt32(dtSetting.Rows[0][8].ToString());
                CustomerCodeFS = Convert.ToInt32(dtSetting.Rows[0][9].ToString());
                //<span style="position: absolute; display: block; margin-top:95px; margin-left:105px;font-size: 23px; font-weight: bold; ">(${ADSPartNo})</span>
                ADSPartNoStyle = "position: absolute; display: block; margin-top:" + CustomerCodeY + "px; margin-left:" + CustomerCodeX + "px;font-size: " + CustomerCodeFS + "px; font-weight: bold; ";

                QtyX = Convert.ToInt32(dtSetting.Rows[0][10].ToString());
                QtyY = Convert.ToInt32(dtSetting.Rows[0][11].ToString());
                QtyFS = Convert.ToInt32(dtSetting.Rows[0][12].ToString());
                //< span style = "position: absolute; display: block; margin-top:53px; margin-left:70px;font-size: 21px; font-weight: bold; " >${ QTY}</ span >
                QTYStyle = "position: absolute; display: block; margin-top:" + QtyY + "px; margin-left:" + QtyX + "px;font-size: " + QtyFS + "px; font-weight: bold; ";

                UserNameX = Convert.ToInt32(dtSetting.Rows[0][13].ToString());
                UserNameY = Convert.ToInt32(dtSetting.Rows[0][14].ToString());
                UserNameFS = Convert.ToInt32(dtSetting.Rows[0][15].ToString());
                //<span style="position: absolute; display: block; margin-top:95px; margin-left:30px;font-size: 11px; font-weight: bold; ">${UserName}</span>
                UserNameStyle = "position: absolute; display: block; margin-top:" + UserNameY + "px; margin-left:" + UserNameX + "px;font-size: " + UserNameFS + "px; font-weight: bold; ";

                SerialNoX = Convert.ToInt32(dtSetting.Rows[0][16].ToString());
                SerialNoY = Convert.ToInt32(dtSetting.Rows[0][17].ToString());
                SerialNoFS = Convert.ToInt32(dtSetting.Rows[0][18].ToString());
                //<span style="position: absolute; display: block; margin-top:115px; margin-left:30px;font-size: 9px; font-weight: bold; ">${SerialNo}</span>
                SerialStyle = "position: absolute; display: block; margin-top:" + SerialNoY + "px; margin-left:" + SerialNoX + "px;font-size: " + SerialNoFS + "px; font-weight: bold; ";

                PartNoX = Convert.ToInt32(dtSetting.Rows[0][19].ToString());
                PartNoY = Convert.ToInt32(dtSetting.Rows[0][20].ToString());
                PartNoFS = Convert.ToInt32(dtSetting.Rows[0][21].ToString());
                //<span style="position: absolute; display: block; margin-top:60px; margin-left:205px;font-size: 21px; font-weight: bold; ">${PartName}</span>
                PartNameStyle = "position: absolute; display: block; margin-top:" + PartNoY + "px; margin-left:" + PartNoX + "px;font-size: " + PartNoFS + "px; font-weight: bold; ";

                CustomerPartNoX = Convert.ToInt32(dtSetting.Rows[0][22].ToString());
                CustomerPartNoY = Convert.ToInt32(dtSetting.Rows[0][23].ToString());
                CustomerPartNoFS = Convert.ToInt32(dtSetting.Rows[0][24].ToString());
                //<span style="position: absolute; display: block; margin-top:113px; margin-left:113px;font-size: 23px; font-weight: bold; ">${CustomerPartNo}</span>
                CustomerPartNoStyle = "position: absolute; display: block; margin-top:" + CustomerPartNoY + "px; margin-left:" + CustomerPartNoX + "px;font-size: " + CustomerPartNoFS + "px; font-weight: bold; ";

                LocationX = Convert.ToInt32(dtSetting.Rows[0][25].ToString());
                LocationY = Convert.ToInt32(dtSetting.Rows[0][26].ToString());
                LocationFS = Convert.ToInt32(dtSetting.Rows[0][27].ToString());
                //< span style = "position: absolute; display: block; margin-top:20px; margin-left:10px;font-size: 21px; font-weight: bold; " >${ Location}</ span >
                LocationStyle = "position: absolute; display: block; margin-top:" + LocationY + "px; margin-left:" + LocationX + "px;font-size: " + LocationFS + "px; font-weight: bold; ";

                SIDEX = Convert.ToInt32(dtSetting.Rows[0][28].ToString());
                SIDEY = Convert.ToInt32(dtSetting.Rows[0][29].ToString());
                SIDEFS = Convert.ToInt32(dtSetting.Rows[0][30].ToString());
                //<span style="position: absolute; display: block; margin-top:53px; margin-left:20px;font-size: 21px; font-weight: bold; ">${SIDE}</span>
                SIDEStyle = "position: absolute; display: block; margin-top:" + SIDEY + "px; margin-left:" + SIDEX + "px;font-size: " + SIDEFS + "px; font-weight: bold; ";

                DateX = Convert.ToInt32(dtSetting.Rows[0][31].ToString());
                DateY = Convert.ToInt32(dtSetting.Rows[0][32].ToString());
                DateFS = Convert.ToInt32(dtSetting.Rows[0][33].ToString());
                //<span style="position: absolute; display: block; margin-top:110px; margin-left:245px;font-size: 12px; font-weight: bold; ">${Scan_date:datetime(dd/MM/yyyy)}</span>
                ScanDateStyle = "position: absolute; display: block; margin-top:" + DateY + "px; margin-left:" + DateX + "px;font-size: " + DateFS + "px; font-weight: bold; ";

                TimeX = Convert.ToInt32(dtSetting.Rows[0][34].ToString());
                TimeY = Convert.ToInt32(dtSetting.Rows[0][35].ToString());
                TimeFS = Convert.ToInt32(dtSetting.Rows[0][36].ToString());
                //<span style="position: absolute; display: block; margin-top:120px; margin-left:250px;font-size: 12px; font-weight: bold; ">${Scan_date:datetime(HH:mm:ss)}</span>
                ScanTimeStyle = "position: absolute; display: block; margin-top:" + TimeY + "px; margin-left:" + TimeX + "px;font-size: " + TimeFS + "px; font-weight: bold; ";

                QRX = Convert.ToInt32(dtSetting.Rows[0][37].ToString());
                QRY = Convert.ToInt32(dtSetting.Rows[0][38].ToString());
                QRFS = Convert.ToInt32(dtSetting.Rows[0][39].ToString());
                //< span style = "position: absolute; display: block; margin-top:70px; margin-left:255px;" >
                QRStyle = "position: absolute; display: block; margin-top:" + QRY + "px; margin-left:" + QRX + "px;font-size: " + QRFS + "px; font-weight: bold; ";

                DetailX = Convert.ToInt32(dtSetting.Rows[0][40].ToString());
                DetailY = Convert.ToInt32(dtSetting.Rows[0][41].ToString());
                DetailFS = Convert.ToInt32(dtSetting.Rows[0][42].ToString());
                //< span style = "position: absolute; display: block; margin-top:70px; margin-left:255px;" >
                DetailStyle = "position: absolute; display: block; margin-top:" + DetailY + "px; margin-left:" + DetailX + "px;font-size: " + DetailFS + "px; font-weight: bold; ";


            }
            else
            {
                ModelNameX = 115;
                ModelNameY = 1;
                ModelNameFS = 38;
                ModelStyle = "position: absolute; display: block; margin-top:" + ModelNameY + "px; margin-left:" + ModelNameX + "px;font-size: " + ModelNameFS + "px; font-weight: bold;  font color: white;";

                CustomerNameX = 215;
                CustomerNameY = 10;
                CustomerNameFS = 32;
                CustomerStyle = "position: absolute; display: block; margin-top:" + CustomerNameY + "px; margin-left:" + CustomerNameX + "px;font-size: " + CustomerNameFS + "px; font-weight: bold; ";

                CustomerCodeX = 139;
                CustomerCodeY = 100;
                CustomerCodeFS = 15;
                ADSPartNoStyle = "position: absolute; display: block; margin-top:" + CustomerCodeY + "px; margin-left:" + CustomerCodeX + "px;font-size: " + CustomerCodeFS + "px; font-weight: bold; ";

                QtyX = 57;
                QtyY = 55;
                QtyFS = 21;
                QTYStyle = "position: absolute; display: block; margin-top:" + QtyY + "px; margin-left:" + QtyX + "px;font-size: " + QtyFS + "px; font-weight: bold; ";

                UserNameX = 36;
                UserNameY = 95;
                UserNameFS = 11;
                UserNameStyle = "position: absolute; display: block; margin-top:" + UserNameY + "px; margin-left:" + UserNameX + "px;font-size: " + UserNameFS + "px; font-weight: bold; ";

                SerialNoX = 5;
                SerialNoY = 115;
                SerialNoFS = 15;
                SerialStyle = "position: absolute; display: block; margin-top:" + SerialNoY + "px; margin-left:" + SerialNoX + "px;font-size: " + SerialNoFS + "px; font-weight: bold; ";

                PartNoX = 175;
                PartNoY = 55;
                PartNoFS = 12;
                PartNameStyle = "position: absolute; display: block; margin-top:" + PartNoY + "px; margin-left:" + PartNoX + "px;font-size: " + PartNoFS + "px; font-weight: bold; ";

                CustomerPartNoX = 143;
                CustomerPartNoY = 118;
                CustomerPartNoFS = 15;
                CustomerPartNoStyle = "position: absolute; display: block; margin-top:" + CustomerPartNoY + "px; margin-left:" + CustomerPartNoX + "px;font-size: " + CustomerPartNoFS + "px; font-weight: bold; ";

                LocationX = 10;
                LocationY = 20;
                LocationFS = 21;
                LocationStyle = "position: absolute; display: block; margin-top:" + LocationY + "px; margin-left:" + LocationX + "px;font-size: " + LocationFS + "px; font-weight: bold; ";

                SIDEX = 10;
                SIDEY = 55;
                SIDEFS = 21;
                SIDEStyle = "position: absolute; display: block; margin-top:" + SIDEY + "px; margin-left:" + SIDEX + "px;font-size: " + SIDEFS + "px; font-weight: bold; ";

                DateX = 220;
                DateY = 110;
                DateFS = 12;
                ScanDateStyle = "position: absolute; display: block; margin-top:" + DateY + "px; margin-left:" + DateX + "px;font-size: " + DateFS + "px; font-weight: bold; ";

                TimeX = 220;
                TimeY = 120;
                TimeFS = 12;
                ScanTimeStyle = "position: absolute; display: block; margin-top:" + TimeY + "px; margin-left:" + TimeX + "px;font-size: " + TimeFS + "px; font-weight: bold; ";

                QRX = 225;
                QRY = 70;
                QRFS = 0;
                QRStyle = "position: absolute; display: block; margin-top:" + QRY + "px; margin-left:" + QRX + "px;font-size: " + QRFS + "px; font-weight: bold; ";

                DetailX = 175;
                DetailY = 70;
                DetailFS = 12;
                DetailStyle = "position: absolute; display: block; margin-top:" + DetailY + "px; margin-left:" + DetailX + "px;font-size: " + DetailFS + "px; font-weight: bold; ";


            }

        }

        private void loadTableSerial()
        {
            strMaxSerial = string.Empty;
            strMaxSerialCut = string.Empty;
            intMaxSerial = 0;
            dtMaxSerial = new DataTable();
            clsUtil_MSSQL.GetDataFromTBserial(RtnDbCon(), "TT_KANBAN_H", ref dtMaxSerial, strComNo);

            if (dtMaxSerial.Rows.Count > 0)
            {
                strMaxSerialCut = dtMaxSerial.Rows[0][0].ToString(); //15
                if (strMaxSerialCut == "")
                {
                    intMaxSerial = 1;
                    //strMaxSerial = "PCK03" + DateTime.Now.ToString("yyyyMMdd") + intMaxSerial.ToString("0000");
                    strMaxSerial = "PCK" + strComNo + DateTime.Now.ToString("yyyyMMdd") + intMaxSerial.ToString("0000");
                }
                else
                {
                    intMaxSerial = Convert.ToInt32(strMaxSerialCut.Substring(strMaxSerialCut.Length - 4, 4)) + 1;
                    strMaxSerial = "PCK" + strMaxSerialCut.Substring(0, strMaxSerialCut.Length - 4) + intMaxSerial.ToString("0000");
                }
            }
            else
            {
                intMaxSerial = 1;
                //strMaxSerial = "PCK03" + DateTime.Now.ToString("yyyyMMdd") + intMaxSerial.ToString("0000");
                strMaxSerial = "PCK" + strComNo + DateTime.Now.ToString("yyyyMMdd") + intMaxSerial.ToString("0000");
            }
        }


        private void loadTableSerialLast(string kanban)
        {
            strMaxSerial = string.Empty;
            strMaxSerialCut = string.Empty;
            intMaxSerial = 0;
            dtMaxSerial = new DataTable();
            clsUtil_MSSQL.GetDataFromTBserialKanban(RtnDbCon(), "TT_KANBAN_H", ref dtMaxSerial, strComNo, kanban);

            if (dtMaxSerial.Rows.Count > 0)
            {
                strMaxSerialCut = dtMaxSerial.Rows[0][0].ToString(); //15
                if (strMaxSerialCut == "")
                {
                    intMaxSerial = 1;
                    //strMaxSerial = "PCK03" + DateTime.Now.ToString("yyyyMMdd") + intMaxSerial.ToString("0000");
                    strMaxSerial = "PCK" + strComNo + DateTime.Now.ToString("yyyyMMdd") + intMaxSerial.ToString("0000");
                }
                else
                {
                    intMaxSerial = Convert.ToInt32(strMaxSerialCut.Substring(strMaxSerialCut.Length - 4, 4));
                    strMaxSerial = "PCK" + strMaxSerialCut.Substring(0, strMaxSerialCut.Length - 4) + intMaxSerial.ToString("0000");
                }
            }
            else
            {
                intMaxSerial = 1;
                //strMaxSerial = "PCK03" + DateTime.Now.ToString("yyyyMMdd") + intMaxSerial.ToString("0000");
                strMaxSerial = "PCK" + strComNo + DateTime.Now.ToString("yyyyMMdd") + intMaxSerial.ToString("0000");
            }
        }

        private void printPriviewLabel(object sender, EventArgs e, string strprintBuffer)
        {
            ini.Write("printer", printerName, selected_preset);
            ini.Write("template", System.IO.Directory.GetCurrentDirectory() + "\\Template-Packing.html", selected_preset);
            ini.Write("width", "500", selected_preset);
            ini.Write("height", "300", selected_preset);

            //Print Label
            if (setContentPrintBuffer(strprintBuffer))
            {
                printPreviewToolStripMenuItem_Click(sender, e);
            }
        }

        private void printLabel(object sender, EventArgs e, string strprintBuffer)
        {
            ini.Write("printer", printerName, selected_preset);
            ini.Write("template", System.IO.Directory.GetCurrentDirectory() + "\\Template-Packing.html", selected_preset);
            ini.Write("width", "500", selected_preset);
            ini.Write("height", "300", selected_preset);

            //Print Label
            if (setContentPrintBuffer(strprintBuffer))
            {
                printDocument.PrinterSettings.PrinterName = this.printerName;
                printDocument.Print();
            }
        }

        private void dgvScanPacking_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvScanPacking_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowindex = dgvScanPacking.CurrentRow.Index;
            string strStatusTable = dgvScanPacking[3, rowindex].Value.ToString();
            strSerialSelect = dgvScanPacking[0, rowindex].Value.ToString();

            intRowID = rowindex;

            if (strSerialSelect == string.Empty)
            {
                MessageBox.Show(this, "กรุณาเลือกรายการที่มีข้อมูล Serial",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }

            if (strStatusTable == "NG")
            {
                MessageBox.Show(this, "กรุณาเลือกรายการที่ไม่ใช่ NG",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }

            if ((strSerialSelect != string.Empty) && (strStatusTable != "NG"))
            {

                ReSendSerialSet();

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

                if (blChangeOKtoNG == true)
                {

                    //ReSendSerialSet();

                    //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, "1");
                            //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;
                            //}


                            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)
                            {
                                txtUNITQRScan.Text = string.Empty;
                                txtUNITQRScan.Focus();
                                return;
                            }

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

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

                                return;
                            }
                            if (strPLCOKNG == "2")
                            {
                                //DataWrite(strUNITQRScan, strUNITQRScan.Length, "9");

                                NGShow("Traceability ชิ้นงานข้าม Process", strSerialSelect);
                                ReadSignalSet();
                                return;
                            }
                            else if (strPLCOKNG != "1")
                            {

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

                                return;
                            }
                            if (blCDUse == true)
                            {
                                if (strPLCDuplicate == "2")
                                {
                                    //DataWrite(strUNITQRScan, strUNITQRScan.Length, "9");

                                    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();
                                    txtUNITQRScan.Text = string.Empty;
                                    txtUNITQRScan.Focus();

                                    return;
                                }
                            }


                        }
                        else
                        {
                            if (blCDUse == true)
                            {
                                if (DataRead() == false)
                                {
                                    txtUNITQRScan.Text = string.Empty;
                                    txtUNITQRScan.Focus();
                                    return;
                                }

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

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

                                    return;
                                }

                                if (strPLCDuplicate == "2")
                                {
                                    //DataWrite(strUNITQRScan, strUNITQRScan.Length, "9");
                                    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();
                                    txtUNITQRScan.Text = string.Empty;
                                    txtUNITQRScan.Focus();

                                    return;
                                }
                            }
                        }

                    }

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


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


                    //            return;
                    //        }

                    //        ReadSignalSet();
                    //    }
                    //}


                    DateTime StartDate = DateTime.Now;
                    DateTime EndDate = DateTime.Now;
                    Double total_days = (EndDate - StartDate).TotalDays;
                    //String strDryDate = dgvScanPacking[1, rowindex].Value.ToString();
                    //String ExpDate = dgvScanPacking[2, rowindex].Value.ToString();

                    //String strDryDate = "20" + txtUNITQRScan.Text.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(lblDaySet.Text));

                    clsUtil_MSSQL.insertHistoryLog(RtnDbCon(), txtPCKBScan.Text, lblPartNo.Text, lblPartID.Text, lblPartNo.Text,
                    lblPartName.Text, Convert.ToInt32(lblQPack.Text), 0, "kg", StartDate.ToString("MMM dd yyyy hh:mmtt"),
                    EndDate.ToString("MMM dd yyyy hh:mmtt"), total_days, strUserQC, DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"), "NG", strMSG, "STAGE2", Environment.MachineName, "", strSerialSelect);

                    //dgvScanPacking[0, SearchRowNGTable(txtUNITQRScan.Text.Trim())].Value = txtUNITQRScan.Text.Trim();
                    //dgvScanPacking[1, rowindex].Value = strDryDate; //DryDate.ToString("yyyyMMdd");
                    //dgvScanPacking[2, rowindex].Value = ExpDate; //.ToString("yyyyMMdd");
                    dgvScanPacking[3, rowindex].Value = "NG";
                    dgvScanPacking[3, rowindex].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    dgvScanPacking[3, rowindex].Style.BackColor = Color.Red;

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

                    Thread.Sleep(3000);
                    dgvScanPacking[0, rowindex].Value = string.Empty;
                    dgvScanPacking[1, rowindex].Value = string.Empty;
                    dgvScanPacking[2, rowindex].Value = string.Empty;
                    dgvScanPacking[3, rowindex].Value = string.Empty;
                    dgvScanPacking[3, rowindex].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    dgvScanPacking[3, rowindex].Style.BackColor = Color.White;

                }
                else
                {
                    ForcedSetNoWait();
                }

            }

        }

        private void btnForcedSet_Click(object sender, EventArgs e)
        {
            ForcedSetTU();
            ForcedSetCSP();
        }

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

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

        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 void WriteSignalOK()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;

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

        }

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

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

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

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

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

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

        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 ReSendSerialSet()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;

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

        }

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

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

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

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

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

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

        private void btnForcedReset_Click(object sender, EventArgs e)
        {
            ForcedResetTU();
            ForcedResetCSP();
        }

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

        private void ForcedResetCSP()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("RS" + (char)_cmd01 + "MR1001" + (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 ForcedResetReInput()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;
            System.Threading.Thread.Sleep(50);
            ExeCommandPLC("RS" + (char)_cmd01 + "MR1004" + (char)_cmd02, "ForcedReset");
        }

        private void btnDataRead_Click(object sender, EventArgs e)
        {
            //DataRead();
        }

        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, 20) == strUNITQRScan.Substring(0, 20))
            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.05))
                    .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, 20) == strUNITQRScan.Substring(0, 20))
                    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;

                    }

                    ForcedSetLive();

                    //if (i == 999)
                    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)
                        {
                            ForcedSetNoWait();

                            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 ForcedSetLive()
        {
            byte _cmd01 = 0x20;
            byte _cmd02 = 0x0D;
            System.Threading.Thread.Sleep(50);

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

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

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

        private void btnBitRead_Click(object sender, EventArgs e)
        {
            //BitRead();
        }

        //private void BitRead()
        //{
        //    byte _cmd01 = 0x20;
        //    byte _cmd02 = 0x0D;
        //    System.Threading.Thread.Sleep(1000);
        //    ExeCommandPLC("RDS" + (char)_cmd01 + "MR1001" + (char)_cmd01 + "4" + (char)_cmd02, "BitRead");
        //}

        private void btnDataWrite_Click(object sender, EventArgs e)
        {
            //DataWrite();
        }

        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 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 backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (PLCStatus.BackColor == Color.LightGreen)
            {
                pnlPLC.BackColor = Color.LightGreen;
            }
            else
            {
                pnlPLC.BackColor = Color.Red;
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            if (PLCStatus.BackColor == Color.LightGreen)
            {
                //DataRead();
                lblTRWaiting.Text = "Traceability Response Waiting......";
                TRWaiting.Text = "Traceability Response Waiting......";
            }
        }

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

        private void btnDelete_Click(object sender, EventArgs e)
        {
            blClearSerial = false;
            if (dgvScanPacking.CurrentRow == null)
            {
                MessageBox.Show(this, "กรุณาเลือกรายการที่จะลบก่อน",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                txtUNITQRScan.Focus();
                return;
            }

            int rowindex = dgvScanPacking.CurrentRow.Index;
            string strStatusTable = dgvScanPacking[3, rowindex].Value.ToString();
            strSerialSelect = dgvScanPacking[0, rowindex].Value.ToString();

            if (strSerialSelect == string.Empty)
            {
                MessageBox.Show(this, "กรุณาเลือกรายการที่มีข้อมูล Serial",
                                       "Production window", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                txtUNITQRScan.Focus();
                return;
            }

            //if (strStatusTable == "NG")
            //{
            //    MessageBox.Show(this, "กรุณาเลือกรายการที่มีข้อมูล Serial OK",
            //                           "Production window", MessageBoxButtons.OK,
            //                           MessageBoxIcon.Warning,
            //                           MessageBoxDefaultButton.Button1, 0);
            //    return;
            //}

            ReSendSerialSet();

            frmCancelKanban frm = new frmCancelKanban(strSerialSelect, "ยกเลิกชิ้นงาน", "ADMINISTRATOR");
            frm.ShowDialog();

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

                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, "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);

                            txtUNITQRScan.Focus();
                            return;
                        }

                        ReadSignalSet();
                    }
                }

                if (PLCStatus.BackColor == Color.LightGreen)
                {
                    if (blCSPUse == true)
                    {
                        if (DataRead() == false)
                        {
                            txtUNITQRScan.Text = string.Empty;
                            txtUNITQRScan.Focus();
                            return;
                        }

                        if (strPLCError == "2")
                        {
                            //NGShow("ERROR");
                            NGShow("Traceability ข้อมูลผิดปกติ", strSerialSelect);
                            ReadSignalSet();

                            txtUNITQRScan.Focus();

                            return;
                        }
                        else if (strPLCError != "1")
                        {

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

                            return;
                        }
                        if (strPLCOKNG == "2")
                        {
                            //DataWrite(strUNITQRScan, strUNITQRScan.Length, "9");

                            NGShow("Traceability ชิ้นงานข้าม Process", strSerialSelect);
                            ReadSignalSet();

                            txtUNITQRScan.Focus();

                            return;
                        }
                        else if (strPLCOKNG != "1")
                        {

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

                            return;
                        }
                        if (blCDUse == true)
                        {
                            if (strPLCDuplicate == "2")
                            {
                                //DataWrite(strUNITQRScan, strUNITQRScan.Length, "9");

                                NGShow("Traceability check Serial ซ้ำ", strSerialSelect);
                                ReadSignalSet();

                                txtUNITQRScan.Focus();

                                return;
                            }
                            else if (strPLCDuplicate != "1")
                            {

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

                                return;
                            }
                        }


                    }
                    else
                    {
                        if (blCDUse == true)
                        {
                            if (DataRead() == false)
                            {
                                txtUNITQRScan.Text = string.Empty;
                                txtUNITQRScan.Focus();
                                return;
                            }

                            if (strPLCError == "2")
                            {
                                //NGShow("ERROR");
                                NGShow("Traceability ข้อมูลผิดปกติ", strSerialSelect);
                                ReadSignalSet();

                                txtUNITQRScan.Focus();

                                return;
                            }
                            else if (strPLCError != "1")
                            {

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

                                return;
                            }

                            if (strPLCDuplicate == "2")
                            {
                                //DataWrite(strUNITQRScan, strUNITQRScan.Length, "9");
                                NGShow("Traceability check Serial ซ้ำ", strSerialSelect);
                                ReadSignalSet();

                                txtUNITQRScan.Focus();

                                return;
                            }
                            else if (strPLCDuplicate != "1")
                            {

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

                                return;
                            }
                        }
                    }

                }

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

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


                //    return;
                //}

                //ReadSignalSet();

                clsUtil_MSSQL.updateCancelQRScanSerial(RtnDbCon(), "Delete", strSerialSelect,
                           userName, DateTime.Now.ToString("yyyyMMdd"),
                           DateTime.Now.ToString("HHmmss"));

                dgvScanPacking[0, rowindex].Value = string.Empty;
                dgvScanPacking[1, rowindex].Value = string.Empty;
                dgvScanPacking[2, rowindex].Value = string.Empty;
                dgvScanPacking[3, rowindex].Value = string.Empty;
                dgvScanPacking[3, rowindex].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgvScanPacking[3, rowindex].Style.BackColor = Color.White;

                bool blCheckEmpty = false;

                for (int i = 0; i < dgvScanPacking.Rows.Count; i++)
                {
                    if (dgvScanPacking[0, i].Value == string.Empty)
                    {
                        blCheckEmpty = true;
                    }
                    else
                    {
                        blCheckEmpty = false;
                        break;
                    }

                }

                if (blCheckEmpty == true)
                {
                    clsUtil_MSSQL.updateCancelKanbanPacking(RtnDbCon(), "Cancel", strMaxSerial,
                                        userName, DateTime.Now.ToString("yyyyMMdd"),
                                        DateTime.Now.ToString("HHmmss"));
                }

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

                txtUNITQRScan.Focus();
            }
            else
            {
                ForcedSetNoWait();

                txtUNITQRScan.Focus();
            }

        }

        private void backgroundWorker3_DoWork(global::System.Object sender, global::System.ComponentModel.DoWorkEventArgs e)
        {

        }

        private void timer3_Tick(global::System.Object sender, global::System.EventArgs e)
        {

        }

        private void btnOpenShutter_Click(object sender, EventArgs e)
        {
            WriteSignalOK();

            txtUNITQRScan.Focus();
        }

        private void txtUNITQRScan_Leave(object sender, EventArgs e)
        {
            if (txtPCKBScan.Text != string.Empty)
            {
              
                txtUNITQRScan.Focus();
            }
            else
            {
                txtPCKBScan.Focus();
            }
        }
    }
}
