using LibraryMangementSystem.BookManage;
using LibraryMangementSystem.BookRental;
using LibraryMangementSystem.Dao;
using LibraryMangementSystem.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows.Forms;

namespace LibraryMangementSystem.UI.LoanManage
{
    public partial class LoanManages : UserControl
    {
        public LoanManages()
        {
            InitializeComponent();
        }
        public LoanManages(object sender, EventArgs e)
        {
            InitializeComponent();
            StandLibWin_Load(sender, e);
            /*dataViewByLoad(sender, e);*/
            buttonQueryByClass_Click(sender, e);
        }
        ArrayList arr = new ArrayList();
        public string checkboxName = "选择";
        LibraryEntities1 dbContext = new LibraryEntities1();
        private void StandLibWin_Load(object sender, EventArgs e)
        {
            DataGridViewCheckBoxColumn CheckColunms = new DataGridViewCheckBoxColumn();
            CheckColunms.Name = checkboxName;
            CheckColunms.HeaderText = checkboxName;
            CheckColunms.Width = 60;
            CheckColunms.TrueValue = "1";
            CheckColunms.FalseValue = "0";
            dataGridViewLoan.AutoGenerateColumns = false;
            dataGridViewLoan.Columns.Insert(0, CheckColunms);
            dataGridViewLoan.CellContentClick += dataGridView1_CellContentClick;

        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1)
                {
                    if (dataGridViewLoan.Columns[e.ColumnIndex].Name == checkboxName)
                    {
                        arr.Clear();
                        for (int i = 0; i < this.dataGridViewLoan.Rows.Count; i++)
                        {
                            if ((bool)dataGridViewLoan.Rows[i].Cells[checkboxName].EditedFormattedValue == true)
                            {
                                if (dataGridViewLoan.Rows[i].Cells[1].Value != null)
                                {
                                    string vClickGridId = dataGridViewLoan.Rows[i].Cells[1].Value.ToString();
                                    arr.Add(vClickGridId);
                                }
                            }
                        }

                    }
                }
                dataGridViewLoan.AllowUserToAddRows = false;
            }
            catch (System.ArgumentException ex)
            {
                Util_UI_Alert alert = new Util_UI_Alert("无有效数据" + ex.Message);
                alert.ShowDialog();
                dataGridViewLoan.Rows.Clear();
            }
        }



        private void buttonQueryByClass_Click(object sender, EventArgs e)
        {
            string ByBookeId = textBoxQueryByBookId.Text;
            string ByCertId = textBoxQueryByCertId.Text;

            string ByIsReturn = comboBoxQueryByIsReturn.Text;
            string ByIsOverDate = comboBoxQueryByIsOverDate.Text;
            string ByName = textBoxQueryByName.Text;
            string ByBookName = textBoxQueryByBookName.Text;
            String sql;
            IDataReader result;
            DaoUtil dao = new DaoUtil();
            if (ByBookeId != "")
            {
                sql = "select * from LoanManage2  WHERE BookID=@byBookId";
                SqlParameter[] sqlParameters = new SqlParameter[] { new SqlParameter("@byBookId", SqlDbType.NChar) { Value = ByBookeId }

            };
                result = dao.Reader(sql, sqlParameters);
            }
            else if (ByCertId != "")
            {
                sql = "select * from LoanManage2  WHERE Cert_id=@ByCertId";
                SqlParameter[] sqlParameters = new SqlParameter[] { new SqlParameter("@ByCertId", SqlDbType.NChar) { Value = ByCertId }
            };
                result = dao.Reader(sql, sqlParameters);
            }
            else if (ByIsReturn != "" || ByIsOverDate != "" || ByName != "" || ByBookName != "")
            {
                sql = "select * from LoanManage2  WHERE  ";
                List<SqlParameter> list = new List<SqlParameter>();
                /*SqlParameter[] sqlParameters = new SqlParameter[4];*/
                if (ByIsReturn != "")
                {


                    int flag = 0;
                    if (ByIsReturn == "未归还")
                    {
                        flag = 1;
                    }
                    sql += " flag=@flag and ";
                    list.Add(new SqlParameter("@flag", SqlDbType.Int) { Value = flag });

                }
                if (ByIsOverDate != "")
                {

                    if (ByIsOverDate == "已逾期")
                    {
                        sql += " IsOverDate<0 and ";
                    }
                    else
                    {
                        sql += " IsOverDate>0 and ";
                    }

                    /*sqlParameters.Append(new SqlParameter("@num", SqlDbType.Int) { Value = 0 });*/

                }
                if (ByName != "")
                {
                    sql += " Name=@Name and";
                    list.Add(new SqlParameter("@Name", SqlDbType.NChar) { Value = ByName });

                }
                if (ByBookName != "")
                {
                    sql += " bookName=@ByBookName and";
                    list.Add(new SqlParameter("@ByBookName", SqlDbType.NChar) { Value = ByBookName });

                }
                sql += " 1=1";
                SqlParameter[] sqlParameters = list.ToArray();
                result = dao.Reader(sql, sqlParameters);


            }
            else
            {
                sql = "select * from LoanManage2";
                result = dao.Reader(sql);
            }








            dataGridViewLoan.Rows.Clear();
            while (result.Read())
            {
                string IsOverDate = result["IsOverDate"].ToString();
                if (IsOverDate == "")
                {
                    IsOverDate = "0";
                }

                string msg;
                string flag = result["flag"].ToString();
                if (int.Parse(flag) == 1)
                {
                    //未还
                    msg = int.Parse(IsOverDate) >= 0 ? "没有逾期,剩余归还天数：" + IsOverDate : "逾期啦,逾期" + (int.Parse(IsOverDate) * (-1)).ToString() + "天";
                }
                else
                {
                    msg = int.Parse(IsOverDate) >= 0 ? "没有逾期" : "逾期啦,逾期" + (int.Parse(IsOverDate) * (-1)).ToString() + "天";
                }
                dataGridViewLoan.Rows.Add("0", BookUtil.trim(result["BookID"].ToString()), BookUtil.trim(result["bookName"].ToString()), BookUtil.trim(result["Cert_id"].ToString()), BookUtil.trim(result["Name"].ToString()), BookUtil.trim(result["Depart"].ToString()), BookUtil.trim(result["cert_type"].ToString()) == "0" ? "学生" : "老师", BookUtil.Format_date(result["Loandates"].ToString()), BookUtil.Format_date(result["ShouldReturnDate"].ToString()), BookUtil.Format_date(result["ReturnDate"].ToString()), BookUtil.trim(result["flag"].ToString()) == "0" ? "已还" : "未还", msg);

            }
            //取消dataGridView取消最后一行空白行
            dataGridViewLoan.AllowUserToAddRows = false;
        }
        private void setByBookIdNull(object sender, EventArgs e)
        {

            textBoxQueryByBookId.Text = "";

        }
        private void setByCertIdNull(object sender, EventArgs e)
        {
            textBoxQueryByCertId.Text = "";

        }
        private void setAllNull(object sender, EventArgs e)
        {
            textBoxQueryByCertId.Text = "";
            textBoxQueryByBookId.Text = "";

        }

        /*private void dataViewByLoad(object sender, EventArgs e)
        {
            foreach (var item in dbContext.BookClass)
            {
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Text = item.Classname.Trim();
                cbi.Value = item.ClassID;
                comboBoxQueryByClass.Items.Add(cbi);
            }
            comboBoxQueryByClass.SelectedIndex = 0;
        }*/

        //删除按钮
        private void button2_Click(object sender, EventArgs e)
        {
            if (arr.Count == 0)
            {
                Util_UI_Alert alert = new Util_UI_Alert("您未勾选数据！");
                alert.ShowDialog();
                return;
            }


            try
            {
                for (int i = 0; i < arr.Count; i++)
                {
                    string item = arr[i].ToString();
                    Loan loan = dbContext.Loan.FirstOrDefault<Loan>(L => L.BookID == item && L.Return == null);

                    loan.Return = BookUtil.Format_date(DateTime.Now);
                    loan.flag = 0;


                }
            }
            catch (System.NullReferenceException ex)
            {
                Util_UI_Alert alert5 = new Util_UI_Alert("您已还过此书，无需再还。");
                alert5.ShowDialog();
                return;
            }

            Util_UI_Alert alert4 = new Util_UI_Alert("还书成功");
            alert4.ShowDialog();
            dbContext.SaveChanges();

            buttonQueryByClass_Click(sender, e);


        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (BookRegistration b = new BookRegistration())
            {
                b.ShowDialog();
                if (b.DialogResult == DialogResult.Yes)
                {
                    buttonQueryByClass_Click(sender, e);


                }

            }
            /*MessageBox.Show(this.dataGridViewBook.Rows.Count.ToString());*/
            /*MessageBox.Show(arr.Count.ToString());*/
        }

        private void button3_Click(object sender, EventArgs e)
        {
            using (ReturnBook returnBook = new ReturnBook())
            {
                returnBook.ShowDialog();
                if (returnBook.DialogResult == DialogResult.OK)
                {
                    buttonQueryByClass_Click(sender, e);
                }
            }
        }


    }
}
