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 WebApplication2
{
	/// <summary>
	/// AdvDetailList 的摘要说明。
	/// </summary>
	public partial class AdvDetailList : System.Web.UI.Page
	{
	
		
		private static string cmdstr;
	
		public string cmd_str
		{
			get
			{
				return cmdstr.ToString();
			}
			set
			{
				cmdstr=value;
			}
		}
		private static string id;
		public static string getid
		{
			get
			{
				return id.ToString();
			}
			set
			{
				id=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("10") || role[i].Equals("0"))
						{
							exists=true;break;
						}
					}
					if(exists)
					{
					
						if(Request.Params["advid"]==null||Request.Params["advid"].ToString()=="")
						{
							cmd_str=" where IsTemp='1'";
							Bind(1);
							pageeEnable();
					
							this.Label3.Visible=false;
						}
						else
						{
							cmd_str=" where AdvListId='"+Request.Params["advid"].ToString()+"'";
							this.Label3.Visible=false;
							Bind(1);
					
						}
				 
					}
					else
					{Response.Redirect("NoAuthor.aspx");}
				}
			}// 在此处放置用户代码以初始化页面
		}

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

		}
		#endregion

	
		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;
			}
		}
		private bool isnumber(string str)
		{
				int leng=str.Length;
			for(int i=0;i<leng;i++)
			{
				if(!char.IsNumber(str[i]))
				{
					return false;
				}
			}
			return true;

		}
		public string GetTitle(string id,string table,string title)
		{
			string titles="无";
			SB.ADOHelper help=new SB.ADOHelper();
			if(help.conn.State==ConnectionState.Closed)
			{
				help.conn.Open();
			}
			SqlCommand cmd=new SqlCommand("select "+title+" from "+table+" where id='"+id+"'",help.conn);
			SqlDataReader rd=cmd.ExecuteReader();
			if(rd.Read())
			{
				title=rd[title].ToString();
			}
			rd.Close();
			help.conn.Close();
			return titles;
		}
		protected void Button1_Click(object sender, System.EventArgs e)
		{
			
			string AdvId=this.TextBox1.Text;	
			string useraccount=SB.ADOHelper.inputText(this.TextBox2.Text);
			string advappearance=this.DropDownList1.SelectedValue.ToString();
			string advtitle=SB.ADOHelper.inputText(this.TextBox3.Text.Trim());
			if(isnumber(AdvId))
			{
				if(AdvId==null||AdvId=="")
				{
					cmd_str=" where IsTemp='1' and AdvTitle like '%"+advtitle+"%' and AcceptAppearance "+advappearance+" and AdvUserName like '%"+useraccount+"%'";
					Bind(1);
					if(this.DataGrid1.Items.Count>0)
					{
						this.Label3.Visible=false;
					}
					else
					{
						this.Label3.Visible=true;
					}
			
					
				}
				else
				{
					cmd_str=" where IsTemp='1' and AcceptAppearance "+advappearance+" and  AdvListId='"+AdvId+"' and  AdvUserName like '%"+useraccount+"%' and AdvTitle like '%"+advtitle+"%'";
					Bind(1);
					if(this.DataGrid1.Items.Count>0)
					{
						this.Label3.Visible=false;
					}
					else
					{
						this.Label3.Visible=true;
					}

				}
			}
			else
			{
				Response.Write("<script>alert(\"ID应为数字！！\")</script>");
			}
			
		}
		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 AdvDetailed"+cmd_str+" order by id desc",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 AdvDetailed"+cmd_str,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.Label4.Text=recordcount.ToString();
				this.DropDownList2.Items.Clear();
				for(int i=1;i<=int.Parse(this.Label2.Text);i++)
				{
					this.DropDownList2.Items.Add(i.ToString());
				}
				this.DropDownList2.SelectedIndex=int.Parse(this.Label1.Text)-1;
				
			}
			else
			{
				this.Label1.Text="0";
				this.Label4.Text="0";
				this.DropDownList2.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)
		{

			SB.ADOHelper help=new SB.ADOHelper();
		getid=(this.DataGrid1.DataKeys[e.Item.ItemIndex]).ToString();
			if(e.CommandName.ToLower().Trim()=="delete")
			{
				
				try
				{
					help.execSql("delete from AdvDetailed where id='"+getid+"'");
				}
				catch
				{
					Response.Write("<script>alert(\"删除出错！可能存在数据关联！\")</script>");
				}
				finally
				{
					Bind(1);
				}
				

			}
			
				if(e.CommandName.ToLower().Trim()=="edit")
				{
					Response.Redirect("ModifAdvDetailList.aspx?getid="+getid);

				}
		if(e.CommandName.ToLower().Trim()=="makefile")
		{

            string advid = Convert.ToString(this.DataGrid1.DataKeys[e.Item.ItemIndex]);

            SqlDataReader rd = help.getReader("select width,height,ImgAddress,url,Format,AdvListId,TemplateBH,AdvList.CountClass as CountClass,AdvList.AdvType as AdvType from AdvDetailed,AdvList where AdvDetailed.AdvListId=AdvList.id and AdvDetailed.id='" + advid + "'");
            if (rd.Read())
            {
                //string id = rd["id"].ToString();
                int width = Convert.ToInt32(rd["width"].ToString());
                int height = Convert.ToInt32(rd["height"].ToString());
                string imgadd = rd["ImgAddress"].ToString();
                string url = rd["url"].ToString();
                int format = Convert.ToInt32(rd["Format"].ToString());
                string advlistid = rd["AdvListId"].ToString();
                int templatebh = Convert.ToInt32(rd["TemplateBH"].ToString());
                string CountClass = "0";
                if (rd["CountClass"] != null)
                 {
                  CountClass = rd["CountClass"].ToString();
                 }

                 int AdvType = Convert.ToInt32(rd["AdvType"].ToString());
                 rd.Close();

                 string CountPV = "0";
                 rd = help.getReader("select WebsiteId from ApplicationAdv where AdvListId='" + advlistid + "' and CountPV=1");
                 while (rd.Read())
                 {
                     CountPV += "," + rd["WebsiteId"];
                 }
                 rd.Close();

                 SB.ADOHelper.JsFile(width, height, imgadd, url, format, templatebh, getid, CountClass, CountPV);
                Response.Write("<script>alert(\"生成文件完成！\")</script>");

            }
			
		}
			
		
		}
		
		
		
		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 DropDownList2_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			Bind(int.Parse(this.DropDownList2.SelectedItem.Text));
		}

		
	}
}
