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 FrmStockTaking : Form
    {
        public static FrmStockTaking _Form_StockTakingInstance;
        public String AppPath = "";
        public List<List<string>> tableList;
        List<DisplayTable> lstTable = new List<DisplayTable>();
        private BtScanLib btScanLib;

        public FrmStockTaking()
        {
            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.FrmStockTaking_KeyDown);

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

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

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

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

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

        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;

            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
                {

                    txtPartsNo.Text = partNoScan;

                    startStocktaking(partNoScan, kanbanSerialNo, quantity);


                    //string takingMonth = dtpCheckDate.Value.ToString("yyyyMM");

                    //Int32 intCheckTaking = SelectStocktaking(takingMonth, partNoScan, kanbanSerialNo);

                    //if (intCheck1 == 2)
                    //{
                    //    WarningErr1 err = new WarningErr1("Stock Taking Not Found");
                    //    err.ShowDialog();

                    //    dataGrid1.Focus();

                    //    return;

                    //}

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

                    //    dataGrid1.Focus();

                    //    return;
                    //}

                                    

                }
                catch (Exception)
                {


                }

            }
        }

        

        private Int32 SelectStocktaking(string takingMonth, string partNo, string serialNo, string qty)
        {
            try
            {

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

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

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

                Decimal dQty = Convert.ToDecimal(qty);

                strSQL = "EXEC sp_get_Stock_Taking_table_HT @takingMonth = '" + takingMonth
                    + "' , @partNo = '" + partNo + "' , @serialNo = '" + serialNo
                    + "' , @qty =" + dQty + " , @userId = '" + FrmLogin._Form_LoginInstance.userName
                    + "'";

                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)
                {
                    lstTable.Clear();

                    for (int i = 0; i <= dt.Rows.Count - 1; i++)
                    {
                        
                        string strRow = dt.Rows[i]["DRow"].ToString();
                        string strPartNo = dt.Rows[i]["item_id"].ToString();
                        string strLocationId = dt.Rows[i]["location_id"].ToString();
                        string strStQty = dt.Rows[i]["qty"].ToString();
                        string strActQty = dt.Rows[i]["st_qty"].ToString();

                        //strStQty = strStQty.Substring(0, strStQty.Length - 3);
                        //strActQty = strActQty.Substring(0, strActQty.Length - 3);

                        lstTable.Add(new DisplayTable
                        {
                            DRow = strRow,
                            Partno = strPartNo,
                            locationId = strLocationId,
                            Qty = strStQty,
                            ActQty = strActQty
                        });

                    }

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

                    InitialDataGrid();


                    dataGrid1.Focus();


                    return 1;
                }
                else
                {
                    return 2;
                }




            }
            catch (Exception)
            {

                return 3;

            }


        }

        private Int32 ConfirmStocktaking(string takingMonth, string partNo, string location, string qty)
        {
            try
            {

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

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

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


                Decimal dQty = Convert.ToDecimal(qty);


                strSQL = "EXEC sp_confirm_Stock_Taking_table @takingMonth = '" + takingMonth
                    + "' , @partNo = '" + partNo + "' , @location = '" + location
                    + "' , @qty =" + dQty + " , @userId = '" + FrmLogin._Form_LoginInstance.userName
                    + "'";

                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)
                //{
                //    lstTable.Clear();

                //    for (int i = 0; i <= dt.Rows.Count - 1; i++)
                //    {
                //        string strRow = dt.Rows[i]["DRow"].ToString();
                //        string strPartNo = dt.Rows[i]["item_id"].ToString();
                //        string strLocationId = dt.Rows[i]["location_id"].ToString();
                //        string strStQty = dt.Rows[i]["st_qty"].ToString();
                //        string strActQty = dt.Rows[i]["qty"].ToString();

                //        lstTable.Add(new DisplayTable
                //        {
                //            DRow = strRow,
                //            Partno = strPartNo,
                //            locationId = strLocationId,
                //            Qty = strStQty,
                //            ActQty = strActQty
                //        });

                //    }

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

                //    InitialDataGrid();


                //    dataGrid1.Focus();


                //    return 1;
                //}
                //else
                //{
                //    return 2;
                //}

                return 1;


            }
            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 = 25;
            tbc0.MappingName = "DRow";
            tbc0.HeaderText = "#";
            tableStyle.GridColumnStyles.Add(tbc0);

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

            // Column 2
            DataGridTextBoxColumn tbc2 = new DataGridTextBoxColumn();
            tbc2.Width = 50;
            tbc2.MappingName = "locationId";
            tbc2.HeaderText = "Location";
            tableStyle.GridColumnStyles.Add(tbc2);

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

            // Column 4
            DataGridTextBoxColumn tbc4 = new DataGridTextBoxColumn();
            tbc4.Width = 35;
            tbc4.MappingName = "ActQty";
            tbc4.HeaderText = "Act";
            tableStyle.GridColumnStyles.Add(tbc4);

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


        }


        private void FrmStockTaking_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_StockTakingInstance = 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;


            startStocktaking("", "", "0");

        }

        private void startStocktaking(string partNo, string serialNo, string qty)
        {
            string takingMonth = dtpCheckDate.Value.ToString("yyyyMM");

            Int32 intCheckTaking = SelectStocktaking(takingMonth, partNo, serialNo, qty);

            if (intCheckTaking == 2)
            {
                WarningErr1 err = new WarningErr1("Stock Taking Not Found");
                err.ShowDialog();

                dataGrid1.Focus();

                return;

            }

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

                dataGrid1.Focus();

                return;
            }
        }

        private Int32 startConfirmStocktaking(string partNo, string location, string qty)
        {
            string takingMonth = dtpCheckDate.Value.ToString("yyyyMM");

            Int32 intCheckTaking = ConfirmStocktaking(takingMonth, partNo, location, qty);

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

                //dataGrid1.Focus();

                return 3;
            }
            else
            {
                return 1;
            }
        }

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

            FrmStockMenu._Form_StockMenuInstance.Show();
            //Bt.ScanLib.Control.btScanDisable();
            //this.Hide();
            this.Close();
        }

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

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

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

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

                return;
            }


            foreach (var item in lstTable)
            {

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

                //    //InsertStockTracking(item.Partno, txtLocation.Text, item.serialNo, item.qtySerial);

                //    InsertInbound(item.Partno, txtLocation.Text, item.serialNo, item.qtySerial);

                //}
                Int32 intCheckTaking = startConfirmStocktaking(item.Partno, item.locationId, item.Qty);

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

                    dataGrid1.Focus();

                    return;
                }

            }

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

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

            FrmStockMenu._Form_StockMenuInstance.Show();
            //Bt.ScanLib.Control.btScanDisable();
            //this.Hide();
            this.Close();
        }

        private void dtpCheckDate_ValueChanged(object sender, EventArgs e)
        {
            txtPartsNo.Text = "";

            startStocktaking("", "", "0");
        }
    }
}