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 temp.Admin
{
	/// <summary>
	/// AdminPwd 的摘要说明。
	/// </summary>
	public partial class SystemUsers : System.Web.UI.Page
	{
		private static string name;
		public string username
		{
			get
			{
				return name.ToString();
			}
			set
			{
				name=value;
			}
		}
		
		
		protected void Page_Load(object sender, System.EventArgs e)
		{
			if(!Page.IsPostBack)
			{
                if(this.Session["USERNAME"]==null||this.Session["Role"]==null||this.Session["USERNAME"].ToString()==""||this.Session["Role"].ToString()=="")
                {
                    Response.Redirect("login.aspx");
                }
                else
                {
                    string [] role=this.Session["Role"].ToString().Split('#');
                    bool exists=false;
                    for(int i=0;i<role.Length;i++)
                    {
                        if (role[i].Equals("18") || role[i].Equals("0"))
                        {
                            exists=true;break;
                        }
                    }
                    if(exists)
                    {
						Bind(1);
						pageeEnable();
                    }
                    else
                    { Response.Redirect("NoAuthor.aspx"); }
                }

			}// 在此处放置用户代码以初始化页面
		}
		private void pageeEnable()
		{
			if(!(this.DataGrid1.Items.Count>0))
			{
				this.LinkButton1.Enabled=false;
				this.LinkButton2.Enabled=false;
				this.LinkButton3.Enabled=false;
				this.LinkButton4.Enabled=false;
			}
		}

		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnadduser.Click += new System.Web.UI.ImageClickEventHandler(this.btnadduser_Click);
			this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
			this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
			this.imgclose.Click += new System.Web.UI.ImageClickEventHandler(this.imgclose_Click);
            this.btnok.Click += new EventHandler(btnok_Click);
		}
		#endregion

		private void Bind(int record)
		{
			
			
			
			
			int maxrecord=20;
			int recordcount;
			int page;
			int startrecord=(record-1)*maxrecord;

		
			string connstr=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
			SqlConnection conn=new SqlConnection (connstr);
			SqlDataAdapter da=new SqlDataAdapter("select * from SystemUser",conn);
			DataSet dataset=new DataSet();
			da.Fill(dataset,startrecord,maxrecord,"websit");
			this.DataGrid1.DataSource=dataset;
			this.DataGrid1.DataBind();
			conn.Close();

			SqlCommand cmd=new SqlCommand("select count(*) from SystemUser",conn);
			conn.Open();
			recordcount=(int)cmd.ExecuteScalar();

			page=((recordcount%maxrecord)==0)?(recordcount/maxrecord):(recordcount/maxrecord+1);
			this.Label2.Text=page.ToString();
			if(this.DataGrid1.Items.Count>0)
			{
				this.Label1.Text=record.ToString();
				this.Label3.Text=recordcount.ToString();
				this.DropDownList1.Items.Clear();
				for(int i=1;i<=int.Parse(this.Label2.Text);i++)
				{
					this.DropDownList1.Items.Add(i.ToString());
				}
				this.DropDownList1.SelectedIndex=int.Parse(this.Label1.Text)-1;
				
			}
			else
			{
				this.Label1.Text="0";
				this.Label3.Text="0";
				this.DropDownList1.Items.Clear();
			}
			this.LinkButton1.Enabled=record<=1?false:true;
			this.LinkButton2.Enabled=record<=1?false:true;
			this.LinkButton3.Enabled=record<page?true:false;
			this.LinkButton4.Enabled=record<page?true:false;

					
		}

		protected void gopage(object sender, System.EventArgs e)
		{
			int prepage=Convert.ToInt32(this.Label1.Text.ToString());
		
			int nextpage=Convert.ToInt32(this.Label2.Text.ToString());
			string cmdname=((LinkButton)sender).CommandArgument.ToString();
			switch(cmdname)
			{
				case "pre":
					if(prepage>1)
						prepage--;break;
				case "next":
					if(prepage<nextpage)
						prepage++;break;
				case "frist":prepage=1;break;
				case "end":prepage=nextpage;break;
			}
			
			Bind(prepage);
		}
		
		


		private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{ 
			this.username=e.Item.Cells[0].Text.ToString();
			for(int j=0;j<this.CheckBoxList1.Items.Count;j++)
			{
				this.CheckBoxList1.Items[j].Selected=false;
			}
			if(e.CommandArgument.ToString().ToLower()=="edit")
			{  
				
				SB.ADOHelper help=new SB.ADOHelper();
				DataSet ds=help.getDataset("select Role,Appearance,Remarks from SystemUser where UserName='"+username+"'");
				string role=ds.Tables[0].Rows[0]["Role"].ToString();
				string appearance=ds.Tables[0].Rows[0]["Appearance"].ToString();
				string remark=ds.Tables[0].Rows[0]["Remarks"].ToString();
				
				
				string [] Role=role.Split('#');
			
			    int index;
				for(int i=0;i<Role.Length-1;i++)
				{index=int.Parse(Role[i]);
					switch(index)
					{   
						case 0:this.rd2.Items[0].Selected=true;for(int j=0;j<this.CheckBoxList1.Items.Count;j++)
																						{
																							this.CheckBoxList1.Items[j].Selected=true;
																							
																						}break;
						case 1:this.rd2.Items[1].Selected=true;break;
						default:this.CheckBoxList1.Items[index-2].Selected=true;break;


					}
			
				

				}
				if(appearance=="1")
				{
					this.rd.Items[0].Selected=true;
				}
				else
				{
					this.rd.Items[1].Selected=true;
				}
				this.textremark.Text=remark;
				this.lbusername.Text=username;
				this.p2.Visible=false;
				this.pl1.Visible=true;
				this.Panel2.Visible=true;
			}
			else
			{
				if(e.CommandArgument.ToString().ToLower()=="delete")
				{
					SB.ADOHelper help=new SB.ADOHelper();
					
					help.execSql("delete from SystemUser where UserName='"+username+"'");
					Bind(1);
				}
			}
		
		}
		

		private void imgclose_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			this.Panel2.Visible=false;
			this.p2.Visible=true;
			this.pl1.Visible=true;
		}

		private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
				ImageButton Imgbtn=(ImageButton)e.Item.FindControl("ImageButton2");
			if(Imgbtn!=null)
				Imgbtn.Attributes.Add("onclick","return confirm('确认要删除!?');");
		}

		protected void btnok_Click(object sender, System.EventArgs e)
		{
			SB.ADOHelper help=new SB.ADOHelper();
			string appearance=this.rd.SelectedValue.ToString();
			string role="";
			if(help.execExecuteScalar("select count(*) from SystemUser where UserName='"+username+"'")>0)
			{
				for(int j=0;j<this.rd2.Items.Count;j++)
				{
					if(this.rd2.Items[j].Selected)
						role+=this.rd2.Items[j].Value;
					
				}
				for(int i=0;i<this.CheckBoxList1.Items.Count;i++)
				{
					if(this.CheckBoxList1.Items[i].Selected)
						role+=this.CheckBoxList1.Items[i].Value;
				}
			if(help.conn.State==ConnectionState.Closed)
				{help.conn.Open();}
				SqlDataAdapter da=new SqlDataAdapter("select * from SystemUser where UserName='"+this.username+"'",help.conn);
                DataSet ds = new DataSet();
				da.Fill(ds,"tp");
				SqlCommandBuilder sb=new SqlCommandBuilder(da);
				DataRow row=ds.Tables[0].Rows[0];
				row.BeginEdit();
				row["Role"]=role;
				row["Appearance"]=appearance;
				if(this.textpwd1.Text.Trim()!="")
				{
					row["PassWord"]=SB.ADOHelper.Encrypt(this.textpwd1.Text);
				}
				else
				{
					if(row["PassWord"].ToString()=="")
					{
						row["PassWord"]=SB.ADOHelper.Encrypt("111");	
					}
				}
				row["Remarks"]=this.textremark.Text;
				row.EndEdit();
				da.Update(ds,"tp");
				Response.Write("<script>alert(\"修改完成！！\")</script>");
				this.Panel2.Visible=false;
				this.p2.Visible=true;
				this.pl1.Visible=true;
				Bind(1);
			}
			else
			{
				Response.Write("<script>alert(\"该用户不存或已被删除！！\")</script>");
			}
		}

		private void btnadduser_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			this.Panel2.Visible=false;
			this.p2.Visible=true;
			this.pl1.Visible=true;
			SB.ADOHelper help=new SB.ADOHelper();
			string name=this.textadduser.Text;
			string realname=this.Textrealname.Text;
			DateTime dt=DateTime.Now;
			string ip=Request.UserHostAddress.ToString();
			

			if((this.textadduser.Text.Trim()!="")&&(this.Textrealname.Text.Trim()!=""))
			{
				if(help.execExecuteScalar("select count(*) from SystemUser where UserName='"+SB.ADOHelper.inputText(this.textadduser.Text)+"'")>0)
				{
					Response.Write("<script>alert(\"此用户已经存在！！\")</script>");
				}
				else
				{
					DataSet ds=new DataSet();
					SqlDataAdapter da=new SqlDataAdapter("select * from SystemUser ",help.conn);
					da.Fill(ds);
					SqlCommandBuilder sb=new SqlCommandBuilder(da);
					DataTable table=ds.Tables[0];
					DataRow row=table.NewRow();
					row.BeginEdit();
					row["UserName"]=name;
                    row["PassWord"] = SB.ADOHelper.Encrypt("111");
					row["Name"]=realname;
                    row["Role"] = "1#";
					row["RegData"]=dt.ToString();
					row["RegisterIp"]=ip;
					row["Register"]=dt.ToShortDateString();
					row["Appearance"]=1;
					row.EndEdit();
					table.Rows.Add(row);
					da.Update(ds,table.TableName);
					help.conn.Close();

				}

					

			}
			else
			{
				Response.Write("<script>alert(\"请输入用户名和姓名！！\")</script>");

			}
			this.Textrealname.Text="";
			this.textadduser.Text="";
			Bind(1);
		}

		protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			Bind(int.Parse(this.DropDownList1.SelectedItem.Text));
		}

		

		private void rd2_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if(this.rd2.Items[0].Selected)
			{

				for(int i=0;i<this.CheckBoxList1.Items.Count;i++)
				{
					this.CheckBoxList1.Items[i].Selected=true;
					
				}
			}
				
			else
			{
				for(int i=0;i<this.CheckBoxList1.Items.Count;i++)
				{
					this.CheckBoxList1.Items[i].Selected=false;
					
				}
			}
		}
		

		
	}
	}
