using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
public partial class ordercar : System.Web.UI.Page
{
    protected Hashtable ht = new Hashtable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["id"] != null)
            {
                this.bookcar();
                this.showcar();
            }
            else
            {
                this.showcar();
            }
        }
    }

 
    protected void showcar()
    {
        if (Session["car"] != null)
        {
            ht = (Hashtable)Session["car"];
            if (ht.Count > 0)
            {
                OleDbConnection conn = DB.connstr();
                DataSet ds = new DataSet();           
                foreach (DictionaryEntry i in ht)
                {
                    int sid = Convert.ToInt32(i.Key);
                    string OleDb = "select book_ID,book_name,nowprice from book_info where book_ID=" + sid;
                    OleDbDataAdapter sda = new OleDbDataAdapter(OleDb, conn);
                    if (sda != null)
                    {
                        sda.Fill(ds);
                    }
                }
                conn.Open();
                this.dlCar.DataSource = ds;
                this.dlCar.DataKeyNames = new string[] { "book_ID" };
                this.dlCar.DataBind();
                conn.Close();
            }
            else
            {
                this.dlCar.DataSource = null;
                this.dlCar.DataBind();
            }
        }
        else
        {
            this.dlCar.DataSource = null;
            this.dlCar.DataBind();
        }
    }


    protected void bookcar()
    {
        string id = Request.QueryString["id"];
        if (Session["car"] == null)
        {
            ht.Add(id, 1);
            Session["car"] = ht;
        }
        else
        {
            ht = (Hashtable)Session["car"];
            if (ht.ContainsKey(id)==true)
            {
                Response.Write("<script language=javascript>alert('此书已经在购物车中！');location='javascript:history.go(-1)' </script>");
            }
            else
            {
                ht.Add(id, ht.Count + 1);
                Session["car"] = ht;
            }
        }
    }

    protected void dlCar_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string id = Convert.ToString(this.dlCar.DataKeys[e.RowIndex].Value);
        ht = (Hashtable)Session["car"];
        if (ht.ContainsKey(id) == true)
        {
            ht.Remove(id);
            Session["car"] = ht;
        }
        this.showcar();
    }

    
    protected void ct_TextChanged(object sender, EventArgs e)
    {
        this.sum();
    }
    protected void deleteBtn_Click(object sender, ImageClickEventArgs e)
    {
        Session["car"] = null;
        showcar();
    }
    protected void dlCar_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((TextBox)(e.Row.Cells[2].FindControl("ct"))).Text = "1";
            float price = (float)Convert.ToDouble(((Label)(e.Row.Cells[1].FindControl("ol"))).Text);
            int num = Convert.ToInt32(((TextBox)(e.Row.Cells[2].FindControl("ct"))).Text);
            ((Label)(e.Row.Cells[1].FindControl("lball"))).Text = "￥" + Convert.ToString(price * num);
        }
        this.sum();
    }
    protected void sum()
    {
        float carprice = 0;
        int carnum = 0;
        int allnum = 0;
        for (int i = 0; i < this.dlCar.Rows.Count; i++)
        {
            float price = (float)Convert.ToDouble(((Label)(this.dlCar.Rows[i].Cells[1].FindControl("ol"))).Text);
            int num = Convert.ToInt32(((TextBox)(this.dlCar.Rows[i].Cells[2].FindControl("ct"))).Text);
            ((Label)(this.dlCar.Rows[i].Cells[3].FindControl("lball"))).Text = Convert.ToString(price * num);
            float lbprice = (float)Convert.ToDouble(price * num);
            carprice = carprice + lbprice;
            carnum = i + 1;
            allnum = allnum + num;
        }
        this.numTxt.Text = Convert.ToString(carnum);
        this.allNumTxt.Text = Convert.ToString(allnum);
        this.CartPriceTxt.Text = Convert.ToString(carprice);
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        if (Session["user"] != null)
        {
            OleDbConnection conn = DB.connstr();
            try
            {
                ht = (Hashtable)Session["car"];
                if (ht.Count > 0)
                {
                    //*********查看用户是否有能力购买*************
                    string OleDbM = "select xingMoney from user_info where userName='" + Session["user"].ToString() + "'";
                    OleDbCommand cmdM = new OleDbCommand(OleDbM, conn);
                    conn.Open();
                    int allMoney = Convert.ToInt32(cmdM.ExecuteScalar());
                    conn.Close();
                    if (allMoney < Convert.ToInt32(this.CartPriceTxt.Text))
                    {
                        this.msg.Text = "对不起，你的欣币不够，请到个人呢中心充值！";
                        this.showcar();
                    }
                    else
                    {
                        //*********插入订单主表信息************* 
                        int uID;    //会员ID
                        int ordID;    //订单编号（ID）
                        conn.Open();
                        string OleDbs = "select userID from user_info where userName='" + Session["user"].ToString() + "'";
                        string OleDbs2 = "select count(*) from order_info";
                        OleDbCommand stcmd = new OleDbCommand(OleDbs, conn);          //会员ID
                        OleDbCommand ordcmd = new OleDbCommand(OleDbs2, conn);          //订单编号（ID）
                        uID = Convert.ToInt32(stcmd.ExecuteScalar());
                        ordID = Convert.ToInt32(ordcmd.ExecuteScalar()) + 1;
                       string OleDbi = "insert into order_info(orderID,userID,orderTime) values('" + Convert.ToString(ordID) + "'," + uID + ",'" + DateTime.Now.ToString() + "')";

                        OleDbCommand ins = new OleDbCommand(OleDbi, conn);
                        ins.ExecuteNonQuery();
                        //*********插入订单附表表信息*************

                        int n = 0;
                        foreach (DictionaryEntry i in ht)
                        {
                            int bid = Convert.ToInt32(i.Key);
                            int num = Convert.ToInt32(((TextBox)(this.dlCar.Rows[n].Cells[2].FindControl("ct"))).Text);
                            float price = (float)Convert.ToDouble(((Label)(this.dlCar.Rows[n].Cells[3].FindControl("lball"))).Text);
                            n++;
                            string OleDbins = "insert into order_book(orderID,book_ID,num,price) values('" + Convert.ToString(ordID) + "'," + bid + "," + num + "," + price + ")";
                            OleDbCommand inscmd = new OleDbCommand(OleDbins, conn);
                            inscmd.ExecuteNonQuery();
                        }

                        this.updateMoney(conn);
                        conn.Close();
                        this.msg.Text = "订单成功，你可以在个人中心里查看你的订单！";

                    }
                }
                else
                {
                        this.msg.Text = "你没有选择要买的图书!";
                   
                }
            }
            catch(Exception ex)
            {
                this.msg.Text = "对不起没有你所要买的图书!";
            }
            finally
            {
                Session["car"] = null;
                this.showcar();
            }
        }
        else
        {
            Response.Redirect("login.aspx");
        }

    }
    protected void updateMoney(OleDbConnection OleDbcon)
    {
        OleDbConnection conn = DB.connstr();
        conn.Open();
        string updateM = "select xingMoney from user_info where userName='" + Session["user"].ToString() + "'";
        OleDbCommand updcmd = new OleDbCommand(updateM, OleDbcon);
        double allM = Convert.ToDouble(updcmd.ExecuteScalar());
        double newM = allM - Convert.ToDouble(this.CartPriceTxt.Text);
        string uped = "update user_info set xingMoney=" + newM + " where userName='" + Session["user"].ToString()+"'";
        OleDbCommand upcmd = new OleDbCommand(uped,OleDbcon);
        upcmd.ExecuteNonQuery();
        conn.Close();
    }
}
