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


public partial  class handinput : System.Web.UI.Page
{
    private SqlConnection conn= new SqlConnection((String)ConfigurationSettings.AppSettings["ConnectionString"]);
    private static string advlist;
    private static string websiteid;
    private static string advdetailed;
    private static string Cmd_txt;
    private static DataSet dataset;
    private static double price;
 
    protected void Page_Load(object sender, 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("15") || role[i].Equals("0"))
						{
							exists=true;break;
						}
					}
					if(exists)
					{
                        this.Session["ok"] = "True";
						date.Value = DateTime.Now.ToShortDateString();     
						ListBox_bind();
					}
					else
					{Response.Redirect("NoAuthor.aspx");}
				}
			}
		
       

    }
   
    private void ListBox_bind()
    {
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        SqlCommand cmd = new SqlCommand("select id,AdvTitle from AdvList", conn);
        SqlDataReader rd = cmd.ExecuteReader();
        int i = 0;
        while (rd.Read())
        {

            DropDownList1.Items.Add("(" + rd["id"].ToString() + ")" + rd["AdvTitle"].ToString());
            DropDownList1.Items[i].Value = rd["id"].ToString();
            i++;
        }
        rd.Close();
        conn.Close();

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
      //  this.Session["ok"] = "True";
        bool ismodif = false;
        for (int j = 0; j < DataGrid2.Items.Count; j++)
        {
            int temp = 0;
          
            try
            {
                temp = int.Parse(((TextBox)DataGrid2.Items[j].FindControl("textbox1")).Text);
                temp = int.Parse(((TextBox)DataGrid2.Items[j].FindControl("textbox2")).Text);
            }
            catch
            {
                Response.Write("<script>alert('第" + (j + 1) + "条输入的数据无效或超限！')</script>");
                return;
            }
        }
        if (Session["ok"].ToString() == "True")
        {
            if (DropDownList1.SelectedIndex >= 0)
            {

                advlist = DropDownList1.SelectedItem.Value.ToString();
                for (int i = 0; i < DataGrid2.Items.Count; i++)
                {
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    string name = DataGrid2.Items[i].Cells[0].Text;
                    websiteid = (((DataBoundLiteralControl)DataGrid2.Items[i].Cells[1].Controls[0]).Text.Split(new char[] { '(', ')' }))[1];
                    SqlCommand cmd = new SqlCommand("SELECT top 1 dbo.AdvDetailed.id FROM dbo.AdvDetailed INNER JOIN" +
                                                    " dbo.ApplicationAdv ON dbo.AdvDetailed.AdvListId = dbo.ApplicationAdv.AdvListId AND " +
                                                    "dbo.ApplicationAdv.WebUserName ='" + name + "' and ApplicationAdv.WebsiteId='" + websiteid + "'", conn);
                    SqlDataReader rd = cmd.ExecuteReader();
                    if (rd.Read())
                    {
                        advdetailed = rd["id"].ToString();
                    }
                    rd.Close();
                    cmd.CommandText = "select Unitprice from AdvList where id='" + advlist + "'";
                    rd = cmd.ExecuteReader();
                    if (rd.Read())
                    {
                        price = double.Parse(rd["Unitprice"].ToString());
                    }
                    rd.Close();
                    int hits = int.Parse(((TextBox)DataGrid2.Items[i].FindControl("textbox1")).Text);
                    int shows = int.Parse(((TextBox)DataGrid2.Items[i].FindControl("textbox2")).Text);
                    string countday = DateTime.Parse(date.Value).Year.ToString() + (DateTime.Parse(date.Value).Month < 10 ? "0" + DateTime.Parse(date.Value).Month.ToString() : DateTime.Parse(date.Value).Month.ToString()) + (DateTime.Parse(date.Value).Day < 10 ? "0" + DateTime.Parse(date.Value).Day.ToString() : DateTime.Parse(date.Value).Day.ToString());


                    cmd.CommandText = "delete from AdvCount where WebUserName='" + name + "' and IsPayment=1 and WebsiteId='" + websiteid + "' and AdvListId='" + advlist + "' and CountDay='" + countday + "'";
                    SqlTransaction tran = conn.BeginTransaction();
                    cmd.Transaction = tran;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        if (hits > 0 || shows > 0)
                        {
                            cmd.CommandText = "insert into AdvCount(WebUserName,WebsiteId,AdvListId,AdvDetailed,Quantity,ShowQuantity,CPAQuantity,CountDay,AddTime,IsPayment,money,Remarks) values('" + name + "','" + websiteid + "','" + advlist + "','" + advdetailed + "','" + hits + "','" + shows + "','0','" + countday + "','" + DateTime.Now.ToString() + "',1," + ((hits + shows) * price) + ",'统计')";
                            cmd.ExecuteNonQuery();
                        }
                        tran.Commit();
                        ismodif = true;
                    }
                    catch
                    {
                        tran.Rollback();
                        ismodif = false;
                    }
                    finally
                    {
                        conn.Close();
                    }

                }
                if (ismodif)
                {
                    Response.Write("<script>alert('修改完成！')</script>");
                }
                else
                { Response.Write("<script>alert('处理中断！')</script>"); }
            }
            else
            {
                Response.Write("<script>alert('当前没有任何广告！')</script>");
            }
            //this.Session["ok"] = "Flse";
        }
        
    }
    private void datagridbind()
    {
        Session["ok"] = true;
        Panel1.Visible = false;
        if (DropDownList1.SelectedIndex >= 0)
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            advlist = DropDownList1.SelectedItem.Value.ToString();
            Cmd_txt = " where ApplicationAdv.AdvListId='" + advlist + "' and ApplicationAdv.WebsiteId=Website.id and ApplicationAdv.Appearance!=2 and ApplicationAdv.Appearance!=3";
            Bind();
            SqlCommand cmd = new SqlCommand();
            string countday = DateTime.Parse(date.Value).Year.ToString() + (DateTime.Parse(date.Value).Month < 10 ? "0" + DateTime.Parse(date.Value).Month.ToString() : DateTime.Parse(date.Value).Month.ToString()) + (DateTime.Parse(date.Value).Day < 10 ? "0" + DateTime.Parse(date.Value).Day.ToString() : DateTime.Parse(date.Value).Day.ToString());
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            for (int i = 0; i < DataGrid2.Items.Count; i++)
            {
                string weblistid = (((DataBoundLiteralControl)DataGrid2.Items[i].Cells[1].Controls[0]).Text.Split(new char[] { ')', '(' }))[1];
                string webusername = DataGrid2.Items[i].Cells[0].Text;
                cmd.CommandText = "select sum(Quantity) as Quantity ,sum(ShowQuantity) as ShowQuantity from AdvCount" +
                 " where WebUserName='" + webusername + "' and AdvCount.WebsiteId='" + weblistid + "'" +
                 " and IsPayment=1 " +
                 " and AdvListId='" + DropDownList1.SelectedItem.Value + "' and CountDay='" + countday + "'";
                cmd.Connection = conn;
                SqlDataReader rd = cmd.ExecuteReader();

                if (rd.Read())
                {
                    if (rd["Quantity"].ToString().Trim() != "")
                    {
                        ((TextBox)DataGrid2.Items[i].FindControl("textbox1")).Text = rd["Quantity"].ToString();
                    }
                    if (rd["ShowQuantity"].ToString().Trim() != "")
                    {
                        ((TextBox)DataGrid2.Items[i].FindControl("textbox2")).Text = rd["ShowQuantity"].ToString();
                    }
                }
                rd.Close();
            }
            if (conn.State == ConnectionState.Open)
            { conn.Close(); }
            Panel1.Visible = false;
        }
        else { Response.Write("<script>alert('当前没有任何广告！')</script>"); }
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        datagridbind();
    }
    private void Bind()
    {

        SqlDataAdapter da = new SqlDataAdapter("select ApplicationAdv.WebUserName,ApplicationAdv.WebsiteId,Website.WebsiteName,Website.url from Website,ApplicationAdv " + Cmd_txt, conn);
        dataset = new DataSet();
        da.Fill(dataset,"websit");
        this.DataGrid2.DataSource = dataset;
        this.DataGrid2.DataBind();
        conn.Close();
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        DataTable table = new DataTable();
        table.Columns.Add(new DataColumn("name", typeof(String)));
        table.Columns.Add(new DataColumn("advlist", typeof(String)));
        table.Columns.Add(new DataColumn("hit", typeof(Int32)));
        table.Columns.Add(new DataColumn("show", typeof(Int32)));
        DataRow row;
        int hits = 0, shows = 0;
        for (int i = 0; i < DataGrid2.Items.Count; i++)
        {
            try
            {
                 hits = int.Parse(((TextBox)DataGrid2.Items[i].FindControl("textbox1")).Text);
                shows = int.Parse(((TextBox)DataGrid2.Items[i].FindControl("textbox2")).Text);
            }
            catch
            {
                Response.Write("<script>alert('第" + (i + 1) + "条输入的数据无效或超限！')</script>");
                return;
            }
            if (hits > 0 || shows > 0)
            {
                row = table.NewRow();
                row[0] = DataGrid2.Items[i].Cells[0].Text.Trim();
                row[1] = ((DataBoundLiteralControl)DataGrid2.Items[i].Cells[1].Controls[0]).Text;
                row[2] = hits;
                row[3] = shows;
                if (table.Rows.Count > 0)
                {
                    bool isexistes = false;
                    for (int j = 0; j < table.Rows.Count; j++)
                    {
                        if (row[0].ToString().Trim()== table.Rows[j][0].ToString().Trim() && row[1].ToString().Trim()== table.Rows[j][1].ToString().Trim())
                        {
                            table.Rows[j][2] = row[2].ToString();
                            table.Rows[j][3] = row[3].ToString();
                            isexistes = true;
                            break;
                        }
                    }
                    if (!isexistes)
                    {
                        table.Rows.Add(row);
                    }
                }
                else
                {
                    table.Rows.Add(row);
                }
                   
            }
        }
        DataGrid1.DataSource = new DataView(table);
        DataGrid1.DataBind();
        Panel1.Visible = true;
    }

	private void InitializeComponent()
	{
		//this.DropDownList1.SelectedIndexChanged += new System.EventHandler(this.DropDownList1_SelectedIndexChanged);

	}





    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        datagridbind();
    }
}
