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

namespace ABC.BaoCao
{
    public partial class BaoCao_SoBanHang_KH : DevExpress.XtraEditors.XtraUserControl
    {
        NhapSi_Class _NhapSi_Class = new NhapSi_Class();
        public BaoCao_SoBanHang_KH()
        {
            InitializeComponent();            
           // data();
            event_click();
           // gv_daluu.CellValueChanged+=new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gv_daluu_CellValueChanged);

            txtngay.Text = Get_CauHinh.ngay_text;  
            Look_tenkh.Properties.DataSource = DuLieu.List_KhachHang.Tables[0];
            cboKHLoai.Properties.DataSource = DuLieu.List_KhachHang.Tables[0];

            this.Load += new EventHandler(BaoCao_SoBaoCao_Si_Le_Load);
            //khai bai report truoc
            
        }

        void BaoCao_SoBaoCao_Si_Le_Load(object sender, EventArgs e)
        {
            tailai();
            
        }

       

        #region lệnh dùng chung
        public void excel()
        {
        }
        public void xoa()
        {
            
        }
        
        public void sua()
        {
            
        }

        void _BaoCao_SoBaoCao_Si_Bien_Edit_FormClosed(object sender, FormClosedEventArgs e)
        {
            tailai();
        }
        public void chon()
        {
          
        }
        public void bochon()
        {
          
        }

