using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

using System.Xml;
using System.IO;
using ABC.DanhMuc.Hang;
using System.Data;
using ABC.DanhMuc.NhomHang;
using ABC.DanhMuc.KhachHang;
using ABC.DanhMuc.NCC;
using ABC.KetNoi;
using ABC.File;
using System.Diagnostics;
using DevExpress.XtraEditors;
 using DevExpress.Utils;
using System.Xml.Linq;


namespace ABC.GiaoDich
{

    public partial class NhapSi_Forms1 : DevExpress.XtraEditors.XtraUserControl
    {
        public NhapSi_Forms1()
        {
            InitializeComponent();
            this.Text = "Nhập sỉ";

            _NhapSi_Class.load_null_data_chualuu();
            if (DuLieu.List_NhapSi_ChuaLuu != null)
            {
                gc_dangnhap.DataSource = DuLieu.List_NhapSi_ChuaLuu.Tables[0];
                look_loaica_dangnhap.DataSource = DuLieu.List_Hang.Tables[0];
                look_khachhang_dangnhap.DataSource = DuLieu.List_KhachHang.Tables[0];
                look_thuonglai_dangnhap.DataSource = DuLieu.List_NCC.Tables[0];


                gv_dangnhap.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gv_dangnhap_CellValueChanged);
                gv_kiemtra.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gv_kiemtra_CellValueChanged);
                gv_daluu.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gv_daluu_CellValueChanged);

                tab_daluu.SelectedChanged += new DevExpress.XtraBars.Ribbon.BackstageViewItemEventHandler(tab_daluu_SelectedChanged);
                tab_dangnhap.SelectedChanged += new DevExpress.XtraBars.Ribbon.BackstageViewItemEventHandler(tab_dangnhap_SelectedChanged);
                tab_kiemtra.SelectedChanged += new DevExpress.XtraBars.Ribbon.BackstageViewItemEventHandler(tab_kiemtra_SelectedChanged);

