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;
using System.Diagnostics;
using DevExpress.XtraRichEdit.Model;

namespace ABC.BaoCao {
    public partial class frmBaoCao_SoBanHang_ChiTiet_KH: DevExpress.XtraEditors.XtraForm {
        NhapSi_Class _NhapSi_Class = new NhapSi_Class();
        public frmBaoCao_SoBanHang_ChiTiet_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];

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

        }

        public bool xemtuformcongno;
        public string hinhthucxem;
        public DateTime ngayxemcongno, ngaytrasaucung;
        public string kh_ten_congno, kh_id_congno;

        public void xem_tu_cn() {
            if(xemtuformcongno == true) {
                if(hinhthucxem == "NoMoi") {
                    txtngay.Value = ngayxemcongno;
                    txtngay2.Value = ngayxemcongno;
                    Look_tenkh.EditValue = kh_id_congno;
                    Look_tenkh.Text = kh_ten_congno;
                    check_ngay.Checked = true;
                    tailai();
                } else {//xem no cu

                    txtngay.Value = ngaytrasaucung;
                    txtngay2.Value = ngayxemcongno;
                    Look_tenkh.EditValue = kh_id_congno;
                    Look_tenkh.Text = kh_ten_congno;
                    check_ngay.Checked = true;

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

        }
    


        #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() {

        }
        int iNgayFrom;
        int iNgayTo;
        public void tailai() {
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast
            sw = Stopwatch.StartNew();
            var idKhachHang = Look_tenkh.EditValue?.ToString()?.ToUpper();
            var nguon = txtnguon.EditValue?.ToString();
            if(!string.IsNullOrEmpty(idKhachHang)) {

                string filter_string = "select * from DuLieu_SI_LE_Extend_KH where Date_Num_Final_UpDate >0 ";
                string filter_tientra = "select *,CONVERT(datetime,NgayPhatSinhNo)as Ngay from tientra1kh where ID_KhachHang ='" + idKhachHang + "' ";
                string filter_string_no = "";
                string filter_string_no1 = "";
                filter_string += " And ID_KhachHang = '" + idKhachHang + "'";
                if(check_ngay.Checked == true) {
                    int fromDate = (int)(txtngay.Value - new DateTime(1900, 1, 1)).TotalDays;
                    int toDate = (int)(txtngay2.Value - new DateTime(1900, 1, 1)).TotalDays;
                    iNgayFrom = fromDate;
                    iNgayTo = toDate;
                    filter_string += "AND Date_Num_Final_UpDate >= " + fromDate + " AND Date_Num_Final_UpDate <= " + toDate + "";
                    filter_tientra += "AND NgayPhatSinhNo >= " + fromDate + " AND NgayPhatSinhNo <= " + toDate + "";
                    filter_string_no = "XemNo_1Ngay_nvCan " + fromDate + ",Null,Null,'" + idKhachHang + "'";
                    filter_string_no1 = "XemNo_1Ngay " + fromDate + ",Null,Null,'" + idKhachHang + "'";
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast

                    if(check_nguon.Checked == true && !string.IsNullOrEmpty(nguon)) {
                        filter_string += " And NguonDL = N'" + nguon + "'";
                    }
#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast
                } else {
                    iNgayFrom = Get_CauHinh.Ngay_DN;
                    iNgayTo = Get_CauHinh.Ngay_DN;
                    filter_string += "AND Date_Num_Final_UpDate = " + Get_CauHinh.Ngay_DN + "";
                    filter_tientra += "AND NgayPhatSinhNo = " + Get_CauHinh.Ngay_DN + "";
                    filter_string_no = "XemNo_1Ngay_nvCan " + Get_CauHinh.Ngay_DN + ",Null,Null,'" + idKhachHang + "'";
                    filter_string_no1 = "XemNo_1Ngay " + Get_CauHinh.Ngay_DN + ",Null,Null,'" + idKhachHang + "'";
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast

                    if(check_nguon.Checked == true && !string.IsNullOrEmpty(nguon)) {
                        filter_string += " And NguonDL = N'" + nguon + "'";
                    }
#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast


                }
                filter_string += " order by Date_Num_Final_UpDate ASC";
                DuLieu.BaoCao_ChiTiet_Theo_KH = _NhapSi_Class.get_dataset(filter_string);
                DataSet tienTraDataSet = _NhapSi_Class.get_dataset(filter_tientra);
                DuLieu.CongNo_1Ngay_1kh = _NhapSi_Class.get_dataset(filter_string_no);
                DataSet dsCN = _NhapSi_Class.get_dataset(filter_string_no1);
                sw.Stop();
                Console.WriteLine($"get data from DB in {sw.ElapsedMilliseconds}ms");
                sw.Reset();
                sw.Start();
                if(dsCN != null)
                    dsCN.Tables.Remove("Table");
                if(DuLieu.CongNo_1Ngay_1kh != null) {
                    DuLieu.CongNo_1Ngay_1kh.Tables.Remove("Table");
                    //set thanh toan
                    Class_KetNoi db = new Class_KetNoi();
                    DataTable oldCongNo = db.T_opendataset("sp_CongNo_TheoIDKhachHang '" + idKhachHang + "'").Tables[0];
                    double _Ton = 0;
                    if(oldCongNo.Rows.Count > 0) {
                        _Ton = oldCongNo.Rows[0]["ChotTien"].TryGetDouble();
                    }
                    var table = DuLieu.CongNo_1Ngay_1kh.Tables[0];
                    if(table.Rows.Count > 0) {
                        var row = table.Rows[0];
                        row["NoCu"] = row["NoCu"].TryGetDouble() + _Ton;
                        row["TongNo"] = row["TongNo"].TryGetDouble() + _Ton;
                        row["Ton"] = row["Ton"].TryGetDouble() + _Ton;
                    } else {
                        DataRow row = table.NewRow();
                        row["NoCu"] = _Ton;
                        row["TongNo"] = _Ton;
                        row["Ton"] = _Ton;
                        table.Rows.Add(row);
                    }
                }
                Type doubleType = typeof(double);
                #region tao bang mau
                DuLieu.BaoCao_ChiTiet_Theo_KH_mau = new DataTable();
                var chiTietTheoKhachHangTable = DuLieu.BaoCao_ChiTiet_Theo_KH.Tables[0];
                for(int i = 0; i < chiTietTheoKhachHangTable.Columns.Count; i++) {
                    var column = chiTietTheoKhachHangTable.Columns[i];
                    DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Columns.Add(column.ColumnName, column.DataType);
                }
                DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Columns.Add("ThanhToan", doubleType);
                DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Columns.Add("TienHang", doubleType);
                DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Columns.Add("ConLai", doubleType);
                #endregion

                //tinh no cu
                //if (DuLieu.CongNo_1Ngay_1kh != null)
                //{
                //    #region
                //    if (DuLieu.CongNo_1Ngay_1kh.Tables[0].Rows.Count > 0)
                //    {
                //        nocu = double.Parse(DuLieu.CongNo_1Ngay_1kh.Tables[0].Rows[0]["NoCu"].ToString());
                //        if (nocu == 0)
                //            nocu = NoCuKH(Look_tenkh.EditValue.ToString().ToUpper());
                //    }
                //    else
                //    {
                //        nocu = NoCuKH(Look_tenkh.EditValue.ToString().ToUpper());
                //    }
                //}
                if(dsCN != null) {
                    #region
                    if(dsCN.Tables[0].Rows.Count > 0) {
                        nocu = dsCN.Tables[0].Rows[0]["NoCu"].TryGetDouble();
                        if(nocu == 0)
                            nocu = NoCuKH(idKhachHang);
                    } else {
                        nocu = NoCuKH(idKhachHang);
                    }
                }
                #endregion
                double _conlai;
                _conlai = nocu;
                for(int iNgay = iNgayFrom; iNgay <= iNgayTo; iNgay++) {
                    #region tim du lieu giao dich 1 ngay
                    DataRow[] filteredRows = chiTietTheoKhachHangTable.Select("Date_Num_Final_UpDate = " + iNgay + "");
                    double tienHang = 0;
                    if(filteredRows.Length > 0) {
                        foreach(var filteredRow in filteredRows) {
                            tienHang += filteredRow["ThanhTien"].TryGetDouble();
                        }
                        var columnNames = filteredRows[0].Table.Columns
                        .Cast<DataColumn>()                  // treat the collection as an IEnumerable<DataColumn>
                        .Select(col => col.ColumnName)       // pick out the ColumnName
                        .ToList();
                        for(int rowIndex = 0; rowIndex < filteredRows.Length; rowIndex++) {
                            var filteredRow = filteredRows[rowIndex];
                            if(rowIndex == 0) {
                                
                                #region
                                DataRow newRow = DuLieu.BaoCao_ChiTiet_Theo_KH_mau.NewRow();
                                foreach(var columnName in columnNames) {
                                    var value = filteredRow[columnName];
                                    newRow[columnName] = 
                                        columnName!= "Ngay"?
                                        value:
                                    value.TryGetDateTime();
                                }
                                //add cong no
                                //b1 : tinh tien hang 1 ngay
                                
                                //for(int k = 0; k < filteredRows.Length; k++) {
                                //    tienHang += double.Parse(filteredRows[k]["ThanhTien"].ToString());
                                //}
                                newRow["TienHang"] = tienHang;
                                //b2 : tinh thanh toan
                                double _ThanhToan = 0;
                                DataRow[] thanhToanRows = tienTraDataSet.Tables[0].Select("NgayPhatSinhNo = " + iNgay + "");
                                if(thanhToanRows.Length > 0) {
                                    _ThanhToan = thanhToanRows[0]["Tien"].TryGetDouble() ;
                                }
                                newRow["ThanhToan"] = _ThanhToan;
                                //b3 tinh con lai
                                _conlai = (_conlai + tienHang) - _ThanhToan;
                                newRow["ConLai"] = _conlai;
                                DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Rows.Add(newRow);
                                #endregion
                            } else {
                                DataRow newRow = DuLieu.BaoCao_ChiTiet_Theo_KH_mau.NewRow();
                                foreach(var columnName in columnNames){

                                    try {
                                        var value = filteredRow[columnName];
                                        newRow[columnName] = columnName!= "Ngay"? value:value.TryGetDateTime().ToShortDateString();
                                    } catch {
                                    }
                                }
                                DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Rows.Add(newRow);
                            }
                        }
                    } else {
                        //tim tien tra
                        double _tienhang = 0;
                        double _ThanhToan = 0;

                        DataRow[] thanhToanRows = tienTraDataSet.Tables[0].Select("NgayPhatSinhNo = " + iNgay + "");
                        if(thanhToanRows.Length > 0) {
                            var thanhToanRow= thanhToanRows[0];
                            _ThanhToan = thanhToanRow["Tien"].TryGetDouble();
                            // add 1 dong chi  co thanh toan
                            DataRow dr_new = DuLieu.BaoCao_ChiTiet_Theo_KH_mau.NewRow();
                            dr_new["Ngay"] = thanhToanRow["Ngay"].TryGetDateTime().ToShortDateString();
                            dr_new["TienHang"] = _tienhang;
                            dr_new["ThanhToan"] = _ThanhToan;
                            _conlai = (_conlai + _tienhang) - _ThanhToan;
                            dr_new["ConLai"] = _conlai;
                            DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Rows.Add(dr_new);
                        }
                    }
                    #endregion
                }
                sw.Stop();
                Console.WriteLine($"Processing data in {sw.ElapsedMilliseconds}ms");
                sw.Reset();
                sw.Start();
                data();
                sw.Stop();
                Console.WriteLine($"Binding data source in {sw.ElapsedMilliseconds}ms");
            } else {
                msgbox.dialog_OK_warning("Vui lòng chọn khách hàng");
            }
#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast
        }
        Label lbnocu = new Label();
        Label lbtienhang = new Label();
        Label lbthanhtoan = new Label();
        Label lbconlai = new Label();
        private double NoCuKH(string ID) {
            Class_KetNoi db = new Class_KetNoi();
            DataSet ds = db.T_opendataset("select top 1 Tien from Tbl_CONGNO WHERE ID_KhachHang='" + ID + "' and NguonPhatSinh='Dau'");
            if(ds.Tables[0].Rows.Count > 0)
                return double.Parse(ds.Tables[0].Rows[0][0].ToString());
            else
                return 0;
        }
        public void print() {

            if(Pow.kiemtra("BaoCao_SoBanHang_ChiTiet_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();
                //rapport.DataSource = DuLieu.BaoCao_ChiTiet_Theo_KH;
                //rapport.LocationFloat = new DevExpress.Utils.PointFloat(10, 10);
                //rapport.ShowPreview();

                Get_CauHinh.ch1kh_ngay = "Từ Ngày : " + txtngay.Value.ToShortDateString() + "  Đến Ngày : " + txtngay2.Value.ToShortDateString();
                Get_CauHinh.ch1kh_nocu = lbnocu.Text;
                // chitietreport.gc = "Từ Ngày " + dateTimePicker1.Value.ToShortDateString();
                Get_CauHinh.ch1kh_tongtienhang = lbtienhang.Text;
                Get_CauHinh.ch1kh_thanhtoan = lbthanhtoan.Text;
                Get_CauHinh.ch1kh_conlai = lbconlai.Text;
                Get_CauHinh.ch1kh_kh = Look_tenkh.Text;

                T_ct_kh rapport = new T_ct_kh();
                rapport.DataSource = DuLieu.BaoCao_ChiTiet_Theo_KH_mau;
                rapport.ShowRibbonPreview();
                #endregion
            }


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


                Get_CauHinh.ch1kh_ngay = "Từ Ngày : " + txtngay.Value.ToShortDateString() + "  Đến Ngày : " + txtngay2.Value.ToShortDateString();
                Get_CauHinh.ch1kh_nocu = lbnocu.Text;
                // chitietreport.gc = "Từ Ngày " + dateTimePicker1.Value.ToShortDateString();
                Get_CauHinh.ch1kh_tongtienhang = lbtienhang.Text;
                Get_CauHinh.ch1kh_thanhtoan = lbthanhtoan.Text;
                Get_CauHinh.ch1kh_conlai = lbconlai.Text;
                Get_CauHinh.ch1kh_kh = Look_tenkh.Text;

                T_ct_kh1 rapport = new T_ct_kh1();
                rapport.DataSource = DuLieu.BaoCao_ChiTiet_Theo_KH_mau;
                rapport.ShowRibbonPreview();
                #endregion
            }
        }
        #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) {
            print_bill();
        }
        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_ChiTiet_KH", "Inan", Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper()) == true) {
                string ten_file_pdf = "SO BAN HANG (KHACH HANG)" + "_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString();

                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();
                    rapport.DataSource = DuLieu.BaoCao_ChiTiet_Theo_KH;
                    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.");
                }
            }
        }
        void btn_sua_Click(object sender, EventArgs e) {
            print_bill();
        }



        void btn_in_Click(object sender, EventArgs e) {
            print();
        }
        Stopwatch sw;
        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();
        }

        private void gv_daluu_DoubleClick(object sender, EventArgs e) {
            try {
                int _Ngay = int.Parse(gv_daluu.GetFocusedRowCellDisplayText("Date_Num_Final_UpDate"));
                string _ID_KH = gv_daluu.GetFocusedRowCellDisplayText("ID_KhachHang");

                Form frm = new frmChiTietKH(_Ngay, _ID_KH);
                frm.ShowDialog();
            } catch(Exception) {

            }

        }

        private void frmBaoCao_SoBanHang_ChiTiet_KH_Load(object sender, EventArgs e) {

        }

        private void btn_in_Click_1(object sender, EventArgs e) {

        }




        #endregion

        #region data     
        double nocu = 0;
        public void data() {
            gc_daluu.DataSource = DuLieu.BaoCao_ChiTiet_Theo_KH_mau;
            gv_daluu.ExpandAllGroups();
            gv_daluu.ExpandAllGroups();


            double tienhang = double.Parse(clum_thanhtien.SummaryText.Replace(",", ""));
            double datra = double.Parse(clum_thanhtoan.SummaryText.Replace(",", ""));

            double conlai = nocu + tienhang - datra;
            lbnocu.Text = String.Format("{0:#,#}", nocu) + " (vnđ)";

            lbtienhang.Text = String.Format("{0:#,#}", tienhang) + " (vnđ)";
            lbthanhtoan.Text = String.Format("{0:#,#}", datra) + " (vnđ)";

            lbconlai.Text = String.Format("{0:#,#}", conlai) + " (vnđ)";



        }
        #endregion











    }
}
