using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Bt.ScanLib;
using Bt;
using CsvReadWrite;
using System.Data.SqlClient;

namespace HT_SKT_Stock
{
    public partial class FrmInspectionDetail : Form
    {
        public static FrmInspectionDetail _Form_InspectionDetailInstance;
        public String AppPath = "";
        List<DisplayTable> _lstInspectionData = new List<DisplayTable>();
        public List<List<string>> tableList;
        List<DisplayTable> lstTable = new List<DisplayTable>();
        List<DisplayTable> lstTableShow = new List<DisplayTable>();
        Int32 _index = 0;
        String partNo = "";
        String sysClassKanban = "";
        String planDate = "";
        Int32 Pid = 0;
        private BtScanLib btScanLib;
        Int32 currentRow = 0;
        public static bool blYes = false;
        public Int32 RowStart = 0;
        public Int32 RowEnd = 9;

        public FrmInspectionDetail(List<DisplayTable> lstInspectionData, Int32 row)
        {
            InitializeComponent();

            // Enable BTScanLib
            btScanLib = BtScanLib.getInstance();
            btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
            btScanLib.Debug = false;
            btScanLib.Enable();

            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmInspectionDetail_KeyDown);

            btnBack.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmInspectionDetail_KeyDown);

            btnConfirm.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmInspectionDetail_KeyDown);

            btnDelete.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmInspectionDetail_KeyDown);

            btnAllDelete.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmInspectionDetail_KeyDown);

            dataGrid1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmInspectionDetail_KeyDown);

            btnBackPage.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmInspectionDetail_KeyDown);

            btnNextPage.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmInspectionDetail_KeyDown);

            _lstInspectionData = lstInspectionData;

            _index = row;

            BindDataList();
        }

        void btScanLib_OnScan(string result)
        {
            string[] kanban = result.Split('|');
            string kanbanCode = "";
            string kanbanClass = "";
            string remainderClass = "";
            string partNoScan = "";
            string quantity = "0";
            string kanbanSerialNo = "";
            Int32 intCheck = 0;

            if (kanban.Length == 6)
            {
                kanbanCode = kanban[0];
                kanbanClass = kanban[1];
                remainderClass = kanban[2];
                partNoScan = kanban[3];
                quantity = kanban[4];
                kanbanSerialNo = kanban[5];

                if (remainderClass == "2")
                {
                    quantity = "";
                }
                    FrmLogin.strQty = quantity;

                    //******* disable BTScanLib
                    btScanLib.OnScan -= btScanLib_OnScan;
                    btScanLib.Disable();

                    FrmInputQty input = new FrmInputQty(quantity);
                    input.ShowDialog();

                    // Enable BTScanLib
                    btScanLib = BtScanLib.getInstance();
                    btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                    btScanLib.Debug = false;
                    btScanLib.Enable();

                    quantity = FrmLogin.strQty;

                    if (quantity == "")
                    {
                        quantity = "0";
                    }
                
                
                try
                {
                    if (partNoScan != partNo)
                    {
                        InsertInspectionDetail(partNoScan, quantity, kanbanSerialNo, "NG", kanbanCode, kanbanClass, remainderClass);

                        //******* disable BTScanLib
                        btScanLib.OnScan -= btScanLib_OnScan;
                        btScanLib.Disable();

                        FrmWarningLeader err = new FrmWarningLeader("", "", "Different part no.");
                        err.ShowDialog();

                        // Enable BTScanLib
                        btScanLib = BtScanLib.getInstance();
                        btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                        btScanLib.Debug = false;
                        btScanLib.Enable();

                        dataGrid1.Focus();

                        return;
                    }

                    if ((kanbanCode != "1") && (kanbanCode != "6"))
                    {
                        InsertInspectionDetail(partNoScan, quantity, kanbanSerialNo, "NG", kanbanCode, kanbanClass, remainderClass);

                        //******* disable BTScanLib
                        btScanLib.OnScan -= btScanLib_OnScan;
                        btScanLib.Disable();

                        FrmWarningLeader err = new FrmWarningLeader("Different types of", "Kanban", "");
                        err.ShowDialog();

                        // Enable BTScanLib
                        btScanLib = BtScanLib.getInstance();
                        btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                        btScanLib.Debug = false;
                        btScanLib.Enable();

                        dataGrid1.Focus();

                        return;
                    }


                    intCheck = CheckDuplicateScan(kanbanSerialNo);

         
                    if (intCheck == 2)
                    {
                        //if (sysClassKanban == "")
                        //{
                        //    sysClassKanban = kanbanClass;
                        //    //InsertInspectionDetail(partNoScan, quantity, kanbanSerialNo, "OK");
                        //}
                        //else
                        //{
                        //    if (sysClassKanban == kanbanClass)
                        //    {
                        //        //InsertInspectionDetail(partNoScan, quantity, kanbanSerialNo, "OK");
                        //    }
                        //    else
                        //    {
                        //        InsertInspectionDetail(partNoScan, quantity, kanbanSerialNo, "NG");

                        //        //******* disable BTScanLib
                        //        btScanLib.OnScan -= btScanLib_OnScan;
                        //        btScanLib.Disable();

                        //        FrmWarningLeader err = new FrmWarningLeader("Kanban status", "dosen't match", "");
                        //        err.ShowDialog();

                        //        // Enable BTScanLib
                        //        btScanLib = BtScanLib.getInstance();
                        //        btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                        //        btScanLib.Debug = false;
                        //        btScanLib.Enable();

                        //        dataGrid1.Focus();

                        //        return;
                        //    }
                        //}
                        


                        //return;
                    }
                    else if (intCheck == 1)
                    {
                        //******* disable BTScanLib
                        btScanLib.OnScan -= btScanLib_OnScan;
                        btScanLib.Disable();

                        InsertInspectionDetail(partNoScan, quantity, kanbanSerialNo, "NG", kanbanCode, kanbanClass, remainderClass);

                        FrmWarningLeader err = new FrmWarningLeader("Duplicate scans of the", "same serial", "");
                        err.ShowDialog();

                        dataGrid1.Focus();

                        // Enable BTScanLib
                        btScanLib = BtScanLib.getInstance();
                        btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                        btScanLib.Debug = false;
                        btScanLib.Enable();

                        return;

                    }
                    else if (intCheck == 3)
                    {
                        WarningErr1 err = new WarningErr1("Error Database Connection ");
                        err.ShowDialog();

                        dataGrid1.Focus();

                        return;
                    }


                    Int32 intCheck1 = CheckStatusScan(kanbanCode, kanbanClass, partNoScan, kanbanSerialNo, remainderClass);


                    if (intCheck1 == 1)
                    {
                        
                        //******* disable BTScanLib
                        btScanLib.OnScan -= btScanLib_OnScan;
                        btScanLib.Disable();

                        InsertInspectionDetail(partNoScan, quantity, kanbanSerialNo, "NG", kanbanCode, kanbanClass, remainderClass);

                        FrmWarningLeader err = new FrmWarningLeader("Kanban status", "doesn't match", "");
                        err.ShowDialog();

                        dataGrid1.Focus();

                        // Enable BTScanLib
                        btScanLib = BtScanLib.getInstance();
                        btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                        btScanLib.Debug = false;
                        btScanLib.Enable();

                        return;


                    }
                    else if (intCheck1 == 2)
                    {
                        
                        //******* disable BTScanLib
                        btScanLib.OnScan -= btScanLib_OnScan;
                        btScanLib.Disable();

                        InsertInspectionDetail(partNoScan, quantity, kanbanSerialNo, "NG", kanbanCode, kanbanClass, remainderClass);

                        FrmWarningLeader err = new FrmWarningLeader("Kanban Master", "not found", "");
                        err.ShowDialog();

                        dataGrid1.Focus();

                        // Enable BTScanLib
                        btScanLib = BtScanLib.getInstance();
                        btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                        btScanLib.Debug = false;
                        btScanLib.Enable();

                        return;
                    }
                    else if (intCheck1 == 3)
                    {
                        WarningErr1 err = new WarningErr1("Error Database Connection ");
                        err.ShowDialog();

                        dataGrid1.Focus();

                        return;
                    }
                    else if (intCheck1 == 4)
                    {
                        InsertInspectionDetail(partNoScan, quantity, kanbanSerialNo, "OK", kanbanCode, kanbanClass, remainderClass);
                    }



                }
                catch (Exception)
                {

                }

            }

            else
            {
                WarningErr1 err = new WarningErr1("Kanban Format Incorrect");
                err.ShowDialog();

                dataGrid1.Focus();
            }
        }

        private Int32 CheckStatusScan(string kanbanCode, string kanbanClass, string partNo, string kanbanSerialNo, string remainderClass)
        {
            try
            {


                tableList = new List<List<string>>();

                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;

                Decimal qtyScan = 0;


                strSQL = "EXEC sp_get_kanban_status @kanbanCode = '" + kanbanCode
                    + "' , @kanbanClass = '" + kanbanClass + "' , @partNo = '" + partNo
                + "' , @serialNo = '" + kanbanSerialNo + "' , @remainderClass = '" + remainderClass + "'";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                dtAdapter.SelectCommand = objCmd;

                dtAdapter.Fill(ds);
                dt = ds.Tables[0];

                dtAdapter = null;
                objConn.Close();
                objConn = null;

                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["status"].ToString() == "1")
                    {
                        return 1;
                    }
                    else
                    {
                        return 4;
                    }


                }
                else
                {
                    return 2;
                }




            }
            catch (Exception)
            {

                return 3;

            }


        }

        private void InsertInspectionDetail(string partNo, string quantity, string kanbanSerialNo, string status, string kanbanCode, string kanbanClass, string remainderClass)
        {
            try
            {
                
                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;

                Decimal qtyScan = Convert.ToDecimal(quantity);


                strSQL = "EXEC sp_insert_Inspection_Detail @prod_schd_id = " + Pid
                    + " , @parts_no = '" + partNo 
                    + "' , @serialNo = '" + kanbanSerialNo + "' , @qtySerial = " + qtyScan
                    + " , @statusSerial = '" + status + "' , @userId = '" + FrmLogin._Form_LoginInstance.userName
                    + "' , @kanbanCode = '" + kanbanCode + "' , @kanbanClass = '" + kanbanClass + "' , @remainderClass = '" + remainderClass + "'";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                objCmd.ExecuteNonQuery();

                objConn.Close();
                objConn = null;

            }
            catch (Exception)
            {

            }

            SetTable(3);
        }

        private Int32 UpdateInspectionDetail(string status)
        {
            try
            {


                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;


                strSQL = "EXEC sp_update_status_Inbound_Inspection @prod_schd_id = " + Pid
                    + " , @userId = '" + FrmLogin._Form_LoginInstance.userName
                    + "' , @status = '" + status
                    + "'";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                objCmd.ExecuteNonQuery();

                objConn.Close();
                objConn = null;

                return 1;

            }
            catch (Exception)
            {
                return 3;
            }

            //SetTable();
        }

        private void DeleteInspectionDetail(string quantity, string kanbanSerialNo, string status)
        {
            try
            {

                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;

                Decimal qtyScan = Convert.ToDecimal(quantity);


                strSQL = "EXEC sp_delete_Inspection_Detail @prod_schd_id = " + Pid
                    + " , @serialNo = '" + kanbanSerialNo + "' , @qtySerial = " + qtyScan
                    + " , @status = '" + status + "'";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                objCmd.ExecuteNonQuery();

                objConn.Close();
                objConn = null;

            }
            catch (Exception)
            {

            }

            SetTable(3);
        }

        private void DeleteAllInspectionDetail()
        {
            try
            {

                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;


                strSQL = "EXEC sp_deleteAll_Inspection_Detail @prod_schd_id = " + Pid
                    + "";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                objCmd.ExecuteNonQuery();

                objConn.Close();
                objConn = null;

            }
            catch (Exception)
            {

            }

            SetTable(0);
        }


        private void BindDataList()
        {
            if (_lstInspectionData.Count > 0)
            {
                lblSName.Text = _lstInspectionData[_index].SName.ToString();
                lblQtyAll.Text = _lstInspectionData[_index].Qty.ToString();
                //txtQty.Text = _lstInspectionData[_index].ActQty.ToString();
                partNo = _lstInspectionData[_index].Partno.ToString();
                planDate = _lstInspectionData[_index].PDate.ToString();
                Pid = Convert.ToInt32(_lstInspectionData[_index].IdPS.ToString());
            }

            //MessageBox.Show(partNo + " | " + _index.ToString());

        }

        private void FrmInspectionDetail_Load(object sender, EventArgs e)
        {
            if (System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width == 240)
            {
                resolution.ScreenSize.VGAtoQVGA(this);
            }

            this.MaximizeBox = !this.MaximizeBox;
            this.MinimizeBox = !this.MinimizeBox;

            _Form_InspectionDetailInstance = this;


            String path = this.GetType().Assembly.GetModules()[0].FullyQualifiedName;
            Int32 en = path.LastIndexOf("\\");
            AppPath = path.Substring(0, en);

            lblUser.Text = "User : " + FrmLogin._Form_LoginInstance.userName;

            RowStart = 0;
            RowEnd = 9;

            sysClassKanban = "";

            SetTable(0);

        }

        private Int32 CheckDuplicateScan(string kanbanSerialNo)
        {
            try
            {


                tableList = new List<List<string>>();

                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;

                Decimal qtyScan = 0;

                strSQL = "EXEC sp_get_Inspection_Detail_duplicate @prod_schd_id = " + Pid
                    + " , @serialNo = '" + kanbanSerialNo + "'";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                dtAdapter.SelectCommand = objCmd;

                dtAdapter.Fill(ds);
                dt = ds.Tables[0];

                dtAdapter = null;
                objConn.Close();
                objConn = null;

                if (dt.Rows.Count > 0)
                {
                    return 1;
                }
                else
                {
                    return 2;
                }




            }
            catch (Exception)
            {

                return 3;

            }


        }


        private void SetTable(Int32 processStart)
        {
            try
            {
                string strCheckStatus = "";

                tableList = new List<List<string>>();

                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;

                Decimal qtyScan = 0;


                strSQL = "EXEC sp_get_Inspection_Detail_table @prod_schd_id = " + Pid
                    + "";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                dtAdapter.SelectCommand = objCmd;

                dtAdapter.Fill(ds);
                dt = ds.Tables[0];

                //dataGrid1.DataSource = dt;

                lblStaus1.Visible = false;
                lblStaus2.Visible = false;
                lblStaus3.Visible = false;
                lblStaus4.Visible = false;
                lblStaus5.Visible = false;
                lblStaus6.Visible = false;
                lblStaus7.Visible = false;
                lblStaus8.Visible = false;
                lblStaus9.Visible = false;
                lblStaus10.Visible = false;

                lstTable.Clear();
                lstTableShow.Clear();

                if (dt.Rows.Count > 10)
                {
                    btnNextPage.Enabled = true;
                    btnBackPage.Enabled = true;
                }
                else
                {
                    btnNextPage.Enabled = false;
                    btnBackPage.Enabled = false;
                }

                if (processStart == 0)
                {
                    RowStart = 0;
                    RowEnd = 9;
                }

                if ((RowStart > dt.Rows.Count - 1) && (dt.Rows.Count > 0))
                {
                    RowStart = RowStart - 10;
                    RowEnd = RowEnd - 10;
                }

                if (processStart == 3)
                {
                    Int32 iPage = Convert.ToInt32(Math.Ceiling(dt.Rows.Count / 10));

                    if ((dt.Rows.Count % 10) > 0)
                    {
                        iPage = iPage + 1;
                    }
                    
                    RowStart = (iPage * 10) - 10;
                    RowEnd = RowStart + 9;
                    
                }

                for (int i = 0; i <= dt.Rows.Count - 1; i++)
                {
                    string strRow = dt.Rows[i]["DRow"].ToString();
                    string strSerialNo = dt.Rows[i]["serialNo"].ToString();
                    string strQty = dt.Rows[i]["qtySerial"].ToString();
                    string strStatus = dt.Rows[i]["statusSerial"].ToString();
                    string strkanbanCode = dt.Rows[i]["kanban_code"].ToString();
                    string strkanbanClass = dt.Rows[i]["kanban_class"].ToString();
                    string strremainderClass = dt.Rows[i]["remainder_class"].ToString();


                    if (strStatus == "OK")
                    {
                        qtyScan = qtyScan + Convert.ToDecimal(strQty);
                    }
                    else
                    {
                        strCheckStatus = "NG";
                    }

                    lstTable.Add(new DisplayTable
                    {
                        Partno = partNo,
                        DRow = strRow,
                        serialNo = strSerialNo,
                        qtySerial = strQty,
                        statusSerial = strStatus,
                        kanbanCode = strkanbanCode,
                        kanbanClass = strkanbanClass,
                        remainderClass = strremainderClass
                    });


                    if ((i >= RowStart) && (i <= RowEnd))
                    {

                        lstTableShow.Add(new DisplayTable
                        {
                            Partno = partNo,
                            DRow = strRow,
                            serialNo = strSerialNo,
                            qtySerial = strQty,
                            statusSerial = strStatus
                        });


                        Int32 rowCheck = i % 10;
                        
                        switch (rowCheck + 1)
                        {
                            case 1:
                                lblStaus1.Text = strStatus;
                                if (lblStaus1.Text == "OK")
                                {
                                    lblStaus1.BackColor = Color.Green;
                                    lblStaus1.ForeColor = Color.White;
                                }
                                else if (lblStaus1.Text == "NG")
                                {
                                    lblStaus1.BackColor = Color.Red;
                                    lblStaus1.ForeColor = Color.White;
                                }
                                else
                                {
                                    lblStaus1.Text = "-";
                                    lblStaus1.BackColor = Color.White;
                                    lblStaus1.ForeColor = Color.Black;
                                }
                                lblStaus1.Visible = true;
                                break;

                            case 2:
                                lblStaus2.Text = strStatus;
                                if (lblStaus2.Text == "OK")
                                {
                                    lblStaus2.BackColor = Color.Green;
                                    lblStaus2.ForeColor = Color.White;
                                }
                                else if (lblStaus2.Text == "NG")
                                {
                                    lblStaus2.BackColor = Color.Red;
                                    lblStaus2.ForeColor = Color.White;
                                }
                                else
                                {
                                    lblStaus2.Text = "-";
                                    lblStaus2.BackColor = Color.White;
                                    lblStaus2.ForeColor = Color.Black;
                                }
                                lblStaus2.Visible = true;
                                break;

                            case 3:
                                lblStaus3.Text = strStatus;
                                if (lblStaus3.Text == "OK")
                                {
                                    lblStaus3.BackColor = Color.Green;
                                    lblStaus3.ForeColor = Color.White;
                                }
                                else if (lblStaus3.Text == "NG")
                                {
                                    lblStaus3.BackColor = Color.Red;
                                    lblStaus3.ForeColor = Color.White;
                                }
                                else
                                {
                                    lblStaus3.Text = "-";
                                    lblStaus3.BackColor = Color.White;
                                    lblStaus3.ForeColor = Color.Black;
                                }
                                lblStaus3.Visible = true;
                                break;

                            case 4:
                                lblStaus4.Text = strStatus;
                                if (lblStaus4.Text == "OK")
                                {
                                    lblStaus4.BackColor = Color.Green;
                                    lblStaus4.ForeColor = Color.White;
                                }
                                else if (lblStaus4.Text == "NG")
                                {
                                    lblStaus4.BackColor = Color.Red;
                                    lblStaus4.ForeColor = Color.White;
                                }
                                else
                                {
                                    lblStaus4.Text = "-";
                                    lblStaus4.BackColor = Color.White;
                                    lblStaus4.ForeColor = Color.Black;
                                }
                                lblStaus4.Visible = true;
                                break;

                            case 5:
                                lblStaus5.Text = strStatus;
                                if (lblStaus5.Text == "OK")
                                {
                                    lblStaus5.BackColor = Color.Green;
                                    lblStaus5.ForeColor = Color.White;
                                }
                                else if (lblStaus5.Text == "NG")
                                {
                                    lblStaus5.BackColor = Color.Red;
                                    lblStaus5.ForeColor = Color.White;
                                }
                                else
                                {
                                    lblStaus5.Text = "-";
                                    lblStaus5.BackColor = Color.White;
                                    lblStaus5.ForeColor = Color.Black;
                                }
                                lblStaus5.Visible = true;
                                break;

                            case 6:
                                lblStaus6.Text = strStatus;
                                if (lblStaus6.Text == "OK")
                                {
                                    lblStaus6.BackColor = Color.Green;
                                    lblStaus6.ForeColor = Color.White;
                                }
                                else if (lblStaus6.Text == "NG")
                                {
                                    lblStaus6.BackColor = Color.Red;
                                    lblStaus6.ForeColor = Color.White;
                                }
                                else
                                {
                                    lblStaus6.Text = "-";
                                    lblStaus6.BackColor = Color.White;
                                    lblStaus6.ForeColor = Color.Black;
                                }
                                lblStaus6.Visible = true;
                                break;

                            case 7:
                                lblStaus7.Text = strStatus;
                                if (lblStaus7.Text == "OK")
                                {
                                    lblStaus7.BackColor = Color.Green;
                                    lblStaus7.ForeColor = Color.White;
                                }
                                else if (lblStaus7.Text == "NG")
                                {
                                    lblStaus7.BackColor = Color.Red;
                                    lblStaus7.ForeColor = Color.White;
                                }
                                else
                                {
                                    lblStaus7.Text = "-";
                                    lblStaus7.BackColor = Color.White;
                                    lblStaus7.ForeColor = Color.Black;
                                }
                                lblStaus7.Visible = true;
                                break;

                            case 8:
                                lblStaus8.Text = strStatus;
                                if (lblStaus8.Text == "OK")
                                {
                                    lblStaus8.BackColor = Color.Green;
                                    lblStaus8.ForeColor = Color.White;
                                }
                                else if (lblStaus8.Text == "NG")
                                {
                                    lblStaus8.BackColor = Color.Red;
                                    lblStaus8.ForeColor = Color.White;
                                }
                               else
                                {
                                    lblStaus8.Text = "-";
                                    lblStaus8.BackColor = Color.White;
                                    lblStaus8.ForeColor = Color.Black;
                                }
                                lblStaus8.Visible = true;
                                break;

                            case 9:
                                lblStaus9.Text = strStatus;
                                if (lblStaus9.Text == "OK")
                                {
                                    lblStaus9.BackColor = Color.Green;
                                    lblStaus9.ForeColor = Color.White;
                                }
                               else if (lblStaus9.Text == "NG")
                                {
                                    lblStaus9.BackColor = Color.Red;
                                    lblStaus9.ForeColor = Color.White;
                                }
                               else
                                {
                                    lblStaus9.Text = "-";
                                    lblStaus9.BackColor = Color.White;
                                    lblStaus9.ForeColor = Color.Black;
                                }
                                lblStaus9.Visible = true;
                                break;

                            case 10:
                                lblStaus10.Text = strStatus;
                                if (lblStaus10.Text == "OK")
                                {
                                    lblStaus10.BackColor = Color.Green;
                                    lblStaus10.ForeColor = Color.White;
                                }
                                else if (lblStaus10.Text == "NG")
                                {
                                    lblStaus10.BackColor = Color.Red;
                                    lblStaus10.ForeColor = Color.White;
                                }
                                else
                                {
                                    lblStaus10.Text = "-";
                                    lblStaus10.BackColor = Color.White;
                                    lblStaus10.ForeColor = Color.Black;
                                }
                                lblStaus10.Visible = true;
                                break;

                            default:
                                break;
                        }

                    }




                }

                lblQty.Text = qtyScan.ToString();

                var blist = new BindingList<DisplayTable>(lstTableShow);
                dataGrid1.DataSource = blist;

                InitialDataGrid();

                //if (lstTable.Count > 0)
                //{
                //    dataGrid1.CurrentRowIndex = lstTable.Count - 1;
                //}

                if (lstTableShow.Count > 0)
                {
                    dataGrid1.CurrentRowIndex = lstTableShow.Count - 1;
                }

                dataGrid1.Focus();

                //dataGrid1.Rows[0].Cells[5].Style.BackColor = Color.Green;

                dtAdapter = null;
                objConn.Close();
                objConn = null;

                if (lstTable.Count > 0)
                {
                    if (strCheckStatus == "NG")
                    {
                        //NG
                        UpdateInspectionDetail("NG");
                    }
                    else
                    {
                        //Working
                        UpdateInspectionDetail("Working");
                    }

                }
                else if (lstTable.Count == 0)
                {
                    //Not Started
                    UpdateInspectionDetail("Not Started");
                }



            }
            catch (Exception)
            {

                SetStartTable();
            }


        }

        private void SetStartTable()
        {
            lblQty.Text = "0";

            lstTable.Clear();

            var blist = new BindingList<DisplayTable>(lstTable);
            dataGrid1.DataSource = blist;

            InitialDataGrid();

        }

        private void InitialDataGrid()
        {
            int grid_width = 445;
            // hidden column and row header
            dataGrid1.ColumnHeadersVisible = true;
            dataGrid1.RowHeadersVisible = false;

            // set style
            DataGridTableStyle tableStyle = new DataGridTableStyle();
            tableStyle.MappingName = (new BindingList<DisplayTable>()).GetType().Name;

            // Column 0
            DataGridTextBoxColumn tbc0 = new DataGridTextBoxColumn();
            tbc0.Width = 29;
            tbc0.MappingName = "DRow";
            tbc0.HeaderText = "#";
            tableStyle.GridColumnStyles.Add(tbc0);

            // Column 1
            DataGridTextBoxColumn tbc1 = new DataGridTextBoxColumn();
            tbc1.Width = 54;
            tbc1.MappingName = "Partno";
            tbc1.HeaderText = "Part no";
            tableStyle.GridColumnStyles.Add(tbc1);

            // Column 2
            DataGridTextBoxColumn tbc2 = new DataGridTextBoxColumn();
            tbc2.Width = 54;
            tbc2.MappingName = "serialNo";
            tbc2.HeaderText = "Serial";
            tableStyle.GridColumnStyles.Add(tbc2);

            // Column 3
            DataGridTextBoxColumn tbc3 = new DataGridTextBoxColumn();
            tbc3.Width = 43;
            tbc3.MappingName = "qtySerial";
            tbc3.HeaderText = "Qty";
            tableStyle.GridColumnStyles.Add(tbc3);

            // Column 4
            DataGridTextBoxColumn tbc4 = new DataGridTextBoxColumn();
            tbc4.Width = 37;
            tbc4.MappingName = "statusSerial";
            tbc4.HeaderText = "Status";
            tableStyle.GridColumnStyles.Add(tbc4);


            dataGrid1.TableStyles.Clear();
            dataGrid1.TableStyles.Add(tableStyle);


        }

        private void FrmInspectionDetail_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode.ToString())
            {

                case "F1":
                    btnBack_Click(sender, e);
                    break;

                case "F2":
                    btnDelete_Click(sender, e);
                    break;

                case "F3":
                    btnAllDelete_Click(sender, e);
                    break;

                case "F4":
                    btnConfirm_Click(sender, e);
                    break;
            }
        }

        private Int32 UpdateStatusKanbanTable()
        {
            foreach (var item in lstTable)
            {

                if (item.statusSerial == "OK")
                {
                    Int32 intCheck = UpdateStatusKanban(item.kanbanCode, item.kanbanClass, item.Partno, item.serialNo, 1);

                    if (intCheck == 3)
                    {
                                                
                        return 3;
                    }

                }
            }

            return 1;
        }

        private Int32 UpdateStatusKanban(string kanbanCode, string kanbanClass, string partNo, string kanbanSerialNo, Int32 status)
        {
            try
            {


                tableList = new List<List<string>>();

                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;

                Decimal qtyScan = 0;


                strSQL = "EXEC sp_update_status_kanban_HT @kanbanCode = '" + kanbanCode
                    + "' , @kanbanClass = '" + kanbanClass + "' , @partNo = '" + partNo
                    + "' , @serialNo = '" + kanbanSerialNo + "' , @userId = '" + FrmLogin._Form_LoginInstance.userName
                    + "' , @status = " + status
                    + "";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                dtAdapter.SelectCommand = objCmd;

                //dtAdapter.Fill(ds);
                //dt = ds.Tables[0];

                dtAdapter = null;
                objConn.Close();
                objConn = null;

     
                return 1;


            }
            catch (Exception)
            {

                return 3;

            }


        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {

            if (lstTable.Count == 0)
            {
                WarningErr1 errEmptyData = new WarningErr1("Empty Data ");
                errEmptyData.ShowDialog();

               
                dataGrid1.Focus();

                return;
            }

            if (lblQtyAll.Text == "")
            {
                WarningErr1 err1 = new WarningErr1("Package Type Master Not Found ");
                        err1.ShowDialog();

                        dataGrid1.Focus();


                        return;
            }

            if (lstTable.Count > 0)
            {
                foreach (var item in lstTable)
                {
                    if (item.statusSerial == "NG")
                    {
                        WarningErr1 errNGData = new WarningErr1("NG Data ");
                        errNGData.ShowDialog();

                        if (lstTableShow.Count > 0)
                        {
                            dataGrid1.CurrentRowIndex = lstTableShow.Count - 1;
                        }

                        dataGrid1.Focus();

                        return;
                    }
                }
            }

            try
            {
                         

            Decimal Qty = Convert.ToDecimal(lblQty.Text);
            Decimal QtyAll = Convert.ToDecimal(lblQtyAll.Text);

            if (Qty < QtyAll)
            {
                WarningErr2YesNo err = new WarningErr2YesNo("Qty is not enough.", "Do you want to confirm?");
                err.ShowDialog();


                if (blYes == true)
                {
                    Int32 intCheck1 = UpdateInspectionDetail("Completed");

                    if (intCheck1 == 3)
                    {
                        WarningErr1 err1 = new WarningErr1("Error Database Connection ");
                        err1.ShowDialog();


                        return;
                    }

                    //Int32 intCheck = UpdateStatusKanbanTable();

                    //if (intCheck == 3)
                    //{
                    //    WarningErr1 err3 = new WarningErr1("Error Database Connection ");
                    //    err3.ShowDialog();


                    //    return ;
                    //}

                    WarningErr2 err2 = new WarningErr2("Data registration", "completed", "Green");
                    err2.ShowDialog();

                    //******* disable BTScanLib
                    btScanLib.OnScan -= btScanLib_OnScan;
                    btScanLib.Disable();

                    Form frm = new FrmInboundInspection();
                    frm.ShowDialog();
                    this.Close();
                }
                else
                {
                    dataGrid1.Focus();

                    return;
                }

            }
            else if (Qty > QtyAll)
            {
                //******* disable BTScanLib
                btScanLib.OnScan -= btScanLib_OnScan;
                btScanLib.Disable();

                FrmWarningLeader err = new FrmWarningLeader("", "", "The quantity is over");
                err.ShowDialog();

                // Enable BTScanLib
                btScanLib = BtScanLib.getInstance();
                btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                btScanLib.Debug = false;
                btScanLib.Enable();

                
                dataGrid1.Focus();
            }
            else
            {
                Int32 intCheck1 = UpdateInspectionDetail("Completed");

                if (intCheck1 == 3)
                {
                    WarningErr1 err1 = new WarningErr1("Error Database Connection ");
                    err1.ShowDialog();


                    return;
                }

                Int32 intCheck = UpdateStatusKanbanTable();

                if (intCheck == 3)
                {
                    WarningErr1 err2 = new WarningErr1("Error Database Connection ");
                    err2.ShowDialog();


                    return;
                }

                WarningErr2 err = new WarningErr2("Data registration", "completed", "Green");
                err.ShowDialog();

                //******* disable BTScanLib
                btScanLib.OnScan -= btScanLib_OnScan;
                btScanLib.Disable();

                Form frm = new FrmInboundInspection();
                frm.ShowDialog();
                this.Close();
            }

            }
            catch (Exception)
            {

                WarningErr1 err1 = new WarningErr1("Package Type Master Not Found ");
                err1.ShowDialog();


                return;
            }

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            string quantity = "0";
            string kanbanSerialNo = "";
            string strStatus = "";

            int row = dataGrid1.CurrentCell.RowNumber;

            //MessageBox.Show(row.ToString());

            int selectIndex = row;

            if (selectIndex >= 0)
            {
                kanbanSerialNo = lstTable[selectIndex].serialNo.ToString();
                quantity = lstTable[selectIndex].qtySerial.ToString();
                strStatus = lstTable[selectIndex].statusSerial.ToString();
            }

            else
            {
                selectIndex = lstTable.Count - 1;

                if (selectIndex >= 0)
                {
                    kanbanSerialNo = lstTable[selectIndex].serialNo.ToString();
                    quantity = lstTable[selectIndex].qtySerial.ToString();
                    strStatus = lstTable[selectIndex].statusSerial.ToString();
                }

                else
                {
                    return;
                }

            }

            //MessageBox.Show(quantity + "  |  " + kanbanSerialNo);


            DeleteInspectionDetail(quantity, kanbanSerialNo, strStatus);

            if (lstTableShow.Count == 0)
            {
                sysClassKanban = "";
            }

        }

        private void btnAllDelete_Click(object sender, EventArgs e)
        {
            DeleteAllInspectionDetail();

            sysClassKanban = "";
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            //FrmInboundInspection._Form_InboundInspectionInstance.ShowDialog();
            //Bt.ScanLib.Control.btScanDisable();
            //this.Hide();

            //******* disable BTScanLib
            btScanLib.OnScan -= btScanLib_OnScan;
            btScanLib.Disable();

            Form frm = new FrmInboundInspection();
            frm.ShowDialog();
            this.Close();
        }



        private void btnNextPage_Click(object sender, EventArgs e)
        {
            RowStart = RowStart + 10;
            RowEnd = RowEnd + 10;

            SetTable(1);
        }

        private void btnBackPage_Click_1(object sender, EventArgs e)
        {
            RowStart = RowStart - 10;
            RowEnd = RowEnd - 10;

            if (RowStart < 0)
            {
                RowStart = 0;
                RowEnd = 9;
            }

            SetTable(1);
        }



    }
}