using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

using DevExpress.XtraReports.UI;
using ABC.KetNoi;
using DevExpress.XtraSplashScreen;
using ABC.File;

namespace ABC.CongNo
{
    public partial class TienTra : DevExpress.XtraEditors.XtraForm
    {
        Class_KetNoi db = new Class_KetNoi();
        public int ngay_tinh;
        public string select_khachhang_name;
        public TienTra()
        {
            
            InitializeComponent();
            look_khachhang.Focus();
            this.Load += new EventHandler(TienTra_Load);
            simpleButton1.Click += new EventHandler(simpleButton1_Click);
            simpleButton2.Click += new EventHandler(simpleButton2_Click);
            simpleButton3.Click += new EventHandler(simpleButton3_Click);
            gv.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gv_CellValueChanged);
            Link_xoa_chitiet.Click += new EventHandler(Link_xoa_chitiet_Click);
            danhmuc();
            
            look_khachhang.SelectAll();
            look_khachhang.Select();
            look_khachhang.Text = "";
            look_khachhang.EditValue = null;
            look_khachhang.ClosePopup();
            look_khachhang.Focus();
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast
            if (look_khachhang.EditValue != null && look_khachhang.EditValue != "")
            {
                select_khachhang_name = look_khachhang.Text;
                if (this.Text.ToString().Substring(0, 1) == "+")
                {
                    this.Text = "-" + "Cập nhật tiền trả ngày "+Get_CauHinh.NgayTinhNo_text+"";
                }
                else
                {
                    this.Text = "+" + "Cập nhật tiền trả ngày " + Get_CauHinh.NgayTinhNo_text + "";
                }
            }
#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast

        }

        void Link_xoa_chitiet_Click(object sender, EventArgs e)
        {
            #region
            DataRow dr = gv.GetDataRow(gv.FocusedRowHandle);
            if (dr["SuDung"].ToString() == "1")
            {
                if (msgbox.dialog_yes_no("Xóa chi tiết này?") == DialogResult.Yes)
                {
                    //
                    string ndCu = "";
                    DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "ID=" + dr["ID_KhachHang"].ToString().ToUpper(), "", "Xoá");
                    string sql = "Tbl_ChiTietTraNo_XoaChiTiet ";
                    //create PROCEDURE Tbl_ChiTietTraNo_XoaChiTiet
                    //@ID_KhachHang uniqueidentifier,
                    sql += "N'" + dr["ID_KhachHang"].ToString().ToUpper() + "',";
                    //@Luc nvarchar(200),
                    sql += "N'" + dr["Luc"].ToString() + "',";
                    //@NgayPhatSinhNo int
                    sql += "N'" + Get_CauHinh.NgayTinhNo + "'";
                    db.T_exc(sql);
                    tailai();
                    //laod lai
                    DataView dtv = new DataView(DuLieu.ChiTiet_TraNo.Tables[0]);
                    dtv.RowFilter = "ID_KhachHang = '" + look_khachhang.EditValue.ToString().ToUpper() + "' and SuDung = 1 and NgayPhatSinhNo = " + Get_CauHinh.NgayTinhNo + "";                    
                    gc.DataSource = dtv;
                    thongkenodau.Text = clum_tienno.SummaryText;

                }
            }
            else
            {
                msgbox.dialog_OK_info("Dòng này đã bị xóa");
            }
            #endregion

        }
        public void load_all()
        {
            #region
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast
            if (look_khachhang.EditValue != "" && look_khachhang.EditValue != null)
            {
                string sql = "sp_TienTraTruoc '" + look_khachhang.EditValue.ToString().ToUpper() + "'";
                DataSet dts = db.T_opendataset(sql);
                gc.DataSource = dts.Tables[0];
                thongkenodau.Text = clum_tienno.SummaryText;
            }
#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast
            #endregion

        }
        void simpleButton3_Click(object sender, EventArgs e)
        {
            load_all();
        }

        void TienTra_Load(object sender, EventArgs e)
        {
            #region
            txttien.Text = "";
                       
            gc.DataSource = null;
            
            
            #endregion
            //laod danh sach chi tiet cua 1 kh trong ngay
        }

        #region danhmuc
        public void danhmuc()
        {
            look_khachhang.Properties.DataSource = DuLieu.List_KhachHang.Tables[0];            
            look_khachhang.Enter += new EventHandler(look_khachhang_Enter);
            look_khachhang.Leave += new EventHandler(look_khachhang_Leave);
            look_khachhang.KeyPress += new KeyPressEventHandler(look_khachhang_KeyPress);
            txttien.KeyPress += new KeyPressEventHandler(txttien_KeyPress);
            txttien.Enter += new EventHandler(txttien_Enter);
            txttien.Leave += new EventHandler(txttien_Leave);
        }
        string ID_KH;
        string Ten_KH;
