using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

namespace norke.admin
{
	/// <summary>
	/// productData 的摘要说明。
	/// </summary>
	public partial class productData : System.Web.UI.Page
	{
        protected System.Web.UI.WebControls.Button btnBack;
    
		protected void Page_Load(object sender, System.EventArgs e)
		{
            //权限检查
            if( Session["adminName"]==null || Session["adminName"].ToString() == String.Empty )
            {
                Response.Write("<font color=#ff0000 style='FONT-SIZE: 12px'>对不起,您没足够权限访问此页!!</font><br>");
                Response.Write("<a href=Default.aspx target=_top style='FONT-SIZE: 12px'>重新登陆</a><br>");
                Response.End();
                return;
            }

            if( !IsPostBack )
            {
                if( Request.QueryString["id"] == null)
                {
                    Response.Write("没有这个产品");
                    Response.End();
                }
                string strID = Request.QueryString["id"].ToString().Trim();
                if( strID == String.Empty )
                {
                    strID = "-1";
                }

                
                ViewState["PID"] = strID;

                getPData();
                getData();
                getNowSellNum();//获取 当前售出数量
            }
		}

        private void getNowSellNum()//获取 当前售出数量
        {
            string strID = ViewState["PID"].ToString();
            
            DBConn myDB1 = new DBConn();
            string sqlP="select count(*) as [NowSellNum] from PList where CardState=1 and PID=" + strID;
            SqlDataReader dr  = myDB1.getDataReader(sqlP);
            
            if( dr.Read() )
            {
                lblNowSellNum.Text = dr["NowSellNum"].ToString();
            }

            dr.Close();
            myDB1.Close();
        }

        private void getPData()//获取ID对应的产品信息
        {
            if( ViewState["PID"] == null )
            {
                Response.Write("<script>");
                Response.Write("alert('没有记录!!!');");
                Response.Write("</script>");
                return;
            }
            string strID = ViewState["PID"].ToString();
            
            DBConn myDB1 = new DBConn();
            string sqlP="select PName,PStock,PSellNum from Products where PID=" + strID;
            SqlDataReader dr  = myDB1.getDataReader(sqlP);
            
            if( dr.Read() )
            {
                lblPName.Text = dr["PName"].ToString();
                lblPStock.Text = dr["PStock"].ToString();
                lblPSellNum.Text = dr["PSellNum"].ToString();
            }
            else
            {
                Response.Write("没有这个产品");
                dr.Close();
                myDB1.Close();
                Response.End();
            }
            dr.Close();
            myDB1.Close();
        }

