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 FrmReOutbound : Form
    {
        public static FrmReOutbound _Form_ReOutboundInstance;
        public String AppPath = "";
        public List<List<string>> tableList;
        List<DisplayTable> lstTableStore = new List<DisplayTable>();
        List<DisplayTable> lstTableShow = new List<DisplayTable>();
        List<DisplayTable> lstTableTemp = new List<DisplayTable>();
        private BtScanLib btScanLib;
        private String sysKanbanCodeStore = "";
        private String sysKanbanPart = "";
        private String sysKanbanSerial = "";
        private String sysRow = "";
        private bool scanSotre = true;
        public Int32 RowStart = 0;
        public Int32 RowEnd = 9;
        public Decimal qtyReOutboung = 0;

        public FrmReOutbound()
        {
            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.FrmReOutbound_KeyDown);

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

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

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

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

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

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

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

        private void FrmReOutbound_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_ReOutboundInstance = 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;

            qtyReOutboung = 0;

        }

        private Int32 CheckInboundScan(string partNo, string kanbanSerialNo, Decimal qtyScan,
            string kanbanCode, string kanbanClass, string remainderClass)
        {
            try
            {
                qtyReOutboung = 0;

                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 iRow = 0;


                strSQL = "EXEC sp_get_Inbound_part_ReOutbound @partNo = '" + partNo
                    + "' , @serialNo = '" + kanbanSerialNo + "' , @qtyScan = "
                    + qtyScan + ""
                    + " , @kanbanCode = '" + kanbanCode
                    + "' , @kanbanClass = '" + kanbanClass
                    + "' , @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];

                iRow = dt.Rows.Count;

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


                if (iRow > 0)
                {

                    //if (dt.Rows[0]["item_id"].ToString() == "")
                    //{

                    qtyReOutboung = Convert.ToDecimal(dt.Rows[0]["qty"].ToString());
                    return 4;
                    //}
                    //else
                    //{
                    //    return 1;
                    //}
                }
                else
                {
                    return 2;
                }




            }
            catch (Exception)
            {

                return 3;

            }


        }

        void btScanLib_OnScan(string result)
        {
            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";
            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];

                try
                {
                    intCheck = CheckInboundScan(partNoScan, kanbanSerialNo, Convert.ToDecimal(quantity),
                        kanbanCode, kanbanClass, remainderClass);

                    if (intCheck == 4)
                    {
                        //quantity = qtyReOutboung.ToString().Substring(0,qtyReOutboung.ToString().Length - 3);
                        quantity = qtyReOutboung.ToString();

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

                        if (Convert.ToDecimal(quantity) > qtyReOutboung)
                        {
                            WarningErr1 err = new WarningErr1("Over Inbound ");
                            err.ShowDialog();

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

                            dgStoreKanban.Focus();

                            return;
                        }


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

                        FrmWarningLeader err = new FrmWarningLeader("Inbound not found", "data", "");
                        err.ShowDialog();

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

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

                        dgStoreKanban.Focus();

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

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

                        dgStoreKanban.Focus();

                        return;
                    }

                    if (lstTableStore.Count == 0)
                    {
                        strStatus = "OK";
                        sysKanbanCodeStore = kanbanCode;
                        sysKanbanPart = partNoScan;
                        sysKanbanSerial = kanbanSerialNo;
                        sysRow = "1";


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


                        if ((intCheck2 == 4) || (intCheck2 == 2))
                        {
                            strStatus = "NG";

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

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

                            dgStoreKanban.Focus();

                            return;
                        }


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

                        SetTable(3);

                        if (intCheck2 == 4)
                        {

                            //******* 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)
                            {
                                dgStoreKanban.CurrentRowIndex = lstTableShow.Count - 1;
                            }

                            dgStoreKanban.Focus();

                            return;
                        }
                        else if (intCheck2 == 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)
                            {
                                dgStoreKanban.CurrentRowIndex = lstTableShow.Count - 1;
                            }

                            dgStoreKanban.Focus();

                            return;
                        }



                        lblQtyAll.Text = quantity;

                        //lblTypeStore.Text = checkTypeKanban(sysKanbanCodeStore);


                        string checkType = CheckTypeKanbanScan(sysKanbanCodeStore);

                        if (checkType == "2")
                        {
                            lblTypeStore.Text = checkTypeKanban(sysKanbanCodeStore);
                        }
                        else if (checkType == "3")
                        {
                            WarningErr1 err = new WarningErr1("Error Database Connection ");
                            err.ShowDialog();

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

                            dgStoreKanban.Focus();

                            return;
                        }
                        else
                        {
                            lblTypeStore.Text = checkType;
                        }


                        //lstTableStore.Add(new DisplayTable
                        //{
                        //    Partno = partNoScan,
                        //    DRow = sysRow,
                        //    serialNo = kanbanSerialNo,
                        //    qtySerial = quantity,
                        //    statusSerial = strStatus,
                        //    kanbanCode = kanbanCode,
                        //    kanbanClass = kanbanClass,
                        //    remainderClass = remainderClass
                        //});

                        //SetTable(3);


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

                            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";
                            lstTableStore.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>(lstTableStore);
                            //dgStoreKanban.DataSource = blist;

                            //InitialDataGridStoreKanban();

                            //******* 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)
                            {
                                dgStoreKanban.CurrentRowIndex = lstTableShow.Count - 1;
                            }

                            dgStoreKanban.Focus();

                            return;
                        }
                        else if (partNoScan != sysKanbanPart)
                        {
                            sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                            strStatus = "NG";
                            lstTableStore.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>(lstTableStore);
                            //dgStoreKanban.DataSource = blist;

                            //InitialDataGridStoreKanban();

                            //******* 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)
                            {
                                dgStoreKanban.CurrentRowIndex = lstTableShow.Count - 1;
                            }

                            dgStoreKanban.Focus();

                            return;
                        }
                        else if (kanbanCode != sysKanbanCodeStore)
                        {
                            sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                            strStatus = "NG";
                            lstTableStore.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>(lstTableStore);
                            //dgStoreKanban.DataSource = blist;

                            //InitialDataGridStoreKanban();

                            //******* 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)
                            {
                                dgStoreKanban.CurrentRowIndex = lstTableShow.Count - 1;
                            }

                            dgStoreKanban.Focus();

                            return;
                        }
                        else
                        {

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

                            if (intCheck4 == 4)
                            {
                                sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                strStatus = "NG";
                                lstTableStore.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)
                                {
                                    dgStoreKanban.CurrentRowIndex = lstTableShow.Count - 1;
                                }

                                dgStoreKanban.Focus();

                                return;
                            }
                            else if (intCheck4 == 2)
                            {
                                sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                strStatus = "NG";
                                lstTableStore.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)
                                {
                                    dgStoreKanban.CurrentRowIndex = lstTableShow.Count - 1;
                                }

                                dgStoreKanban.Focus();

                                return;
                            }

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

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

                                dgStoreKanban.Focus();

                                return;
                            }


                            sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                            strStatus = "OK";
                            quantityAll = (Convert.ToDecimal(quantityAll) + Convert.ToDecimal(quantity)).ToString();
                            lblQtyAll.Text = quantityAll;
                            lstTableStore.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>(lstTableStore);
                            //dgStoreKanban.DataSource = blist;

                            //InitialDataGridStoreKanban();

                            //if (lstTableStore.Count > 0)
                            //{
                            //    dgStoreKanban.CurrentRowIndex = lstTableStore.Count - 1;
                            //}

                            //dgStoreKanban.Focus();
                        }
                    }



                }
                catch (Exception)
                {

                }

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

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

                dgStoreKanban.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 string CheckTypeKanbanScan(string kanbanCode)
        {
            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;


                strSQL = "EXEC sp_get_kanban_code @kanbanCode = '" + kanbanCode
                    + "'";

                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 dt.Rows[0]["kanban_name"].ToString();


                }
                else
                {
                    return "2";
                }




            }
            catch (Exception)
            {

                return "3";

            }


        }

        private string checkTypeKanban(string kanbanCode)
        {
            switch (kanbanCode)
            {
                case "1":
                    return "Material";
                case "2":
                    return "Molding Shopping";
                case "3":
                    return "Molding FG Kanban";
                case "4":
                    return "Insert";
                case "5":
                    return "Process";
                case "6":
                    return "Supplier";
                case "7":
                    return "Shopping";
                case "8":
                    return "FG";
                case "9":
                    return "Lot card";
                case "10":
                    return "Customer";
                case "11":
                    return "Remainder";
                case "12":
                    return "Setup card";
                default:
                    return "";
            }
        }

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

            FrmOutboundMenu._Form_OutboundMenuInstance.Show();
            //Bt.ScanLib.Control.btScanDisable();
            //this.Hide();
            this.Close();
        }

        private void FrmReOutbound_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 (lstTableStore.Count == 0)
            {
                return;
            }

            int row = dgStoreKanban.CurrentCell.RowNumber;

            if (row == -1)
            {
                row = lstTableStore.Count;
            }

            lstTableStore.RemoveAt(Convert.ToInt32(dgStoreKanban[row, 0].ToString()) - 1);

            //lstTableStore.RemoveAt(row);

            int iRow = 1;
            lstTableTemp.Clear();
            foreach (var item in lstTableStore)
            {

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


                iRow = iRow + 1;
            }
            lstTableStore.Clear();
            foreach (var item in lstTableTemp)
            {

                lstTableStore.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 lstTableStore)
            {

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

                }

            }

            if (lstTableStore.Count == 0)
            {
                lblTypeStore.Text = string.Empty;
                lblQtyAll.Text = string.Empty;
            }
            else
            {
                lblQtyAll.Text = quantityAll;
            }

            SetTable(3);

            //var blist = new BindingList<DisplayTable>(lstTableStore);
            //dgStoreKanban.DataSource = blist;

            //InitialDataGridStoreKanban();

            //if (lstTableStore.Count > 0)
            //{
            //    dgStoreKanban.CurrentRowIndex = lstTableStore.Count - 1;
            //}

            //dgStoreKanban.Focus();
        }

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

            SetTable(0);

            //var blist1 = new BindingList<DisplayTable>(lstTableStore);
            //dgStoreKanban.DataSource = blist1;

            //InitialDataGridStoreKanban();

            //dgStoreKanban.Focus();

            lblQtyAll.Text = string.Empty;
            lblTypeStore.Text = string.Empty;
        }

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

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

                dgStoreKanban.Focus();

                return;
            }

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

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

                        dgStoreKanban.Focus();

                        return;
                    }
                }
            }

            foreach (var item in lstTableStore)
            {

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

                    Int32 intCheck1 = InsertOutbound(item.Partno, 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)
                        {
                            dgStoreKanban.CurrentRowIndex = lstTableShow.Count - 1;
                        }

                        dgStoreKanban.Focus();

                        return;
                    }

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

                    if (intCheck == 3)
                    {

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

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

                        dgStoreKanban.Focus();

                        return;
                    }

                }

            }

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

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

            FrmOutboundMenu._Form_OutboundMenuInstance.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;

                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 + " , @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 Int32 InsertOutbound(string partNo, 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_Stock_Tracking_Outbound @partNo = '" + partNo
                //    + "' , @serial = '" + serial
                //    + "' , @qtySerial = " + quantity + " , @userId = '" + FrmLogin._Form_LoginInstance.userName
                //    + "'";

                strSQL = "EXEC sp_update_Outbound @partNo = '" + partNo
                    + "' , @serial = '" + serial
                    + "' , @qtySerial = " + qtyScan + " , @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 InitialDataGridStoreKanban()
        {
            int grid_width = 445;
            // hidden column and row header
            dgStoreKanban.ColumnHeadersVisible = true;
            dgStoreKanban.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);

            dgStoreKanban.TableStyles.Clear();
            dgStoreKanban.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 (lstTableStore.Count > 10)
            {
                btnNextPage.Enabled = true;
                btnBackPage.Enabled = true;
            }
            else
            {
                btnNextPage.Enabled = false;
                btnBackPage.Enabled = false;
            }

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

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

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

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

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

            }

            Int32 iRow = 0;
            foreach (var item in lstTableStore)
            {
                //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);
            dgStoreKanban.DataSource = blist;

            InitialDataGridStoreKanban();

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

            dgStoreKanban.Focus();

        }

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


    }
}