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 FrmStoreInbound : Form
    {
        public static FrmStoreInbound _Form_StoreInboundInstance;
        public String AppPath = "";
        public List<List<string>> tableList;
        List<DisplayTable> lstTable = new List<DisplayTable>();
        List<DisplayTable> lstTableShow = new List<DisplayTable>();
        List<DisplayTable> lstTableTemp = new List<DisplayTable>();
        private BtScanLib btScanLib;
        private String sysKanbanCode = "";
        private String sysKanbanPart = "";
        private String sysKanbanSerial = "";
        private String sysRow = "";
        public Int32 RowStart = 0;
        public Int32 RowEnd = 9;
        private String sysClassKanban = "";

        public FrmStoreInbound()
        {
            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.FrmStoreInbound_KeyDown);

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

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

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

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

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

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

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

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

        }

        private void FrmStoreInbound_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_StoreInboundInstance = 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;

            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;

            btnNextPage.Enabled = false;
            btnBackPage.Enabled = false;

        }

        private Int32 CheckLocationScan(string location)
        {
            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;

                Int32 qtyScan = 0;


                strSQL = "EXEC sp_get_location @location = '" + location
                    + "'";

                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];

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


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

            }
            catch (Exception)
            {
                return 3;

            }


        }

        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 = 67;
            tbc1.MappingName = "Partno";
            tbc1.HeaderText = "Part no";
            tableStyle.GridColumnStyles.Add(tbc1);

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

            // Column 3
            DataGridTextBoxColumn tbc3 = new DataGridTextBoxColumn();
            tbc3.Width = 40;
            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 SetTable(Int32 processStart)
        {

            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;

            lstTableShow.Clear();

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

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

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

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

                if ((lstTable.Count % 10) > 0)
                {
                    iPage = iPage + 1;
                }

                RowStart = (iPage * 10) - 10;
                RowEnd = RowStart + 9;

            }

            Int32 iRow = 0;
            foreach (var item in lstTable)
            {
                //MessageBox.Show(iRow.ToString() + " | " + RowStart.ToString() + " | " + RowEnd.ToString());

                iRow = iRow + 1;
                if ((iRow >= RowStart + 1) && (iRow <= RowEnd + 1))
                {
                    //iRow = iRow + 1;
                    lstTableShow.Add(new DisplayTable
                    {
                        Partno = item.Partno,
                        DRow = iRow.ToString(),
                        serialNo = item.serialNo,
                        qtySerial = item.qtySerial,
                        statusSerial = item.statusSerial
                    });

                    Int32 rowCheck = iRow % 10;
                    String strStatus = item.statusSerial;

                    if (rowCheck == 0)
                    {
                        rowCheck = 10;
                    }

                    switch (rowCheck)
                    {
                        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;
                    }

                }
            }

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

            InitialDataGrid();

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

            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;

                Int32 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 Int32 CheckItemLocation(string Location, string partNo)
        {
            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;

                Int32 qtyScan = 0;


                strSQL = "EXEC sp_get_item_location @partNo = '" + partNo
                    + "' , @location = '" + Location + "'";

                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;

            }


        }




        void btScanLib_OnScan(string result)
        {

            if (txtLocation.Text == "")
            {
                string location = result;
                Int32 intCheck = CheckLocationScan(location);

                if (intCheck == 1)
                {
                    txtLocation.Text = result;
                    return;
                }
                else if (intCheck == 2)
                {
                    WarningErr1 err = new WarningErr1("Scan Location Incorrect");
                    err.ShowDialog();

                    txtLocation.Focus();

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

                    txtLocation.Focus();

                }

            }
            else
            {

                string[] kanban = result.Split('|');
                string kanbanCode = "";
                string kanbanClass = "";
                string remainderClass = "";
                string partNoScan = "";
                string quantity = "0";
                string kanbanSerialNo = "";
                Int32 intCheck1 = 0;
                string strStatus = "";
                bool blCheckDuplicate = false;
                string quantityAll = "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 (lstTable.Count == 0)
                        {
                            strStatus = "OK";
                            sysKanbanCode = kanbanCode;
                            sysKanbanPart = partNoScan;
                            sysKanbanSerial = kanbanSerialNo;
                            sysRow = "1";


                            Int32 intCheckIL = CheckItemLocation(txtLocation.Text,sysKanbanPart);

                            if (intCheckIL == 2)
                            {
                                strStatus = "NG";
                            }

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

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

                                dataGrid1.Focus();

                                return;
                            }


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


                            if ((intCheck == 1) || (intCheck == 2))
                            {
                                strStatus = "NG";

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

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

                                dataGrid1.Focus();

                                return;
                            }
                                                                                 

                            lstTable.Add(new DisplayTable
                            {
                                Partno = partNoScan,
                                DRow = sysRow,
                                serialNo = kanbanSerialNo,
                                qtySerial = quantity,
                                statusSerial = strStatus,
                                kanbanCode = kanbanCode,
                                kanbanClass = kanbanClass,
                                remainderClass = remainderClass

                            });


                            SetTable(3);

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

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

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

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

                                dataGrid1.Focus();

                                return;
                            }

                            if (intCheck == 1)
                            {

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

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

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

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

                                dataGrid1.Focus();

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

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

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

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

                                dataGrid1.Focus();

                                return;
                            }

                            lblQtyAll.Text = quantity;

                        }
                        else
                        {
                            quantityAll = "0";
                            foreach (var item in lstTable)
                            {

                                if (item.serialNo == kanbanSerialNo)
                                {
                                    blCheckDuplicate = true;

                                }

                                if (item.statusSerial == "OK")
                                {

                                    quantityAll = (Convert.ToDecimal(quantityAll) + Convert.ToDecimal(item.qtySerial)).ToString();

                                }

                            }

                            
                            if (blCheckDuplicate == true)
                            {
                                sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                strStatus = "NG";
                                lstTable.Add(new DisplayTable
                                {
                                    Partno = partNoScan,
                                    DRow = sysRow,
                                    serialNo = kanbanSerialNo,
                                    qtySerial = quantity,
                                    statusSerial = strStatus,
                                    kanbanCode = kanbanCode,
                                    kanbanClass = kanbanClass,
                                    remainderClass = remainderClass
                                });

                                SetTable(3);

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

                                //InitialDataGrid();

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

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

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

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

                                dataGrid1.Focus();

                                return;
                            }
                            else if (partNoScan != sysKanbanPart)
                            {
                                sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                strStatus = "NG";
                                lstTable.Add(new DisplayTable
                                {
                                    Partno = partNoScan,
                                    DRow = sysRow,
                                    serialNo = kanbanSerialNo,
                                    qtySerial = quantity,
                                    statusSerial = strStatus,
                                    kanbanCode = kanbanCode,
                                    kanbanClass = kanbanClass,
                                    remainderClass = remainderClass
                                });

                                SetTable(3);

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

                                //InitialDataGrid();

                                //******* 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();

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

                                dataGrid1.Focus();

                                return;
                            }
                            else if (kanbanCode != sysKanbanCode)
                            {
                                sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                strStatus = "NG";
                                lstTable.Add(new DisplayTable
                                {
                                    Partno = partNoScan,
                                    DRow = sysRow,
                                    serialNo = kanbanSerialNo,
                                    qtySerial = quantity,
                                    statusSerial = strStatus,
                                    kanbanCode = kanbanCode,
                                    kanbanClass = kanbanClass,
                                    remainderClass = remainderClass
                                });

                                SetTable(3);

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

                                //InitialDataGrid();

                                //******* 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();

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

                                dataGrid1.Focus();

                                return;
                            }
                            else
                            {
                                Int32 intCheckIL = CheckItemLocation(txtLocation.Text, sysKanbanPart);

                                if (intCheckIL == 2)
                                {
                                    sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                    strStatus = "NG";
                                    lstTable.Add(new DisplayTable
                                    {
                                        Partno = partNoScan,
                                        DRow = sysRow,
                                        serialNo = kanbanSerialNo,
                                        qtySerial = quantity,
                                        statusSerial = strStatus,
                                        kanbanCode = kanbanCode,
                                        kanbanClass = kanbanClass,
                                        remainderClass = remainderClass
                                    });

                                    SetTable(3);

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

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

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

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

                                    dataGrid1.Focus();

                                    return;
                                }



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

                                if (intCheck == 1)
                                {
                                    sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                    strStatus = "NG";
                                    lstTable.Add(new DisplayTable
                                    {
                                        Partno = partNoScan,
                                        DRow = sysRow,
                                        serialNo = kanbanSerialNo,
                                        qtySerial = quantity,
                                        statusSerial = strStatus,
                                        kanbanCode = kanbanCode,
                                        kanbanClass = kanbanClass,
                                        remainderClass = remainderClass
                                    });

                                    SetTable(3);

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

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

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

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

                                    dataGrid1.Focus();

                                    return;
                                }
                                else if (intCheck == 2)
                                {
                                    sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                    strStatus = "NG";
                                    lstTable.Add(new DisplayTable
                                    {
                                        Partno = partNoScan,
                                        DRow = sysRow,
                                        serialNo = kanbanSerialNo,
                                        qtySerial = quantity,
                                        statusSerial = strStatus,
                                        kanbanCode = kanbanCode,
                                        kanbanClass = kanbanClass,
                                        remainderClass = remainderClass
                                    });

                                    SetTable(3);

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

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

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

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

                                    dataGrid1.Focus();

                                    return;
                                }

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

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

                                    dataGrid1.Focus();

                                    return;
                                }





                                sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                strStatus = "OK";
                                quantityAll = (Convert.ToDecimal(quantityAll) + Convert.ToDecimal(quantity)).ToString();
                                lblQtyAll.Text = quantityAll;
                                lstTable.Add(new DisplayTable
                                {
                                    Partno = partNoScan,
                                    DRow = sysRow,
                                    serialNo = kanbanSerialNo,
                                    qtySerial = quantity,
                                    statusSerial = strStatus,
                                    kanbanCode = kanbanCode,
                                    kanbanClass = kanbanClass,
                                    remainderClass = remainderClass
                                });

                                SetTable(3);

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

                                //InitialDataGrid();

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

                                //dataGrid1.Focus();
                            }
                        }



                    }
                    catch (Exception)
                    {

                    }

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

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

                    dataGrid1.Focus();
                }

            }

        }



        private void btnBack_Click(object sender, EventArgs e)
        {
            //******* disable BTScanLib
            btScanLib.OnScan -= btScanLib_OnScan;
            btScanLib.Disable();

            FrmInboundMenu._Form_InboundMenuInstance.Show();
            //Bt.ScanLib.Control.btScanDisable();
            //this.Hide();
            this.Close();
        }

        private Int32 UpdateStatusKanban(string kanbanCode, string kanbanClass, string partNo, string kanbanSerialNo, Int32 status, 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;

                Int32 qtyScan = 0;


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

               
                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;

            }


        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (lstTable.Count == 0)
            {
                WarningErr1 errEmptyData = new WarningErr1("Empty Data ");
                errEmptyData.ShowDialog();

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

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

            foreach (var item in lstTable)
            {

                if (item.statusSerial == "OK")
                {

                    Int32 intCheck1 = InsertInbound(item.Partno, txtLocation.Text, item.serialNo, item.qtySerial
                        , item.kanbanCode, item.kanbanClass, item.remainderClass);

                    if (intCheck1 == 3)
                    {

                        WarningErr1 err1 = new WarningErr1("Error Database Connection ");
                        err1.ShowDialog();

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

                        dataGrid1.Focus();

                        return;
                    }

                    Int32 intCheck = UpdateStatusKanban(item.kanbanCode, item.kanbanClass, item.Partno, item.serialNo, 1, item.remainderClass);

                    if (intCheck == 3)
                    {

                        WarningErr1 err2 = new WarningErr1("Error Database Connection ");
                        err2.ShowDialog();

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

                        dataGrid1.Focus();
                                               
                        return;
                    }

                }

            }

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

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

            FrmInboundMenu._Form_InboundMenuInstance.Show();
            //Bt.ScanLib.Control.btScanDisable();
            //this.Hide();
            this.Close();

        }

        private Int32 InsertInbound(string partNo, string locationId, string serial, string quantity, 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_Inbound @partNo = '" + partNo
                    + "' , @locationId = '" + locationId + "' , @serial = '" + serial
                    + "' , @qtySerial = " + quantity + " , @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;

                return 1;

            }
            catch (Exception)
            {
                return 3;
            }

        }

        private void FrmStoreInbound_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 void btnDelete_Click(object sender, EventArgs e)
        {
            if (lstTable.Count == 0)
            {
                return;
            }

            int row = dataGrid1.CurrentCell.RowNumber;

            if (row == -1)
            {
                row = lstTable.Count;
            }
            
            lstTable.RemoveAt(Convert.ToInt32(dataGrid1[row, 0].ToString()) - 1);
            
            //lstTable.RemoveAt(row);
            int iRow = 1;
            lstTableTemp.Clear();
            foreach (var item in lstTable)
            {

                lstTableTemp.Add(new DisplayTable
                {
                    Partno = item.Partno,
                    DRow = iRow.ToString(),
                    serialNo = item.serialNo,
                    qtySerial = item.qtySerial,
                    statusSerial = item.statusSerial
                });


                iRow = iRow + 1;
            }
            lstTable.Clear();
            foreach (var item in lstTableTemp)
            {
                
                lstTable.Add(new DisplayTable
                {
                    Partno = item.Partno,
                    DRow = item.DRow,
                    serialNo = item.serialNo,
                    qtySerial = item.qtySerial,
                    statusSerial = item.statusSerial
                });
                          
            }


            String quantityAll = "0";
            foreach (var item in lstTable)
            {


                if (item.statusSerial == "OK")
                {
                    quantityAll = (Convert.ToInt32(quantityAll) + Convert.ToInt32(item.qtySerial)).ToString();

                }


            }

            lblQtyAll.Text = quantityAll;

            SetTable(3);

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

            //InitialDataGrid();

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

            //dataGrid1.Focus();
        }

        private void btnAllDelete_Click(object sender, EventArgs e)
        {
            lstTable.Clear();

            SetTable(0);

            lblQtyAll.Text = string.Empty;

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

            //InitialDataGrid();

            //dataGrid1.Focus();

        }
               

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

            SetTable(1);
        }

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

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

            SetTable(1);
        }
    }
}