#pragma warning disable CS0169 // The field 'TienTra.TongNo' is never used
        decimal TienMat,TongNo;
#pragma warning restore CS0169 // The field 'TienTra.TongNo' is never used
        public bool kientra_tongtra_va_tongno(decimal _tongtra,decimal _Tongno)
        {
            #region
            //if (_tongtra > _Tongno)
            //{
            //    msgbox.dialog_OK_error("Tiền trả vược mức tiền nợ .");
            //    return false;
            //}
            //else
            //{
            //    return true;
            //}
            return true;
            #endregion
        }
        public decimal check_tienmat()
        {
            #region
            if (txttien.Text == "")
            {
                return -2;
            }
            else
            {
                try
                {
                    decimal tm = decimal.Parse(txttien.Text);
                    return tm;
                }
                catch
                {

                    return -1;
                }
            }
            #endregion
        }
        void txttien_KeyPress(object sender, KeyPressEventArgs e)
        {
            #region
            if (e.KeyChar == 13)
            {
                save();
         
            }
            else
            {
                if (e.KeyChar == 27)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
            }
            #endregion

        }

        #region lever
        void txttien_Leave(object sender, EventArgs e)
        {
            txttien.BackColor = Color.White;
        }

        void txttien_Enter(object sender, EventArgs e)
        {
            txttien.BackColor = Color.NavajoWhite;

        }
        #endregion

        public void load_chitiet(string id_kh)
        {
            #region
            DataView dtv = new DataView(DuLieu.ChiTiet_TraNo.Tables[0]);
            dtv.RowFilter = "ID_KhachHang = '"+id_kh.ToUpper()+"' and SuDung = 1";
            gc.DataSource = dtv;
            thongkenodau.Text = clum_tienno.SummaryText;
            #endregion

        }
        void look_khachhang_KeyPress(object sender, KeyPressEventArgs e)
        {
            #region
            if (e.KeyChar == 13)
            {
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast
                if (look_khachhang.EditValue != null && look_khachhang.EditValue != "")
                {
                    load_chitiet(look_khachhang.EditValue.ToString());
                    txttien.Focus();
                    select_khachhang_name = look_khachhang.Text;
                    if (this.Text.ToString().Substring(0, 1) == "+")
                    {
                        this.Text = "-" + "Cập nhật tiền trả ngày " + Get_CauHinh.NgayTinhNo_text + "";
                    }
                    else
                    {
                        this.Text = "+" + "Cập nhật tiền trả ngày " + Get_CauHinh.NgayTinhNo_text + "";
                    }
                }
                else
                {
                    msgbox.dialog_OK_warning("Vui lòng chọn khách hàng");
                }
#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast
            }
            else
            {
                if (e.KeyChar == 27)
                {
                    txttien.Focus();
                    look_khachhang.EditValue = null;
                    look_khachhang.Text = "";
                    look_khachhang.ClosePopup();
                }
            }
            #endregion

        }

        #region
        void look_khachhang_Leave(object sender, EventArgs e)
        {
            look_khachhang.BackColor = Color.White;
        }

        void look_khachhang_Enter(object sender, EventArgs e)
        {
            look_khachhang.BackColor = Color.NavajoWhite;
        }
        #endregion

        #endregion

        public void save()
        {
            #region
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast
            if (look_khachhang.EditValue != null&&look_khachhang.EditValue != "")
            {
                ID_KH = look_khachhang.EditValue.ToString().ToUpper();
                Ten_KH = look_khachhang.Text;
                TienMat = check_tienmat();
               
                    if (TienMat == -1)
                    {
                        msgbox.dialog_OK_error("Nhập sai định dạng số");
                        txttien.SelectAll();
                        txttien.Focus();
                    }
                    else
                    {
                        if (TienMat == -2)
                        {
                            msgbox.dialog_OK_error("vui lòng nhập số tiền.");
                            txttien.SelectAll();
                            txttien.Focus();
                        }
                        else
                        {
                            TienMat = TienMat * 1000;
                            decimal Tramoi = 0;
                            decimal TongNo_chuatinhtramoi = 0;
                            DataRow[] dtr = DuLieu.CongNo_1Ngay.Tables[0].Select("ID_KhachHang = '" + look_khachhang.EditValue.ToString().ToUpper() + "'");
                            if (dtr.Length == 0)
                            {
                                TongNo_chuatinhtramoi = 0; Tramoi = 0;
                            }
                            else
                            {
                                Tramoi = decimal.Parse(dtr[0]["MoiTra"].ToString());
                                TongNo_chuatinhtramoi = decimal.Parse(dtr[0]["TongNo"].ToString());

                            }
                            decimal _TongTra = Tramoi + TienMat;
                            if (_TongTra <= TongNo_chuatinhtramoi)
                            {
                                //create PROCEDURE Tbl_ChiTietTraNo_insert
                                string sql = "Tbl_ChiTietTraNo_insert ";
                                //@ID_KhachHang uniqueidentifier,
                                sql += "N'" + look_khachhang.EditValue.ToString().ToUpper() + "',";
                                //@Luc nvarchar(200),
                                sql += "N'" + DateTime.Now.Hour.ToString() + " giờ " + DateTime.Now.Minute.ToString() + " phút " + DateTime.Now.Second.ToString() + " giây " + DateTime.Now.Date.ToShortDateString() + "',";
                                //@NgayPhatSinhNo int,
                                sql += "N'" + Get_CauHinh.NgayTinhNo + "',";
                                //@Tien decimal
                                sql += "N'" + TienMat + "'";
                                db.T_exc(sql);
                            DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "", sql, "Thêm");
                            //tinh lai tong tra thay vi load form
                            string sql_tinhlai = "sp_ChiTietTraNo_TrongNgay " + Get_CauHinh.NgayTinhNo + ",'" + look_khachhang.EditValue.ToString().ToUpper() + "'";
                                DataSet dts = db.T_opendataset(sql_tinhlai);
                                if (dts.Tables[0].Rows.Count > 0)
                                {
                                    double tongtra_laytu_sql;
                                    try
                                    {
                                        tongtra_laytu_sql = double.Parse(dts.Tables[0].Rows[0]["tongtra"].ToString());
                                    }
                                    catch
                                    {
                                        tongtra_laytu_sql = 0;
                                    }

                                    if (tongtra_laytu_sql != 0)
                                    {
                                       // DataRow[] dr = DuLieu.CongNo_1Ngay.Tables[0].Select();
                                        DataRow[] dt_r = DuLieu.CongNo_1Ngay.Tables[0].Select("ID_KhachHang = '" + look_khachhang.EditValue.ToString().ToUpper()+"'");
                                        double nommoi = double.Parse(dt_r[0]["NoMoi"].ToString());
                                        double nocu = double.Parse(dt_r[0]["NoCu"].ToString());

                                        double ton = (nommoi + nocu) - tongtra_laytu_sql;
                                        dt_r[0]["Ton"] = ton;
                                        dt_r[0]["MoiTra"] = tongtra_laytu_sql;
                                        dt_r[0]["GhiChu"] = "";
                                        DuLieu.CongNo_1Ngay.Tables[0].AcceptChanges();

                                    }
                                }


                                this.DialogResult = DialogResult.OK;
                                this.Close();
                            }
                            else
                            {
                                msgbox.dialog_OK_warning("Tiền trả vược mức tiền nợ.");
                                txttien.Focus();
                            }
                        }
                    }
            }
            else
            {
                msgbox.dialog_OK_warning("Vui lòng chọn khách hàng");
            }
