using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ABC.Report;
using DevExpress.XtraSplashScreen;

using DevExpress.XtraReports.UI;
using DevExpress.XtraEditors;
using System.IO;
using ABC.File;
using ABC.KetNoi;
using System.Windows.Input;
//using DevExpress.XtraEditors;

namespace ABC.BanLe
{
    public partial class Le_Forms :XtraUserControl
    {
        private int btnT_ClickCount = 0; // Biến đếm số lần nhấp cho Btn_T
        public Le_Forms()
        {
            InitializeComponent();
            //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            this.clickSequenceTimer.Tick += new System.EventHandler(this.ClickSequenceTimer_Tick);
            load_Xml();
            khoitao_Nhom_NCC();
            DuLieu.Le_ID = Guid.NewGuid().ToString().ToUpper();
            this.Load += new EventHandler(Le_Forms_Load);
            link_click();
            event_menu();
            gv_loaica.CellValueChanged+=new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gv_loaica_CellValueChanged);
            gv_loaica.KeyPress+=new KeyPressEventHandler(gv_loaica_KeyPress);
            gv_toaxem.CellValueChanged+=new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gv_toaxem_CellValueChanged);
            _NhapLe_Class.load_conno();
            
        }

        NhapLe_Class _NhapLe_Class = new NhapLe_Class();

        void Le_Forms_Load(object sender, EventArgs e)
        {
            this.BeginInvoke(new MethodInvoker(() =>
            {
                chonnhom();            // chọn nhóm
                load_all_toa();        // load danh sách sau khi control đã render
                load_toa_ghichu();
                fu_btn_new();          // tạo toa mới
            }));
            Class_KetNoi db = new Class_KetNoi();
            string fileTemp = "";
            int thamso = 1;
            string[] arr_name = new string[thamso];
            object[] arr_value = new object[thamso];
            arr_name[0] = "@ID";
            arr_value[0] = Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper();
            DataTable dt = db.T_opendataset_store("sp_CauHinh_TheoID", arr_name, arr_value, thamso).Tables[0];
            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                fileTemp = row["ThuMucFileTemp"].ToString();
            }
            thumuc = fileTemp;
            //chonnhom();
            //load_all_toa();
            ////load_toa_ghichu();
            //fu_btn_new();
