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;
using System.Text;

namespace WebApplication2.Admin
{
	/// <summary>
	/// AdvCount 的摘要说明。
	/// </summary>
	public partial class AdvDayDetail : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.TextBox Textbox2;
		private static string cmdstr;
		
        public string cmd_str
		{
			get
			{
				return cmdstr.ToString();
			}
			set
			{
				cmdstr=value;
			}
		}
	 private static  string db;
		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("14") || role[i].Equals("0"))
					 {
						 exists=true;break;
					 }
				 }
				 if(exists)
				 {
                     begdate.Value = DateTime.Now.ToShortDateString();
                     enddate.Value = DateTime.Now.ToShortDateString();
                     Text1.Value = DateTime.Now.ToShortDateString();
					 if(Request.Params["bool"]!=null)
					 {
						 cmd_str="";
						 if(Request.Params["bool"].ToString().Trim()=="true")
						 {
							 this.pl1.Visible=false;
							db=" HistoryDetail";

						 }
					 }
					 else
					 {
						 db="ToDayDetail";
						 cmd_str = "";
						 //  Response.Write("<script>alert('" + Request.QueryString["name"].ToString() + "')</script>");
						 if (Request.Params["name"] != null)
						 {
							 cmd_str = " where WebUserName='" + Request.Params["name"].ToString() + "'";
							 this.TextBox1.Text = Request.Params["name"].ToString();
                       
						 }
						 if (Request.Params["websetid"] != null)
						 {
					  cmd_str += " and Websiteid='" + Request.Params["websetid"].ToString() + "'";
							
						 }
						 if(Request.Params["websetname"]!=null)
						 {
							 this.TextBox2.Text= Request.Params["websetname"].ToString();
						 }
						 if (Request.Params["advlistid"] != null)
						 {
							 cmd_str += " and AdvListId='" + Request.Params["advlistid"].ToString() + "'";
							 this.ddladvlistid.SelectedValue=Request.Params["advlistid"].ToString();
						 }
						 if (Request.Params["advdetailid"] != null)
						 {
							 cmd_str += " and AdvDetailedId='" + Request.Params["advdetailid"].ToString() + "'";
							 this.ddladvdetailid.SelectedValue = Request.Params["advdetailid"].ToString();
						 }
						 if (Request.Params["hitdate"] != null)
						 {
                       
							 this.begdate.Value =Convert.ToDateTime(Request.Params["hitdate"].ToString()).ToShortDateString();
							 this.enddate.Value =Convert.ToDateTime(Request.Params["hitdate"].ToString()).ToShortDateString();
                             cmd_str += " and convert(smalldatetime,convert(varchar(10),HitData))>='" +begdate.Value+ "' and convert(smalldatetime,convert(varchar(10),HitData))<='" +enddate.Value+ "'";
						 }
					 }
					 this.Label3.Visible=false;
					 ddlbind();
					 Bind(1);		
				 }
				 else
				 {Response.Redirect("NoAuthor.aspx");}
			 }
		 }// 在此处放置用户代码以初始化页面
		}
		private void ddlbind()
		{  ArrayList sb;
			SB.ADOHelper help=new SB.ADOHelper();
			sb=help.AdvListID();
			this.ddladvlistid.Items.Add("全部");
			this.ddladvlistid.Items[0].Value="0";
			for(int i=1;i<sb.Count+1;i++)
			{
				this.ddladvlistid.Items.Add(sb[i-1].ToString().Split('&')[1].ToString());
			
			}
			for(int j=1;j<sb.Count+1;j++)
			{
				this.ddladvlistid.Items[j].Value=sb[j-1].ToString().Split('&')[0].ToString();
			}
			sb=help.GetAdvDetailID(this.ddladvlistid.SelectedItem.Value);
			this.ddladvdetailid.Items.Add("全部");
			this.ddladvlistid.Items[0].Value="0";
			for(int i=1;i<sb.Count+1;i++)
			{
				this.ddladvdetailid.Items.Add(sb[i-1].ToString().Split('&')[1].ToString());
			
			}
			for(int j=1;j<sb.Count+1;j++)
			{
				this.ddladvdetailid.Items[j].Value=sb[j-1].ToString().Split('&')[0].ToString();
			}
            if (help.conn.State == ConnectionState.Open)
            {
                help.conn.Close();
            }
	     
		}
		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);
            conn.Open();
			SqlDataAdapter da=new SqlDataAdapter("select * from "+db+" "+cmd_str+" order by id desc",conn);
			DataSet dataset=new DataSet();
			da.Fill(dataset,startrecord,maxrecord,"websit");
			this.DataGrid1.DataSource=dataset;
			this.DataGrid1.DataBind();
			SqlCommand cmd=new SqlCommand("select count(*) from "+db+" "+cmd_str,conn);
			recordcount=(int)cmd.ExecuteScalar();
            conn.Close();
			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.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.Label4.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);
		}

		#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

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

        protected void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
            if (e.CommandName == "delete")
			{
				string id=Convert.ToString(this.DataGrid1.DataKeys[e.Item.ItemIndex]);
				SB.ADOHelper help=new SB.ADOHelper();
				help.execSql("delete from "+db+" where id='"+id+"'");
                if (help.conn.State == ConnectionState.Open)
                { help.conn.Close(); }	
                Bind(1);
			}
		}
		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;

		}

		protected void Button1_Click(object sender, System.EventArgs e)
		{	SB.ADOHelper help=new SB.ADOHelper();
			string username=SB.ADOHelper.inputText(this.TextBox1.Text.Trim());
			string website=SB.ADOHelper.inputText(this.TextBox2.Text);
			SqlCommand cmd=new SqlCommand("select top 1 id from Website where WebsiteName='"+website+"'",help.conn);
			if(help.conn.State==ConnectionState.Closed)
			{
				help.conn.Open();
			}
			SqlDataReader rd=cmd.ExecuteReader();
			if(rd.Read())
			{
				website=rd["id"].ToString();
			}
			else
			{
				website="";
			}
            rd.Close();
			help.conn.Close();
			string webid=website==""? "is not null":"='"+website+"'";
			string advlistid=this.ddladvlistid.SelectedIndex<1? "is not null":"='"+this.ddladvlistid.SelectedValue.Trim()+"'";
			string advid=this.ddladvdetailid.SelectedIndex<1? "is not null":"='"+this.ddladvdetailid.SelectedValue.Trim()+"'";
			string hour1=this.TextBox5.Text.Trim()==""? "is not null":">='"+this.TextBox5.Text.Trim()+"'";
			string hour2=this.TextBox6.Text.Trim()==""? "is not null":"<='"+this.TextBox6.Text.Trim()+"'";
				string data1,data2;
			try
			{
				data1=this.begdate.Value.Trim()==""? "is not null":">='"+Convert.ToDateTime(this.begdate.Value.Trim()).ToString()+"'";
				data2=this.enddate.Value.Trim()==""? "is not null":"<='"+Convert.ToDateTime(this.enddate.Value.Trim()).ToString()+"'";
			}
			
			catch
			{ Response.Write("<script>alert('输入的日期格式不正确!')</script>");return;}
		
		   	cmd_str=" where WebUserName like '%"+username+"%' and WebsiteId "+webid+" and AdvListId "+advlistid+" and AdvDetailedId "+advid+" and HitHour "+hour1+" and HitHour "+hour2+" and HitData "+data1+" and HitData "+data2;  
             Bind(1);
			
		}

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

		protected void ddlwebsiteid_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			ArrayList sb;
			SB.ADOHelper help=new SB.ADOHelper();
			sb=help.GetAdvDetailID(this.ddladvlistid.SelectedItem.Value);
			this.ddladvdetailid.Items.Clear();
			this.ddladvdetailid.Items.Add("全部");
			for(int i=1;i<sb.Count+1;i++)
			{
				this.ddladvdetailid.Items.Add(sb[i-1].ToString().Split('&')[1].ToString());
			
			}
			for(int j=1;j<sb.Count+1;j++)
			{
				this.ddladvdetailid.Items[j].Value=sb[j-1].ToString().Split('&')[0].ToString();
			}
            if (help.conn.State == ConnectionState.Open)
            {
                help.conn.Close();
            }
			
		}
	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())
			{
				titles=rd[title].ToString();
			}
		    
			rd.Close();
			help.conn.Close();
			return titles;
		}

		protected void input_Click(object sender, System.EventArgs e)
		{
		    SB.ADOHelper help=new SB.ADOHelper();
			string cmdtxt;
		    DateTime dt;
			if(this.Text1.Value.Trim()!="")
			{
			
				try
				{
					dt=Convert.ToDateTime(this.Text1.Value);
				}
				catch
				{ Response.Write("<script>alert('输入的日期格式不正确!')</script>");return;}
				cmdtxt="insert into HistoryDetail(WebUserName,WebsiteId,AdvListId,AdvDetailedId,FromPage,AdvPage,Ip,Appearance,HitDay,HitHour,country,HitData)"+
					" select WebUserName,WebsiteId,AdvListId,AdvDetailedId,FromPage,AdvPage,Ip,Appearance,HitDay,HitHour,country,HitData from ToDayDetail where HitData='"+dt+"'";
				if(this.rdlist.Items[0].Selected)
				{
					cmdtxt="insert into HistoryDetail(WebUserName,WebsiteId,AdvListId,AdvDetailedId,FromPage,AdvPage,Ip,Appearance,HitDay,HitHour,country,HitData)"+
						" select WebUserName,WebsiteId,AdvListId,AdvDetailedId,FromPage,AdvPage,Ip,Appearance,HitDay,HitHour,country,HitData from ToDayDetail where HitData='"+dt+"'";
				}
				if(this.rdlist.Items[1].Selected)
				{
					cmdtxt="insert into HistoryDetail(WebUserName,WebsiteId,AdvListId,AdvDetailedId,FromPage,AdvPage,Ip,Appearance,HitDay,HitHour,country,HitData)"+
						" select WebUserName,WebsiteId,AdvListId,AdvDetailedId,FromPage,AdvPage,Ip,Appearance,HitDay,HitHour,country,HitData from ToDayDetail where HitData<='"+dt+"'";
				}
				if(this.rdlist.Items[2].Selected)
				{
					cmdtxt="insert into HistoryDetail(WebUserName,WebsiteId,AdvListId,AdvDetailedId,FromPage,AdvPage,Ip,Appearance,HitDay,HitHour,country,HitData)"+
						" select WebUserName,WebsiteId,AdvListId,AdvDetailedId,FromPage,AdvPage,Ip,Appearance,HitDay,HitHour,country,HitData from ToDayDetail where HitData>='"+dt+"'";
				}
				SqlCommand cmd=new SqlCommand();
				if(help.conn.State==ConnectionState.Closed)
				{
					help.conn.Open();
				}
					SqlTransaction tran=help.conn.BeginTransaction();
				    cmd.CommandText=cmdtxt;
				    cmd.Transaction=tran;
				    cmd.Connection=help.conn;
				try
				{
			
					int sum=cmd.ExecuteNonQuery();
					cmd.CommandText="delete from ToDayDetail where HitData='"+dt+"'";
					if(this.rdlist.Items[0].Selected)
					{
						cmd.CommandText="delete from ToDayDetail where HitData='"+dt+"'";
					}
					if(this.rdlist.Items[1].Selected)
					{
						cmd.CommandText="delete from ToDayDetail where HitData<='"+dt+"'";
					}
					if(this.rdlist.Items[2].Selected)
					{cmd.CommandText="delete from ToDayDetail where HitData>='"+dt+"'"; }
					cmd.ExecuteNonQuery();
					tran.Commit();
					Response.Write("<script>alert('导入工作完成！共完成"+sum+"条数据!')</script>");
					Bind(1);
				}
				catch
				{   tran.Rollback();
					Response.Write("<script>alert('导入中断！')</script>");
				}
				finally
				{   
					help.conn.Close();
				}
			}
			else
			{ Response.Write("<script>alert('请选择导入时间!')</script>"); }
		}



}
}