        private void getData()//绑定数据
        {
            if( ViewState["PID"] == null )
            {
                Response.Write("<script>");
                Response.Write("alert('没有记录!!!');");
                Response.Write("</script>");
                return;
            }
            string strID = ViewState["PID"].ToString();

            string sql="select * from PList Left Outer join Products on PList.PID = Products.PID where PList.PID=" + strID + " order by PLID desc";
            /*
            DBConn myDB = new DBConn();
            DataGrid1.DataSource  = myDB.getDataReader(sql);
            DataGrid1.DataBind();
            myDB.Close();
            */

            if( ViewState["CurrentPageIndex"] == null )//添加 ViewState["CurrentPageIndex"]对象 为了解决编辑时的分页问题
            {
                //分页
                mySqlPager.setAttribute( SqlPager1, "DataGrid1", sql, "10000000000-PLID", 20);
            }
            else
            {
                mySqlPager.setAttribute( SqlPager1, "DataGrid1", sql, "10000000000-PLID", 20, (int)ViewState["CurrentPageIndex"]);
            }
        }

		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{    
            this.DataGrid1.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_CancelCommand);
            this.DataGrid1.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_EditCommand);
            this.DataGrid1.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand);
            this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_DeleteCommand);
            this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);

        }
		#endregion


        private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            //  确保处理的是数据行，而不是Header或者Footer
            if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
            { 
                /*
                string strCardState = ( (EmptyControlCollection)e.Item.Controls[3].Controls[0].Controls ).ToString(); 
                //string strCardState = e.Item.Cells[3].Text;	

                switch( strCardState )
                {
                    case "0":
                        strCardState = "出售中";
                        break;
                    case "1":
                        strCardState = "已售出";
                        break;
                    case "2":
                        strCardState = "停止出售";
                        break;
                    default:
                        strCardState = "其他";
                        break;
                }                                   
                e.Item.Cells[3].Text = strCardState; */

                //加密对象
                DCard.Encode myEncode = new DCard.Encode();
                try
                {
                    e.Item.Cells[2].Text = myEncode.DecryptString( e.Item.Cells[2].Text );
                }
                catch
                {
                    //如果不是已加密字符串 就会出错
                }
                //删除确认            
                LinkButton delBttn = (LinkButton) e.Item.Cells[5].Controls[0]; 
                delBttn.Attributes.Add("onclick","javascript:return confirm('确定删除[ " + CleanString.htmlOutputText(e.Item.Cells[1].Text) + " ]?');"); 
            }
            //编辑状态下
            if( e.Item.ItemType == ListItemType.EditItem  )
            {
                //加密对象
                DCard.Encode myEncode = new DCard.Encode();
                try
                {
                    TextBox myText = (TextBox)e.Item.Cells[2].Controls[0]; 
                    myText.Text = myEncode.DecryptString( myText.Text );
                }
                catch
                {
                    //如果不是已加密字符串 就会出错
                }
            }
        }

        private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
            { 
                string strID = e.Item.Cells[0].Text;

                //查询当前状态
                DBConn myDB = new DBConn();
                string sql = "select CardState from PList where PLID=" + strID;
                SqlDataReader dr = myDB.getDataReader ( sql );
                string strState = "-1";
                if( dr.Read() )
                {
                    strState = dr["CardState"].ToString();
                }
                else
                {
                    Response.Write("<script>");
                    Response.Write("alert('没有这条记录!!!');");
                    Response.Write("</script>");
                    dr.Close();
                    myDB.Close();
                    return;
                }
                dr.Close();
                myDB.Close();

                //删除
                DBConn myDB1 = new DBConn();
                string sql1 = "Delete from PList where PLID=" + strID;
                myDB1.Delete( sql1 );
                myDB1.Close();

                if( strState.Equals("0") )//是否出售中
                {
                    //库存减一
                    DBConn myDB2 = new DBConn();
                    string sql2 = "update Products set PStock=PStock-1 where PID=" + ViewState["PID"].ToString();
                    myDB2.Update( sql2 );
                    myDB2.Close();
                }

                getPData();
                getData();
            }
        }

        protected void btnCheck_Click(object sender, System.EventArgs e)
        {
            string strPID = ViewState["PID"].ToString();
            //同步当前产品的库存
            DBConn myDB = new DBConn();
            string sql = "update Products set PStock=(select count(*) from PList where CardState=0 and PID=" + strPID + ") where PID=" + strPID;
            myDB.Update( sql );
            myDB.Close();

            getPData();
            getData();
            getNowSellNum();//获取 当前售出数量

            Response.Write("<script>");
            Response.Write("alert('同步完成!!!');");
            Response.Write("</script>");
        }

        private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            ViewState["CurrentPageIndex"] = SqlPager1.CurrentPageIndex;//获取当前页数
            
            DataGrid1.EditItemIndex = e.Item.ItemIndex;
            getData();
        }

        private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            ViewState["CurrentPageIndex"] = SqlPager1.CurrentPageIndex;//获取当前页数

            DataGrid1.EditItemIndex  = -1;
            getData();
        }

        private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            string strID = e.Item.Cells[0].Text;

            TextBox tb1 = (TextBox)(e.Item.Cells[1].Controls[0]);
            TextBox tb2 = (TextBox)(e.Item.Cells[2].Controls[0]);
            DropDownList ddl1 = (DropDownList)e.Item.FindControl("ddlCardState");

            string strNum = tb1.Text.Trim();
            string strPassword = tb2.Text.Trim();
            string strState = ddl1.SelectedValue;

            if( strNum == String.Empty || strPassword == String.Empty )
            {
                Response.Write("<script>");
                Response.Write("alert('请输入卡号/密码!!!');");
                Response.Write("</script>");
                return;
            }
			
            strNum = CleanString.htmlInputText( strNum );
            strPassword = CleanString.htmlInputText( strPassword );

            //加密对象
            DCard.Encode myEncode = new DCard.Encode();
            strPassword = myEncode.EncryptString( strPassword );

            //查询当前状态
            DBConn myDB = new DBConn();
            string sql = "select CardState from PList where PLID=" + strID;
            SqlDataReader dr = myDB.getDataReader ( sql );
            string strOState = "-1";
            if( dr.Read() )
            {
                strOState = dr["CardState"].ToString();
            }
            else
            {
                Response.Write("<script>");
                Response.Write("alert('没有这条记录!!!');");
                Response.Write("</script>");
                dr.Close();
                myDB.Close();
                return;
            }
            dr.Close();
            myDB.Close();

            //更新修改后的数据
            DBConn myDB1 = new DBConn();
            string sql1="update PList set CardNum='" + strNum + "',CardPassword='" + strPassword + 
                        "',CardState=" + strState + " where PLID=" + strID;
            myDB1.Update( sql1 );
            myDB1.Close();

            if( strOState.Equals("0") && !strState.Equals("0") )//减少库存
            {
                //库存减一
                DBConn myDB2 = new DBConn();
                string sql2 = "update Products set PStock=PStock-1 where PID=" + ViewState["PID"].ToString();
                myDB2.Update( sql2 );
                myDB2.Close();
            }
            else if( !strOState.Equals("0") && strState.Equals("0") )//增加库存
            {
                //库存加一
                DBConn myDB2 = new DBConn();
                string sql2 = "update Products set PStock=PStock+1 where PID=" + ViewState["PID"].ToString();
                myDB2.Update( sql2 );
                myDB2.Close();
            }

            Response.Write("<script>");
            Response.Write("alert('更新成功!!!');");
            Response.Write("</script>");

            DataGrid1.EditItemIndex  = -1;

            ViewState["CurrentPageIndex"] = SqlPager1.CurrentPageIndex;//获取当前页数

            getPData();
            getData();
        }

        protected void btnSelect_Click(object sender, System.EventArgs e)
        {
            string strSelect = CleanString.htmlInputText( txtSelect.Text );
            string mySql="select * from [PList] PID=" + ViewState["PID"].ToString() + " order by PLID desc";

            switch( ddlSelect.SelectedValue )
            {
                case "0":
                    mySql="select * from [PList] where PID=" + ViewState["PID"].ToString() + " and PLID like '%" + strSelect + "%' order by PLID desc";
                    break;
                case "1":
                    mySql="select * from [PList] where PID=" + ViewState["PID"].ToString() + " and CardNum like '%" + strSelect + "%' order by PLID desc";
                    break;
            }
            /*
            DBConn myDB = new DBConn();  
            DataGrid1.DataSource  = myDB.getDataReader( mySql );
            DataGrid1.DataBind();
            myDB.Close();
            */

            //分页
            mySqlPager.setAttribute( SqlPager1, "DataGrid1", mySql, "10000000000-PLID", 20);
        }

        protected void btnFiltrate_Click(object sender, System.EventArgs e)
        {
            string mySql="select * from [PList] PID=" + ViewState["PID"].ToString() + " order by PLID desc";

            switch( ddlFiltrate.SelectedValue )
            {
                case "0":
                    mySql="select * from [PList] where PID=" + ViewState["PID"].ToString() + " and CardState=0 order by PLID desc";
                    break;
                case "1":
                    mySql="select * from [PList] where PID=" + ViewState["PID"].ToString() + " and CardState=1 order by PLID desc";
                    break;
                case "2":
                    mySql="select * from [PList] where PID=" + ViewState["PID"].ToString() + " and CardState=2 order by PLID desc";
                    break;
            }
            /*
            DBConn myDB = new DBConn();  
            DataGrid1.DataSource  = myDB.getDataReader( mySql );
            DataGrid1.DataBind();
            myDB.Close();
            */

            //分页
            mySqlPager.setAttribute( SqlPager1, "DataGrid1", mySql, "10000000000-PLID", 20);
        }

        protected void btnResetPSellNum_Click(object sender, System.EventArgs e)
        {
            string strID = ViewState["PID"].ToString();
            
            DBConn myDB1 = new DBConn();
            string sqlP="update Products set PSellNum=(select count(*) from PList where CardState=1 and PID=" + strID +") where PID=" + strID;
            myDB1.getDataReader(sqlP);
            myDB1.Close();

            getPData();
            getData();
            getNowSellNum();//获取 当前售出数量

            Response.Write("<script>");
            Response.Write("alert('重新累积 完成!!!');");
            Response.Write("</script>");
        }

       
	}
}
