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 ABC.GiaoDich;
using ABC.KetNoi;
using ABC.Report;
using System.IO;
using DevExpress.XtraReports.UI;
using DevExpress.XtraEditors;

using System.Xml;
using ABC.File;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraGrid.Views.Grid;

namespace ABC.Toa
{
    public partial class LamToa : XtraUserControl
    {
        public LamToa()
        {
            InitializeComponent();
            
            event_click();
           

            txtngay.Text = Get_CauHinh.ngay_text;
            txtngayden.Text = Get_CauHinh.ngay_text;
            Look_tenlai.Properties.DataSource = DuLieu.List_NCC.Tables[0];
            lool_nhomLai.Properties.DataSource = DuLieu.List_Nhom_NCC.Tables[0];
            this.Load += new EventHandler(Toa_QuanLyDuLieu_Load);
            
            Link_add.Click += new EventHandler(Link_add_Click);
            link_in.Click += new EventHandler(link_in_Click);
            Link_xoa.Click += new EventHandler(Link_xoa_Click);
            link_pdf.Click += new EventHandler(link_pdf_Click);
            link_xoachitiet.Click += new EventHandler(link_xoachitiet_Click);
            link_gop.Click += new EventHandler(link_gop_Click);
        }
        
        Gop _Gop;
        void link_gop_Click(object sender, EventArgs e)
        {
            #region
            DataRow dr = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);

            _Gop = new Gop();
            _Gop.dr_chinh = dr;
            if (check_ngay.Checked == true)
            {
                _Gop.ngay_chon = txtngay.Value;
            }
            else
            {
                _Gop.ngay_chon = Convert.ToDateTime(Get_CauHinh.ngay_text);
            }
            _Gop.FormClosed += new FormClosedEventHandler(_Gop_FormClosed);
            _Gop.ShowDialog();

            #endregion

        }

