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;

namespace ABC.BaoCao
{
    public partial class BaoCao_SoBanHang_ChiTiet_KH : DevExpress.XtraEditors.XtraUserControl
    {
        NhapSi_Class _NhapSi_Class = new NhapSi_Class();
        public BaoCao_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 ngay_chay_from;
        int ngay_chay_to;
        public void tailai()
        {
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast
            if (Look_tenkh.EditValue != "" && Look_tenkh.EditValue != null)
            {
                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 ='" + Look_tenkh.EditValue.ToString().ToUpper() + "' ";
                string filter_string_no = "";
                filter_string += " And ID_KhachHang = '" + Look_tenkh.EditValue.ToString().ToUpper() + "'";
                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;
                    ngay_chay_from=ng;
                    ngay_chay_to=ng2;
                    filter_string += "AND Date_Num_Final_UpDate >= " + ng + " AND Date_Num_Final_UpDate <= " + ng2 + "";
                    filter_tientra += "AND NgayPhatSinhNo >= " + ng + " AND NgayPhatSinhNo <= " + ng2 + "";
                    filter_string_no = "XemNo_1Ngay " + ng + ",Null,Null,'" + 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
                {
                    ngay_chay_from=Get_CauHinh.Ngay_DN;
                    ngay_chay_to=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 " + Get_CauHinh.Ngay_DN + ",Null,Null,'" + 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)) ";
                filter_string += " order by Date_Num_Final_UpDate ASC";
                DuLieu.BaoCao_ChiTiet_Theo_KH = _NhapSi_Class.get_dataset(filter_string);
                DataSet dt_tientra = _NhapSi_Class.get_dataset(filter_tientra);
                DuLieu.CongNo_1Ngay_1kh = _NhapSi_Class.get_dataset(filter_string_no);
                DuLieu.CongNo_1Ngay_1kh.Tables.Remove("Table"); 
                //set thanh toan
               

                #region tao bang mau
                DuLieu.BaoCao_ChiTiet_Theo_KH_mau = new DataTable();

                for (int i = 0; i < DuLieu.BaoCao_ChiTiet_Theo_KH.Tables[0].Columns.Count; i++)
                {
                    DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Columns.Add(DuLieu.BaoCao_ChiTiet_Theo_KH.Tables[0].Columns[i].ColumnName.ToString(),DuLieu.BaoCao_ChiTiet_Theo_KH.Tables[0].Columns[i].DataType);
                }
                 DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Columns.Add("ThanhToan",typeof(double));
                 DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Columns.Add("TienHang", typeof(double));
                 DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Columns.Add("ConLai", typeof(double));
                #endregion

                    //tinh no cu
                    #region
                    if (DuLieu.CongNo_1Ngay_1kh.Tables[0].Rows.Count > 0)
                    {
                        nocu = double.Parse(DuLieu.CongNo_1Ngay_1kh.Tables[0].Rows[0]["NoCu"].ToString());
                    }
                    else
                    {
                        nocu = 0;
                    }
                #endregion
              double _conlai;
             _conlai=nocu;
               for(int i=ngay_chay_from;i<=ngay_chay_to;i++)
               {
                    #region tim du lieu giao dich 1 ngay
                        DataRow [] dr_chitiet = DuLieu.BaoCao_ChiTiet_Theo_KH.Tables[0].Select("Date_Num_Final_UpDate = "+i+"");
                        if(dr_chitiet.Length>0)
                        {
                            for(int d=0;d<dr_chitiet.Length;d++)
                            {
                                if(d==0)
                                {
                                    #region
                                    //add dl + cong no
                                    DataRow dr_new = DuLieu.BaoCao_ChiTiet_Theo_KH_mau.NewRow();
                                    for (int ii = 0; ii < dr_chitiet[d].Table.Columns.Count; ii++)
                                    {
                                        dr_new[dr_chitiet[d].Table.Columns[ii].ColumnName.ToString()] = dr_chitiet[d][dr_chitiet[d].Table.Columns[ii].ColumnName.ToString()].ToString();
                                    }
                                    dr_new["Ngay"] = Convert.ToDateTime(dr_new["Ngay"].ToString()).ToShortDateString();
                                    //add cong no
                                    //b1 : tinh tien hang 1 ngay
                                    double _tienhang=0;
                                    for(int k=0;k<dr_chitiet.Length;k++)
                                    {
                                        _tienhang+=double.Parse(dr_chitiet[k]["ThanhTien"].ToString());
                                    }
                                    dr_new["TienHang"]=_tienhang;
                                    //b2 : tinh thanh toan
                                    double _ThanhToan=0;
                                     DataRow[] dr_thanhtoan = dt_tientra.Tables[0].Select("NgayPhatSinhNo = " + i + "");
                                    if(dr_thanhtoan.Length>0)
                                    {
                                      _ThanhToan = double.Parse(dr_thanhtoan[0]["Tien"].ToString());
                                    }
                                    dr_new["ThanhToan"]=_ThanhToan;
                                    //b3 tinh con lai
                                    _conlai = (_conlai+_tienhang)-_ThanhToan;
                                    dr_new["ConLai"]=_conlai;
                                    DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Rows.Add(dr_new);
                                    #endregion
                                }
                                else
                                {
                                     DataRow dr_new = DuLieu.BaoCao_ChiTiet_Theo_KH_mau.NewRow();
                                    for(int ii=0;ii<dr_new.Table.Columns.Count;ii++)
                                    {
                                        try
                                        {
                                            dr_new[dr_new.Table.Columns[ii].ColumnName.ToString()] = dr_chitiet[d][dr_new.Table.Columns[ii].ColumnName.ToString()].ToString();
                                        }
                                        catch
                                        {
                                        }
                                    }
                                    dr_new["Ngay"] = Convert.ToDateTime(dr_new["Ngay"].ToString()).ToShortDateString();
                                    DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Rows.Add(dr_new);


                            }
                            }
                        }
                   else
                        {
                            //tim tien tra
                            double _tienhang=0;
                            double _ThanhToan=0;

                             DataRow[] dr_thanhtoan = dt_tientra.Tables[0].Select("NgayPhatSinhNo = " + i + "");
                                    if(dr_thanhtoan.Length>0)
                                    {
                                      _ThanhToan = double.Parse(dr_thanhtoan[0]["Tien"].ToString());
                                        // add 1 dong chi  co thanh toan
                                        DataRow dr_new = DuLieu.BaoCao_ChiTiet_Theo_KH_mau.NewRow();
                                        dr_new["Ngay"] = dr_thanhtoan[0]["Ngay"].ToString();
                                        dr_new["TienHang"]=_tienhang;
                                        dr_new["ThanhToan"]=_ThanhToan;
                                        _conlai = (_conlai+_tienhang)-_ThanhToan;
                                        dr_new["ConLai"]=_conlai;
                                        dr_new["Ngay"] = Convert.ToDateTime(dr_new["Ngay"].ToString()).ToShortDateString();
                                        DuLieu.BaoCao_ChiTiet_Theo_KH_mau.Rows.Add(dr_new);
                                    }
                        }
                    #endregion
               }


             
                data();
            }
            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();
        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();
        }

        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

        #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

 



      

       



    }
}