///
            

        }

        #region khoi tao cac form    
        ChonNhom_Form_Le _ChonNhom_Form_Le;
        ThanhToan_Le _ThanhToan_Le;
        GhiChu_Le _GhiChu_Le;
        public void khoitao_Nhom_NCC()
        {
           // _ChonNhom_Form_Le = new ChonNhom_Form_Le();
           // _ChonNhom_Form_Le.FormClosed += new FormClosedEventHandler(_ChonNhom_Form_Le_FormClosed);
           // _ChonNhom_Form_Le.TextChanged += new EventHandler(_ChonNhom_Form_Le_TextChanged);

            _ThanhToan_Le = new ThanhToan_Le();
            _ThanhToan_Le.FormClosed += new FormClosedEventHandler(_ThanhToan_Le_FormClosed);

            _GhiChu_Le = new GhiChu_Le();
            _GhiChu_Le.FormClosed += new FormClosedEventHandler(_GhiChu_Le_FormClosed);
        }

        void _GhiChu_Le_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_GhiChu_Le.DialogResult == DialogResult.OK)
            {
                select_khachhang_name = _GhiChu_Le.GhiChu;
                kiemtra_decapnhat("GC");
            }
            else
            {
            }
            _GhiChu_Le = new GhiChu_Le();
            _GhiChu_Le.FormClosed += new FormClosedEventHandler(_GhiChu_Le_FormClosed);
        }

        void _ThanhToan_Le_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_ThanhToan_Le.DialogResult == DialogResult.OK)
            {
                TienMat = _ThanhToan_Le.TienMat;
                select_khachhang_id = _ThanhToan_Le.ID_KH;
                select_khachhang_name = _ThanhToan_Le.Ten_KH;
                kiemtra_decapnhat("KH");
               // #region canh bao cong no vuot
              //  DataTable dtCongNoKH = DanhSachCongNo1KH(_ThanhToan_Le.ID_KH.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(_ThanhToan_Le.ID_KH.ToUpper());
                   //     MessageBox.Show(mess);
                   // }
                //}
               // #endregion
            }
            else
            {
            }
            _ThanhToan_Le = new ThanhToan_Le();
            _ThanhToan_Le.FormClosed += new FormClosedEventHandler(_ThanhToan_Le_FormClosed);
        }
        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 nhom

        void _ChonNhom_Form_Le_TextChanged(object sender, EventArgs e)
        {
           // nhom = _ChonNhom_Form_Le.Text;
           //filter_theonhom();
        }

        void _ChonNhom_Form_Le_FormClosed(object sender, FormClosedEventArgs e)
        {
            
            
            filter_theonhom();
        }
        public void chonnhom()
        {
            _ChonNhom_Form_Le = new ChonNhom_Form_Le();
            _ChonNhom_Form_Le.FormClosed+=new FormClosedEventHandler(_ChonNhom_Form_Le_FormClosed);
            _ChonNhom_Form_Le.ShowDialog();
        }
        #endregion

        DataView dtv_Thuonglai, dtv_loaica;
        public void filter_theonhom()
        {
            DataTable dt = new DataTable();
            dt.Columns.Clear();
            dt = DuLieu.NhapLe_List_NCC.Tables[0];
            bool chk = false;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (dt.Columns[i].ColumnName == "STT")
                {
                    chk = true;
                    break;
                }
            }
            if (!chk)
            {
                dt.Columns.Add("STT", typeof(int));
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dt.Rows[i]["STT"] = i + 1;
                }
            }
            dtv_Thuonglai = new DataView(dt);
            #region
            if (NhapLe_Class._nhom == "All")
            {
                // dtv_Thuonglai = new DataView(DuLieu.NhapLe_List_NCC.Tables[0]);
                gv_thuonglai.ClearSorting();
                dtv_Thuonglai.RowFilter = "Nhom is not null";
                dtv_Thuonglai.Sort = "[STT] asc";
                gc_thuonglai.DataSource = dtv_Thuonglai;
                if (select_thuonglai_id != null != null)
                {
                    if (dtv_Thuonglai.Count > 0)
                    {
                        Filter_theo_lai("Auto", "");
                    }
                    else
                    {
                        Filter_theo_lai("Trong", "");
                    }
                }
            }
            else
            {
                try
                {
                    //dtv_Thuonglai = new DataView(DuLieu.NhapLe_List_NCC.Tables[0]);
                    dtv_Thuonglai.RowFilter = "Nhom = '" + NhapLe_Class._nhom.ToUpper() + "'";
                    dtv_Thuonglai.Sort = "[STT] asc";
                    gc_thuonglai.DataSource = dtv_Thuonglai;
                    if (select_thuonglai_id != null != null)
                    {
                        if (dtv_Thuonglai.Count > 0)
                        {
                            Filter_theo_lai("Auto", "");
                        }
                        else
                        {
                            Filter_theo_lai("Trong", "");
                        }
                    }
                }
                catch (Exception)
                {
                   
                }
                
            }
            #endregion
        }
           string select_thuonglai_id, select_thuonglai_name;
        public void Filter_theo_lai(string truonghop,string ten)
        {
            #region
            if (truonghop == "Trong")
            {
                select_thuonglai_id = null;
                select_thuonglai_name = "Không có";
                gc_loaica.DataSource = null;
                gv_loaica.RefreshData();
                clum_tenca.Caption = select_thuonglai_name;
            }
            else
            {
                if (truonghop == "Auto")
                {
                    DataRow dr = gv_thuonglai.GetDataRow(0);
                    select_thuonglai_id =  dr["NCC_ID"].ToString().ToUpper();
                    select_thuonglai_name = dr["Name"].ToString().ToUpper();
                    dtv_loaica = new DataView(DuLieu.NhapLe_List_Ca.Tables[0]);
                    dtv_loaica.RowFilter = "NCC_ID = '" + select_thuonglai_id + "'";
                    gc_loaica.DataSource = dtv_loaica;
                    gv_loaica.RefreshData();
                    clum_tenca.Caption = select_thuonglai_name;
                    gv_loaica.FocusedRowHandle = 0;
                    gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[1];
                    gv_loaica.ShowEditor();
                    
                }
                else
                {
                    dtv_loaica = new DataView(DuLieu.NhapLe_List_Ca.Tables[0]);
                    dtv_loaica.RowFilter = "NCC_ID = '" + select_thuonglai_id + "'";
                    gc_loaica.DataSource = dtv_loaica;
                    gv_loaica.RefreshData();
                    clum_tenca.Caption =  select_thuonglai_name;
                    gv_loaica.FocusedRowHandle = 0;
                    gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[1];
                    gv_loaica.ShowEditor();
                }
            }
            #endregion
        }
        #endregion

        #region load XML
        public void load_Xml()
        {
            _NhapLe_Class.load_xml_kytu();
            _NhapLe_Class.load_xml_hoadon();
            _NhapLe_Class.load_xml_hoadon_chitiet();
        }
        #endregion

        #region event button

        public void fu_btn_saveall()
        {
           // _NhapLe_Class.load_xml_hoadon_chitiet();
            SplashScreenManager.ShowForm(typeof(WaitForm1));     
         
          
            _NhapLe_Class.load_xml_hoadon();
            _NhapLe_Class.load_xml_hoadon_chitiet();
            _NhapLe_Class.save_all();
            // msgbox.dialog_OK_info("ĐÃ LƯU TẤT CẢ THÀNH CÔNG");
            MessageBox.Show("ĐÃ LƯU ");
            load_all_toa();
            _NhapLe_Class.load_conno();
            
            SplashScreenManager.CloseForm();
            fu_btn_new();
        }
        Setup _Setup;
        public void fu_btn_setup()
        {
            _Setup = new Setup();
            _Setup.nhom = NhapLe_Class._nhom;
            _Setup.FormClosed += new FormClosedEventHandler(_Setup_FormClosed);
            _Setup.ShowDialog();
        }

        void _Setup_FormClosed(object sender, FormClosedEventArgs e)
        {
            filter_theonhom();
        }
        CaSetup _CaSetup;
        public void fu_btn_setup_ca()
        {
            if (select_thuonglai_id == null || select_thuonglai_name == "")
            {
                msgbox.dialog_OK_info("Vui lòng chọn lái");
            }
            else
            {
                _CaSetup = new CaSetup();
                _CaSetup.thuonglai_id = select_thuonglai_id;
                _CaSetup.ThuongLai_name = select_thuonglai_name;
                _CaSetup.FormClosed += new FormClosedEventHandler(_CaSetup_FormClosed);
                _CaSetup.ShowDialog();
            }
        }
        // Đặt phương thức này BÊN TRONG lớp Le_Forms của bạn
        // Ví dụ, bạn có thể đặt nó ngay sau constructor hoặc trước dấu } cuối cùng của lớp Le_Forms

        

        void _CaSetup_FormClosed(object sender, FormClosedEventArgs e)
        {
  
            Filter_theo_lai(select_thuonglai_id, select_thuonglai_name);
            load_all_toa();
        }
        public void fu_btn_timkiem()
        {
            tabbedControlGroup1.SelectedTabPageIndex = 1;
        }
        public void fu_btn_thanhtoan()
        {
            string ttt = VthanhTien.SummaryText.Replace("v", "").Replace("n", "").Replace("đ", "").Replace(",", "").Replace(".", "").Replace("(", "").Replace(")", "");
            try
            {
                DuLieu.Le_TongTien = decimal.Parse(ttt);
            }
            catch
            {
                DuLieu.Le_TongTien = 0;
            }
            if (DuLieu.Le_TongTien == 0)
            {
                msgbox.dialog_OK_info("Toa rỗng");
            }
            else
            {
                _ThanhToan_Le.ShowDialog();
            }
            
        }
        public void fu_btn_ghichu()
        {
            if (DuLieu.Le_Tbl_KhachHang_ID.Length > 10)
            {
                msgbox.dialog_OK_warning("Toa này đã thanh toán không thể thêm ghi chú");
            }
            else
            {
                _GhiChu_Le.ShowDialog();
            }
        }
      
        public void fu_btn_in()
        {
            phatlenhin = 1;
            
            fu_btn_save();
         
        }
        public void xoa_toa()
        {
            #region
            DataRow[] dt_xoa = DuLieu.List_NhapLe_HoaDon.Tables[0].Select("ID = '" + DuLieu.Le_ID.ToUpper() + "'");
            if (dt_xoa.Length > 0)
            {
                DuLieu.List_NhapLe_HoaDon.Tables[0].Rows.Remove(dt_xoa[0]);
                DuLieu.List_NhapLe_HoaDon.Tables[0].AcceptChanges();


                _Xml_control.delete_xml_node(NhapLe_Class._xmlfile, DuLieu.Le_ID);
                DuLieu.Le_Toa = "XXX";
                _NhapLe_Class.add_toa_saukhixoa();
                DataRow dtr_new = DuLieu.List_NhapLe_HoaDon.Tables[0].NewRow();
                //dan
                dtr_new["ID"] = DuLieu.Le_ID;
                dtr_new["KyTu"] = DuLieu.Le_KyTu;
                dtr_new["SoHD"] = DuLieu.Le_SoHD;

                dtr_new["Tbl_KhachHang_ID"] = DuLieu.Le_Tbl_KhachHang_ID;
                dtr_new["Tbl_KhachHang_Name"] = DuLieu.Le_Tbl_KhachHang_Name;
                dtr_new["TienMat"] = DuLieu.Le_TienMat;

                dtr_new["ID_NCC"] = DuLieu.Le_ID_NCC;
                dtr_new["Tbl_NCC_Name"] = DuLieu.Le_Tbl_NCC_Name;
                dtr_new["Toa"] = "XXX";
                dtr_new["TongTien"] = DuLieu.Le_TongTien;

                DuLieu.List_NhapLe_HoaDon.Tables[0].Rows.Add(dtr_new);
                DuLieu.List_NhapLe_HoaDon.Tables[0].AcceptChanges();
                thongke_toa();
                fu_btn_new();
                tabbedControlGroup1.SelectedTabPageIndex = 1;
            }
            #endregion
        }


        public void fu_btn_xoa()
        {
            if (XtraMessageBox.Show("đơn hàng này sẽ bị xóa?", "Xác nhận", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                xoa_toa();
            }
        }





        public void event_menu()
        {
            //btn_saveallZ.Click += new EventHandler(btn_saveall_Click);
            //btn_setupZ.Click += new EventHandler(btn_setup_Click);
            //btn_setupcaZ.Click += new EventHandler(btn_setupca_Click);
            //btn_timkiem.Click += new EventHandler(btn_timkiem_Click);
            //btn_thanhtoan.Click += new EventHandler(btn_thanhtoan_Click);
            //btn_ghichu.Click += new EventHandler(btn_ghichu_Click);
            //btn_newZ.Click += new EventHandler(btn_new_Click);
            //btn_save.Click += new EventHandler(btn_save_Click);
            //btn_inZ.Click += new EventHandler(btn_in_Click);
            //btn_xoaZ.Click += new EventHandler(btn_xoa_Click);
            //btn_xemtatca.Click += new EventHandler(btn_xemtatca_Click);
            //btn_sobanleZ.Click += new EventHandler(btn_sobanle_Click);

        }

        void btn_sobanle_Click(object sender, EventArgs e)
        {
            show_sobanle();
        }

        //void btn_setupca_Click(object sender, EventArgs e)
        //{
        //    fu_btn_setup_ca();
        //}

        //void btn_xemtatca_Click(object sender, EventArgs e)
        //{
        //    load_all_toa();
        //}

        //void btn_xoa_Click(object sender, EventArgs e)
        //{
        //    fu_btn_xoa();
        //}

        //void btn_in_Click(object sender, EventArgs e)
        //{
        //    fu_btn_in();
        //}

        //void btn_save_Click(object sender, EventArgs e)
        //{
        //    fu_btn_save();
        //}

        //void btn_new_Click(object sender, EventArgs e)
        //{
        //    fu_btn_new();
        //}

        //void btn_ghichu_Click(object sender, EventArgs e)
        //{
        //    fu_btn_ghichu();
        //}

        //void btn_thanhtoan_Click(object sender, EventArgs e)
        //{
        //    fu_btn_thanhtoan();
        //}

        //void btn_timkiem_Click(object sender, EventArgs e)
        //{
        //    fu_btn_timkiem();
        //}

        //void btn_setup_Click(object sender, EventArgs e)
        //{
        //    fu_btn_setup();
        //}

        //void btn_saveall_Click(object sender, EventArgs e)
        //{
        //    fu_btn_saveall();
        //}

       
        #endregion
        //SoBanLe _SoBanLe;
        public void show_sobanle()
        {

            SoBanLe _SoBanLe; 
            _SoBanLe = new SoBanLe();
          
             _SoBanLe.nhom = NhapLe_Class._nhom;
            _NhapLe_Class.load_xml_hoadon();
            _NhapLe_Class.load_xml_hoadon_chitiet();
            _SoBanLe.FormClosed += new FormClosedEventHandler(_CaSetup_FormClosed);
            _SoBanLe.ShowDialog();
            

        }
        #region register event
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.F7))
            {
                show_sobanle();
            }

            

            if (keyData == (Keys.F10))
            {
                fu_btn_setup_ca();
            }

            if (keyData == (Keys.F11))
            {
                fu_btn_setup();
            }

            if (keyData == (Keys.F8))
            {
                fu_btn_timkiem();
            }


            if (keyData == (Keys.F5))
            {
                fu_btn_thanhtoan();
            }


            if (keyData == (Keys.F6))
            {
                fu_btn_ghichu();
            }


            if (keyData == (Keys.F1))
            {
                fu_btn_new();
            }
            if (keyData == (Keys.Control | Keys.N))
            {
                fu_btn_new();
            }



            if (keyData == (Keys.F2))
            {
                fu_btn_save();
                new ToastForm("✅ Đã lưu toa thành công").Show();
            }
            //if (keyData == (Keys.Control | Keys.S))
            //{
            //    fu_btn_save();
            //}


            if (keyData == (Keys.F3))
            {
                
                fu_btn_in();
            }

            if (keyData == (Keys.Control | Keys.Z))
            {
                fu_btn_in();
            }



            if (keyData == (Keys.F12))
            {
                fu_btn_xoa();
            }


            if (keyData == (Keys.Control|Keys.A))
            {
                load_all_toa();
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }
        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // Lấy GridView đang hoạt động
            DevExpress.XtraGrid.Views.Grid.GridView view = gc_toaxem.FocusedView as DevExpress.XtraGrid.Views.Grid.GridView;

            if (view == null) return;

            // Lấy giá trị hiện tại của ô "Số Lượng" tại dòng đang được focus
            // Giả sử tên cột là "SoLuong" và kiểu dữ liệu là decimal hoặc int
            string fieldNameSoLuong = "SL"; // Thay "SoLuong" bằng tên thật của cột Số Lượng trong GridView của bạn

            // Lấy giá trị hiện tại
            object currentValue = view.GetRowCellValue(view.FocusedRowHandle, fieldNameSoLuong);
            decimal quantity = 0;

            if (currentValue != null)
            {
                decimal.TryParse(currentValue.ToString(), out quantity);
            }

            // Kiểm tra nút nào được nhấn dựa vào Index hoặc Caption
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus || e.Button.Caption == "+")
            {
                quantity++;
            }
            else if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Minus || e.Button.Caption == "-")
            {
                if (quantity > 0) // Ngăn không cho số lượng âm (tùy theo logic của bạn)
                {
                    quantity--;
                }
            }

            // Cập nhật lại giá trị cho ô
            view.SetRowCellValue(view.FocusedRowHandle, fieldNameSoLuong, quantity);

            // Nếu bạn muốn editor đóng lại ngay sau khi nhấn nút
            // view.CloseEditor();
            // view.UpdateCurrentRow(); // Có thể cần nếu bạn không dùng DataSource tự động cập nhật
            view.PostEditor(); // Đẩy giá trị hiện tại của editor vào datasource của cell
            view.ShowEditor(); // Yêu cầu GridView mở lại (hoặc giữ mở) editor cho ô hiện tại
        }

        #endregion

        #region link_click
        public void link_click()
        {
            Link_chonLai.Click += new EventHandler(Link_chonLai_Click);
            link_sp.Click += new EventHandler(link_sp_Click);
            link_tenkh.Click += new EventHandler(link_tenkh_Click);
            link_tongten.Click += new EventHandler(link_tongten_Click);

            Link_ghichu_sp.Click += new EventHandler(Link_ghichu_sp_Click);
            link_ghichu_ghichu.Click += new EventHandler(link_ghichu_ghichu_Click);
            Link_ghichu_tongtien.Click += new EventHandler(Link_ghichu_tongtien_Click);
            linkxoachitiet.Click += new EventHandler(linkxoachitiet_Click);
        }

        void linkxoachitiet_Click(object sender, EventArgs e)
        {
            DataRow dr = gv_toaxem.GetDataRow(gv_toaxem.FocusedRowHandle);
            _Xml_control.delete_xml_node(NhapLe_Class.__xmlfile_chitiet, dr["ID"].ToString().ToUpper());
            DataRow[] dr_xoa_chitiet = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID = '" + dr["ID"].ToString().ToUpper() + "'");
            DuLieu.List_NhapLe_ChiTiet.Tables[0].Rows.Remove(dr_xoa_chitiet[0]);
            DuLieu.List_NhapLe_ChiTiet.Tables[0].AcceptChanges();
        
            DataView dtv_ct = new DataView(DuLieu.List_NhapLe_ChiTiet.Tables[0]);
            dtv_ct.RowFilter = "ID_HD = '"+DuLieu.Le_ID.ToUpper()+"'";
            if (dtv_ct.Count == 0)
            {
                xoa_toa();
            }
            else
            {
                hienthichitiet();
                kiemtra_decapnhat("Tien_NCC");
            }
        }

        void Link_ghichu_tongtien_Click(object sender, EventArgs e)
        {
            DataRow dr = gv_ds_cho.GetDataRow(gv_ds_cho.FocusedRowHandle);
            xem_1Toa(dr["ID"].ToString().ToUpper());
        }

        void link_ghichu_ghichu_Click(object sender, EventArgs e)
        {
            DataRow dr = gv_ds_cho.GetDataRow(gv_ds_cho.FocusedRowHandle);
            xem_1Toa(dr["ID"].ToString().ToUpper());
        }

        void Link_ghichu_sp_Click(object sender, EventArgs e)
        {
            DataRow dr = gv_ds_cho.GetDataRow(gv_ds_cho.FocusedRowHandle);
            xem_1Toa(dr["ID"].ToString().ToUpper());
        }

        void link_tongten_Click(object sender, EventArgs e)
        {
            DataRow dr = gv_danhsach.GetDataRow(gv_danhsach.FocusedRowHandle);
            xem_1Toa(dr["ID"].ToString().ToUpper());
        }

        void link_tenkh_Click(object sender, EventArgs e)
        {
            
            DataRow dr = gv_danhsach.GetDataRow(gv_danhsach.FocusedRowHandle);
            xem_1Toa(dr["ID"].ToString().ToUpper());
        }

        void link_sp_Click(object sender, EventArgs e)
        {
            DataRow dr = gv_danhsach.GetDataRow(gv_danhsach.FocusedRowHandle);
            xem_1Toa(dr["ID"].ToString().ToUpper());
        }

        void Link_chonLai_Click(object sender, EventArgs e)
        {
            DataRow dr = gv_thuonglai.GetDataRow(gv_thuonglai.FocusedRowHandle);
            select_thuonglai_id = dr["NCC_ID"].ToString().ToUpper();
            select_thuonglai_name = dr["Name"].ToString().ToUpper();
            Filter_theo_lai(select_thuonglai_id, select_thuonglai_name);
            load_all_toa();
        }
        #endregion     

        #region gv_key_press
        void gv_loaica_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (gv_loaica.FocusedColumn == gv_loaica.VisibleColumns[1])
                {
                    gv_loaica.FocusedRowHandle = gv_loaica.FocusedRowHandle;
                    gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[2];
                    gv_loaica.ShowEditor();
                }
                else
                {
                    if (gv_loaica.FocusedColumn == gv_loaica.VisibleColumns[2])
                    {
                        gv_loaica.FocusedRowHandle = gv_loaica.FocusedRowHandle;
                        gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[1];
                        gv_loaica.ShowEditor();
                    }
                }
            }
        }
        bool set_trong = false;
        public decimal check_so(string value)
        {
            try
            {
                decimal so = decimal.Parse(value);
                return so;
            }
            catch
            {
                msgbox.dialog_OK_error("Nhập sai định dạng số");
                return 0;
            }
        }
        void gv_loaica_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (set_trong == false)
            {
                #region
                if (gv_loaica.FocusedColumn == gv_loaica.VisibleColumns[1])
                {
                    if (check_so(e.Value.ToString()) > 0)
                    {

                        gv_loaica.FocusedRowHandle = gv_loaica.FocusedRowHandle;
                        gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[2];
                        gv_loaica.ShowEditor();
                    }
                    else
                    {

                        gv_loaica.FocusedRowHandle = gv_loaica.FocusedRowHandle;
                        gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[1];
                        gv_loaica.ShowEditor();
                    }
                }
                else
                {
                    if (gv_loaica.FocusedColumn == gv_loaica.VisibleColumns[2])
                    {
                        if (check_so(e.Value.ToString()) > 0)
                        {

                            add();

                        }
                        else
                        {

                        }
                    }
                }
                #endregion
            }
        }
        public void add()
        {
            msgbox.dialog_OK_info("Đã Thêm");
            set_trong = true;//bat dau dung kiem tra de set trong
            DataRow dr = gv_loaica.GetDataRow(gv_loaica.FocusedRowHandle);
            decimal SL = decimal.Parse(dr["SL"].ToString());
            decimal Gia = (decimal.Parse(dr["Gia"].ToString()) * 1000);
            //bat dau them xml
            add_dulieu_chualuu(dr["Hang_ID"].ToString().ToUpper(), dr["Name"].ToString(), select_thuonglai_id.ToUpper(), select_thuonglai_name, SL, Gia);
            hienthichitiet();
            kiemtra_decapnhat("Tien");
            //ket thuc them
            gv_loaica.SetFocusedRowCellValue(COLSL, null);
            gv_loaica.SetFocusedRowCellValue(COLGIA, null);
            set_trong = false; //end set trong
            gv_loaica.FocusedRowHandle = gv_loaica.FocusedRowHandle;
            gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[1];
            gv_loaica.ShowEditor();

        }
        public void add_dulieu_chualuu(string _ID_Hang, string _TenHang, String _ID_NCC, string _Ten_NCC, decimal _SL, decimal _Gia)
        {
            #region
            DataRow[] dt_count = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'");
            DataRow dtr = DuLieu.List_NhapLe_ChiTiet.Tables[0].NewRow();
            decimal _ThanhTien = (_SL * _Gia);
            //gan
            dtr["ID"] = Guid.NewGuid().ToString().ToUpper();
            dtr["ID_Hang"] = _ID_Hang;
            dtr["ID_NCC"] = _ID_NCC;

            dtr["SL"] = _SL;
            dtr["Gia"] = _Gia;
            dtr["ThanhTien"] = _ThanhTien;

            dtr["Tbl_NCC_Name"] = _Ten_NCC;
            dtr["Tbl_Hang_Name"] = _TenHang;

            dtr["STT_Them"] = (dt_count.Length + 1);
            dtr["ID_HD"] = DuLieu.Le_ID.ToUpper();
            //them vo list
            DuLieu.List_NhapLe_ChiTiet.Tables[0].Rows.Add(dtr);


            XmlDocument doc = new XmlDocument();
            doc.Load(NhapLe_Class.__xmlfile_chitiet);
            XmlNode root = doc.DocumentElement;
            //Create a new node.
            XmlElement elem = doc.CreateElement("Table");
            //add element
            XmlElement ID = doc.CreateElement("ID");
            XmlElement ID_Hang = doc.CreateElement("ID_Hang");
            XmlElement ID_NCC = doc.CreateElement("ID_NCC");

            XmlElement SL = doc.CreateElement("SL");
            XmlElement Gia = doc.CreateElement("Gia");
            XmlElement ThanhTien = doc.CreateElement("ThanhTien");

            XmlElement Tbl_NCC_Name = doc.CreateElement("Tbl_NCC_Name");
            XmlElement Tbl_Hang_Name = doc.CreateElement("Tbl_Hang_Name");

            XmlElement STT_Them = doc.CreateElement("STT_Them");
            XmlElement ID_HD = doc.CreateElement("ID_HD");

            // add inner text
            ID.InnerText = dtr["ID"].ToString();
            ID_Hang.InnerText = dtr["ID_Hang"].ToString();
            ID_NCC.InnerText = dtr["ID_NCC"].ToString();

            SL.InnerText = dtr["SL"].ToString();
            Gia.InnerText = dtr["Gia"].ToString();
            ThanhTien.InnerText = dtr["ThanhTien"].ToString();

            Tbl_NCC_Name.InnerText = dtr["Tbl_NCC_Name"].ToString();
            Tbl_Hang_Name.InnerText = dtr["Tbl_Hang_Name"].ToString();
            STT_Them.InnerText = dtr["STT_Them"].ToString();
            ID_HD.InnerText = dtr["ID_HD"].ToString();
            // add to element
            elem.AppendChild(ID);
            elem.AppendChild(ID_Hang);
            elem.AppendChild(ID_NCC);

            elem.AppendChild(SL);
            elem.AppendChild(Gia);
            elem.AppendChild(ThanhTien);

            elem.AppendChild(Tbl_NCC_Name);
            elem.AppendChild(Tbl_Hang_Name);

            elem.AppendChild(STT_Them);
            elem.AppendChild(ID_HD);

            root.AppendChild(elem);
            doc.Save(NhapLe_Class.__xmlfile_chitiet);
            #endregion
        }
        #endregion

        #region gv_toaxem
        Xml_control _Xml_control = new Xml_control();
        void gv_toaxem_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DataRow dtr = gv_toaxem.GetDataRow(gv_toaxem.FocusedRowHandle);
            //DataRowView row_hang = look_tenhang_grid.GetDataSourceRowByKeyValue(dtr["Tbl_Hang_Name"].ToString()) as DataRowView;
            DataRowView row_hang = look_tenhang_grid.GetDataSourceRowByKeyValue(dtr["Tbl_Hang_Name"].ToString()) as  DataRowView;
            dtr["ID_Hang"] = row_hang["ID"].ToString().ToUpper();
            dtr[e.Column.FieldName] = e.Value;
            decimal _TT = (decimal.Parse(dtr["SL"].ToString()) * decimal.Parse(dtr["Gia"].ToString()));
            dtr["ThanhTien"] = _TT;
            //xoa dong xml va add lai
            _Xml_control.delete_xml_node(NhapLe_Class.__xmlfile_chitiet, dtr["ID"].ToString().ToUpper());
            //add lai
            #region
            XmlDocument doc = new XmlDocument();
            doc.Load(NhapLe_Class.__xmlfile_chitiet);
            XmlNode root = doc.DocumentElement;
            //Create a new node.
            XmlElement elem = doc.CreateElement("Table");
            //add element
            XmlElement ID = doc.CreateElement("ID");
            XmlElement ID_Hang = doc.CreateElement("ID_Hang");
            XmlElement ID_NCC = doc.CreateElement("ID_NCC");

            XmlElement SL = doc.CreateElement("SL");
            XmlElement Gia = doc.CreateElement("Gia");
            XmlElement ThanhTien = doc.CreateElement("ThanhTien");

            XmlElement Tbl_NCC_Name = doc.CreateElement("Tbl_NCC_Name");
            XmlElement Tbl_Hang_Name = doc.CreateElement("Tbl_Hang_Name");

            XmlElement STT_Them = doc.CreateElement("STT_Them");
            XmlElement ID_HD = doc.CreateElement("ID_HD");

            // add inner text
            ID.InnerText = dtr["ID"].ToString();
            ID_Hang.InnerText = dtr["ID_Hang"].ToString();
            ID_NCC.InnerText = dtr["ID_NCC"].ToString();

            SL.InnerText = dtr["SL"].ToString();
            Gia.InnerText = dtr["Gia"].ToString();
            ThanhTien.InnerText = dtr["ThanhTien"].ToString();

            Tbl_NCC_Name.InnerText = dtr["Tbl_NCC_Name"].ToString();
            Tbl_Hang_Name.InnerText = dtr["Tbl_Hang_Name"].ToString();
            STT_Them.InnerText = dtr["STT_Them"].ToString();
            ID_HD.InnerText = dtr["ID_HD"].ToString();
            // add to element
            elem.AppendChild(ID);
            elem.AppendChild(ID_Hang);
            elem.AppendChild(ID_NCC);

            elem.AppendChild(SL);
            elem.AppendChild(Gia);
            elem.AppendChild(ThanhTien);

            elem.AppendChild(Tbl_NCC_Name);
            elem.AppendChild(Tbl_Hang_Name);

            elem.AppendChild(STT_Them);
            elem.AppendChild(ID_HD);

            root.AppendChild(elem);
            doc.Save(NhapLe_Class.__xmlfile_chitiet);

            #endregion

            hienthichitiet();
            kiemtra_decapnhat("Tien");
        }
        #endregion

        #region hien thi
        public void xem_1Toa(string _Toa_ID)
        {
            DataRow[] dr = DuLieu.List_NhapLe_HoaDon.Tables[0].Select("ID = '"+_Toa_ID+"'");
            DataRow[] dr_chitiet = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID_HD = '"+_Toa_ID+"'");

            //kiem tra toa dang lam co du lieu chi tiet khong nen co thong bao
            if (dr.Length == 0 && dr_chitiet.Length > 0)
            {
                if (msgbox.dialog_yes_no("Toa " + DuLieu.Le_Toa + " \n Đang làm đở dang. \n Bạn có muốn lưu không") == DialogResult.Yes)
                {
                    fu_btn_save();
                }
            }
            // gan
            DuLieu.Le_ID = dr[0]["ID"].ToString();
            DuLieu.Le_KyTu = dr[0]["KyTu"].ToString();
            DuLieu.Le_SoHD = decimal.Parse(dr[0]["SoHD"].ToString());

            DuLieu.Le_Tbl_KhachHang_ID = dr[0]["Tbl_KhachHang_ID"].ToString();
            DuLieu.Le_Tbl_KhachHang_Name = dr[0]["Tbl_KhachHang_Name"].ToString();
            DuLieu.Le_TienMat = decimal.Parse(dr[0]["TienMat"].ToString());

            DuLieu.Le_ID_NCC = dr[0]["ID_NCC"].ToString();
            DuLieu.Le_Tbl_NCC_Name = dr[0]["Tbl_NCC_Name"].ToString();
            DuLieu.Le_Toa = dr[0]["Toa"].ToString();
            DuLieu.Le_TongTien = decimal.Parse(dr[0]["TongTien"].ToString());

            select_khachhang_id = DuLieu.Le_Tbl_KhachHang_ID;
            select_khachhang_name = DuLieu.Le_Tbl_KhachHang_Name;
            hienthi_hoadon();
            hienthichitiet();
        }

        public void thongke_toa()
        {
            decimal _TongTien = decimal.Parse(Clum_tongtien_toa.SummaryText);
            decimal _TongTienMat = decimal.Parse(clum_tienmat_toa.SummaryText);
            decimal _no = _TongTien - _TongTienMat;

            tk_tienhang.Text = Clum_tongtien_toa.SummaryText;
            tk_tienmat.Text = clum_tienmat_toa.SummaryText;
            tk_no.Text = String.Format("{0:#,#}", _no);
        }
        public void load_ds_toa_theolai()
        {
            DataView toacualai = new DataView(DuLieu.List_NhapLe_HoaDon.Tables[0]);
            toacualai.RowFilter = "ID_NCC = '" + select_thuonglai_id.ToUpper() + "' and Toa <> 'XXX'";
            gc_danhsach.DataSource = toacualai;
            //gv_danhsach.ExpandAllGroups();
            gv_danhsach.RefreshData();
            thongke_toa();

        }
        public void load_toa_ghichu()
        {
            DataView dtv_cho = new DataView(DuLieu.List_NhapLe_HoaDon.Tables[0]);
            dtv_cho.RowFilter = "(Tbl_KhachHang_ID = '' or Tbl_KhachHang_ID is null or Tbl_KhachHang_ID = 'Null') and Tbl_KhachHang_Name <> 'Vãng Lai' and Toa <>'XXX'";
            gc_ds_cho.DataSource = dtv_cho;
            gv_ds_cho.RefreshData();
        }
        public void load_all_toa()
        {
            
     
           
            DataView dtv = new DataView(DuLieu.List_NhapLe_HoaDon.Tables[0]);
            dtv.RowFilter = "Toa <> 'XXX'";
            gc_danhsach.DataSource = dtv;

            Application.DoEvents(); // ép UI xử lý trước khi expand group

            gc_danhsach.ForceInitialize();
            gv_danhsach.RefreshData();
            gv_danhsach.ExpandAllGroups();
            gv_danhsach.MakeRowVisible(0);
            gv_danhsach.LayoutChanged();
            thongke_toa();
            
        }
        public void hienthi_hoadon()
        {
            #region
            Lable_Sotoa.Text = "" + DuLieu.Le_KyTu + DuLieu.Le_SoHD.ToString();
            lblngay.Text = Get_CauHinh.ngay_text;
            lb_tenkh.Text =DuLieu.Le_Tbl_KhachHang_Name;
            //Thongkesoluong.Text = String.Format("{0:#,#}", DuLieu.dr_HoaDon_DangXem["TongLuong"]) + " (kg)";
            //ThongKeTien.Text = String.Format("{0:#,#}", DuLieu.dr_HoaDon_DangXem["TongTien"]) + " (vnđ)";
            #endregion
        }
        public void hienthichitiet()
        {
            #region
            DataView dtv = new DataView(DuLieu.List_NhapLe_ChiTiet.Tables[0]);
            dtv.RowFilter = "ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'";
            gc_toaxem.DataSource = dtv;
            gv_toaxem.ExpandAllGroups();
            look_tenhang_grid.DataSource = DuLieu.List_Hang.Tables[0];
            gv_toaxem.ExpandAllGroups();
            //Thongkesoluong.Text = VSL.SummaryText;
            ThongKeTien.Text = VthanhTien.SummaryText;
            //lbtienmat.Text = String.Format("{0:#,#}", DuLieu.Le_TienMat) + " (vnđ)";
            #endregion
        }
        #endregion

        #region them toa
        public void check_before_new()
        {
            
        }

        public void fu_btn_new()
        {
            #region          
            DataRow[] dr_chitiet = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'");
            DataRow[] dr_hd = DuLieu.List_NhapLe_HoaDon.Tables[0].Select("ID = '" + DuLieu.Le_ID.ToUpper() + "'");
            if (dr_chitiet.Length > 0 && dr_hd.Length==0)
            {
                if (msgbox.dialog_yes_no("Lưu Toa ?") == DialogResult.Yes)
                {
                    fu_btn_save();

                    #region new
                    tabbedControlGroup1.SelectedTabPageIndex = 0;
                    _NhapLe_Class.tao_toa();
                    hienthi_hoadon();
                    hienthichitiet();

                    select_khachhang_name = "Vãng Lai";
                    select_khachhang_id = null;
                    select_tien = "0,00 (đ)";
                    //tiep tuc
                    gv_loaica.FocusedRowHandle = gv_loaica.FocusedRowHandle;
                    gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[1];
                    gv_loaica.ShowEditor();
                    #endregion
                }
                else
                {
                    #region new
                    tabbedControlGroup1.SelectedTabPageIndex = 0;
                    _NhapLe_Class.tao_toa();
                    hienthi_hoadon();
                    hienthichitiet();

                    select_khachhang_name = "Vãng Lai";
                    select_khachhang_id = null;
                    select_tien = "0,00";
                    //tiep tuc
                    gv_loaica.FocusedRowHandle = gv_loaica.FocusedRowHandle;
                    gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[1];
                    gv_loaica.ShowEditor();
                    #endregion
                }
            }
            else
            {
                #region new
                tabbedControlGroup1.SelectedTabPageIndex = 0;
                _NhapLe_Class.tao_toa();
                hienthi_hoadon();
                hienthichitiet();

                select_khachhang_name = "Vãng Lai";
                select_khachhang_id = null;
                select_tien = "0,00 (vnđ)";
                //tiep tuc
                gv_loaica.FocusedRowHandle = gv_loaica.FocusedRowHandle;
                gv_loaica.FocusedColumn = gv_loaica.VisibleColumns[1];
                gv_loaica.ShowEditor();
                #endregion
            }

            #endregion
           
        }
        #endregion

        #region luu 1 toa
        string select_khachhang_id, select_khachhang_name,select_tien ;
        decimal TienMat;
        public void fu_btn_save()
        {

            check_exists(DuLieu.Le_ID);
        }
        public void check_exists(string ID_toa)
        {
            DataRow[] dr = DuLieu.List_NhapLe_HoaDon.Tables[0].Select("ID = '" + ID_toa.ToUpper() + "'");
            DataRow[] dr_chitiet = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID_HD = '" + ID_toa.ToUpper() + "'");
            //neu khong co trong ds thi luu moi
            if (dr.Length == 0)
            {
                if (dr_chitiet.Length > 0)
                {
                    fu_save_new(dr_chitiet);
                }
            }
            else //neu da co trong danh sách thi update
            {
                if (dr_chitiet.Length > 0)
                {
                    fu_update_toa(dr_chitiet,dr[0]);
                    if (phatlenhin == 1)
                    {
                        print();
                    }
                }
                else//neu da co nhung khong co du lieu chi tiet thi xoa
                {
                    fu_btn_xoa();
                    fu_btn_new();
                }
            }
           
            
        }
        public void kiemtra_decapnhat(string truonghop)
        {
             DataRow[] dr = DuLieu.List_NhapLe_HoaDon.Tables[0].Select("ID = '" + DuLieu.Le_ID.ToUpper() + "'");
             if (dr.Length > 0)
             {
                 switch (truonghop)
                 {
                     case "Tien_NCC":
                         {
                             #region
                             string tt = VthanhTien.SummaryText.Replace(",", "").Replace(".", "").Replace("(vnđ)", "").Replace(" ", "");
                             if (tt == "")
                             {
                                 DuLieu.Le_TongTien = 0;
                             }
                             else
                             {
                                 DuLieu.Le_TongTien = decimal.Parse(tt);
                             }
                             DataRow[] dr_chitiet = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'");
                             DuLieu.Le_ID_NCC = dr_chitiet[0]["ID_NCC"].ToString();
                             DuLieu.Le_Tbl_NCC_Name = dr_chitiet[0]["Tbl_NCC_Name"].ToString();
                             xoa_themlai();
                             gv_danhsach.RefreshData();
                             gv_danhsach.ExpandAllGroups();
                             gv_ds_cho.RefreshData();
                           
                             #endregion
                             break;
                         }
                     case "Tien":
                         {
                             #region
                             string tt = VthanhTien.SummaryText.Replace(",", "").Replace(".", "").Replace("(vnđ)", "").Replace(" ", "");
                             DuLieu.Le_TongTien = decimal.Parse(tt);
                             xoa_themlai();
                             gv_danhsach.RefreshData();
                             gv_danhsach.ExpandAllGroups();
                             gv_ds_cho.RefreshData();
                             #endregion
                             break;
                         }
                     case "NCC":
                         {
                             DataRow[] dr_chitiet = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'");
                             DuLieu.Le_ID_NCC = dr_chitiet[0]["ID_NCC"].ToString();
                             DuLieu.Le_Tbl_NCC_Name = dr_chitiet[0]["Tbl_NCC_Name"].ToString();
                             xoa_themlai();
                             gv_danhsach.RefreshData();
                             gv_danhsach.ExpandAllGroups();
                             gv_ds_cho.RefreshData();
                             break;
                         }
                     case "KH": //co lien quan tien mat
                         {
                             DuLieu.Le_Tbl_KhachHang_ID = select_khachhang_id;
                             DuLieu.Le_Tbl_KhachHang_Name = select_khachhang_name;
                             DuLieu.Le_TienMat = TienMat;
                             xoa_themlai();
                             if (msgbox.dialog_yes_no("In Toa ?") == DialogResult.Yes)
                             {
                                 phatlenhin = 1;
                                 fu_btn_save();
                             }
                             else
                             {
                                 fu_btn_save();
                             }
                             break;
                         }
                     case "GC":
                         {
                             DuLieu.Le_Tbl_KhachHang_ID = select_khachhang_id;
                             DuLieu.Le_Tbl_KhachHang_Name = select_khachhang_name;
                             DuLieu.Le_TienMat = 0;
                             xoa_themlai();
                             fu_btn_save();
                             break;
                         }
                 }

            }
             else
             {
                 if (truonghop == "GC" || truonghop == "KH")
                 {
                     //fu_btn_save();
                     if (msgbox.dialog_yes_no("In Toa ?") == DialogResult.Yes)
                     {
                         phatlenhin = 1;
                         fu_btn_save();
                     }
                     else
                     {
                         fu_btn_save();
                     }
                 }
             }
           
        }
        public void xoa_themlai()
        {
            #region
            DataRow[] dt_xoa = DuLieu.List_NhapLe_HoaDon.Tables[0].Select("ID = '" + DuLieu.Le_ID.ToUpper() + "'");
            DuLieu.List_NhapLe_HoaDon.Tables[0].Rows.Remove(dt_xoa[0]);
            DuLieu.List_NhapLe_HoaDon.Tables[0].AcceptChanges();

            _Xml_control.delete_xml_node(NhapLe_Class._xmlfile, DuLieu.Le_ID);
            _NhapLe_Class.add_toa_saukhixoa();
            DataRow dtr_new = DuLieu.List_NhapLe_HoaDon.Tables[0].NewRow();
            //dan
            dtr_new["ID"] = DuLieu.Le_ID;
            dtr_new["KyTu"] = DuLieu.Le_KyTu;
            dtr_new["SoHD"] = DuLieu.Le_SoHD;

            dtr_new["Tbl_KhachHang_ID"] = DuLieu.Le_Tbl_KhachHang_ID;
            dtr_new["Tbl_KhachHang_Name"] = DuLieu.Le_Tbl_KhachHang_Name;
            dtr_new["TienMat"] = DuLieu.Le_TienMat;

            dtr_new["ID_NCC"] = DuLieu.Le_ID_NCC;
            dtr_new["Tbl_NCC_Name"] = DuLieu.Le_Tbl_NCC_Name;
            dtr_new["Toa"] = DuLieu.Le_Toa;
            dtr_new["TongTien"] = DuLieu.Le_TongTien;

            DuLieu.List_NhapLe_HoaDon.Tables[0].Rows.Add(dtr_new);
            DuLieu.List_NhapLe_HoaDon.Tables[0].AcceptChanges();
            #endregion
        }
        public void fu_update_toa(DataRow[] dr_kiemtra_chitiet,DataRow dr)
        {
            //se thuc hien khi xem add,edit,delete,ghichu,thanhtoan
            // TH1 neu dang lam moi thi khong can update
            //TH2 neu dang xem thi goi ham nay
            // TH dang update va bam f2
            //các buoc thuc hien
            //1 thong ke lai : ID_NCC,Ten_NCC,ID_KH,Ten_KH,TienMat,TongTien
            //2 Xoa XML
          
            //them XML
            //update dong trong ds xoa and add

            DuLieu.Le_Tbl_KhachHang_ID = select_khachhang_id;
            DuLieu.Le_Tbl_KhachHang_Name = select_khachhang_name;
            DuLieu.Le_TienMat = TienMat;

            DuLieu.Le_ID_NCC = dr_kiemtra_chitiet[0]["ID_NCC"].ToString();
            DuLieu.Le_Tbl_NCC_Name = dr_kiemtra_chitiet[0]["Tbl_NCC_Name"].ToString();
            string tt = VthanhTien.SummaryText.Replace(",", "").Replace(".", "").Replace("(vnđ)", "").Replace(" ", "");
            DuLieu.Le_TongTien = decimal.Parse(tt);
            //2
            xoa_themlai();


        }
        public void fu_save_new(DataRow[] dr_kiemtra_chitiet)
        {
            #region
            // save - >update Xml = cach xoa va add lai
            //DataRow[] dr_kiemtra_chitiet = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'");
            //if (dr_kiemtra_chitiet.Length > 0)
            //{

            //1 thong ke lai : ID_NCC,Ten_NCC,ID_KH,Ten_KH,TienMat,TongTien
            //Add XML 
            // Add ds toa
            //Load lai gc
                #region

                DuLieu.Le_Tbl_KhachHang_ID = select_khachhang_id;
                DuLieu.Le_Tbl_KhachHang_Name = select_khachhang_name;
                DuLieu.Le_TienMat = TienMat;

                DuLieu.Le_ID_NCC = dr_kiemtra_chitiet[0]["ID_NCC"].ToString();
                DuLieu.Le_Tbl_NCC_Name = dr_kiemtra_chitiet[0]["Tbl_NCC_Name"].ToString();
                string tt = VthanhTien.SummaryText.Replace(",", "").Replace(".", "").Replace("(vnđ)", "").Replace(" ", "");
                DuLieu.Le_TongTien = decimal.Parse(tt);
                if (DuLieu.Le_Tbl_KhachHang_ID == "") //TH la khach vang lai
                {
                    DuLieu.Le_TongTien = decimal.Parse(tt);
                }

                

               // _Xml_control.delete_xml_node(NhapLe_Class._xmlfile, DuLieu.Le_ID);
                _NhapLe_Class.add_toa_saukhixoa();
             //   _NhapLe_Class.load_xml_hoadon();
            //add ds toa
                DataRow dtr_new = DuLieu.List_NhapLe_HoaDon.Tables[0].NewRow();
            //dan
                dtr_new["ID"] = DuLieu.Le_ID;
                dtr_new["KyTu"] = DuLieu.Le_KyTu;
                dtr_new["SoHD"] = DuLieu.Le_SoHD;

                dtr_new["Tbl_KhachHang_ID"] = DuLieu.Le_Tbl_KhachHang_ID;
                dtr_new["Tbl_KhachHang_Name"] = DuLieu.Le_Tbl_KhachHang_Name;
                if (DuLieu.Le_Tbl_KhachHang_ID == null || DuLieu.Le_Tbl_KhachHang_ID == "")
                {
                    dtr_new["TienMat"] = DuLieu.Le_TongTien;
                }
                else
                {
                    dtr_new["TienMat"] = DuLieu.Le_TienMat;
                }

                dtr_new["ID_NCC"] = DuLieu.Le_ID_NCC;
                dtr_new["Tbl_NCC_Name"] = DuLieu.Le_Tbl_NCC_Name;
                dtr_new["Toa"] = DuLieu.Le_Toa;
                dtr_new["TongTien"] = DuLieu.Le_TongTien;

                DuLieu.List_NhapLe_HoaDon.Tables[0].Rows.Add(dtr_new);
                DuLieu.List_NhapLe_HoaDon.Tables[0].AcceptChanges();
            //xong phan luu
                
                load_all_toa();
                load_toa_ghichu();
              TaoPDF();
                if (phatlenhin == 1)
                {
                    print();
                }
                fu_btn_new();
                #endregion
            //}
            //else
            //{
            //    msgbox.dialog_OK_warning("Toa Trống");
            //    tabbedControlGroup1.SelectedTabPageIndex = 0;

            //}


            #endregion
        }
        private void TaoPDF()
        {
            INTOALE.KH = select_khachhang_name;
            INTOALE.TOA = DuLieu.Le_Toa;

            T_billle rapport = new T_billle();
            DataView dtv = new DataView(DuLieu.List_NhapLe_ChiTiet.Tables[0]);
            dtv.RowFilter = "ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'";
            DataTable dt1 = dtv.ToTable();
            // DataRow []dr = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'");
            rapport.DataSource = dt1;
            try
            {
                StringBuilder p = new StringBuilder();
                // p.Append(string.Format("Ngày:{0} - {1}", DateTime.Now.ToString("dd/MM/  hh:mm"), INTOALE.KH));
                p.AppendLine(string.Format("🕓 Ngày: {0}", DateTime.Now.ToString("dd/MM/yyyy HH:mm")));
                p.AppendLine(string.Format("📌 Khách nợ: {0}", INTOALE.KH));
                p.AppendLine();
                double tt = 0;
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    tt += double.Parse(dt1.Rows[i]["ThanhTien"].ToString());
                    string kh = dt1.Rows[i]["Tbl_Hang_Name"].ToString();
                    string sl = double.Parse(dt1.Rows[i]["SL"].ToString()).ToString("#,##");
                    string gia = double.Parse(dt1.Rows[i]["Gia"].ToString()).ToString("#,##");
                    p.Append(string.Format("{0}:  {1} * {2}", kh, sl, gia));
                    p.AppendLine();
                }
                p.Append("_______________");
                p.AppendLine();
                //p.Append("💰Tổng tiền : " + tt.ToString("#,##"));
                p.Append(string.Format("*Tổng tiền: {0}*", tt.ToString("#,##"))); // Sử dụng in đậm

                //#region gui file telegram
                //Telegram_bot clsBot = new Telegram_bot();
                //clsBot.FormGui = this.Name;
                //clsBot.GoiNoiDungQuaTelegram(p.ToString());
                //#endregion
                // Chỉ gửi nếu KH không phải Vãng lai
                if (!INTOALE.KH.Trim().Equals("Vãng lai", StringComparison.OrdinalIgnoreCase))
                {
                    //GoiNoiDungQuaSlack(p.ToString());
                    SlackHelper.GoiNoiDungQuaSlack($"```{p}```", "nhaple", "🧾 Nhập Lẻ"); // đã tạo class chung là SlackHelper 
                }
            }
            catch (Exception ex)
            {
                // Xử lý lỗi nếu cần
                MessageBox.Show("Lỗi khi gửi qua /slack: " + ex.Message);
            }
        }
          
            //rapport.Print();
        
        //copy file Temp
        string thumuc = "";

        private void button1_Click(object sender, EventArgs e)
        {
            fu_btn_thanhtoan();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            fu_btn_thanhtoan();
        }

        
        private void btn_saveall_Click_1(object sender, EventArgs e)
        {
            fu_btn_saveall();
        }

        private void btn_setup_Click_1(object sender, EventArgs e)
        {
            fu_btn_setup();

        }

        private void btn_setupca_Click_1(object sender, EventArgs e)
        {
            fu_btn_setup_ca();

        }
    //    public void GoiNoiDungQuaSlack(string message)
    //    {
    //        string slackWebhookUrl = "https://hooks.slack.com/services/T01S5ND/B08TZ9T/Utsywy"; // Thay URL bằng của bạn _đây là channel tên là nhaple 

    //        var payload = new
    //        {
    //            attachments = new[] {
    //    new {
    //        color = "#36a64f",
    //        title = "🧾Hóa đơn bán hàng",
    //        text = message
    //    }
    //}
    //        };   

        //    string jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);

        //    using (var client = new System.Net.WebClient())
        //    {
        //        client.Encoding = System.Text.Encoding.UTF8; // 👈 Đây là dòng QUAN TRỌNG để hỗ trợ tiếng Việt
        //        client.Headers.Add("Content-Type", "application/json; charset=utf-8");
        //        client.UploadString(slackWebhookUrl, "POST", jsonPayload);
        //    }
        //}   ĐÃ DÙNG CLASS CHUNG NÊN KHÔNG CẦN KHAI BÁO PHẦN NÀY NỮA

        private void btn_sobanle_Click_1(object sender, EventArgs e)
        {
            
            show_sobanle();
            //BeginInvoke(new MethodInvoker(() =>
            //{
            //    load_all_toa(); // GỌI TRỄ HƠN, khi UI đã ổn định
            //    load_ds_toa_theolai();
            //}));
            //gc_danhsach.MinimumSize = new Size(0, 300);
            //_NhapLe_Class = new NhapLe_Class();
            //_NhapLe_Class.load_xml_hoadon();
            //_NhapLe_Class.load_xml_hoadon_chitiet();
            //_NhapLe_Class.load_conno();
            //load_ds_toa_theolai();

            //gc_danhsach.Focus();
            //gv_danhsach.SetFocusedRowModified();
            //gv_thuonglai.FocusedRowHandle = 0;
         // t//hongke_toa();
        }

        private void btn_new_Click_2(object sender, EventArgs e)
        {
            fu_btn_new();

        }

        private void btn_in_Click_1(object sender, EventArgs e)
        {
            fu_btn_in();

        }

        private void btn_luutoa_Click(object sender, EventArgs e)
        {
            fu_btn_save();
            // toolTip1.Show("✅ Đã lưu thành công", btn_luutoa, 0, -40, 3500); // Hiển thị phía trên nút 2 giây
            new ToastForm("✅ Đã lưu toa thành công").Show();


        }

        private void btn_xoa_Click_1(object sender, EventArgs e)
        {
            fu_btn_xoa();

        }

        private void simpleButton2_Click_1(object sender, EventArgs e)
        {
            fu_btn_thanhtoan();
        }

        private void btn_ghichu_Click(object sender, EventArgs e)
        {
            fu_btn_ghichu();
        }

        private void tabbedControlGroup1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {


            //_NhapLe_Class = new NhapLe_Class();
            //_NhapLe_Class.load_xml_hoadon();
            //_NhapLe_Class.load_xml_hoadon_chitiet();
            //// show_sobanle();
            //load_Xml();
            //load_all_toa();
            //load_toa_ghichu();
            //load_ds_toa_theolai();
            //thongke_toa();
        }

        private void tabbedControlGroup1_Click(object sender, EventArgs e)
        {
            //_NhapLe_Class = new NhapLe_Class();
            //_NhapLe_Class.load_xml_hoadon();
            //_NhapLe_Class.load_xml_hoadon_chitiet();
            //// show_sobanle();
            //load_Xml();
            //load_all_toa();
            //load_toa_ghichu();
            //load_ds_toa_theolai();
            //thongke_toa();

            

        }

        private void xtraTabPage2_Click(object sender, EventArgs e)
        {
            
            //_NhapLe_Class = new NhapLe_Class();
            //_NhapLe_Class.load_xml_hoadon();
            //_NhapLe_Class.load_xml_hoadon_chitiet();
            //// show_sobanle();
            //load_Xml();
            //load_ds_toa_theolai();
            //load_all_toa();
            //load_toa_ghichu();
            //load_ds_toa_theolai();
            //thongke_toa();
        }

        private void xtraTabPage2_DoubleClick(object sender, EventArgs e)
        {

        }

        private void Btn_T_Click(object sender, EventArgs e)
        {
            btnT_ClickCount++; // Tăng biến đếm mỗi khi nhấp

            if (btnT_ClickCount == 3)
            {
                // Đặt lại biến đếm ngay sau khi đủ 3 lần
                btnT_ClickCount = 0;
                fu_btn_saveall();

                // Hiển thị bảng thông báo xác nhận
                //DialogResult confirmation = MessageBox.Show(
                //    "Bạn có chắc chắn muốn thực hiện thay đổi không?", // Nội dung thông báo
                //    "Xác nhận ?", // Tiêu đề thông báo
                //    MessageBoxButtons.YesNo,
                //    MessageBoxIcon.Question);

                //if (confirmation == DialogResult.Yes)
                {
                    // Nếu người dùng chọn "Yes", thực hiện thay đổi database
                    string newDatabaseName = "fish"; // Tên database cố định bạn muốn đặt

                    if (ABC.KetNoi.ConfigManager.UpdateDatabaseNameInFile(newDatabaseName))
                    {
                        MessageBox.Show(
                            $" cập nhật thành công thành " + // Thêm tên DB vào thông báo cho rõ ràng
                            "Các thay đổi có thể yêu cầu khởi động lại ứng dụng hoặc tải lại cấu hình ở các thành phần liên quan.",
                            "Thành công",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(
                            "Không thể cập nhật tên cơ sở dữ liệu. Vui lòng kiểm tra lại.", // Thông báo lỗi cụ thể hơn một chút
                            "Lỗi cập nhật",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }
                }
                // else: Người dùng chọn "No", không làm gì cả. Biến đếm đã được reset.
            }
            // Nếu btnT_ClickCount < 3, không có hành động nào xảy ra.
        }

        //private void SimpleButton1_Click(object sender, EventArgs e)
        //{            
        //    FolderBrowserDialog dialog = new FolderBrowserDialog();
        //    if(dialog.ShowDialog()==DialogResult.OK)
        //    {
        //        string thumuc = dialog.SelectedPath;
        //        string fileNguon = Path.GetDirectoryName(Application.ExecutablePath) + @"\BanLe\TempDataLe\ChiTietHD\" + Get_CauHinh.Ngay_DN + ".xml";
        //        string FileTemp=thumuc+ "/"+Get_CauHinh.Ngay_DN + ".xml";
        //        System.IO.File.Copy(fileNguon, FileTemp,true);
        //    }
        //}
        //chep temp
        //private void SimpleButton2_Click(object sender, EventArgs e)
        //{
        //    FolderBrowserDialog dialog = new FolderBrowserDialog();
        //    if (dialog.ShowDialog() == DialogResult.OK)
        //    {
        //        string thumuc = dialog.SelectedPath;
        //        string FileTemp = thumuc + "/" + Get_CauHinh.Ngay_DN + ".xml";
        //        string fileDich = Path.GetDirectoryName(Application.ExecutablePath) + @"\BanLe\TempDataLe\ChiTietHD\" + Get_CauHinh.Ngay_DN + ".xml";             
        //        System.IO.File.Copy(FileTemp, fileDich,true);
        //    }
        //}
        #endregion

        #region print
        public int phatlenhin;
        public void print()
        {
            #region
            //  dts_1phieu = ex.load_data_1phieu(ID_active.ToString());
            INTOALE.KH = select_khachhang_name;
            INTOALE.TOA = DuLieu.Le_Toa;
           
            T_billle rapport = new T_billle();
            DataView dtv = new DataView(DuLieu.List_NhapLe_ChiTiet.Tables[0]);
            dtv.RowFilter = "ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'";
            DataTable dt1 = dtv.ToTable();
           // DataRow []dr = DuLieu.List_NhapLe_ChiTiet.Tables[0].Select("ID_HD = '" + DuLieu.Le_ID.ToUpper() + "'");
            rapport.DataSource = dt1; ;
            rapport.Print();
          //  rapport.ShowPreview();
            phatlenhin = 0;
            #endregion
        }
        #endregion

        private void btn_thanhtoan_Click_1(object sender, EventArgs e)
        {

        }

        private void gc_loaica_Click(object sender, EventArgs e)
        {

        }

        private void ClickSequenceTimer_Tick(object sender, EventArgs e)
        {
            // Dừng Timer lại vì thời gian chờ giữa các click đã hết
            clickSequenceTimer.Stop();

            // Đặt lại bộ đếm số lần nhấp về 0
            btnT_ClickCount = 0;

            // Tùy chọn: Bạn có thể thêm một thông báo nhỏ ở đây (ví dụ trên một Label hoặc StatusBar)
            // để người dùng biết chuỗi nhấp đã bị reset, nhưng thường không cần thiết.
            // Ví dụ: if (statusBar1 != null) statusBar1.Text = "Chuỗi nhấp đã được đặt lại.";
        }


    }
}