        void _Gop_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_Gop.DialogResult == DialogResult.OK)
            {
                tailai();
            }
        }

        void link_xoachitiet_Click(object sender, EventArgs e)
        {
            if (Pow.kiemtra("LamToa", "Xoa", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                DataRow dr = gv1.GetDataRow(gv1.FocusedRowHandle);
                DevExpress.XtraGrid.Views.Base.ColumnView bw = (DevExpress.XtraGrid.Views.Base.ColumnView)gc1.FocusedView;
                if (bw.IsDetailView)
                {
                    int detailrowhandle = bw.FocusedRowHandle;
                    DataRow dr1 = bw.GetDataRow(detailrowhandle);

                    string row = dr1["LoaiDL"].ToString();
                    if (row == "Nhâp Thêm")
                    {
                        if (msgbox.dialog_yes_no("Xóa dữ liệu nhập thêm?") == DialogResult.Yes)
                        {

                            int ng;
                            if (check_ngay.Checked == true)
                            {
                                ng = (int)(Convert.ToDateTime(txtngay.Text) - new DateTime(1900, 1, 1)).TotalDays;
                            }
                            else
                            {
                                ng = Get_CauHinh.Ngay_DN;
                            }
                            string sql = "Delete from Tbl_GIAODICH_Them where ID_NCC = '" + dr["ID_NCC"].ToString().ToUpper() + "' and Date_Num_Final_UpDate = " + ng + "";
                            db.T_exc(sql);
                            tailai();
                        }
                    }
                }
            }
        }

        void link_pdf_Click(object sender, EventArgs e)
        {
            xuatpdf();
            btn_load_Click(sender, e);
        }

        void Link_xoa_Click(object sender, EventArgs e)
        {
            if (Pow.kiemtra("LamToa", "Xoa", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                #region
                DataRow dr = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);
                if (msgbox.dialog_yes_no("Xóa toa " + dr["TOA1"].ToString() + " ?") == DialogResult.Yes)
                {
                    string kiemtra_sql = "sp_GiaoDich_Them_TOAID '" + dr["ID"].ToString().ToUpper() + "'";
                    DataTable dt_kientra = db.T_opendataset(kiemtra_sql).Tables[0];
                    if (dt_kientra.Rows.Count > 0)
                    {
                        //hoi
                        if (msgbox.dialog_yes_no("Có dữ liệu nhập thêm trên toa \n Bạn muốn xóa dữ liệu nhập thêm không ?") == DialogResult.Yes)
                        {
                            //xoa dl nhap them truoc
                            string sql_xoa_nhapthem = "delete from Tbl_GIAODICH_Them where Toa_ID = '" + dr["ID"].ToString().ToUpper() + "'";
                            db.T_exc(sql_xoa_nhapthem);
                            DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "Tbl_GIAODICH_Them Toa_ID"+ dr["ID"].ToString().ToUpper(), "", "Xoá");
                            string sql = "Xoa_toa '" + dr["ID"].ToString().ToUpper() + "'";
                            db.T_exc(sql);
                          
                            tailai();
                        }
                        else
                        {
                            string sql = "Xoa_toa '" + dr["ID"].ToString().ToUpper() + "'";
                            db.T_exc(sql);
                            DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "Xoa_toa Toa_ID" + dr["ID"].ToString().ToUpper(), "", "Xoá");
                            tailai();
                        }
                    }
                    else
                    {
                        string sql = "Xoa_toa '" + dr["ID"].ToString().ToUpper() + "'";
                        db.T_exc(sql);
                        DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "Xoa_toa Toa_ID" + dr["ID"].ToString().ToUpper(), "", "Xoá");
                        tailai();
                    }


                }
                #endregion
            }
        }

        void link_in_Click(object sender, EventArgs e)
        {
            print1();
        }

        void Link_add_Click(object sender, EventArgs e)
        {
            try
            {
                // thiet lap
                if (Pow.kiemtra("LamToa", "Them", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
                {
                    DataRow dr = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);
                    #region
                    _Toa_New = new Toa_New();
                    _Toa_New.User_Case = "Edit";
                    _Toa_New.ID_Toa = dr["ID"].ToString();
                    //------------------thong tin chi tiet toa

                    _Toa_New.KyTu_Toa = dr["KYTU"].ToString();
                    _Toa_New.SoToa = int.Parse(dr["SOTOA"].ToString());
                    _Toa_New.Ngay_ToaNum = int.Parse(dr["NGAYLAMTOA"].ToString());
                    _Toa_New.NgayTuNum = int.Parse(dr["FROM_N"].ToString());
                    _Toa_New.NgayDenNum = int.Parse(dr["TO_N"].ToString());

                    _Toa_New.Ngay_Toa = Convert.ToDateTime(dr["NGAYLAMTOA_TEXT"].ToString()).ToShortDateString();
                    _Toa_New.NgayTu = Convert.ToDateTime(dr["FROM_TEXT"].ToString()).ToShortDateString();
                    _Toa_New.NgayDen = Convert.ToDateTime(dr["TO_TEXT"].ToString()).ToShortDateString();

                    _Toa_New.NCC_ID = dr["NCC_ID"].ToString().ToUpper();
                    _Toa_New.NCC_Name = dr["Tbl_NCC_Name"].ToString();
                    //load chi tra
                    _Toa_New.TKHIEN = double.Parse(dr["TKHIEN"].ToString());
                    _Toa_New.TNUOC = double.Parse(dr["TNUOC"].ToString());
                    _Toa_New.TUNG = double.Parse(dr["TUNG"].ToString());
                    _Toa_New.TXE = double.Parse(dr["TXE"].ToString());
                    _Toa_New.TKY = double.Parse(dr["TKY"].ToString());
                    _Toa_New.T_HH = double.Parse(dr["THH"].ToString());


                    _Toa_New.TTHEM1 = double.Parse(dr["TTHEM1"].ToString());
                    _Toa_New.TTHEM2 = double.Parse(dr["TTHEM2"].ToString());
                    _Toa_New.TTHEM3 = double.Parse(dr["TTHEM3"].ToString());

                    _Toa_New.TEN_THEM1 = dr["TEN_THEM1"].ToString();
                    _Toa_New.TEN_THEM2 = dr["TEN_THEM2"].ToString();
                    _Toa_New.TEN_THEM3 = dr["TEN_THEM3"].ToString();

                    _Toa_New.xe1 = dr["C1"].ToString();
                    _Toa_New.xe2 = dr["C2"].ToString();
                    _Toa_New.xe3 = dr["C3"].ToString();
                    _Toa_New.TrangThai = dr["TINHTRANG"].ToString();
                    _Toa_New.GhiChu = dr["C5"].ToString();
                    _Toa_New.FormClosed += new FormClosedEventHandler(_Toa_New_FormClosed);
                    _Toa_New.ShowDialog();
                    #endregion
                }
            }
            catch (Exception)
            {

                MessageBox.Show("Không có thông tin!");
            }
           

        }

        void Toa_QuanLyDuLieu_Load(object sender, EventArgs e)
        {
            tailai();
            simpleButton1_Click(sender, e);
        }
        #region lệnh dùng chung
        void _BaoCao_SoBaoCao_Si_Bien_Edit_FormClosed(object sender, FormClosedEventArgs e)
        {
            tailai();
        }
        public void chon()
        {

        }
        public void bochon()
        {

        }
        NhapSi_Class _NhapSi_Class = new NhapSi_Class();
        public void tailai()
        {
            #region
            string store = "Loadtoa ";
            string filter_string = "select * from Toa_DaTao where khoa is null and NGAYLAMTOA >0 ";
            if (check_ngay.Checked == true)
            {
                int ng = (int)(Convert.ToDateTime(txtngay.Text) - new DateTime(1900, 1, 1)).TotalDays;
                int ngden = (int)(Convert.ToDateTime(txtngayden.Text) - new DateTime(1900, 1, 1)).TotalDays;
                filter_string += " AND NGAYLAMTOA >= " + ng + " AND NGAYLAMTOA <= " + ngden + "";
                store += "" + ng + ",";
                if (check_ten_thuonglai.Checked == true && Look_tenlai.EditValue != null)
                {
                    filter_string += " And NCC_ID = '" + Look_tenlai.EditValue.ToString().ToUpper() + "'";
                    store += "'" + Look_tenlai.EditValue.ToString().ToUpper() + "',";
                }
                else
                {
                    store += "Null,";
                }

                if (check_nhom_lai.Checked == true && lool_nhomLai.EditValue != null && lool_nhomLai.EditValue != "")
                {
                    filter_string += " And NHOM_NCC_ID = '" + lool_nhomLai.EditValue.ToString().ToUpper() + "'";
                    store += "'" + lool_nhomLai.EditValue.ToString().ToUpper() + "'";
                }
                else
                {
                    store += "Null";
                }
            }
            else
            {
                filter_string += "AND NGAYLAMTOA = " + Get_CauHinh.Ngay_DN + "";
                store += "" + Get_CauHinh.Ngay_DN + ",";
                if (check_ten_thuonglai.Checked == true && Look_tenlai.EditValue != null)
                {
                    filter_string += " And NCC_ID = '" + Look_tenlai.EditValue.ToString().ToUpper() + "'";
                    store += "'" + Look_tenlai.EditValue.ToString().ToUpper() + "',";
                }
                else
                {
                    store += "Null,";
                }

                if (check_nhom_lai.Checked == true && lool_nhomLai.EditValue != null && lool_nhomLai.EditValue != "")
                {
                    filter_string += " And NHOM_NCC_ID = '" + lool_nhomLai.EditValue.ToString().ToUpper() + "'";
                    store += "'" + lool_nhomLai.EditValue.ToString().ToUpper() + "'";
                }
                else
                {
                    store += "Null";
                }
            }
            DuLieu.QuanLyToa = _NhapSi_Class.get_dataset(filter_string);
            DuLieu.QuanLyToa.Tables[0].Columns.Add("Select", typeof(bool));

            DuLieu.QuanLyduLieu_group = _NhapSi_Class.get_dataset(store);

            DuLieu.QuanLyduLieu_group.Relations.Add("Orders",
            DuLieu.QuanLyduLieu_group.Tables[0].Columns["ID_NCC"],
            DuLieu.QuanLyduLieu_group.Tables[1].Columns["ID_NCC"]);
            data();
            #endregion
        }

        public void print()
        {
            if (Pow.kiemtra("Toa_QuanLy", "Inan", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                #region
                #endregion
            }
        }
        public void print_bill()// in tong hop
        {
            if (Pow.kiemtra("Toa_QuanLy", "Inan", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                #region

                #endregion
            }
        }
        #endregion

        #region menu click
        public void event_click()
        {
            // btn_close.Click += new EventHandler(btn_close_Click);
            btn_load.Click += new EventHandler(btn_load_Click);
            Linnk_TaoToa.Click += new EventHandler(Linnk_TaoToa_Click);
            btn_new.Click += new EventHandler(btn_new_Click);
        }

        void Linnk_TaoToa_Click(object sender, EventArgs e)
        {
            #region
            DataRow dr = gv1.GetDataRow(gv1.FocusedRowHandle);
            _Toa_New = new Toa_New();
            _Toa_New.ID_Toa = null;

            int ng = (int)(Convert.ToDateTime(txtngay.Text) - new DateTime(1900, 1, 1)).TotalDays;
            if (check_ngay.Checked == true)
            {
                _Toa_New.Ngay_ToaNum = ng;
                _Toa_New.Ngay_Toa = txtngay.Text;
                _Toa_New.NgayTuNum = ng;
                _Toa_New.NgayDenNum = ng;
                _Toa_New.NgayTu = txtngay.Text;
                _Toa_New.NgayDen = txtngay.Text;
            }
            else
            {
                _Toa_New.Ngay_ToaNum = Get_CauHinh.Ngay_DN; ;
                _Toa_New.Ngay_Toa = Get_CauHinh.ngay_text;
                _Toa_New.NgayTuNum = Get_CauHinh.Ngay_DN;
                _Toa_New.NgayDenNum = Get_CauHinh.Ngay_DN;
                _Toa_New.NgayTu = Get_CauHinh.ngay_text;
                _Toa_New.NgayDen = Get_CauHinh.ngay_text;
            }
            _Toa_New.NCC_ID = dr["ID_NCC"].ToString().ToUpper();
            _Toa_New.NCC_Name = dr["Tbl_NCC_Name"].ToString();

            _Toa_New.User_Case = "New";


            _Toa_New.FormClosed += new FormClosedEventHandler(_Toa_New_FormClosed);
            _Toa_New.ShowDialog();
            #endregion
        }
        Toa_New _Toa_New;
        public void taotoa()
        {
            _Toa_New = new Toa_New();
            _Toa_New.ID_Toa = null;
            _Toa_New.User_Case = "New";
            _Toa_New.FormClosed += new FormClosedEventHandler(_Toa_New_FormClosed);
            _Toa_New.ShowDialog();
        }
        void btn_new_Click(object sender, EventArgs e)
        {
            taotoa();

        }
        Class_KetNoi db = new Class_KetNoi();
        void _Toa_New_FormClosed(object sender, FormClosedEventArgs e)
        {
            tailai();
        }
        Toa_Class _Toa_Class = new Toa_Class();
        void btn_sua_Click(object sender, EventArgs e)
        {
            print_bill();
        }



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

        void btn_load_Click(object sender, EventArgs e)
        {
            SplashScreenManager.ShowForm(typeof(SplashScreen1));
            tailai();
            SplashScreenManager.CloseForm();
        }

        void btn_close_Click(object sender, EventArgs e)
        {
            //  this.Close();
        }

        void btn_none_Click(object sender, EventArgs e)
        {
            bochon();
        }

        void btn_all_Click(object sender, EventArgs e)
        {
            chon();
        }






        #endregion

        #region data
        public void data()
        {
            gc1.DataSource = DuLieu.QuanLyduLieu_group.Tables[0];
            gv1.ExpandAllGroups();


            DataTable dtLuu = DuLieu.QuanLyToa.Tables[0];
            dtLuu.Columns.Add("DaGui", typeof(bool));
            dtLuu.Columns.Add("DaLuuFile", typeof(bool));
            dtLuu.Columns.Add();
            dtLuu.Columns.Add("TenFilePDF");
            dtLuu.Columns.Add("gop");
            for (int i = 0; i < dtLuu.Rows.Count; i++)
            {
                string _IDToa = dtLuu.Rows[i]["ID"].ToString().Trim();
                DataTable dt = DSThongTinToaTheoIDToa(_IDToa);
                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.Rows[0];
                    dtLuu.Rows[i]["DaGui"] = (row["DaGui"].ToString() == "") ? false : bool.Parse(row["DaGui"].ToString());
                    dtLuu.Rows[i]["DaLuuFile"] = (row["DaLuuFile"].ToString() == "") ? false : bool.Parse(row["DaLuuFile"].ToString());
                    dtLuu.Rows[i]["TenFilePDF"] = row["TenFilePDF"].ToString();
                }
               
                int thamso = 1;
                string[] arr_name = new string[thamso];
                object[] arr_value = new object[thamso];
                arr_name[0] = "@ID";
                arr_value[0] = dtLuu.Rows[i]["ID"].ToString().Trim().ToUpper();
                DataTable dt1 = db.T_opendataset_store("sp_TOA_GOP_TheoIDTOA",arr_name,arr_value,thamso).Tables[0];
                if (dt1.Rows.Count > 0)
                    dtLuu.Rows[i]["gop"] = "+";
            }
            gc_daluu.DataSource = dtLuu;
            gv_daluu.ExpandAllGroups();
        }

        #endregion


        #region in
        chang _chang = new chang();
        public void print1()
        {

            //   DataRow dr321 = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);

            #region

            if (Pow.kiemtra("LamToa", "Inan") == true)
            {

                progess_print("");
            }
            #endregion
        }
        #endregion

        private DataTable DSThongTinToaTheoIDToa(string IDToa)
        {
            Class_KetNoi cls = new Class_KetNoi();
            DataTable dt = cls.T_opendataset("select * from TOA where ID='" + IDToa + "'").Tables[0];
            return dt;
        }
        #region pdf
        Toa_Class tl = new Toa_Class();
        public void xuatpdf()
        {
            DataRow dtrchon = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);
            pdf1();
        }
        public void pdf1()
        {
            #region load cau hinh
            string thumuPDF1 = "";
            DataTable dt = Main_Form._dtCauHinh;
            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                thumuPDF1 = row["ThuMucPDF2"].ToString();
            }
            #endregion
            #region
            if (Pow.kiemtra("LamToa", "Inan") == true)
            {
                #region
                DataRow dr = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);
                #region
                string ID_Toa = dr["ID"].ToString(); // ID_Toa gốc
                string SOTOA_value = dr["SOTOA"].ToString(); // Lấy giá trị SOTOA


                //------------------thong tin chi tiet toa
                string sql = "Get_data_toa '" + ID_Toa + "'";
                Toa_Class.Table_Data = db.T_opendataset(sql);
                T_TL.KyTu_Toa = dr["KYTU"].ToString();
                T_TL.SoToa = int.Parse(dr["SOTOA"].ToString()); // Bạn đã có SOTOA ở đây dưới dạng số
                T_TL.Ngay_ToaNum = int.Parse(dr["NGAYLAMTOA"].ToString());
                T_TL.NgayTuNum = int.Parse(dr["FROM_N"].ToString());
                T_TL.NgayDenNum = int.Parse(dr["TO_N"].ToString());

                T_TL.Ngay_Toa = Convert.ToDateTime(dr["NGAYLAMTOA_TEXT"].ToString()).ToShortDateString();
                T_TL.NgayTu = Convert.ToDateTime(dr["FROM_TEXT"].ToString()).ToShortDateString();
                T_TL.NgayDen = Convert.ToDateTime(dr["TO_TEXT"].ToString()).ToShortDateString();

                //  T_TL.NCC_ID = dr["NCC_ID"].ToString().ToUpper();
                T_TL.NCC_Name = dr["Tbl_NCC_Name"].ToString();
                //load chi tra
                T_TL.TKHIEN = double.Parse(dr["TKHIEN"].ToString());
                T_TL.TNUOC = double.Parse(dr["TNUOC"].ToString());
                T_TL.TUNG = double.Parse(dr["TUNG"].ToString());
                T_TL.TXE = double.Parse(dr["TXE"].ToString());
                T_TL.TKY = double.Parse(dr["TKY"].ToString());
                T_TL.T_HH = double.Parse(dr["THH"].ToString());


                T_TL.TTHEM1 = double.Parse(dr["TTHEM1"].ToString());
                T_TL.TTHEM2 = double.Parse(dr["TTHEM2"].ToString());
                T_TL.TTHEM3 = double.Parse(dr["TTHEM3"].ToString());

                T_TL.TEN_THEM1 = dr["TEN_THEM1"].ToString();
                T_TL.TEN_THEM2 = dr["TEN_THEM2"].ToString();
                T_TL.TEN_THEM3 = dr["TEN_THEM3"].ToString();

                T_TL.xe1 = dr["C1"].ToString();
                T_TL.xe2 = dr["C2"].ToString();
                T_TL.xe3 = dr["C3"].ToString();
                T_TL.TrangThai = dr["TINHTRANG"].ToString();
                T_TL.GhiChu = dr["C5"].ToString();
                //--------------------------------------------------------------
                double TongchiPhi = T_TL.TKHIEN + T_TL.TNUOC;

                double ChiPhikhac = T_TL.TUNG + T_TL.TXE + T_TL.TKY + T_TL.TTHEM1 + T_TL.TTHEM2 + T_TL.TTHEM3;
                double DS_Toa;
                object Sum = Toa_Class.Table_Data.Tables[0].Compute("Sum(ThanhTien)", "");
                try { DS_Toa = (double)Sum; }
                catch { DS_Toa = 0; }
                T_TL.TPHAITRA = DS_Toa - T_TL.T_HH - TongchiPhi - ChiPhikhac;
                //--------------------------------------------------------------

                double SL_Toa;
                object SumSL = Toa_Class.Table_Data.Tables[0].Compute("Sum(Toa_SL)", "");
                try { SL_Toa = (double)SumSL; }
                catch { SL_Toa = 0; }
                // public double SL_Goc, SL_Toa, SL_Lech;
                try { T_TL.Gia_Toa = DS_Toa / SL_Toa; }
                catch { T_TL.Gia_Toa = 0; }
                // public double DS_Goc, DS_Toa, DS_Lech;
                try { T_TL._GiaT_cophi = (DS_Toa - TongchiPhi - T_TL.T_HH) / SL_Toa; }
                catch { T_TL._GiaT_cophi = 0; }
                //get du lieu chi tiet

                //get toa
                #endregion

                #region
                DataTable dsSelectData = new DataTable();
                double pt = T_TL.TPHAITRA / 1000;
                double pt1 = System.Math.Round(pt, 0, MidpointRounding.ToEven);
                double tientra = pt1 * 1000;
                // msgbox.dialog_OK_info(tientra.ToString());
                T_TL.TPHAITRA = tientra;
                DuLieu.tien_chu = "Bằng chữ : " + _chang.ChuyenSo(tientra.ToString().Replace(",", ""));
                // DuLieu.tien_chu = "Bằng chữ : " + _chang.ChuyenSo(T_TL.TPHAITRA.ToString().Replace(",", "").Replace(".", ""));
                dsSelectData = Toa_Class.Table_Data.Tables[1].Copy();
                //dsSelectData.Tables[0].DefaultView.Sort = " criterian";
                string CA = dsSelectData.Rows[0]["Toa_NhomHang_Ten"].ToString();
                string HSL = dsSelectData.Rows[0]["MHHSL"].ToString();
                string HPC = dsSelectData.Rows[0]["MHHPC"].ToString();
                dsSelectData.Columns.Add("HH");
                for (int i = 1; i < dsSelectData.Rows.Count; i++)
                {
                    if (dsSelectData.Rows[i]["Toa_NhomHang_Ten"].ToString() == CA && dsSelectData.Rows[i]["MHHSL"].ToString() == HSL && dsSelectData.Rows[i]["MHHPC"].ToString() == HPC)
                    {
                        dsSelectData.Rows[i]["Toa_NhomHang_Ten"] = "";
                        dsSelectData.AcceptChanges();
                    }
                    else
                    {
                        CA = dsSelectData.Rows[i]["Toa_NhomHang_Ten"].ToString();
                        HPC = dsSelectData.Rows[i]["MHHPC"].ToString();
                        HSL = dsSelectData.Rows[i]["MHHSL"].ToString();
                    }

                }
                for (int i = 0; i < dsSelectData.Rows.Count; i++)
                {
                    if (float.Parse(dsSelectData.Rows[i]["MHHSL"].ToString()) > 0)
                    {
                        dsSelectData.Rows[i]["HH"] = String.Format("{0:#,#}", double.Parse(dsSelectData.Rows[i]["MHHSL"].ToString())) + " vnđ";
                    }
                    else
                    {
                        dsSelectData.Rows[i]["HH"] = String.Format("{0:N1}", double.Parse(dsSelectData.Rows[i]["MHHPC"].ToString())) + " %";
                    }
                }
                dsSelectData.AcceptChanges();
                dsSelectData.Columns.Add("ABC");
                for (int i = 0; i < dsSelectData.Rows.Count; i++)
                {
                    if (dsSelectData.Rows[i]["Toa_NhomHang_Ten"].ToString() != "")
                    {

                        DataView dtv = new DataView(Toa_Class.Table_Data.Tables[2]);
                        dtv.RowFilter = "Toa_NhomHang_Ten = '" + dsSelectData.Rows[i]["Toa_NhomHang_Ten"].ToString() + "' AND MHHSL = " + dsSelectData.Rows[i]["MHHSL"].ToString() + " AND MHHPC = " + dsSelectData.Rows[i]["MHHPC"].ToString() + "";
                        double sl, g;
                        try
                        {
                            sl = double.Parse(dtv[0]["Sum_SL"].ToString());
                        }
                        catch
                        {
                            sl = 0;
                        }
                        try
                        {
                            g = double.Parse(dtv[0]["Gia"].ToString());
                        }
                        catch
                        {
                            g = 0;
                        }

                        dsSelectData.Rows[i]["ABC"] = "  (" + String.Format("{0:N1}", sl) + " x " + String.Format("{0:N0}", g) + ")";
                        dsSelectData.AcceptChanges();
                    }
                }


                //xoa cac dong co sl =0
                DataRow[] dtrx = dsSelectData.Select("Sum_SL=0");
                for (int i = 0; i < dtrx.Length; i++)
                {
                    dtrx[i].Delete();

                }
                dsSelectData.AcceptChanges();
                //
                MessageBoxManager.Yes = "Ngắt Trang";
                MessageBoxManager.No = "Không Ngắt";
                MessageBoxManager.Cancel = "Bỏ qua";
                MessageBoxManager.Register();
                DialogResult da = MessageBox.Show("Chọn Mẫu in? ", "Phần mềm quản lý cá", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
                if (da == DialogResult.Yes)
                {
                    DuLieu.ngattrang = 1;
                }
                if (da == DialogResult.No)
                {
                    DuLieu.ngattrang = 0;
                }
                MessageBoxManager.Unregister();
                //gan bien



                T_TL rapport1 = new T_TL();
                rapport1.DataSource = dsSelectData;
                rapport1.LocationFloat = new DevExpress.Utils.PointFloat(10, 10);
                //  rapport1.ShowPreviewDialog();
                #endregion

                // Thay đổi cách đặt tên file ở đây
                // Lựa chọn 1: Sử dụng SOTOA_value
                // string ten_file_pdf = dr["Tbl_NCC_Name"].ToString()  + "_" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + "_" + SOTOA_value;
                string ten_file_pdf = dr["Tbl_NCC_Name"].ToString() + "_" +
                          DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() +
                          "_SoToa" + SOTOA_value; // <--- Đã cập nhật
                                                  // Lựa chọn 2a: Sử dụng SOTOA_value với thời gian chi tiết
                                                  // string ten_file_pdf = dr["Tbl_NCC_Name"].ToString() + "_" +
                                                  //  DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss") + "_" +
                                                  // SOTOA_value;

                // Lựa chọn 2b: Sử dụng SOTOA_value với GUID ngắn
                // string uniqueSuffix = Guid.NewGuid().ToString("N").Substring(0, 6); // Lấy 6 ký tự cho ngắn gọn
                // string ten_file_pdf = dr["Tbl_NCC_Name"].ToString()  + "_" +
                //                       DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + "_" +
                //                       SOTOA_value + "_" +
                //                       uniqueSuffix;

                string thumuc = thumuPDF1;

                if (!Directory.Exists(thumuc))
                {
                    msgbox.dialog_OK_warning("Không tìm thấy thư mục " + thumuc + " \n Vui lòng kiểm tra lại");

                }
                else
                {
                    var cultureInfo = new System.Globalization.CultureInfo("vi-VN");
                    string thangNamHienTai = DateTime.Now.ToString("'tháng' M 'năm' yyyy", cultureInfo); // Đảm bảo yyyy để lấy đủ 4 chữ số năm
                    string thuMucCha = Path.Combine(thumuc, thangNamHienTai);

                    if (!Directory.Exists(thuMucCha))
                    {
                        Directory.CreateDirectory(thuMucCha);
                    }

                    string thumucmoi = Path.Combine(thuMucCha, Get_CauHinh.ngay_text.Replace(@"\", "_").Replace("-", "_").Replace("/", "_"));
                    check_va_taothumuc(thumucmoi);
                    var reportPath = Path.Combine(thumucmoi, ten_file_pdf + ".pdf");

                    var stream = new MemoryStream();
                    rapport1.ExportToPdf(stream);

                    using (var fs = System.IO.File.Create(reportPath))
                    {
                        stream.WriteTo(fs);
                    }
                    var reportStream = System.IO.File.OpenRead(reportPath);
                    #region luu file vao SQL
                    LuuTenFileVaoSQL(reportPath, ID_Toa); // Bạn vẫn có thể muốn lưu ID_Toa gốc vào SQL để tham chiếu
                    #endregion
                    #region set trang thai daGui=1

                    #endregion
                    msgbox.dialog_OK_info("Đã xuất pdf.");
                }
            }
            #endregion
        }
            #endregion

        
        string _ID_NCC = "";
        string _ID_Toa = "";
        string _TenFilePDF = "";
        private void LinkGuiZalo_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "/Data.dat";
            string _tk = "";
            string _mk = "";
            string _tieude = "";
            string _noidung = "";

            if (System.IO.File.Exists(path))
            {
                using (BinaryReader reader = new BinaryReader(System.IO.File.Open(path, FileMode.Open)))
                {

                    string a = reader.ReadString();
                    string b = reader.ReadString();
                    string c = reader.ReadString();
                    string d = reader.ReadString();
                    string e1 = reader.ReadString();
                    string e2 = reader.ReadString();
                    string e3 = reader.ReadString();
                    string e4 = reader.ReadString();
                    string e5 = reader.ReadString();
                    string e6 = reader.ReadString();
                    string e7 = reader.ReadString();
                    string e8 = reader.ReadString();
                    string e9 = reader.ReadString();
                    string e10 = reader.ReadString();
                    string e11 = reader.ReadString();
                    
                    //gmail_tk
                    string[] gmail_tk = e7.Split(',');
                    byte[] datgmail_tk = new byte[gmail_tk.Length];
                    for (int l = 0; l < gmail_tk.Length; l++)
                    {
                        datgmail_tk[l] = Byte.Parse(gmail_tk[l]);
                    }
                   _tk = Encoding.UTF8.GetString(datgmail_tk);
                    //gmail_mk
                    string[] gmail_mk = e8.Split(',');
                    byte[] datgmail_mk = new byte[gmail_mk.Length];
                    for (int l = 0; l < gmail_mk.Length; l++)
                    {
                        datgmail_mk[l] = Byte.Parse(gmail_mk[l]);
                    }
                   _mk = Encoding.UTF8.GetString(datgmail_mk);
                    //gmail_tieude
                    string[] gmail_tieude = e9.Split(',');
                    byte[] datgmail_tieude = new byte[gmail_tieude.Length];
                    for (int l = 0; l < gmail_tieude.Length; l++)
                    {
                        datgmail_tieude[l] = Byte.Parse(gmail_tieude[l]);
                    }
                    _tieude = Encoding.UTF8.GetString(datgmail_tieude);
                    //gmail_noidung
                    string[] gmail_noidung = e10.Split(',');
                    byte[] dagmail_noidung = new byte[gmail_noidung.Length];
                    for (int l = 0; l < gmail_noidung.Length; l++)
                    {
                        dagmail_noidung[l] = Byte.Parse(gmail_noidung[l]);
                    }
                   _noidung = Encoding.UTF8.GetString(dagmail_noidung);
                }
               
            }
            //
            DataRow dr = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);
            string _ID_Toa = dr["ID"].ToString();
          
            _ID_NCC = dr["NCC_ID"].ToString();
            _TenFilePDF = dr["TenFilePDF"].ToString();
            string ten = dr["Tbl_NCC_Name"].ToString();
            Class_KetNoi cls = new Class_KetNoi();
            int thamso = 1;
            string[] arr_name = new string[thamso];
            object[] arr_value = new object[thamso];
            arr_name[0] = "@ID";
            arr_value[0] = _ID_NCC;
            DataTable dtThongTinNCC = cls.T_opendataset_store("sp_NhaCC_TheoID",arr_name,arr_value,thamso).Tables[0];
            if (dtThongTinNCC.Rows.Count > 0)
            {
                string _mail = dtThongTinNCC.Rows[0]["Mail"].ToString();
                string _zalo = dtThongTinNCC.Rows[0]["Zalo"].ToString();
                string[] arr_mail = _mail.Trim().Split('-');
                string[] arr_zalo = _zalo.Trim().Split('-');
                //
                #region gui Email
                if (_mail != "")
                {
                    for (int i = 0; i < arr_mail.Length; i++)
                    {
                       // GmailClient client = new GmailClient();
                       // client.send(_tk, _mk, arr_mail[i], _tieude, _noidung, _TenFilePDF == "" ? null : _TenFilePDF);
                        #region old
                        //string ThuMuc = Path.GetDirectoryName(Application.ExecutablePath) + @"\File\CauHinh.xml";
                        //XmlDocument doc = new XmlDocument();
                        //doc.Load(ThuMuc);
                        //XmlNodeList aNodes = doc.SelectNodes("/NewDataSet/Table");
                        //string tk_gmail = "";
                        //string mk_gmail = "";
                        //foreach (XmlNode node1 in aNodes)
                        //{

                        //    foreach (XmlNode node2 in node1.ChildNodes)
                        //    {

                        //        if (node2.Name == "gmail_tk")
                        //            tk_gmail = node2.InnerText;
                        //        if (node2.Name == "gmail_mk")
                        //            mk_gmail = node2.InnerText;
                        //        string subject = "Gởi toa";
                        //        string body = "VỰA CÁ 5 MỌI GỬI TOA";
                        //        if (node2.Name == "gmail_tieude")
                        //            subject = node2.InnerText;
                        //        if (node2.Name == "gmail_noidung")
                        //            body = node2.InnerText;
                        //        if (tk_gmail != "" && mk_gmail != "")
                        //            client.send(tk_gmail, mk_gmail, arr_mail[i], subject, body, _TenFilePDF == "" ? null : _TenFilePDF);
                        //    }
                        //}

                        #endregion

                    }
                    MessageBox.Show("ĐÃ GỬI TOA QUA EMAIL", "THÔNG BÁO");
                }
                #endregion
                #region gui zalo

                #endregion
                //
                CapNhatGuiFileVaoSQL(_ID_Toa);
            }
            btn_load_Click(sender, e);
        }
        private void CapNhatGuiFileVaoSQL(string ID)
        {
            Class_KetNoi cls = new Class_KetNoi();
            cls.T_exc("update TOA set DaGui=1 where ID='" + ID + "'");
        }
        private void LuuTenFileVaoSQL(string PathFile, string ID)
        {
            Class_KetNoi cls = new Class_KetNoi();
            cls.T_exc("update TOA set DaLuuFile=1,TenFilePDF=N'" + PathFile + "' where ID='" + ID + "'");
        }
        public void check_va_taothumuc(string pa)
        {
            string path = pa;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            else
            {
            }
        }
        #endregion

        private void gc_daluu_Click(object sender, EventArgs e)
        {

        }

        //------------------------------------------------------------------------------------------------
        //------------------------------------------------------------------------------------------------
        //---------------------------------------                                     ---------------------
        //---------------------------------------          IN TOA                -------------------
        //---------------------------------------                                     --------------------
        //------------------------------------------------------------------------------------------------
        //------------------------------------------------------------------------------------------------
        #region ham progess in

        public void progess_print(string ID_TOA)
        {
            #region
            DataRow dr = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);
            #region


            string ID_Toa = dr["ID"].ToString();
            string sql = "Get_data_toa '" + ID_Toa + "'";
            Toa_Class.Table_Data = db.T_opendataset(sql);
            //------------------thong tin chi tiet toa

            T_TL.KyTu_Toa = dr["KYTU"].ToString();
            T_TL.SoToa = int.Parse(dr["SOTOA"].ToString());
            T_TL.Ngay_ToaNum = int.Parse(dr["NGAYLAMTOA"].ToString());
            T_TL.NgayTuNum = int.Parse(dr["FROM_N"].ToString());
            T_TL.NgayDenNum = int.Parse(dr["TO_N"].ToString());

            T_TL.Ngay_Toa = Convert.ToDateTime(dr["NGAYLAMTOA_TEXT"].ToString()).ToShortDateString();
            T_TL.NgayTu = Convert.ToDateTime(dr["FROM_TEXT"].ToString()).ToShortDateString();
            T_TL.NgayDen = Convert.ToDateTime(dr["TO_TEXT"].ToString()).ToShortDateString();

            //  T_TL.NCC_ID = dr["NCC_ID"].ToString().ToUpper();
            T_TL.NCC_Name = dr["Tbl_NCC_Name"].ToString();
            //load chi tra
            T_TL.TKHIEN = double.Parse(dr["TKHIEN"].ToString());
            T_TL.TNUOC = double.Parse(dr["TNUOC"].ToString());
            T_TL.TUNG = double.Parse(dr["TUNG"].ToString());
            T_TL.TXE = double.Parse(dr["TXE"].ToString());
            T_TL.TKY = double.Parse(dr["TKY"].ToString());
            T_TL.T_HH = double.Parse(dr["THH"].ToString());


            T_TL.TTHEM1 = double.Parse(dr["TTHEM1"].ToString());
            T_TL.TTHEM2 = double.Parse(dr["TTHEM2"].ToString());
            T_TL.TTHEM3 = double.Parse(dr["TTHEM3"].ToString());

            T_TL.TEN_THEM1 = dr["TEN_THEM1"].ToString();
            T_TL.TEN_THEM2 = dr["TEN_THEM2"].ToString();
            T_TL.TEN_THEM3 = dr["TEN_THEM3"].ToString();

            T_TL.xe1 = dr["C1"].ToString();
            T_TL.xe2 = dr["C2"].ToString();
            T_TL.xe3 = dr["C3"].ToString();
            T_TL.TrangThai = dr["TINHTRANG"].ToString();
            T_TL.GhiChu = dr["C5"].ToString();
            //--------------------------------------------------------------
            double TongchiPhi = T_TL.TKHIEN + T_TL.TNUOC;

            double ChiPhikhac = T_TL.TUNG + T_TL.TXE + T_TL.TKY + T_TL.TTHEM1 + T_TL.TTHEM2 + T_TL.TTHEM3;
            double DS_Toa;
            object Sum = Toa_Class.Table_Data.Tables[0].Compute("Sum(ThanhTien)", "");
            try { DS_Toa = (double)Sum; }
            catch { DS_Toa = 0; }
            T_TL.TPHAITRA = DS_Toa - T_TL.T_HH - TongchiPhi - ChiPhikhac;
            //--------------------------------------------------------------

            double SL_Toa;
            object SumSL = Toa_Class.Table_Data.Tables[0].Compute("Sum(Toa_SL)", "");
            try { SL_Toa = (double)SumSL; }
            catch { SL_Toa = 0; }
            // public double SL_Goc, SL_Toa, SL_Lech;
            try { T_TL.Gia_Toa = DS_Toa / SL_Toa; }
            catch { T_TL.Gia_Toa = 0; }
            // public double DS_Goc, DS_Toa, DS_Lech;
            try { T_TL._GiaT_cophi = (DS_Toa - TongchiPhi - T_TL.T_HH) / SL_Toa; }
            catch { T_TL._GiaT_cophi = 0; }
            //get du lieu chi tiet

            //get toa
            #endregion

            #region
            DataTable dsSelectData = new DataTable();
            double pt = T_TL.TPHAITRA / 1000;
            double pt1 = System.Math.Round(pt, 0, MidpointRounding.ToEven);
            double tientra = pt1 * 1000;
            // msgbox.dialog_OK_info(tientra.ToString());
            T_TL.TPHAITRA = tientra;
            DuLieu.tien_chu = "Bằng chữ : " + _chang.ChuyenSo(tientra.ToString().Replace(",", ""));
            dsSelectData = Toa_Class.Table_Data.Tables[1].Copy();
            //dsSelectData.Tables[0].DefaultView.Sort = " criterian";
            string CA = dsSelectData.Rows[0]["Toa_NhomHang_Ten"].ToString();
            string HSL = dsSelectData.Rows[0]["MHHSL"].ToString();
            string HPC = dsSelectData.Rows[0]["MHHPC"].ToString();
            dsSelectData.Columns.Add("HH");
            for (int i = 1; i < dsSelectData.Rows.Count; i++)
            {
                if (dsSelectData.Rows[i]["Toa_NhomHang_Ten"].ToString() == CA && dsSelectData.Rows[i]["MHHSL"].ToString() == HSL && dsSelectData.Rows[i]["MHHPC"].ToString() == HPC)
                {
                    dsSelectData.Rows[i]["Toa_NhomHang_Ten"] = "";
                    dsSelectData.AcceptChanges();
                }
                else
                {
                    CA = dsSelectData.Rows[i]["Toa_NhomHang_Ten"].ToString();
                    HPC = dsSelectData.Rows[i]["MHHPC"].ToString();
                    HSL = dsSelectData.Rows[i]["MHHSL"].ToString();
                }

            }
            for (int i = 0; i < dsSelectData.Rows.Count; i++)
            {
                if (float.Parse(dsSelectData.Rows[i]["MHHSL"].ToString()) > 0)
                {
                    dsSelectData.Rows[i]["HH"] = String.Format("{0:#,#}", double.Parse(dsSelectData.Rows[i]["MHHSL"].ToString())) + " vnđ";
                }
                else
                {
                    dsSelectData.Rows[i]["HH"] = String.Format("{0:N1}", double.Parse(dsSelectData.Rows[i]["MHHPC"].ToString())) + " %";
                }
            }
            dsSelectData.AcceptChanges();
            dsSelectData.Columns.Add("ABC");
            for (int i = 0; i < dsSelectData.Rows.Count; i++)
            {
                if (dsSelectData.Rows[i]["Toa_NhomHang_Ten"].ToString() != "")
                {

                    DataView dtv = new DataView(Toa_Class.Table_Data.Tables[2]);
                    dtv.RowFilter = "Toa_NhomHang_Ten = '" + dsSelectData.Rows[i]["Toa_NhomHang_Ten"].ToString() + "' AND MHHSL = " + dsSelectData.Rows[i]["MHHSL"].ToString() + " AND MHHPC = " + dsSelectData.Rows[i]["MHHPC"].ToString() + "";
                    double sl, g;
                    try
                    {
                        sl = double.Parse(dtv[0]["Sum_SL"].ToString());
                    }
                    catch
                    {
                        sl = 0;
                    }
                    try
                    {
                        g = double.Parse(dtv[0]["Gia"].ToString());
                    }
                    catch
                    {
                        g = 0;
                    }

                    dsSelectData.Rows[i]["ABC"] = "  (" + String.Format("{0:N1}", sl) + " x " + String.Format("{0:N0}", g) + ")";
                    dsSelectData.AcceptChanges();
                }
            }


            //xoa cac dong co sl =0
            DataRow[] dtrx = dsSelectData.Select("Sum_SL=0");
            for (int i = 0; i < dtrx.Length; i++)
            {
                dtrx[i].Delete();

            }
            dsSelectData.AcceptChanges();
            //
            MessageBoxManager.Yes = "Ngắt Trang";
            MessageBoxManager.No = "Không Ngắt";
            MessageBoxManager.Cancel = "Bỏ qua";
            MessageBoxManager.Register();
            DialogResult da = MessageBox.Show("Chọn Mẫu in? ", "Phần mềm quản lý vựa", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
            if (da == DialogResult.Yes)
            {
                DuLieu.ngattrang = 1;
            }
            if (da == DialogResult.No)
            {
                DuLieu.ngattrang = 0;
            }
            MessageBoxManager.Unregister();
            //gan bien 



            T_TL rapport1 = new T_TL();
            rapport1.DataSource = dsSelectData;
            rapport1.LocationFloat = new DevExpress.Utils.PointFloat(10, 10);
            rapport1.ShowRibbonPreviewDialog();
            #endregion

            #endregion

        }
        #endregion

        private void gv_daluu_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
          
        }

        private void gv_daluu_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "DaGui" && bool.Parse(e.CellValue.ToString()) == true)
            {
                e.Appearance.BackColor = Color.Coral;
            }
            if (e.Column.FieldName == "DaLuuFile" && bool.Parse(e.CellValue.ToString()) == true)
            {
                e.Appearance.BackColor = Color.CadetBlue;
            }
            //if (e.Column.FieldName == "gop" &&e.CellValue.ToString()=="+")
            //{
            //    e.Appearance.ForeColor = Color.Red;
            //}
        }

        private void repositoryItemGuiToa_Click(object sender, EventArgs e)
        {
            DataRow dr = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);
            if (msgbox.dialog_yes_no("Bạn muốn gởi toa " + dr["TOA1"].ToString() + " ?") == DialogResult.Yes)
            {
                Class_KetNoi cls = new Class_KetNoi();
                Class_KetNoi_ToaNhan clsNhan = new Class_KetNoi_ToaNhan();

               
                int ts = 1;
                string[] name1 = new string[ts];
                object[] value1 = new object[ts];
                name1[0] = "@ID";value1[0] = dr["ID"].ToString().ToUpper();
                DataTable dt = cls.T_opendataset_store("sp_TOA_TheoID",name1,value1,ts).Tables[0];
                if(dt.Rows.Count>0)
                {
                    //update gui
                    cls.T_exc("update TOA set ThoiGianGuiToa=getdate(),GuiToa=1 where ID='" + dr["ID"].ToString().ToUpper() + "'");
                    #region luu vao Toa_Nhan
                    DataRow row = dt.Rows[0];
                    int para = 40;
                    string[] name = new string[para];
                    object[] value = new object[para];
                    name[0] = "@STT";
                    value[0] = row["STT"].ToString();
                    name[1] = "@ID";
                    value[1] = row["ID"].ToString();
                    name[2] = "@SOTOA";
                    value[2] = row["SOTOA"].ToString();
                    name[3] = "@KYTU";
                    value[3] = row["KYTU"].ToString();
                    name[4] = "@NGAYLAMTOA";
                    value[4] = row["NGAYLAMTOA"].ToString();
                    name[5] = "@FROM_N";
                    value[5] = row["FROM_N"].ToString();
                    name[6] = "@TO_N";
                    value[6] = row["TO_N"].ToString();
                    name[7] = "@TINHTRANG";
                    value[7] = row["TINHTRANG"].ToString();
                    name[8] = "@NCC_ID";
                    value[8] = row["NCC_ID"].ToString();
                    name[9] = "@TKHIEN";
                    value[9] = row["TKHIEN"].ToString();
                    name[10] = "@TIEN";
                    value[10] = row["TIEN"].ToString();
                    name[11] = "@TNUOC";
                    value[11] = row["TNUOC"].ToString();
                    name[12] = "@TUNG";
                    value[12] = row["TUNG"].ToString();
                    name[13] = "@TXE";
                    value[13] = row["TXE"].ToString();
                    name[14] = "@TKY";
                    value[14] = row["TKY"].ToString();
                    name[15] = "@TEN_THEM1";
                    value[15] = row["TEN_THEM1"].ToString();
                    name[16] = "@TEN_THEM2";
                    value[16] = row["TEN_THEM2"].ToString();
                    name[17] = "@TEN_THEM3";
                    value[17] = row["TEN_THEM3"].ToString();
                    name[18] = "@TTHEM1";
                    value[18] = row["TTHEM1"].ToString();
                    name[19] = "@TTHEM2";
                    value[19] = row["TTHEM2"].ToString();
                    name[20] = "@TTHEM3";
                    value[20] = row["TTHEM3"].ToString();
                    name[21] = "@TTHANG";
                    value[21] = row["TTHANG"].ToString();
                    name[22] = "@THH";
                    value[22] = row["THH"].ToString();
                    name[23] = "@C1";
                    value[23] = row["C1"].ToString();
                    name[24] = "@C2";
                    value[24] = row["C2"].ToString();
                    name[25] = "@C3";
                    value[25] = row["C3"].ToString();
                    name[26] = "@C4";
                    value[26] = row["C4"].ToString();
                    name[27] = "@C5";
                    value[27] = row["C5"].ToString();
                    name[28] = "@THANH_TOAN";
                    value[28] = row["THANH_TOAN"].ToString();
                    name[29] = "@NGAY_THANH_TOAN";
                    value[29] = row["NGAY_THANH_TOAN"].ToString();
                    name[30] = "@GHI_CHU";
                    value[30] = row["GHI_CHU"].ToString();
                    name[31] = "@DA_TRA_HET";
                    value[31] = row["DA_TRA_HET"].ToString();
                    name[32] = "@DaGui";
                    value[32] = row["DaGui"].ToString();
                    name[33] = "@TenFilePDF";
                    value[33] = row["TenFilePDF"].ToString();
                    name[34] = "@DaLuuFile";
                    value[34] = row["DaLuuFile"].ToString();
                    name[35] = "@khoa";
                    value[35] = row["khoa"].ToString();
                    name[36] = "@ThoiGianGuiToa";
                    value[36] = txtngayden.Value.ToString("yyyy/MM/dd");
                    name[37] = "@GuiToa";
                    value[37] = true;
                    name[38] = "@ThoiGianNhanToa";
                    value[38] = row["ThoiGianNhanToa"].ToString();
                    name[39] = "@NhanToa";
                    value[39] = row["NhanToa"].ToString();

                   value1[0] = row["ID"].ToString().ToUpper();
                    string sql1 = "select * from TOA_Nhan where ID='"+ row["ID"].ToString().Trim()+"'";
                    DataTable dt1 = cls.T_opendataset_store("sp_TOA_Nhan_TheoID",name1,value1,ts).Tables[0];
                    if (dt1.Rows.Count==0)
                    {
                        string _bien = "";
                        string _gt = "";
                        for (int i = 0; i < para; i++)
                        {
                            _bien += name[i].Replace('@',' ').Trim()+",";
                            _gt +="N'"+ value[i] + "',";
                        }
                        _bien = _bien.Substring(0, _bien.Length - 1);
                        _gt = _gt.Substring(0, _gt.Length - 1);
                        string sql2 = string.Format("insert into TOA_Nhan({0}) values({1})",_bien,_gt);
                       int kq= cls.updateTable(sql2);
                        if(kq>0)
                        {
                            MessageBox.Show("Gởi toa thành công!");
                            tailai();
                        }
                    }
                    else
                        MessageBox.Show("Toa này đã tồn tại!");
                    #endregion
                }
               
            }
        }

        private void btnLayToa_Click(object sender, EventArgs e)
        {
            Form frm = new frmLayToa();
            frm.ShowDialog();
            tailai();
        }

        private void gv_daluu_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            try
            {
                if (e.Column.FieldName == "gop")
                {
                    if (e.CellValue.ToString().Trim() == "+")
                        e.Appearance.BackColor = Color.DarkOrange;
                }
            }
            catch (Exception)
            {

            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (simpleButton1.Text.ToLower().Trim() == "mở điều kiện lọc")
            {
                panelControl1.Visible = true;
                simpleButton1.Text = "Tắt điều kiện lọc";
            }
            else
            {
                panelControl1.Visible = false;
                simpleButton1.Text = "Mở điều kiện lọc";
            }
        }

        private void linkTelegram_Click(object sender, EventArgs e)
        {
            DataRow dr = gv_daluu.GetDataRow(gv_daluu.FocusedRowHandle);
            Telegram_bot clsBot = new Telegram_bot();
            clsBot.FormGui = this.Name;
            if (!System.IO.File.Exists(dr["TenFilePDF"].ToString().Trim()))
                msgbox.dialog_OK_info("Chưa tọa file pdf!");
            else
            {

                clsBot.GoiFileQuaTelegram(dr["TenFilePDF"].ToString().Trim(), dr["Tbl_NCC_Name"].ToString().Trim());
                msgbox.dialog_OK_info("Đã gởi pdf đến Telegram 5Moi.");
                btn_load_Click(sender, e);
            }
        }


    }
}