#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast
            #endregion
        }

        void gv_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            #region
            
            DataRow dr = gv.GetDataRow(gv.FocusedRowHandle);
            if (dr["SuDung"].ToString() == "1")
            {
                decimal TienTruoc_Update = decimal.Parse(dr["TienTruoc_Update"].ToString());
                decimal _Tienchinhsua = decimal.Parse(e.Value.ToString());
                decimal chenhlech = _Tienchinhsua - TienTruoc_Update;

                decimal Tramoi = 0;
                decimal TongNo_chuatinhtramoi=0;
                DataRow[] dtr = DuLieu.CongNo_1Ngay.Tables[0].Select("ID_KhachHang = '" + look_khachhang.EditValue.ToString().ToUpper() + "'");
                if (dtr.Length == 0)
                {
                    TongNo_chuatinhtramoi = 0; Tramoi = 0;
                }
                else
                {
                    Tramoi = decimal.Parse(dtr[0]["MoiTra"].ToString());
                    TongNo_chuatinhtramoi = decimal.Parse(dtr[0]["TongNo"].ToString());

                }
                if ((Tramoi+chenhlech) <= TongNo_chuatinhtramoi)
                {
                    DuLieu.ChiTiet_TraNo.Tables[0].AcceptChanges();
                    //create PROCEDURE Tbl_ChiTietTraNo_insert
                    string sql = "Tbl_ChiTietTraNo_insert ";
                    //@ID_KhachHang uniqueidentifier,
                    sql += "N'" + dr["ID_KhachHang"].ToString().ToUpper() + "',";
                    //@Luc nvarchar(200),
                    sql += "N'" + dr["Luc"].ToString() + "',";
                    //@NgayPhatSinhNo int,
                    sql += "N'" + Get_CauHinh.NgayTinhNo + "',";
                    //@Tien decimal
                    sql += "N'" + dr["Tien"].ToString() + "'";
                    db.T_exc(sql);

                    DuLieu.LuuLuocSu(Main_Form._tk, this.Name, "", sql, "Thêm");
                    gv.RefreshData();
                    thongkenodau.Text = clum_tienno.SummaryText;
                }
                else
                {
                    msgbox.dialog_OK_warning("Tiền trả vược mức tiền nợ.");
                    gv.CancelUpdateCurrentRow();
                    gv.RefreshData();
                }
            }
            else
            {
                msgbox.dialog_OK_warning("Chi Tiêt đã xóa không cập nhật!");
                gv.CancelUpdateCurrentRow();
            }
            #endregion


        }

        #region button
        void simpleButton2_Click(object sender, EventArgs e)
        {
          
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        void simpleButton1_Click(object sender, EventArgs e)
        {
            if (txttien.Text != "")
            {
                save();
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
       
        }
#endregion

        public DataSet dt_main;    
        #region load_bandau

        public DataTable dt_kh;
        public void tailai()
        {
            string sql = "sp_ChiTietTraNo_TheoNgay " + Get_CauHinh.NgayTinhNo + "";
            DuLieu.ChiTiet_TraNo = db.T_opendataset(sql);
        }
        public void data()
        {
            gc.DataSource = dt_main.Tables[0];
            thongkenodau.Text = clum_tienno.SummaryText;
        }
      
        #endregion

        #region register event
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            
            if (keyData == (Keys.Control | Keys.A))
            {
                load_all();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }


        #endregion
      
    }
}