        public void tailai()
        {
            string filter_string = "select * from DuLieu_SI_LE_Extend_KH where Date_Num_Final_UpDate >0 ";
            if (check_ngay.Checked == true)
            {
                int ng = (int)(Convert.ToDateTime(txtngay.Text) - new DateTime(1900, 1, 1)).TotalDays;
                int ng2 = (int)(Convert.ToDateTime(txtngay2.Text) - new DateTime(1900, 1, 1)).TotalDays;
                filter_string += "AND Date_Num_Final_UpDate >= " + ng + " AND Date_Num_Final_UpDate <= " + ng2 + "";
                if (check_ten_thuonglai.Checked == true && Look_tenkh.EditValue != null)
                {
                    filter_string += " And ID_KhachHang = '" + Look_tenkh.EditValue.ToString().ToUpper() + "'";
                }
               
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast
                if (check_nguon.Checked == true && txtnguon.EditValue != null && txtnguon.EditValue != "")
                {
                    filter_string += " And NguonDL = N'" + txtnguon.EditValue.ToString() + "'";
                }
#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast
            }
            else
            {
                filter_string += "AND Date_Num_Final_UpDate = " + Get_CauHinh.Ngay_DN + "";
                if (check_ten_thuonglai.Checked == true && Look_tenkh.EditValue != null)
                {
                    filter_string += " And ID_KhachHang = '" + Look_tenkh.EditValue.ToString().ToUpper() + "'";
                }

#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast
                if (check_nguon.Checked == true && txtnguon.EditValue != null && txtnguon.EditValue != "")
                {
                    filter_string += " And NguonDL = N'" + txtnguon.EditValue.ToString() + "'";
                }
#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast
            }
            filter_string += " and  (Date_Num_Final_UpDate in(select Date_Num_Final_UpDate from Tbl_GIAODICH where khoa is null) or ";
            filter_string += " Date_Num_Final_UpDate in(select Date_Num_Final_UpDate from Tbl_GIAODICH_LE where khoa is null)) ";
            DuLieu.BaoCao_TheoKhachHang = _NhapSi_Class.get_dataset(filter_string);
            data();
        }
        public void print()
        {
           
            if (Pow.kiemtra("BaoCao_SoBanHang_KH", "Inan", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                #region

                Get_CauHinh.T_chitietbanhang_kh = " Ngày : " + txtngay.Value.ToShortDateString();
                T_chitietbanhang_kh rapport = new T_chitietbanhang_kh();
                DataTable dt = DuLieu.BaoCao_TheoKhachHang.Tables[0];
                DataView view = dt.Copy().DefaultView;
                if (cboKHLoai.EditValue != null)
                    view.RowFilter = "ID_KhachHang<>'" + cboKHLoai.EditValue.ToString().ToUpper() + "'";
                rapport.DataSource = view.ToTable();
                rapport.LocationFloat = new DevExpress.Utils.PointFloat(10, 10);
                rapport.ShowRibbonPreview();
                #endregion
            }

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

        #region menu click
        public void event_click()
        {
           
            //btn_del.Click += new EventHandler(btn_del_Click);          
            //btn_all.Click += new EventHandler(btn_all_Click);
            //btn_none.Click += new EventHandler(btn_none_Click);
           // btn_close.Click += new EventHandler(btn_close_Click);
            btn_load.Click += new EventHandler(btn_load_Click);
            btn_in.Click += new EventHandler(btn_in_Click);
            btn_pdf.Click += new EventHandler(btn_pdf_Click);
           // btn_sua.Click += new EventHandler(btn_sua_Click);
        }

        void btn_pdf_Click(object sender, EventArgs e)
        {
            pdf();
        }
        public void check_va_taothumuc(string pa)
        {
            string path = pa;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);

            }
            else
            {

            }
        }
        public void pdf()
        {
            if (Pow.kiemtra("BaoCao_SoBanHang_KH", "Inan", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true)
            {
                string ten_file_pdf = "SỔ CHI TIẾT ( KHÁCH HÀNG )" ;
                #region cau hinh file
                Class_KetNoi db = 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] = Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper();
                DataTable dtx = db.T_opendataset_store("sp_CauHinh_TheoID", arr_name, arr_value, thamso).Tables[0];
                if (dtx.Rows.Count > 0)
                {
                    DataRow row = dtx.Rows[0];
                    Get_CauHinh.Dt_DAT.Rows[0]["Fordel_pdf1"] = row["ThuMucPDF1"].ToString();
                    Get_CauHinh.Dt_DAT.Rows[0]["Fordel_pdf2"] = row["ThuMucPDF2"].ToString();
                }
                #endregion
                string thumuc = Get_CauHinh.Dt_DAT.Rows[0]["Fordel_pdf2"].ToString();
                if (!Directory.Exists(thumuc))
                {
                    msgbox.dialog_OK_warning("Không tìm thấy thư mục " + thumuc + " \n Vui lòng kiểm tra lại");

                }
                else
                {
                    Get_CauHinh.T_chitietbanhang_kh = " Ngày : " + txtngay.Value.ToShortDateString();
                    T_chitietbanhang_kh rapport = new T_chitietbanhang_kh();
                    DataTable dt = DuLieu.BaoCao_TheoKhachHang.Tables[0];
                    DataView view = dt.Copy().DefaultView;
                    if (cboKHLoai.EditValue != null)
                        view.RowFilter = "ID_KhachHang<>'" + cboKHLoai.EditValue.ToString().ToUpper() + "'";
                    rapport.DataSource = view.ToTable();
                    rapport.LocationFloat = new DevExpress.Utils.PointFloat(10, 10);

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

                    //var stream = new MemoryStream();
                    //rapport.ExportToPdf(stream);

                    //using (var fs = System.IO.File.Create(reportPath))
                    //{
                    //    stream.WriteTo(fs);
                    //}

                    //var reportStream = System.IO.File.OpenRead(reportPath);
                    //msgbox.dialog_OK_info("Đã xuất pdf.");
                    var cultureInfo = new System.Globalization.CultureInfo("vi-VN");

                    // Lấy tháng và năm hiện tại với định dạng tên tháng và năm
                    string thangNamHienTai = DateTime.Now.ToString("'tháng' M 'năm' yyyy", cultureInfo);
                    // Tạo đường dẫn cho thư mục cha
                    string thuMucCha = Path.Combine(thumuc, thangNamHienTai);

                    // Kiểm tra và tạo thư mục cha nếu chưa tồn tại
                    if (!Directory.Exists(thuMucCha))
                    {
                        Directory.CreateDirectory(thuMucCha);
                    }

                    // Tạo đường dẫn cho thư mục mới
                    string thumucmoi = Path.Combine(thuMucCha, Get_CauHinh.ngay_text.Replace(@"\", "_").Replace("-", "_").Replace("/", "_"));

                    // Kiểm tra và tạo thư mục mới
                    check_va_taothumuc(thumucmoi);

                    // Tạo đường dẫn cho file PDF
                    var reportPath = Path.Combine(thumucmoi, ten_file_pdf + ".pdf");

                    // Xuất báo cáo ra file PDF
                    var stream = new MemoryStream();
                    rapport.ExportToPdf(stream);

                    using (var fs = System.IO.File.Create(reportPath))
                    {
                        stream.WriteTo(fs);
                    }
                    var reportStream = System.IO.File.OpenRead(reportPath);
                    msgbox.dialog_OK_info("Đã xuất PDF.");
                }
            }
        }
        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();
        } 

        void btn_del_Click(object sender, EventArgs e)
        {
            xoa();
        }




        #endregion
        Label Thongkesoluong = new Label();
        Label thongketien = new Label();
        Label ThongkeGiaBQ = new Label();
        #region data       
        public void data()
        {
            DataTable dt= DuLieu.BaoCao_TheoKhachHang.Tables[0];
            DataView view = dt.Copy().DefaultView;
            if (cboKHLoai.EditValue != null)
                view.RowFilter = "ID_KhachHang<>'"+cboKHLoai.EditValue.ToString().ToUpper()+"'";
            gc_daluu.DataSource = view.ToTable();
            gv_daluu.ExpandAllGroups();
            gv_daluu.ExpandAllGroups();
   
            Thongkesoluong.Text = clum_sl.SummaryText;
            thongketien.Text = clum_thanhtien.SummaryText;
            ThongkeGiaBQ.Text = clum_Gia.SummaryText;
            
            
        }
        #endregion

      

       



    }
}
