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.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class sysadmin_stat_stat_manage : System.Web.UI.Page
{

    private Cls_Operation Operation = new Cls_Operation();
    public DateTime Stat_DateTime = Convert.ToDateTime("2008-11-30 10:00:00");
    public int Stat_Days = 0, iOnline = 0;
    public int iTodayPV = 0, iTodayUV = 0, iTodayIP = 0;
    public int iYesterdayPV = 0, iYesterdayUV = 0, iYesterdayIP = 0;
    public int iAvgdayPV = 0, iAvgdayUV = 0, iAvgdayIP = 0;
    public int iMonthPV = 0, iMonthUV = 0, iMonthIP = 0;
    public int iTotalPV = 0, iTotalUV = 0, iTotalIP = 0;
    public int iHighPV = 0, iHighUV = 0, iHighIP = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["WtoRightName"] == null)
        {
            Response.Redirect("~/sysadmin/main/error.aspx?err=非法登陆!或系统超时，请刷新后重新登录");
        }
        else
        {
            this.Stat_Days = Convert.ToInt32(Operation.DateDiff(Stat_DateTime, DateTime.Now, "day"));
            this.iOnline = Operation.GetRecordCount_Child("Select Count(Distinct S_IP) As Counts From Stat_Details Where S_VisitDate >= '" + DateTime.Now.AddMinutes(-15) + "'");
            this.iTodayPV = Operation.GetRecordCount_Child("Select Sum(S_PV) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 0");
            this.iTodayUV = Operation.GetRecordCount_Child("Select Sum(S_UV) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 0");
            this.iTodayIP = Operation.GetRecordCount_Child("Select Sum(S_IP) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 0");
            this.iYesterdayPV = Operation.GetRecordCount_Child("Select Sum(S_PV) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 1");
            this.iYesterdayUV = Operation.GetRecordCount_Child("Select Sum(S_UV) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 1");
            this.iYesterdayIP = Operation.GetRecordCount_Child("Select Sum(S_IP) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 1");
            this.iMonthPV = Operation.GetRecordCount_Child("Select Sum(S_PV) As Sums From Stat_Analysis Where Datediff(month, S_Date, Getdate()) = 0");
            this.iMonthUV = Operation.GetRecordCount_Child("Select Sum(S_UV) As Sums From Stat_Analysis Where Datediff(month, S_Date, Getdate()) = 0");
            this.iMonthIP = Operation.GetRecordCount_Child("Select Sum(S_IP) As Sums From Stat_Analysis Where Datediff(month, S_Date, Getdate()) = 0");
            this.iTotalPV = Operation.GetRecordCount_Child("Select Sum(S_PV) As Sums From Stat_Analysis");
            this.iTotalUV = Operation.GetRecordCount_Child("Select Sum(S_UV) As Sums From Stat_Analysis");
            this.iTotalIP = Operation.GetRecordCount_Child("Select Sum(S_IP) As Sums From Stat_Analysis");
            this.iAvgdayPV = this.iTotalPV / this.Stat_Days;
            this.iAvgdayUV = this.iTotalUV / this.Stat_Days;
            this.iAvgdayIP = this.iTotalIP / this.Stat_Days;
            this.iHighPV = Operation.GetRecordCount_Child("Select S_PV From Stat_Analysis Union Select Sum(S_PV) From Stat_Analysis Group By DatePart(day, S_Date) Order by S_PV Desc");
            this.iHighUV = Operation.GetRecordCount_Child("Select S_UV From Stat_Analysis Union Select Sum(S_UV) From Stat_Analysis Group By DatePart(day, S_Date) Order by S_UV Desc");
            this.iHighIP = Operation.GetRecordCount_Child("Select S_IP From Stat_Analysis Union Select Sum(S_IP) From Stat_Analysis Group By DatePart(day, S_Date) Order by S_IP Desc");
            this.SaveFluxData("Select Sum(S_PV),Sum(S_UV),Sum(S_IP),DatePart(day, S_Date) As Sums From Stat_Analysis Where S_Date > '" + DateTime.Now.AddMonths(-1) + "' Group By DatePart(day, S_Date),DatePart(month, S_Date),DatePart(year, S_Date)", "chart/day_analysis.txt", "day");
            this.SaveFluxData("Select Sum(S_PV),Sum(S_UV),Sum(S_IP),DatePart(month, S_Date) As Sums From Stat_Analysis Where S_Date > '" + DateTime.Now.AddYears(-1) + "' Group By DatePart(month, S_Date),DatePart(year, S_Date)", "chart/month_analysis.txt", "month");
            this.SaveFluxData("Select Sum(S_PV),Sum(S_UV),Sum(S_IP),DatePart(year, S_Date) As Sums From Stat_Analysis Group By DatePart(year, S_Date)", "chart/year_analysis.txt", "year");
            this.SaveContentData("chart/search_analysis.xml", "seanalysis");
            this.SaveContentData("chart/keywords_analysis.xml", "kwanalysis");
            this.SaveHourFluxData("chart/hour_analysis.txt");
            if (!IsPostBack)
            {
                this.UpdateVisitDetails();
            }
        }
    }

    private void SaveHourFluxData(string sFileName)
    {
        string sPV = this.GetArray("PV");
        string sUV = this.GetArray("UV");
        string sIP = this.GetArray("IP");
        string sDT = this.GetArray("DT");
        string sHV = this.GetNumberInteger(this.GetArrayMaxValue(sPV));
        string sFileContent = "&title=,5,&\r\n" +
                            "&y_ticks=2,10,10&\r\n" +
                            "&y_legend=Chart,10,0xD2D2D2&\r\n" +
                            "&y_min=0&\r\n" +
                            "&bg_colour=#FFFFFF&\r\n" +
                            "&x_labels=" + sDT + "&\r\n" +
                            "&values=" + sPV + "&\r\n" +
                            "&values_2=" + sUV + "&\r\n" +
                            "&values_3=" + sIP + "&\r\n" +
                            "&line_dot=2,0xFF6600,访问量,12,5&\r\n" +
                            "&line_dot_2=2,0x04D215,独立访客,12,5&\r\n" +
                            "&line_dot_3=2,0x0D8ECF,独立IP,12,5&\r\n" +
                            "&y_max=" + sHV + "&";
        Operation.WriteFile(Server.MapPath(sFileName), sFileContent);
    }

    private string GetArray(string sType)
    {
        string sDT = "";
        for (int x = DateTime.Now.Hour + 1; x < 24; x++)
        {
            sDT += x.ToString() + ",";
        }
        for (int y = 0; y <= DateTime.Now.Hour; y++)
        {
            sDT += y.ToString() + ",";
        }
        sDT = sDT.Substring(0, sDT.LastIndexOf(","));
        if (sType.ToUpper() != "DT")
        {
            string sArray = "";
            DataSet dataSet = new DataSet();
            switch (sType.ToUpper())
            {
                case "PV":
                    dataSet = Operation.GetDataSet_Child("Select Count(*),DatePart(hour, S_VisitDate) From Stat_Details Where Datediff(day, S_VisitDate, GetDate()) = 0 Group By DatePart(hour, S_VisitDate)", "HourFluxData");
                    break;
                case "UV":                    
                    dataSet = Operation.GetDataSet_Child("Select Count(Distinct S_SerialNumber) As Counts,DatePart(hour, S_VisitDate) As Hours into #temptable From Stat_Details Where Datediff(day, S_VisitDate, GetDate()) = 0 Group By DatePart(hour, S_VisitDate),S_IP Select Sum(Counts) As Counts,Hours From #temptable Group By hours Drop Table #temptable", "HourFluxData");
                    break;
                case "IP":
                    dataSet = Operation.GetDataSet_Child("Select Count(Distinct S_IP) As Counts,DatePart(hour, S_VisitDate) As Hours From Stat_Details Where Datediff(day, S_VisitDate, GetDate()) = 0 Group By DatePart(hour, S_VisitDate)", "HourFluxData");
                    break;
            }
            string[] aDT = sDT.Split(',');
            for (int i = 0; i < aDT.Length; i++)
            {
                int iPatch = 0;
                for (int j = 0; j < dataSet.Tables["HourFluxData"].Rows.Count; j++)
                {
                    if (aDT[i] == dataSet.Tables["HourFluxData"].Rows[j][1].ToString())
                    {
                        sArray += dataSet.Tables["HourFluxData"].Rows[j][0].ToString() + ",";
                        iPatch = 1;
                        break;
                    }
                    else
                    {
                        iPatch = 0;
                    }
                }
                if (iPatch == 0)
                {
                    sArray += "0,";
                }
            }
            sArray = sArray.Substring(0, sArray.LastIndexOf(","));
            return sArray;
        }
        else
        {
            return sDT;
        }
    }

    private string GetArrayMaxValue(string sArray)
    {
        string[] sValue = sArray.Split(',');
        int[] iValue = new int[sValue.Length];
        for (int i = 0; i < sValue.Length; i++)
        {
            iValue[i] = Convert.ToInt32(sValue[i]);
        }
        Array.Sort(iValue);
        return iValue[iValue.Length - 1].ToString();
    }

    private string GetNumberInteger(string sValue)
    {
        int Step = 1;
        int Step_Entries = 1;
        System.Text.StringBuilder sb = new System.Text.StringBuilder(sValue);
        for (int i = 1; i < sb.Length; i++)
        {
            Step = Step * 10;
        }
        switch (sb.Length)
        {
            case 1:
            case 2:
            case 3:
                Step = Step * Convert.ToInt32(sValue.Substring(0, 1)) + Step;
                break;
            default:
                for (int j = 1; j < sb.Length - 1; j++)
                {
                    Step_Entries = Step_Entries * 10;
                }
                Step = Step * Convert.ToInt32(sValue.Substring(0, 1)) + Step_Entries * Convert.ToInt32(sValue.Substring(1, 1)) + Step_Entries;
                break;
        }
        return Step.ToString();
    }

    private void SaveFluxData(string sCmd, string sFileName, string sType)
    {
        string sPV = "";
        string sUV = "";
        string sIP = "";
        string sDT = "";
        int iDT = 0;
        switch (sType)
        {
            case "day":
                iDT = Convert.ToInt32(Operation.DateDiff(DateTime.Now.AddMonths(-1), DateTime.Now, "day"));
                for (int i = DateTime.Now.Day + 1; i <= iDT; i++)
                {
                    sDT += i.ToString() + ",";
                }
                for (int j = 1; j <= DateTime.Now.Day; j++)
                {
                    sDT += j.ToString() + ",";
                }
                break;
            case "month":
                for (int i = DateTime.Now.Month + 1; i <= 12; i++)
                {
                    sDT += i.ToString() + ",";
                }
                for (int j = 1; j <= DateTime.Now.Month; j++)
                {
                    sDT += j.ToString() + ",";
                }
                break;
            case "year":
                for (int i = DateTime.Now.Year; i <= DateTime.Now.Year + 10; i++)
                {
                    sDT += i.ToString() + ",";
                }
                break;
        }
        sDT = sDT.Substring(0, sDT.LastIndexOf(","));
        string[] aDT = sDT.Split(',');
        int[] iPV = new int[aDT.Length];
        DataSet dataSet = Operation.GetDataSet_Child(sCmd, "FluxData");
        for (int x = 0; x < aDT.Length; x++)
        {
            int iPatch = 0;
            for (int y = 0; y < dataSet.Tables["FluxData"].Rows.Count; y++)
            {
                if (aDT[x] == dataSet.Tables["FluxData"].Rows[y][3].ToString())
                {
                    sPV += dataSet.Tables["FluxData"].Rows[y][0].ToString() + ",";
                    sUV += dataSet.Tables["FluxData"].Rows[y][1].ToString() + ",";
                    sIP += dataSet.Tables["FluxData"].Rows[y][2].ToString() + ",";
                    iPV.SetValue(dataSet.Tables["FluxData"].Rows[y][0], x);
                    iPatch = 1;
                    break;
                }
                else
                {
                    iPatch = 0;
                }
            }
            if (iPatch == 0)
            {
                sPV += "0,";
                sUV += "0,";
                sIP += "0,";
            }
        }
        sPV = sPV.Substring(0, sPV.LastIndexOf(","));
        sUV = sUV.Substring(0, sUV.LastIndexOf(","));
        sIP = sIP.Substring(0, sIP.LastIndexOf(","));
        Array.Sort(iPV);
        string sFileContent = "&title=,5,&\r\n" +
                            "&y_ticks=2,10,10&\r\n" +
                            "&y_legend=Chart,10,0xD2D2D2&\r\n" +
                            "&y_min=0&\r\n" +
                            "&bg_colour=#FFFFFF&\r\n" +
                            "&x_labels=" + sDT + "&\r\n" +
                            "&values=" + sPV + "&\r\n" +
                            "&values_2=" + sUV + "&\r\n" +
                            "&values_3=" + sIP + "&\r\n" +
                            "&line_dot=2,0xFF6600,访问量,12,5&\r\n" +
                            "&line_dot_2=2,0x04D215,独立访客,12,5&\r\n" +
                            "&line_dot_3=2,0x0D8ECF,独立IP,12,5&\r\n" +
                            "&y_max=" + this.GetNumberInteger(iPV[iPV.Length - 1].ToString()) + "&";
        Operation.WriteFile(Server.MapPath(sFileName), sFileContent);
    }

    private void SaveContentData(string sFileName, string sType)
    {
        string[] Colors = new string[] { "0x54F034", "0x04D215", "0xB0DE09", "0xF8FF01", "0xFF9E01", "0xFF6600", "0xFF1F11", "0x814EE6", "0x008800", "0x880000", "0xF234B0", "0x0D8ECF" };
        string sLice = "";
        DataSet dataSet = new DataSet();
        switch (sType.ToLower())
        {
            case "seanalysis":
                dataSet = Operation.GetDataSet_Child("Select Top 12 S_Name,S_Url From Stat_Search_Engine", "SearchEngine");
                int iRecordCount = dataSet.Tables["SearchEngine"].Rows.Count;
                string[,] Lices = new string[iRecordCount, 2];
                int[] aCount = new int[iRecordCount];
                for (int i = 0; i < iRecordCount; i++)
                {
                    int iCount = Operation.GetRecordCount_Child("Select Count(S_SourceUrl) As Counts From Stat_Details Where S_SourceUrl like '%" + dataSet.Tables["SearchEngine"].Rows[i][1].ToString() + "%'");
                    if (iCount != 0)
                    {
                        Lices[i,0] = dataSet.Tables["SearchEngine"].Rows[i][0].ToString();
                        Lices[i,1] = Convert.ToString(iCount);
                        aCount[i] = iCount;
                    }
                }
                Array.Sort(aCount);
                for (int j = 0; j < iRecordCount; j++)
                {
                    if (Lices[j, 1] == aCount[aCount.Length - 1].ToString())
                    {
                        sLice += "<slice title=\"" + Lices[j, 0] + "\" color=\"" + Colors[j] + "\" pull_out=\"true\">" + Lices[j, 1] + "</slice>\r\n";
                    }
                    else
                    {
                        sLice += "<slice title=\"" + Lices[j, 0] + "\" color=\"" + Colors[j] + "\">" + Lices[j, 1] + "</slice>\r\n";
                    }
                }
                break;
            case "kwanalysis":
                string[] SearchKeys = new string[] { "query=", "q=", "w=", "wd=", "word=", "p=", "search:" };
                string[] UTF8Sites = new string[] { "google", "live", "youdao", "yisou", "yahoo" };
                dataSet = Operation.GetDataSet_Child("Select S_SourceUrl,Count(S_SourceUrl) As Counts into #tempTable From Stat_Details Group By S_SourceUrl Having Patindex('%/%', Replace(S_SourceUrl, 'http://', '')) > 0 And (Patindex('%?%', Replace(S_SourceUrl, 'http://', '')) > 0 Or Patindex('%:%', Replace(S_SourceUrl, 'http://', '')) > 0) Select Top 12 S_SourceUrl,Counts From #tempTable Order By Counts Desc Drop Table #tempTable", "KeyWords");
                for (int i = 0; i < dataSet.Tables["KeyWords"].Rows.Count; i++)
                {
                    bool isSub = false;
                    bool isUTFKey = false;
                    string sKeyWord = dataSet.Tables["KeyWords"].Rows[i][0].ToString();
                    for (int k = 0; k < UTF8Sites.Length; k++)
                    {
                        if (sKeyWord.Contains(UTF8Sites[k]) && sKeyWord.Contains("cn.yahoo") == false)
                        {
                            isUTFKey = true;
                        }
                    }
                    for (int j = 0; j < SearchKeys.Length; j++)
                    {
                        if (sKeyWord.Contains(SearchKeys[j]))
                        {
                            sKeyWord = sKeyWord.Substring(sKeyWord.IndexOf(SearchKeys[j]) + SearchKeys[j].Length);
                            if (sKeyWord.Contains("&"))
                            {
                                sKeyWord = sKeyWord.Substring(0, sKeyWord.IndexOf("&"));
                            }
                            isSub = true;
                            break;
                        }
                    }
                    if (isSub && sKeyWord != "")
                    {
                        if (isUTFKey)
                        {
                            sKeyWord = HttpUtility.UrlDecode(sKeyWord, System.Text.Encoding.UTF8);
                        }
                        else
                        {
                            sKeyWord = Server.UrlDecode(sKeyWord);
                        }
                        if (i == 0)
                        {
                            sLice += "<slice title=\"" + sKeyWord + "\" color=\"" + Colors[i] + "\" pull_out=\"true\">" + dataSet.Tables["KeyWords"].Rows[i][1].ToString() + "</slice>\r\n";
                        }
                        else
                        {
                            sLice += "<slice title=\"" + sKeyWord + "\" color=\"" + Colors[i] + "\">" + dataSet.Tables["KeyWords"].Rows[i][1].ToString() + "</slice>\r\n";
                        }
                    }
                }
                break;
        }
        string sFileContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<pie>\r\n" + sLice + "</pie>\r\n";
        Operation.WriteFile(Server.MapPath(sFileName), sFileContent);
    }

    private void UpdateVisitDetails()
    {
        string dataSetName = "visit_details";
        DataSet dataSet = Operation.GetDataSet_Child("Select * From Stat_Details Order By S_Id Desc", dataSetName);
        this.GridView.DataSource = Cls_Operation.PageBar(dataSet, dataSetName, pagebar, 10, 0);
        this.GridView.DataKeyNames = new string[] { "S_Id" };
        this.GridView.DataBind();
        if (this.GridView.Rows.Count == 0)
        {
            this.PagePanel.Visible = false;
            this.RecordPanel.Visible = true;
        }
    }

}
