using LibraryMangementSystem.Dao;
using LibraryMangementSystem.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LibraryMangementSystem.BookRental
{
    public partial class BookRegistration : Form
    {
        public BookRegistration()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
        }




        //文本框只允许输入数字 0-9数字  
        private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }

        private void button_loan_Click_1(object sender, EventArgs e)
        {
            if (textBox_bookId.Text != null && textBox_certId.Text != null)
            {
                LibraryEntities1 library = new LibraryEntities1();
                //获取可借天数
                BaseSet b = library.BaseSet.Find("1");


                byte flag = 1;//1 代表已借 0 代表未借
                Loan loan = new Loan();
                loan.BookID = textBox_bookId.Text;
                loan.Cert_id = textBox_certId.Text;
                Nullable<System.DateTime> return_date = null;
                loan.Return = return_date;
                loan.flag = flag;
                //获取当前日期（借书日期）
                DateTime Loandates = DateTime.Now;
                loan.Loandates = BookUtil.Format_date(Loandates);
                //判断此借书证是否能用
                try
                {
                    CertificateInfo certificate = library.CertificateInfo.FirstOrDefault<CertificateInfo>(L => L.Cert_id == loan.Cert_id);
                    if (certificate == null)
                    {
                        Util_UI_Alert alter1 = new Util_UI_Alert("此借书证不存在");
                        alter1.ShowDialog();
                        return;
                    }
                    if (certificate.flag == 2)
                    {
                        Util_UI_Alert alter2 = new Util_UI_Alert("此借书证已挂失");
                        alter2.ShowDialog();
                        return;

                    }

                    //判断是否有此图书
                    BookInfo bookInfo = library.BookInfo.FirstOrDefault<BookInfo>(L => L.BookID == loan.BookID);
                    if (bookInfo == null)
                    {
                        Util_UI_Alert alter3 = new Util_UI_Alert("抱歉，没有此图书");
                        alter3.ShowDialog();
                        return;
                    }
                    //减借书次数
                    /* int i = BookUtil.reduceCert(loan.Cert_id, library);
                     if (i != 1)
                     {
                         str = "你的借书次数为零，不能借书";
                         MessageBox.Show(str);
                         return;
                     }*/
                    //先减库存
                    /* result = BookUtil.reduceStock(bookInfo.BookID, library);
                     if (result != 1)
                     {

                         str = "借书失败,此书库存为0";
                         MessageBox.Show(str);
                         return;

                     }*/



                    /*判断借阅次数*/
                    int residueTime=0;
                    DaoUtil dao = new DaoUtil();
                    string sql = "select cm.ResidueTime from CertManage cm where cm.cert_id=@cert_id";
                    string cert_id = loan.Cert_id;
                    SqlParameter[] sqlParameters = new SqlParameter[] { new SqlParameter("@cert_id", SqlDbType.Char) { Value= cert_id }  };
                    SqlCommand sqlCommand = dao.Command(sql, sqlParameters);
                    /* cmd.Parameters.AddRange(sqlParameters);*/
                    var k= sqlCommand.ExecuteScalar();
                    if (k!=null) { 
                    residueTime = int .Parse(k.ToString());
                    }
                    if (residueTime <= 0) {
                        Util_UI_Alert alter3 = new Util_UI_Alert("您的借阅次数为："+residueTime+"不可借阅！");
                        alter3.ShowDialog();
                        return;
                    }
                    int result = 0;
                    String str;
                    library.Loan.Add(loan);
                    result = library.SaveChanges();
                    str = result == 1 ? "借阅成功" : "借阅失败";
                    Util_UI_Alert alter = new Util_UI_Alert(str);
                    alter.ShowDialog();
                    this.DialogResult = DialogResult.Yes;
                    dao.DaoClose();

                }
                catch (System.NullReferenceException ex)
                {
                    Util_UI_Alert alter = new Util_UI_Alert("没有此借书证，请检查借书证ID是否输入错误！" + ex.Message);
                    alter.ShowDialog();
                }
                catch (System.Data.Entity.Infrastructure.DbUpdateException ex)
                {

                    Util_UI_Alert alter = new Util_UI_Alert("您今天已经借了此书，不能重复借哦！\n" + ex.Message);
                    alter.ShowDialog();
                }

            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