                btn_saveall.ItemClick += new DevExpress.XtraBars.Ribbon.BackstageViewItemEventHandler(btn_saveall_ItemClick);
                btnThemMoi.ItemClick += new DevExpress.XtraBars.Ribbon.BackstageViewItemEventHandler(btn_new_ItemClick);
                btn_xoa.ItemClick += new DevExpress.XtraBars.Ribbon.BackstageViewItemEventHandler(btn_xoa_ItemClick);
                btn_select_all.ItemClick += new DevExpress.XtraBars.Ribbon.BackstageViewItemEventHandler(btn_select_all_ItemClick);
                btn_unselect.ItemClick += new DevExpress.XtraBars.Ribbon.BackstageViewItemEventHandler(btn_unselect_ItemClick);
            }
        }
        #region event
        void btn_load_Click(object sender, EventArgs e)
        {
            tailai();
        }
        void btn_close_ItemClick(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            //this.Close();
        }
        void btn_unselect_ItemClick(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            bochon();
        }

        void btn_select_all_ItemClick(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            chon();
        }

        void btn_xoa_ItemClick(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            xoa();
           // tailai();
        }

        void btn_new_ItemClick(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            them();
           // tailai();
        }
        #endregion

        #region select tab
        void tab_kiemtra_SelectedChanged(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            thongke_daluu();
        }
        void tab_dangnhap_SelectedChanged(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            thongke_chualuu();
        }

        void tab_daluu_SelectedChanged(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            thongke_daluu();
        }
        #endregion

        #region gv_daluu
        DataRow row_Sua;
        string _ID_GiaoDich = "";
        string d_cu = "", d_moi = "";
        int dong = -1;
        void gv_daluu_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            string _ID = gv_daluu.GetFocusedRowCellValue("ID").ToString().Trim().ToUpper();
            dong = e.RowHandle;
            id_logic = _ID;
            if (Pow.kiemtra("NhapSi_Forms", "Sua", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                d_moi = gv_daluu.GetFocusedRowCellDisplayText(e.Column.FieldName);
                string key = string.Format("Dữ liệu sẽ thay đổi {3} [{0}] Qua [{1}] bởi [{2}] STT={4} Ngày {5}",
                    d_cu, d_moi,Main_Form._tk,e.Column.Caption, gv_daluu.GetFocusedRowCellValue("STT").ToString().Trim(), DateTime.Parse(gv_daluu.GetFocusedRowCellValue("Ngay").ToString().Trim()).ToString("dd/MM/yyyy hh:mm:ss"));
                if (d_cu != d_moi)
                {
                    if (MessageBox.Show(key, "Cảnh báo!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        DataRow dt_update = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);
                        string colum = e.Column.FieldName;
                        string value = e.Value.ToString();

                        DataRowView row_ncc = look_thuonglai_daluu.GetDataSourceRowByKeyValue(dt_update["Tbl_NCC_Name"].ToString()) as DataRowView;
                        DataRowView row_khachhang = look_khachhang_daluu.GetDataSourceRowByKeyValue(dt_update["Tbl_KhachHang_Name"].ToString()) as DataRowView;
                        DataRowView row_hang = look_loaica_daluu.GetDataSourceRowByKeyValue(dt_update["Tbl_Hang_Name"].ToString()) as DataRowView;
                        #region send telegram
                        Telegram_bot clsBot = new Telegram_bot();
                        clsBot.FormGui = this.Name;
                        clsBot.GoiNoiDungQuaTelegram(key);
                        #endregion
                        //update id referent
                        #region
                        dt_update["ID_NCC"] = row_ncc["ID"].ToString().ToUpper();
                        dt_update["ID_KhachHang"] = row_khachhang["ID"].ToString().ToUpper();
                        dt_update["ID_Hang"] = row_hang["ID"].ToString().ToUpper();
                        #endregion

                        dt_update[colum] = value;
                        DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                        //cap nhat thanh tien
                        dt_update["ThanhTien"] = decimal.Parse(dt_update["SL"].ToString()) * decimal.Parse(dt_update["Gia"].ToString());
                        DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                        gv_daluu.RefreshData();
                        thongke_daluu();
                        DataRow[] dr = DuLieu.List_NhapSi_DaLuu.Tables[0].Select("ID = '" + _ID + "'");
                        DataView view = DuLieu.List_NhapSi_DaLuu.Tables[0].DefaultView;
                        view.RowFilter = "ID='" + _ID + "'";
                        if (view.ToTable().Rows.Count > 0)
                            row_Sua = view.ToTable().Rows[0];
                        // for (int i = 0; i < dr.Length; i++)
                        // {                    
                        //dat 1 dong kiem tra id_toa
                        if (row_Sua["Toa_ID"].ToString().Length > 5)
                        {
                            // da lam toa
                            _ID_GiaoDich = _ID;
                            id_toa_logic = row_Sua["Toa_ID"].ToString().ToUpper();
                            string sql = "select * from Toa_DaTao where ID='" + id_toa_logic + "'";
                            DataTable dt_toa = _NhapSi_Class.get_dataset(sql).Tables[0];
                            DataRow row3 = dr[0];
                            _Logic_Sua = new Logic_Sua();
                            _Logic_Sua.dr = row3;
                            thanhtien_logic = double.Parse(dt_toa.Rows[0]["TTHANG"].ToString());

                            _Logic_Sua.sotoa = dt_toa.Rows[0]["TOA1"].ToString();
                            _Logic_Sua.tinhtrang = dt_toa.Rows[0]["TINHTRANG"].ToString();
                            //  row_Sua = dt_update;
                            _Logic_Sua.FormClosed += new FormClosedEventHandler(_Logic_Sua_FormClosed);
                            _Logic_Sua.ShowDialog();
                            //if (_Logic_Sua.DialogResult != DialogResult.Cancel)
                            //{
                            //    DuLieu.List_NhapSi_DaLuu.Tables[0].Rows.Remove(dr[i]);
                            //}

                        }
                        else
                        {
                            id_logic = _ID;
                            #region khong sua toa
                            string sqlSua = "sp_GiaoDich_TheoID '" + id_logic + "'";
                            Class_KetNoi db = new Class_KetNoi();
                            DataTable dtSua = db.T_opendataset(sqlSua).Tables[0];
                            DataRow row_update = null;
                            if (dtSua.Rows.Count > 0)
                                row_update = dtSua.Rows[0];
                            //xoa lun dong do
                            string sql1 = "NhapSi_Xoa '" + id_logic + "'";
                            _NhapSi_Class.set(sql1);
                            #region
                            //save and add vao muc du lieu da luu
                            string sql = "NhapSi ";
                            //  @STT
                            sql += "N'" + row_Sua["STT"].ToString().ToUpper() + "',";
                            //,@ID
                            sql += "N'" + row_Sua["ID"].ToString().ToUpper() + "',";
                            //,@ID_Hang
                            sql += "N'" + row_Sua["ID_Hang"].ToString().ToUpper() + "',";
                            //,@ID_KhachHang
                            sql += "N'" + row_Sua["ID_KhachHang"].ToString().ToUpper() + "',";
                            //,@ID_NCC
                            sql += "N'" + row_Sua["ID_NCC"].ToString().ToUpper() + "',";
                            //,@Date_Num_Final_UpDate
                            sql += "N'" + row_Sua["Date_Num_Final_UpDate"].ToString().ToUpper() + "',";
                            //,@User_ID_Final_UpDate
                            sql += "N'" + Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper() + "',";
                            //,@IS_User
                            sql += "N'" + row_update["IS_User"].ToString().ToUpper() + "',";
                            //,@NguonGoc
                            sql += "N'" + row_update["NguonGoc"].ToString().ToUpper() + "',";
                            //,@SL
                            sql += "N'" + row_Sua["SL"].ToString() + "',";
                            //,@Gia_0 --------SE THAY DOI VI LA GIA UU TIEN
                            sql += "N'" + row_Sua["Gia"].ToString() + "',";
                            //,@Gia_1            
                            sql += "N'" + row_Sua["Gia_1"].ToString() + "',";
                            //,@Gia_2
                            sql += "N'" + row_Sua["Gia_2"].ToString() + "',";
                            //,@Sot
                            sql += "N'" + row_Sua["Sot"].ToString() + "',";
                            //,@Ket
                            sql += "N'" + row_Sua["Ket"].ToString() + "',";
                            //,@TienMat
                            sql += "N'0',";

                            //,@Toa_ID
                            sql += "Null,";
                            //,@Toa_SL
                            sql += "Null,";
                            //,@Toa_Gia
                            sql += "Null,";
                            //,@Toa_HHSL
                            sql += "Null,";
                            //,@Toa_HHPC
                            sql += "Null,";
                            //,@Toa_Xoa
                            sql += "Null,";
                            //,@_Text1
                            sql += "Null,";
                            //,@_Text2
                            sql += "Null,";
                            //,@_Text3
                            sql += "Null,";
                            //,@_Text4
                            sql += "Null,";
                            //,@_Text5
                            sql += "Null,";
                            //,@_Num1
                            sql += "Null,";
                            //,@_Num2
                            sql += "Null,";
                            //,@_Num3
                            sql += "Null,";
                            //,@_ID1
                            sql += "Null,";
                            //,@Lu
                            sql += "N'" + row_Sua["Lu"].ToString() + "',";
                            //,@Cat
                            sql += "N'" + row_Sua["Cat"].ToString() + "',";
                            //,@Bom
                            sql += "N'" + row_Sua["Bom"].ToString() + "'";
                            _NhapSi_Class.set(sql);

                            #endregion

                            #endregion
                        }

                        // }
                        // gv_daluu.RefreshData();
                        //thongke_daluu();

                        tailai();
                        tab_daluu.Selected = true;
                        
                    }
                    else
                    {
                       
                        gv_daluu.CancelUpdateCurrentRow();
                        dong = -1;
                    }
                }
                else
                {
                  
                    gv_daluu.CancelUpdateCurrentRow();
                    dong = -1;
                }    
            }
        }
        #endregion

        #region gv_kiemtra
        void gv_kiemtra_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (Pow.kiemtra("NhapSi_Forms", "Sua", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                dong = e.RowHandle;
                d_moi = gv_kiemtra.GetFocusedRowCellDisplayText(e.Column.FieldName);
              //  string key = string.Format("Dữ liệu sẽ thay đổi từ [{0}] Qua [{1}]", d_cu, d_moi);
                string key = string.Format("Dữ liệu sẽ thay đổi {3} [{0}] Qua [{1}] bởi user [{2}] STT={4} Ngày {5}",
                   d_cu, d_moi, Main_Form._tk, e.Column.Caption, gv_kiemtra.GetFocusedRowCellValue("STT").ToString().Trim(), gv_kiemtra.GetFocusedRowCellValue("Ngay").ToString().Trim());
                if (d_cu != d_moi)
                {
                    if (MessageBox.Show(key, "Cảnh báo!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        #region sen telegram
                        Telegram_bot clsBot = new Telegram_bot();
                        clsBot.FormGui = this.Name;
                        clsBot.GoiNoiDungQuaTelegram(key);
                        #endregion
                        if (e.Column.FieldName != "Select")
                        {
                            #region
                            DataRow dt_update = gv_kiemtra.GetDataRow(gv_kiemtra.FocusedRowHandle);
                            string colum = e.Column.FieldName;
                            string value = e.Value.ToString();

                            DataRowView row_ncc = look_thuonglai_kiemtra.GetDataSourceRowByKeyValue(dt_update["Tbl_NCC_Name"].ToString()) as DataRowView;
                            DataRowView row_khachhang = look_khachhang_kiemtra.GetDataSourceRowByKeyValue(dt_update["Tbl_KhachHang_Name"].ToString()) as DataRowView;
                            DataRowView row_hang = look_loaica_kiemtra.GetDataSourceRowByKeyValue(dt_update["Tbl_Hang_Name"].ToString()) as DataRowView;

                            //update id referent
                            #region
                            dt_update["ID_NCC"] = row_ncc["ID"].ToString().ToUpper();
                            dt_update["ID_KhachHang"] = row_khachhang["ID"].ToString().ToUpper();
                            dt_update["ID_Hang"] = row_hang["ID"].ToString().ToUpper();
                            #endregion

                            dt_update[colum] = value;
                            DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                            //cap nhat thanh tien
                            dt_update["ThanhTien"] = decimal.Parse(dt_update["SL"].ToString()) * decimal.Parse(dt_update["Gia"].ToString());
                            DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                            gv_kiemtra.RefreshData();
                            thongke_daluu();

                            #region save to database
                            #region
                            //save and add vao muc du lieu da luu
                            string sql = "NhapSi ";
                            //  @STT
                            sql += "N'" + dt_update["STT"].ToString().ToUpper() + "',";
                            //,@ID
                            sql += "N'" + dt_update["ID"].ToString().ToUpper() + "',";
                            //,@ID_Hang
                            sql += "N'" + dt_update["ID_Hang"].ToString().ToUpper() + "',";
                            //,@ID_KhachHang
                            sql += "N'" + dt_update["ID_KhachHang"].ToString().ToUpper() + "',";
                            //,@ID_NCC
                            sql += "N'" + dt_update["ID_NCC"].ToString().ToUpper() + "',";
                            //,@Date_Num_Final_UpDate
                            sql += "N'" + dt_update["Date_Num_Final_UpDate"].ToString().ToUpper() + "',";
                            //,@User_ID_Final_UpDate
                            sql += "N'" + Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper() + "',";
                            //,@IS_User
                            sql += "N'1',";
                            //,@NguonGoc
                            sql += "N'SI',";
                            //,@SL
                            sql += "N'" + dt_update["SL"].ToString() + "',";
                            //,@Gia_0 --------SE THAY DOI VI LA GIA UU TIEN
                            sql += "N'" + dt_update["Gia"].ToString() + "',";
                            //,@Gia_1            
                            sql += "N'" + dt_update["Gia_1"].ToString() + "',";
                            //,@Gia_2
                            sql += "N'" + dt_update["Gia_2"].ToString() + "',";
                            //,@Sot
                            sql += "N'" + dt_update["Sot"].ToString() + "',";
                            //,@Ket
                            sql += "N'" + dt_update["Ket"].ToString() + "',";
                            //,@TienMat
                            sql += "N'0',";

                            //,@Toa_ID
                            sql += "Null,";
                            //,@Toa_SL
                            sql += "Null,";
                            //,@Toa_Gia
                            sql += "Null,";
                            //,@Toa_HHSL
                            sql += "Null,";
                            //,@Toa_HHPC
                            sql += "Null,";
                            //,@Toa_Xoa
                            sql += "Null,";
                            //,@_Text1
                            sql += "Null,";
                            //,@_Text2
                            sql += "Null,";
                            //,@_Text3
                            sql += "Null,";
                            //,@_Text4
                            sql += "Null,";
                            //,@_Text5
                            sql += "Null,";
                            //,@_Num1
                            sql += "Null,";
                            //,@_Num2
                            sql += "Null,";
                            //,@_Num3
                            sql += "Null,";
                            //,@_ID1
                            sql += "Null,";
                            //,@Lu
                            sql += "N'" + dt_update["Lu"].ToString() + "',";
                            //,@Cat
                            sql += "N'" + dt_update["Cat"].ToString() + "',";
                            //,@Bom
                            sql += "N'" + dt_update["Bom"].ToString() + "'";
                            _NhapSi_Class.set(sql);
                            #endregion
                            #endregion
                            #endregion
                            tailai();
                            tab_kiemtra.Selected = true;
                        }
                        else
                        {
                            if ((bool)e.Value == true)
                            {
                                DataRow dr = gv_kiemtra.GetDataRow(gv_kiemtra.FocusedRowHandle);
                                dr["Select"] = true;
                                DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                            }
                            else
                            {
                                DataRow dr = gv_kiemtra.GetDataRow(gv_kiemtra.FocusedRowHandle);
                                dr["Select"] = false;
                                DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                            }
                            gv_kiemtra.RefreshData();
                        }
                    }
                    else
                    {
                        gv_kiemtra.CancelUpdateCurrentRow();
                        dong = -1;
                    }
                }
                else
                {
                    gv_kiemtra.CancelUpdateCurrentRow();
                    dong = -1;
                }
            }
            else
            {
                gv_kiemtra.CancelUpdateCurrentRow();
                dong = -1;
            }
        }
        #endregion

        #region gv_dangnhap
        void gv_dangnhap_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (Pow.kiemtra("NhapSi_Forms", "Sua", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                if (e.Column.FieldName != "Select")
                {
                    #region
                    DataRow dt_update = gv_dangnhap.GetDataRow(gv_dangnhap.FocusedRowHandle);
                    string colum = e.Column.FieldName;
                    string value = e.Value.ToString();
                    DataRowView row_ncc = look_thuonglai_dangnhap.GetDataSourceRowByKeyValue(dt_update["Tbl_NCC_Name"].ToString()) as DataRowView;
                    DataRowView row_khachhang = look_khachhang_dangnhap.GetDataSourceRowByKeyValue(dt_update["Tbl_KhachHang_Name"].ToString()) as DataRowView;
                    DataRowView row_hang = look_loaica_dangnhap.GetDataSourceRowByKeyValue(dt_update["Tbl_Hang_Name"].ToString()) as DataRowView;

                    //update id referent
                    #region
                    dt_update["ID_NCC"] = row_ncc["ID"].ToString().ToUpper();
                    dt_update["ID_KhachHang"] = row_khachhang["ID"].ToString().ToUpper();
                    dt_update["ID_Hang"] = row_hang["ID"].ToString().ToUpper();
                    #endregion

                    dt_update[colum] = value;
                    DuLieu.List_NhapSi_ChuaLuu.Tables[0].AcceptChanges();
                    //cap nhat thanh tien
                    dt_update["ThanhTien"] = decimal.Parse(dt_update["SL"].ToString()) * decimal.Parse(dt_update["Gia_1"].ToString());
                    DuLieu.List_NhapSi_ChuaLuu.Tables[0].AcceptChanges();
                    gv_dangnhap.RefreshData();
                    thongke_chualuu();
                    //update xml
                    bool next = false;
                    #region
                    XmlDocument doc = new XmlDocument();
                    doc.Load(NhapSi_Class._xmlfile);
                    XmlNodeList aNodes = doc.SelectNodes("/NewDataSet/Table");
                    XmlNode node1 = aNodes[gv_dangnhap.FocusedRowHandle];
                    foreach (XmlNode node2 in node1.ChildNodes)
                    {
                        if (node2.Name == "ID_Hang")
                            node2.InnerText = dt_update["ID_Hang"].ToString();
                        if (node2.Name == "ID_KhachHang")
                            node2.InnerText = dt_update["ID_KhachHang"].ToString();
                        if (node2.Name == "ID_NCC")
                            node2.InnerText = dt_update["ID_NCC"].ToString();
                        if (node2.Name == "SL")
                            node2.InnerText = dt_update["SL"].ToString();
                        if (node2.Name == "Gia_1")
                            node2.InnerText = dt_update["Gia_1"].ToString();
                        if (node2.Name == "Sot")
                            node2.InnerText = dt_update["Sot"].ToString();
                        if (node2.Name == "Ket")
                            node2.InnerText = dt_update["Ket"].ToString();
                        if (node2.Name == "Lu")
                            node2.InnerText = dt_update["Lu"].ToString();
                        if (node2.Name == "Cat")
                            node2.InnerText = dt_update["Cat"].ToString();
                        if (node2.Name == "Bom")
                            node2.InnerText = dt_update["Bom"].ToString();
                        if (node2.Name == "ThanhTien")
                            node2.InnerText = dt_update["ThanhTien"].ToString();
                        if (node2.Name == "Tbl_NCC_Name")
                            node2.InnerText = dt_update["Tbl_NCC_Name"].ToString();
                        if (node2.Name == "Tbl_KhachHang_Name")
                            node2.InnerText = dt_update["Tbl_KhachHang_Name"].ToString();
                        if (node2.Name == "Tbl_Hang_Name")
                        {
                            node2.InnerText = dt_update["Tbl_Hang_Name"].ToString();
                            break;
                        }
                    }
                    doc.Save(NhapSi_Class._xmlfile);


                    #endregion
                    #endregion
                }
                else
                {
                    if ((bool)e.Value == true)
                    {
                        DataRow dr = gv_dangnhap.GetDataRow(gv_dangnhap.FocusedRowHandle);
                        dr["Select"] = true;
                        DuLieu.List_NhapSi_ChuaLuu.Tables[0].AcceptChanges();
                    }
                    else
                    {
                        DataRow dr = gv_dangnhap.GetDataRow(gv_dangnhap.FocusedRowHandle);
                        dr["Select"] = false;
                        DuLieu.List_NhapSi_ChuaLuu.Tables[0].AcceptChanges();
                    }
                    gv_dangnhap.RefreshData();
                }
            }
            else
            {
                gv_dangnhap.CancelUpdateCurrentRow();
            }
        }
        #endregion

        #region save all

        public void save()
        {


            if (DuLieu.List_NhapSi_ChuaLuu == null || DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows.Count == 0)
            {
               
                msgbox.dialog_OK_error("Không có dữ liệu để lưu.");
            }
            else
            {
                if (MessageBox.Show("Đang chọn ngày: [ " + txtngay.Text + " ]. Bạn có chắc chắn muốn lưu (Y/N)?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    for (int i = 0; i < DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows.Count; i++)
                    {
                        #region
                        //save and add vao muc du lieu da luu
                        string nd = "NhapSi ";
                        string sql = "NhapSi ";
                        //  @STT
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["STT_Them"].ToString().ToUpper() + "',";
                        //,@ID
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID"].ToString().ToUpper() + "',";
                        nd += " ID=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID"].ToString().ToUpper();
                        //,@ID_Hang
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID_Hang"].ToString().ToUpper() + "',";
                        nd += " ID_Hang=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID_Hang"].ToString().ToUpper();
                        //,@ID_KhachHang
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID_KhachHang"].ToString().ToUpper() + "',";
                        nd += " ID_KhachHang=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID_KhachHang"].ToString().ToUpper();
                        //,@ID_NCC
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID_NCC"].ToString().ToUpper() + "',";
                        nd += " ID_NCC=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID_NCC"].ToString().ToUpper();
                        //,@Date_Num_Final_UpDate
                        int ng2 = (int)(Convert.ToDateTime(txtngay2.Text) - new DateTime(1900, 1, 1)).TotalDays;
                        sql += "N'" + ng2.ToString() + "',";
                        //,@User_ID_Final_UpDate
                        sql += "N'" + Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper() + "',";
                        //,@IS_User
                        sql += "N'1',";
                        //,@NguonGoc
                        sql += "N'SI',";
                        //,@SL
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["SL"].ToString() + "',";
                        nd += " SL=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["SL"].ToString().ToUpper();
                        //,@Gia_0
                        sql += "N'0',";
                        //,@Gia_1
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Gia_1"].ToString() + "',";
                        nd += " Gia_1=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Gia_1"].ToString().ToUpper();
                        //,@Gia_2
                        sql += "N'0',";
                        //,@Sot
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Sot"].ToString() + "',";
                        nd += " Sot=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Sot"].ToString().ToUpper();
                        //,@Ket
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Ket"].ToString() + "',";
                        nd += " Ket=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Ket"].ToString().ToUpper();
                        //,@TienMat
                        sql += "N'0',";

                        //,@Toa_ID
                        sql += "Null,";
                        //,@Toa_SL
                        sql += "Null,";
                        //,@Toa_Gia
                        sql += "Null,";
                        //,@Toa_HHSL
                        sql += "Null,";
                        //,@Toa_HHPC
                        sql += "Null,";
                        //,@Toa_Xoa
                        sql += "Null,";
                        //,@_Text1
                        sql += "Null,";
                        //,@_Text2
                        sql += "Null,";
                        //,@_Text3
                        sql += "Null,";
                        //,@_Text4
                        sql += "Null,";
                        //,@_Text5
                        sql += "Null,";
                        //,@_Num1
                        sql += "Null,";
                        //,@_Num2
                        sql += "Null,";
                        //,@_Num3
                        sql += "Null,";
                        //,@_ID1
                        sql += "Null,";
                        //,@Lu
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Lu"].ToString() + "',";
                        nd += " Lu=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Lu"].ToString().ToUpper();
                        //,@Cat
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Cat"].ToString() + "',";
                        nd += " Cat=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Cat"].ToString().ToUpper();
                        //,@Bom
                        sql += "N'" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Bom"].ToString() + "'";
                        nd += " Bom=" + DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Bom"].ToString().ToUpper();
                        _NhapSi_Class.set(sql);
                        DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "", nd, "Thêm");
                        #endregion
                        #region canh bao cong no vuot
                        // DataTable dtCongNoKH = DanhSachCongNo1KH(DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID_KhachHang"].ToString().ToUpper());
                        // if(dtCongNoKH.Rows.Count>0)
                        // {
                        //     double ton = double.Parse(dtCongNoKH.Rows[0]["Ton"].ToString());
                        //    double han_muc = double.Parse(dtCongNoKH.Rows[0]["HanMuc"].ToString());
                        //    if(ton>han_muc)
                        //   {
                        //       string mess = string.Format("Khách hàng  {0} có công nợ {1} vượt hạn mức {2}!", dtCongNoKH.Rows[0]["Ten"].ToString(), ton.ToString("#,##"),han_muc.ToString("#,##"));
                        //      CapNhatChon(DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["ID_KhachHang"].ToString().ToUpper());
                        //      MessageBox.Show(mess);
                        // }
                        //}
                        #endregion
                    }
                    msgbox.dialog_OK_info("Đã lưu.");
                    //xoa gio hang
                    //xoa file xml
                    System.IO.File.Delete(NhapSi_Class._xmlfile);
                    _NhapSi_Class.load_null_data_chualuu();
                    load_dulieu_chualuu();
                    load_dulieu_daluu();
                }
            }

        }
        #endregion
        private void CapNhatChon(string ID)
        {
            Class_KetNoi db = new Class_KetNoi();
            string sql = "update Tbl_KhachHang set Chon=1 where ID='"+ID+"'";
            db.T_exc(sql);
        }
        private DataTable DanhSachCongNo1KH(string ID)
        {
            Class_KetNoi db = new Class_KetNoi();
            string sql = "with abc as(select      " +
                         " HanMuc,      " +
                         "   ID_KhachHang, " +
                         "   sum(Sum_TienNo) + Sum(Ton) - Sum(Sum_tienTra) as Ton " +
                         " FROM No_Tra_Ton_1ngay " +
                         " left join Tbl_KhachHang on No_Tra_Ton_1ngay.ID_KhachHang = Tbl_KhachHang.ID " +
                         " where Tbl_KhachHang.ID = '" + ID + "'" +
                         " group by " +
                          "    ID_KhachHang ,HanMuc) "+
                          "select *,(select Name from Tbl_KhachHang where ID=abc.ID_KhachHang)as Ten from abc";
            DataTable dt = db.T_opendataset(sql).Tables[0];
            return dt;
        }
        #region btn_saveall
        void btn_saveall_ItemClick(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            save();
        }
        #endregion      

        #region lệnh dùng chung
        NhapSi_Class _NhapSi_Class = new NhapSi_Class();
        NhapSi_New _NhapSi_New = new NhapSi_New();
        public void them()
        {
            if (Pow.kiemtra("NhapSi_Forms", "Them", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                _NhapSi_New.TextChanged += new EventHandler(_NhapSi_Form_TextChanged);
                _NhapSi_New.FormClosed += new FormClosedEventHandler(_NhapSi_New_FormClosed);
                tab_dangnhap.Selected = true;
                _NhapSi_New.ShowDialog();
            }
        }

        void _NhapSi_New_FormClosed(object sender, FormClosedEventArgs e)
        {
            _NhapSi_New = new NhapSi_New();
        }
        void _NhapSi_Form_TextChanged(object sender, EventArgs e)
        {
            load_dulieu_chualuu();
            gv_dangnhap.RefreshData();
            gv_dangnhap.FocusedRowHandle = 0;
            thongke_chualuu();
        }
        public void excel()
        {
        }
        public void xoa()
        {

            if (Pow.kiemtra("NhapSi_Forms", "Xoa", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                if (msgbox.dialog_yes_no("Xóa dòng chọn?") == DialogResult.Yes)
                {
                    if (tab_daluu.Selected == true)
                    {
                        //gv_daluu.FocusedRowHandle = 0;
                        //gv_daluu.FocusedColumn = stt_daluu;
                        xoa_daluu();
                    }
                    else
                    {
                        if (tab_kiemtra.Selected == true)
                        {
                            gv_kiemtra.FocusedRowHandle = 0;
                            gv_kiemtra.FocusedColumn = stt_kiemtra;
                            xoa_kiemtra();
                        }
                        else
                        {
                            gv_dangnhap.FocusedRowHandle = 0;
                            gv_dangnhap.FocusedColumn = stt_dangnhap;
                            xoa_dangnhap();
                        }
                    }

                }
            }
        }
        public void xoa_dangnhap()
        {
            DataRow[] dr = DuLieu.List_NhapSi_ChuaLuu.Tables[0].Select("Select = " + true + "");
            Xml_control _Xml_control = new Xml_control();
            for (int i = 0; i < dr.Length; i++)
            {
                _Xml_control.delete_xml_node(NhapSi_Class._xmlfile, dr[i]["ID"].ToString());
                DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows.Remove(dr[i]);
            }
            DuLieu.List_NhapSi_ChuaLuu.Tables[0].AcceptChanges();
            gv_dangnhap.RefreshData();
            thongke_chualuu();
        }
        public void xoa_daluu()
        {
            string sqlSua = "sp_GiaoDich_TheoID '" + id_logic + "'";
            Class_KetNoi db = new Class_KetNoi();
            DataTable dtSua = db.T_opendataset(sqlSua).Tables[0];
            if (dtSua.Rows.Count > 0)
                id_toa_logic = dtSua.Rows[0]["Toa_ID"].ToString().ToUpper().Trim();
            //DataRow[] dr = DuLieu.List_NhapSi_DaLuu.Tables[0].Select("Select = 'True'");
            //for (int i = 0; i < dr.Length; i++)
            //{
            //dat 1 dong kiem tra id_toa
            if (id_toa_logic.Length > 5)
            {
                // da lam toa
                _IDXoa = id_logic.ToUpper();



                //load toa len form
                string sql = "sp_ToaDaTao_TheoID '" + id_toa_logic.ToUpper() + "'";
                DataTable dt_toa = _NhapSi_Class.get_dataset(sql).Tables[0];
                if (dt_toa.Rows.Count > 0)
                {
                    DataRow row = dtSua.Rows[0];
                    DataRow[] dr = DuLieu.List_NhapSi_DaLuu.Tables[0].Select("ID = '" + id_logic + "'");
                    _Logic = new Logic();
                    _Logic.dr = dr[0];
                    thanhtien_logic = double.Parse(dt_toa.Rows[0]["TTHANG"].ToString());

                    _Logic.sotoa = dt_toa.Rows[0]["TOA1"].ToString();
                    _Logic.tinhtrang = dt_toa.Rows[0]["TINHTRANG"].ToString();
                    _Logic.FormClosed += new FormClosedEventHandler(_Logic_FormClosed);
                    _Logic.ShowDialog();
                    //if (_Logic.DialogResult != DialogResult.Cancel)
                    //{
                    //    DuLieu.List_NhapSi_DaLuu.Tables[0].Rows.Remove(dr[i]);
                    //}
                }
            }
            else
            {
                string sql = "NhapSi_Xoa '" + id_logic + "'";
                _NhapSi_Class.set(sql);
                DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "", "NhapSi_Xoa ID="+ id_logic, "Xoá");
                //DuLieu.List_NhapSi_DaLuu.Tables[0].Rows.Remove(dr[i]);
            }

            // }
            gv_daluu.RefreshData();
            thongke_daluu();
            tailai();
        }
        string id_logic, id_toa_logic;
        Logic _Logic;
        Logic_Sua _Logic_Sua;
        float sl_tam_tinh, gia_tam_tinh;
        double thanhtien_logic;

        void _Logic_Sua_FormClosed(object sender, FormClosedEventArgs e)
        {
            id_logic = _ID_GiaoDich;
            string sqlSua = "sp_GiaoDich_TheoID '" + id_logic + "'";
            Class_KetNoi db = new Class_KetNoi();
            DataTable dtSua = db.T_opendataset(sqlSua).Tables[0];
            DataRow row_update = null;
            if (dtSua.Rows.Count > 0)
                row_update = dtSua.Rows[0];
            if (_Logic_Sua.DialogResult == DialogResult.Yes)
            {
                //xoa lun dong do
                string sql1 = "NhapSi_Xoa '" + row_Sua["ID"].ToString().ToUpper() + "'";
                _NhapSi_Class.set(sql1);
                DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "", "NhapSi_Xoa ID=" + row_Sua["ID"].ToString().ToUpper(), "Xoá");
                #region
                //save and add vao muc du lieu da luu
                string nd = "NhapSi ";
                string sql = "NhapSi ";
                //  @STT
                sql += "N'" + row_Sua["STT"].ToString().ToUpper() + "',";
                //,@ID
                sql += "N'" + row_Sua["ID"].ToString().ToUpper() + "',";
                //,@ID_Hang
                sql += "N'" + row_Sua["ID_Hang"].ToString().ToUpper() + "',";
                nd += " ID_Hang="+ row_Sua["ID_Hang"].ToString().ToUpper();
                //,@ID_KhachHang
                sql += "N'" + row_Sua["ID_KhachHang"].ToString().ToUpper() + "',";
                nd += " ID_KhachHang=" + row_Sua["ID_KhachHang"].ToString().ToUpper();
                //,@ID_NCC
                sql += "N'" + row_Sua["ID_NCC"].ToString().ToUpper() + "',";
                nd += " ID_NCC=" + row_Sua["ID_NCC"].ToString().ToUpper();
                //,@Date_Num_Final_UpDate
                sql += "N'" + row_Sua["Date_Num_Final_UpDate"].ToString().ToUpper() + "',";
                //,@User_ID_Final_UpDate
                sql += "N'" + Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper() + "',";
                //,@IS_User
                sql += "N'" + row_update["IS_User"].ToString().ToUpper() + "',";
                //,@NguonGoc
                sql += "N'" + row_update["NguonGoc"].ToString().ToUpper() + "',";
                nd += " NguonGoc=" + row_update["NguonGoc"].ToString().ToUpper();
                //,@SL
                sql += "N'" + row_Sua["SL"].ToString() + "',";
                nd += " SL=" + row_Sua["SL"].ToString().ToUpper();
                //,@Gia_0 --------SE THAY DOI VI LA GIA UU TIEN
                sql += "N'" + row_Sua["Gia"].ToString() + "',";
                nd += " Gia=" + row_Sua["Gia"].ToString().ToUpper();
                //,@Gia_1            
                sql += "N'" + row_Sua["Gia_1"].ToString() + "',";
                nd += " Gia_1=" + row_Sua["Gia_1"].ToString().ToUpper();
                //,@Gia_2
                sql += "N'" + row_Sua["Gia_2"].ToString() + "',";
                nd += " Gia_2=" + row_Sua["Gia_2"].ToString().ToUpper();
                //,@Sot
                sql += "N'" + row_Sua["Sot"].ToString() + "',";
                nd += " Sot=" + row_Sua["Sot"].ToString().ToUpper();
                //,@Ket
                sql += "N'" + row_Sua["Ket"].ToString() + "',";
                nd += " Ket=" + row_Sua["Ket"].ToString().ToUpper();
                //,@TienMat
                sql += "N'0',";

                //,@Toa_ID
                sql += "N'" + row_update["Toa_ID"].ToString().ToUpper() + "',";
                nd += " Toa_ID=" + row_update["Ket"].ToString().ToUpper();
                //,@Toa_SL
                sql += "N'" + row_Sua["SL"].ToString() + "',";
                //,@Toa_Gia
                sql += "N'" + row_Sua["Gia"].ToString() + "',";
                //,@Toa_HHSL
                sql += "N'" + row_update["Toa_HHSL"].ToString().ToUpper() + "',";
                //,@Toa_HHPC
                sql += "N'" + row_update["Toa_HHPC"].ToString().ToUpper() + "',";
                //,@Toa_Xoa
                sql += "N'" + row_update["Toa_Xoa"].ToString().ToUpper() + "',";
                //,@_Text1
                sql += "N'" + row_update["_Text1"].ToString().ToUpper() + "',";
                //,@_Text2
                sql += "N'" + row_update["_Text2"].ToString().ToUpper() + "',";
                //,@_Text3
                sql += "N'" + row_update["_Text3"].ToString().ToUpper() + "',";
                //,@_Text4
                sql += "N'" + row_update["_Text4"].ToString().ToUpper() + "',";
                //,@_Text5
                sql += "N'" + row_update["_Text5"].ToString().ToUpper() + "',";
                //,@_Num1
                sql += "N'" + row_update["_Num1"].ToString().ToUpper() + "',";
                //,@_Num2
                sql += "N'" + row_update["_Num2"].ToString().ToUpper() + "',";
                //,@_Num3
                sql += "N'" + row_update["_Num3"].ToString().ToUpper() + "',";
                //,@_ID1
                sql += "N'" + row_update["_ID1"].ToString().ToUpper() + "',";
                //,@Lu
                sql += "N'" + row_Sua["Lu"].ToString() + "',";
                nd += " Lu=" + row_Sua["Lu"].ToString().ToUpper();
                //,@Cat
                sql += "N'" + row_Sua["Cat"].ToString() + "',";
                nd += " Cat=" + row_Sua["Cat"].ToString().ToUpper();
                //,@Bom
                sql += "N'" + row_Sua["Bom"].ToString() + "'";
                nd += " Bom=" + row_Sua["Bom"].ToString().ToUpper();
                //,@Bom
                _NhapSi_Class.set(sql);
                DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "", nd, "Thêm");
                #endregion


                double thanhtien_tam_tinh = 0;
                string sqlToa = "sp_GiaoDich_TheoTOAID '" + row_Sua["Toa_ID"].ToString().ToUpper().Trim() + "'";
                DataTable dtToa = db.T_opendataset(sqlToa).Tables[0];
                for (int i = 0; i < dtToa.Rows.Count; i++)
                {
                    thanhtien_tam_tinh += double.Parse(dtToa.Rows[i]["Toa_SL"].ToString()) * double.Parse(dtToa.Rows[i]["Toa_Gia"].ToString());
                }
                string capnhattoa = "UPDATE TOA SET NCC_ID=N'" + row_Sua["ID_NCC"].ToString().ToUpper() + "', TTHANG = '" + thanhtien_tam_tinh + "' where ID='" + row_Sua["Toa_ID"].ToString().ToUpper() + "'";
                _NhapSi_Class.set(capnhattoa);

            }
            if (_Logic_Sua.DialogResult == DialogResult.No)
            {
                #region khong sua toa
                //xoa lun dong do
                string sql1 = "NhapSi_Xoa2019 '" + id_logic + "'";
                _NhapSi_Class.set(sql1);
                #region
                //save and add vao muc du lieu da luu
                string sql = "update Tbl_GIAODICH set  ID_Hang='" + row_Sua["ID_Hang"].ToString().ToUpper() + "',";
                sql += "ID_KhachHang='" + row_Sua["ID_KhachHang"].ToString().ToUpper() + "',";
                sql += "ID_NCC='" + row_Sua["ID_NCC"].ToString().ToUpper() + "',";
                sql += "SL='" + row_Sua["SL"].ToString().ToUpper() + "',";
                sql += "Gia_0='" + row_Sua["Gia"].ToString().ToUpper() + "',";
                sql += "Gia_1='" + row_Sua["Gia_1"].ToString().ToUpper() + "',";
                sql += "Gia_2='" + row_Sua["Gia_2"].ToString().ToUpper() + "',";
                sql += "Sot='" + row_Sua["Sot"].ToString().ToUpper() + "',";
                sql += "Ket='" + row_Sua["Ket"].ToString().ToUpper() + "',";
                sql += "Lu='" + row_Sua["Lu"].ToString().ToUpper() + "',";
                sql += "Cat='" + row_Sua["Cat"].ToString().ToUpper() + "',";
                sql += "Bom='" + row_Sua["Bom"].ToString().ToUpper() + "' ";
                sql += " where ID='" + row_Sua["ID"].ToString().ToUpper() + "'";
                db.T_exc(sql);
                DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "", sql, "Sửa");
                //
                sql = "NhapSi_CongNo2019 ";
                sql += "N'" + row_Sua["ID"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["ID_KhachHang"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["Date_Num_Final_UpDate"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["SL"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["Gia"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["Gia_1"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["Gia_2"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["Sot"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["Ket"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["Lu"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["Cat"].ToString().ToUpper() + "',";
                sql += "N'" + row_Sua["Bom"].ToString().ToUpper() + "'";
                db.T_exc(sql);
                DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "", sql, "Sửa NhapSi_CongNo2019");
                // //  @STT
                // sql += "N'" + row_Sua["STT"].ToString().ToUpper() + "',";
                // //,@ID
                // sql += "N'" + row_Sua["ID"].ToString().ToUpper() + "',";
                // //,@ID_Hang
                // sql += "N'" + row_Sua["ID_Hang"].ToString().ToUpper() + "',";
                // //,@ID_KhachHang
                // sql += "N'" + row_Sua["ID_KhachHang"].ToString().ToUpper() + "',";
                // //,@ID_NCC
                // sql += "N'" + row_Sua["ID_NCC"].ToString().ToUpper() + "',";
                // //,@Date_Num_Final_UpDate
                // sql += "N'" + row_Sua["Date_Num_Final_UpDate"].ToString().ToUpper() + "',";
                // //,@User_ID_Final_UpDate
                // sql += "N'" + Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper() + "',";
                // //,@IS_User
                // sql += "N'" + row_update["IS_User"].ToString().ToUpper() + "',";
                // //,@NguonGoc
                // sql += "N'" + row_update["NguonGoc"].ToString().ToUpper() + "',";
                // //,@SL
                // sql += "N'" + row_Sua["SL"].ToString() + "',";
                // //,@Gia_0 --------SE THAY DOI VI LA GIA UU TIEN
                // sql += "N'" + row_Sua["Gia"].ToString() + "',";
                // //,@Gia_1            
                // sql += "N'" + row_Sua["Gia_1"].ToString() + "',";
                // //,@Gia_2
                // sql += "N'" + row_Sua["Gia_2"].ToString() + "',";
                // //,@Sot
                // sql += "N'" + row_Sua["Sot"].ToString() + "',";
                // //,@Ket
                // sql += "N'" + row_Sua["Ket"].ToString() + "',";
                // //,@TienMat
                // sql += "N'0',";

                // //,@Toa_ID
                // sql += "N'" + row_update["Toa_ID"].ToString().ToUpper() + "',";
                // //,@Toa_SL
                // sql += "N'" + row_Sua["SL"].ToString() + "',";
                // //,@Toa_Gia
                // sql += "N'" + row_Sua["Gia_1"].ToString() + "',";
                // //,@Toa_HHSL
                // sql += "N'" + row_update["Toa_HHSL"].ToString().ToUpper() + "',";
                // //,@Toa_HHPC
                // sql += "N'" + row_update["Toa_HHPC"].ToString().ToUpper() + "',";
                // //,@Toa_Xoa
                // sql += "N'" + row_update["Toa_Xoa"].ToString().ToUpper() + "',";
                // //,@_Text1
                // sql += "N'" + row_update["_Text1"].ToString().ToUpper() + "',";
                // //,@_Text2
                // sql += "N'" + row_update["_Text2"].ToString().ToUpper() + "',";
                // //,@_Text3
                // sql += "N'" + row_update["_Text3"].ToString().ToUpper() + "',";
                // //,@_Text4
                // sql += "N'" + row_update["_Text4"].ToString().ToUpper() + "',";
                // //,@_Text5
                // sql += "N'" + row_update["_Text5"].ToString().ToUpper() + "',";
                // //,@_Num1
                // sql += "N'" + row_update["_Num1"].ToString().ToUpper() + "',";
                // //,@_Num2
                //// sql +="Null,";
                // sql += "N'" + row_update["_Num2"].ToString().ToUpper() + "',";
                // //,@_Num3
                // sql += "N'" + row_update["_Num3"].ToString().ToUpper() + "',";
                // //,@_ID1               
                // sql += "N'" + row_update["_ID1"].ToString().ToUpper() + "'";
                /// _NhapSi_Class.set(sql);

                #endregion

                #endregion
            }
        }
        string _IDXoa = "";
        void _Logic_FormClosed(object sender, FormClosedEventArgs e)
        {
            Class_KetNoi db = new Class_KetNoi();
            if (_Logic.DialogResult == DialogResult.Yes)
            {
                //xoa lun dong do

                string sql = "NhapSi_Xoa '" + id_logic + "'";
                db.T_exc(sql);

                DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "NhapSi_Xoa ID="+ id_logic, "", "Xoá");
                string sql_GiaoDichCu = "sp_GiaoDich_TheoTOAID '" + id_toa_logic + "'";
                DataTable dt = db.T_opendataset(sql_GiaoDichCu).Tables[0];
                double _TienHang = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    _TienHang += double.Parse(dt.Rows[i]["Toa_SL"].ToString()) * double.Parse(dt.Rows[i]["Toa_Gia"].ToString());
                }
                string capnhattoa = "";
                if (_TienHang <= 0)
                    capnhattoa = "Delete TOA where ID = '" + id_toa_logic.ToUpper() + "'";
                else
                    capnhattoa = "Update TOA set TTHANG='" + _TienHang + "' where ID = '" + id_toa_logic.ToUpper() + "'";
                db.T_exc(capnhattoa);

            }
            else
            {
                if (_Logic.DialogResult == DialogResult.No)
                {
                    string sql = "NhapSi_Xoa_khongdoitoa '" + id_logic + "'";
                    db.T_exc(sql);
                }
                else
                {

                }
            }
        }
        public void xoa_kiemtra()
        {
            DataRow[] dr = DuLieu.List_NhapSi_DaLuu.Tables[0].Select("Select = " + true + "");
            for (int i = 0; i < dr.Length; i++)
            {
                string sql = "NhapSi_Xoa '" + dr[i]["ID"].ToString().ToUpper() + "'";
                _NhapSi_Class.set(sql);
                DuLieu.List_NhapSi_DaLuu.Tables[0].Rows.Remove(dr[i]);
            }
            gv_daluu.RefreshData();
            thongke_daluu();
        }
        public void sua()
        {
        }
        public void chon()
        {
            if (tab_daluu.Selected == true)
            {
                for (int i = 0; i < DuLieu.List_NhapSi_DaLuu.Tables[0].Rows.Count; i++)
                {
                    DuLieu.List_NhapSi_DaLuu.Tables[0].Rows[i]["Select"] = true;
                }
                DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                gv_daluu.RefreshData();
            }
            else
            {
                if (tab_kiemtra.Selected == true)
                {
                    for (int i = 0; i < DuLieu.List_NhapSi_DaLuu.Tables[0].Rows.Count; i++)
                    {
                        DuLieu.List_NhapSi_DaLuu.Tables[0].Rows[i]["Select"] = true;
                    }
                    DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                    gv_kiemtra.RefreshData();
                }
                else
                {
                    for (int i = 0; i < DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows.Count; i++)
                    {
                        DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Select"] = true;
                    }
                    DuLieu.List_NhapSi_ChuaLuu.Tables[0].AcceptChanges();
                    gv_dangnhap.RefreshData();
                }
            }

        }
        public void bochon()
        {
            if (tab_daluu.Selected == true)
            {
                for (int i = 0; i < DuLieu.List_NhapSi_DaLuu.Tables[0].Rows.Count; i++)
                {
                    DuLieu.List_NhapSi_DaLuu.Tables[0].Rows[i]["Select"] = false;
                }
                DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                gv_daluu.RefreshData();
            }
            else
            {
                if (tab_kiemtra.Selected == true)
                {
                    for (int i = 0; i < DuLieu.List_NhapSi_DaLuu.Tables[0].Rows.Count; i++)
                    {
                        DuLieu.List_NhapSi_DaLuu.Tables[0].Rows[i]["Select"] = false;
                    }
                    DuLieu.List_NhapSi_DaLuu.Tables[0].AcceptChanges();
                    gv_kiemtra.RefreshData();
                }
                else
                {
                    for (int i = 0; i < DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows.Count; i++)
                    {
                        DuLieu.List_NhapSi_ChuaLuu.Tables[0].Rows[i]["Select"] = false;
                    }
                    DuLieu.List_NhapSi_ChuaLuu.Tables[0].AcceptChanges();
                    gv_dangnhap.RefreshData();
                }
            }
        }
        public void chep()
        {
            //DataRow dr = gv.GetDataRow(gv.FocusedRowHandle);
            //if (Pow.kiemtra("NhapSi_Forms", "Them", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            //{
            //    _NhapSi_Form = new NhapSi_Form();
            //    _NhapSi_Form.TextChanged += new EventHandler(_NhapSi_Form_TextChanged);
            //    _NhapSi_Form.dr = dr;
            //    _NhapSi_Form.ShowDialog();
            //}
        }
        public void tailai()
        {
            int ng = (int)(Convert.ToDateTime(txtngay.Text) - new DateTime(1900, 1, 1)).TotalDays;
            int ng2 = (int)(Convert.ToDateTime(txtngay2.Text) - new DateTime(1900, 1, 1)).TotalDays;
            int thamso = 2;
            string[] arr_name = new string[thamso];
            object[] arr_value = new object[thamso];
            arr_name[0] = "@ng";
            arr_name[1] = "@ng2";
            arr_value[0] = ng;
            arr_value[1] = ng2;
            _NhapSi_Class.get_store("sp_NhapSi_TheoNgay",arr_name, arr_value, thamso);
            data();
            gv_daluu.ExpandAllGroups();

        }
        #endregion

        #region thong ke 
        public void thongke_chualuu()
        {
            object TL = DuLieu.List_NhapSi_ChuaLuu.Tables[0].Compute("Sum(SL)", "");
            object TS = DuLieu.List_NhapSi_ChuaLuu.Tables[0].Compute("Sum(Sot)", "");
            object TK = DuLieu.List_NhapSi_ChuaLuu.Tables[0].Compute("Sum(Ket)", "");
            object TIEN = DuLieu.List_NhapSi_ChuaLuu.Tables[0].Compute("Sum(ThanhTien)", "");
            object mahang = DuLieu.List_NhapSi_ChuaLuu.Tables[0].Compute("count(ID)", "");
            try
            {
                lbtongluong.Text = String.Format("{0:N1}", TL) + " (kg)";
                lbtongtien.Text = String.Format("{0:#,#}", TIEN) + " (vnđ)";
                //  lbtongsot.Text = String.Format("{0:#,#}", TS) + " (Sọt)";
                // lbtongket.Text = String.Format("{0:#,#}", TK) + " (Két)";
                tab_dangnhap.Caption = "Dữ liệu đang nhập\r\nchưa lưu " + String.Format("{0:N0}", mahang) + " (Mã hàng)";
            }
            catch
            {
                lbtongluong.Text = "0.00 (Kg)";
                lbtongtien.Text = "0.00 (vnđ)";
                // lbtongsot.Text =  "0.00 (Sọt)";
                // lbtongket.Text = "0.00 (Két)";
                tab_dangnhap.Caption = "Dữ liệu đang nhập\r\nchưa lưu " + "0 (Mã hàng)";
            }
        }
        public void thongke_daluu()
        {
            object TL = DuLieu.List_NhapSi_DaLuu.Tables[0].Compute("Sum(SL)", "");
            object TS = DuLieu.List_NhapSi_DaLuu.Tables[0].Compute("Sum(Sot)", "");
            object TK = DuLieu.List_NhapSi_DaLuu.Tables[0].Compute("Sum(Ket)", "");
            object TIEN = DuLieu.List_NhapSi_DaLuu.Tables[0].Compute("Sum(ThanhTien)", "");
            object mahang = DuLieu.List_NhapSi_DaLuu.Tables[0].Compute("count(STT)", "");
            try
            {
                lbtongluong.Text = String.Format("{0:N1}", TL) + " (kg)";
                lbtongtien.Text = String.Format("{0:#,#}", TIEN) + " (vnđ)";
                //  lbtongsot.Text = String.Format("{0:#,#}", TS) + " (Sọt)";
                //  lbtongket.Text = String.Format("{0:#,#}", TK) + " (Két)";
                tab_kiemtra.Caption = "Dữ liệu đối chiếu\r\nsổ sách " + String.Format("{0:N0}", mahang) + " (Mã hàng)";
            }
            catch
            {
                lbtongluong.Text = "0.0 (Kg)";
                lbtongtien.Text = "0.00 (vnđ)";
                // lbtongsot.Text = "0.00 (Sọt)";
                // lbtongket.Text = "0.00 (Két)";
                tab_kiemtra.Caption = "Dữ liệu đối chiếu\r\nsổ sách " + String.Format("{0:N0}", 0) + " (Mã hàng)";
            }
        }
        #endregion

        #region load du lieu da luu
        public void load_dulieu_daluu()
        {
            //string sql = "select * from NhapSi_DaLuu where Date_Num_Final_UpDate = " + Get_CauHinh.Ngay_DN + "";
            //DuLieu.List_NhapSi_DaLuu = _NhapSi_Class.get_dataset(sql);
            //DuLieu.List_NhapSi_DaLuu.Tables[0].Columns.Add("Select", typeof(bool));
            int thamso = 1;
            string[] arr_name = new string[thamso];
            object[] arr_value = new object[thamso];
            arr_name[0] = "@Ngay";
            arr_value[0] = Get_CauHinh.Ngay_DN;
            _NhapSi_Class.get_store("sp_NhapSiDaLuu_KhongKhoa_TheoNgay", arr_name, arr_value, thamso);
            gc_daluu.DataSource = DuLieu.List_NhapSi_DaLuu.Tables[0];
            look_loaica_daluu.DataSource = DuLieu.List_Hang.Tables[0];
            look_khachhang_daluu.DataSource = DuLieu.List_KhachHang.Tables[0];
            look_thuonglai_daluu.DataSource = DuLieu.List_NCC.Tables[0];
            gv_daluu.ExpandAllGroups();
            thongke_daluu();
            tab_daluu.Selected = true;
            //--------------
            gc_kiemtra.DataSource = DuLieu.List_NhapSi_DaLuu.Tables[0];
            look_loaica_kiemtra.DataSource = DuLieu.List_Hang.Tables[0];
            look_khachhang_kiemtra.DataSource = DuLieu.List_KhachHang.Tables[0];
            look_thuonglai_kiemtra.DataSource = DuLieu.List_NCC.Tables[0];
        }
        #endregion

        #region load du lieu chua luu
        public void load_dulieu_chualuu()
        {

            gc_dangnhap.DataSource = DuLieu.List_NhapSi_ChuaLuu.Tables[0];
            look_loaica_dangnhap.DataSource = DuLieu.List_Hang.Tables[0];
            look_khachhang_dangnhap.DataSource = DuLieu.List_KhachHang.Tables[0];
            look_thuonglai_dangnhap.DataSource = DuLieu.List_NCC.Tables[0];

        }
        #endregion

        #region menu click
        public void event_click()
        {

        }

        #endregion

        #region data
        public void data()
        {

            gc_daluu.DataSource = DuLieu.List_NhapSi_DaLuu.Tables[0];
            look_loaica_daluu.DataSource = DuLieu.List_Hang.Tables[0];
            look_khachhang_daluu.DataSource = DuLieu.List_KhachHang.Tables[0];
            look_thuonglai_daluu.DataSource = DuLieu.List_NCC.Tables[0];
            gv_daluu.ExpandAllGroups();
            thongke_daluu();
            tab_daluu.Selected = true;
            //--------------
            gc_kiemtra.DataSource = DuLieu.List_NhapSi_DaLuu.Tables[0];
            look_loaica_kiemtra.DataSource = DuLieu.List_Hang.Tables[0];
            look_khachhang_kiemtra.DataSource = DuLieu.List_KhachHang.Tables[0];
            look_thuonglai_kiemtra.DataSource = DuLieu.List_NCC.Tables[0];
        }

        #endregion

        private void NhapSi_Forms_Load(object sender, EventArgs e)
        {
            btn_load_Click(sender, e);
        }

        private void gv_daluu_CustomRowCellEditForEditing(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            try
            {
                if (gv_daluu.GetFocusedRowCellValue("ID") != null)
                {
                    string _ID = gv_daluu.GetFocusedRowCellValue("ID").ToString().Trim().ToUpper();
                    id_logic = _ID;
                    d_cu = gv_daluu.GetFocusedRowCellValue(e.Column.FieldName).ToString().Trim().ToUpper();
                }
            }
            catch (Exception)
            {
            }
        }

        private void gc_daluu_Click(object sender, EventArgs e)
        {

        }

        private void gv_dangnhap_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "Sot" || e.Column.FieldName == "Ket" || e.Column.FieldName == "Lu" || e.Column.FieldName == "Cat" || e.Column.FieldName == "Bom")
            {
                if (e.Value != null)
                {
                    if (e.Value.ToString().Trim() == "0")
                        e.DisplayText = "";
                }

            }
        }

        private void tab_dangnhap_SelectedChanged_1(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {

        }

        private void lbtongtien_Click(object sender, EventArgs e)
        {

        }

        private void gv_daluu_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle == dong && dong >= 0)
            {
                e.Appearance.BackColor = Color.Red;
                //gv_daluu.FocusedRowHandle = dong;
            }
           // else
              //  e.Appearance.BackColor = Color.White;
        }

        private void gv_daluu_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

        }

        private void gv_kiemtra_CustomRowCellEditForEditing(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            try
            {
                d_cu = gv_kiemtra.GetFocusedRowCellValue(e.Column.FieldName).ToString().Trim().ToUpper();
            }
            catch (Exception)
            {

               
            }
           
        }

        private void gv_kiemtra_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle == dong && dong >= 0)
            {
                e.Appearance.BackColor = Color.Red;
               // gv_kiemtra.FocusedRowHandle = dong;
            }    
                
            else
                e.Appearance.BackColor = Color.White;
        }

        private void gc_dangnhap_Click(object sender, EventArgs e)
        {

        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string path = dialog.SelectedPath;

                // Xuất file Excel (.xls)
                string excelFilePath = Path.Combine(path, "NHAPLIEU.xls");
                gc_daluu.ExportToXls(excelFilePath);

                // Xuất file PDF (.pdf)
                string pdfFilePath = Path.Combine(path, "NHAPLIEU.pdf");
                gc_daluu.ExportToPdf(pdfFilePath);

                // MessageBox.Show("Xuất tệp tin Excel và PDF thành công!");
                XtraMessageBox.Show("Đã xuất tệp tin Excel và PDF thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
               
            }
        }

       

        private void gc_kiemtra_Click(object sender, EventArgs e)
        {

        }

        private void gv_kiemtra_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "Sot" || e.Column.FieldName == "Ket" || e.Column.FieldName == "Lu" || e.Column.FieldName == "Cat" || e.Column.FieldName == "Bom")
            {
                if (e.Value != null)
                {
                    if (e.Value.ToString().Trim() == "0")
                        e.DisplayText = "";
                }

            }
        }

        private void gv_daluu_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "Sot" || e.Column.FieldName == "Ket" || e.Column.FieldName == "Lu" || e.Column.FieldName == "Cat" || e.Column.FieldName == "Bom")
            {
                if (e.Value != null)
                {
                    if (e.Value.ToString().Trim() == "0")
                        e.DisplayText = "";
                }

            }
        }
    }
}

