using System;
using System.Data;
using System.Text;namespace ZKXP.BLL
{
    /// <summary>
    /// OnLine 的摘要说明。
    /// </summary>
    public class OnLine
    {    
        private string USERNAME;
        private int OFFLINEDIFF;
        private int REMOVEDIFF;
                public OnLine()
        {
            //直接在这里设定、或从配置文件中读取配置参数
            ///存放用户名的Session名
            USERNAME = "UserName";
            ///多少分钟不活动的用户从在线列表中删除
            OFFLINEDIFF = 5;
            ///多少秒执行一次删除不活动用户
            REMOVEDIFF = 30;
            
            if(System.Web.HttpContext.Current.Application["OnlineTalbe"] == null)
            {
                this.CashTableInit();
            }
        }        public void CheckOnline()
        {
            //从Application获取数据表、获取SessionID
            DataTable dtOnline;
            dtOnline = (DataTable)System.Web.HttpContext.Current.Application["OnlineTalbe"];
            string sessionId = System.Web.HttpContext.Current.Session.SessionID.ToString();
            
            //数据表中是否有我的记录
            DataRow drFind = dtOnline.Rows.Find(sessionId);
            if(drFind != null)
            {
                //有;更新我的状态
                Info.Write("更新");
                drFind["LastActiveTime"] = DateTime.Now;
                drFind["UserWhere"] = this.AtWhere;
                //用户由访客状态变为了登陆会员、或反之
                if(Extend.GetSession(USERNAME) != null)
                {
                    drFind["VisitorName"] = Extend.GetSession(USERNAME);
                    drFind["VisitorLevel"] = Extend.GetSession("UserLevel");
                }
                else
                {
                    drFind["VisitorName"] = "vst";
                    drFind["VisitorLevel"] = -1;
                }    
            }
            else
            {
                //无;加入关于我的在线信息
                Info.Write("插入");
                DataRow drNew = dtOnline.NewRow();
                drNew["SessionID"] = sessionId;
                drNew["VisitorName"] = "vst";
                drNew["VisitorLevel"] = -1;
                drNew["LastActiveTime"] = DateTime.Now;
                drNew["LoginTime"] = DateTime.Now;
                drNew["VisitorIP"] = Extend.GetRealIP();;
                drNew["UserWhere"] = this.AtWhere;
                
                dtOnline.Rows.Add(drNew);                
            }
            //如果没有人正在执行删除且离上次删除的时间间隔超过设定值
            TimeSpan tsRemove = DateTime.Now - Convert.ToDateTime(GetApplication("LastRemove"));
            if(tsRemove.Seconds > REMOVEDIFF && this.GetApplication("Removing").ToString() == "n")
            {
                //锁定,我正在删除过期用户
                System.Web.HttpContext.Current.Application.Lock();
                SetApplication("Removing", "y");
                System.Web.HttpContext.Current.Application.UnLock();
                //不知道Rows.Count是否随循环减少,如果是效率就大于foreach且这里不能使用foreach
                for(int i=0; i< dtOnline.Rows.Count; i++ )
                {
                    DataRow drDel = dtOnline.Rows[i];
                    TimeSpan ts= DateTime.Now - Convert.ToDateTime(drDel["LastActiveTime"]);
                    if(ts.Minutes > OFFLINEDIFF)
                    {
                        dtOnline.Rows.Remove(drDel);
                    }
                }                //我删完了,Response.Write("好累") ;
                System.Web.HttpContext.Current.Application.Lock();
                SetApplication("Removing", "n");
                SetApplication("LastRemove", DateTime.Now.ToString());
                System.Web.HttpContext.Current.Application.UnLock();
            }
            
            //把被我揉腻完了的数据表放回Application
            dtOnline.AcceptChanges();
            System.Web.HttpContext.Current.Application.Lock();
            System.Web.HttpContext.Current.Application["DataTalbeOnline"] = dtOnline;
            System.Web.HttpContext.Current.Application.UnLock();            
        }
        private string GetApplication(string apcname)
        {
            return System.Web.HttpContext.Current.Application[apcname].ToString();
        }
        public void SetApplication(string apcname, string apcvalue)
        {
            
            System.Web.HttpContext.Current.Application[apcname] = apcvalue;
            
        }
        /// <summary>
        /// 返回用户当前位置
        /// </summary>
        private string AtWhere
        {
            get
            {    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append(System.Web.HttpContext.Current.Request.ServerVariables["url"]);
                if(System.Web.HttpContext.Current.Request.ServerVariables["QUERY_STRING"] != String.Empty)
                {
                    sb.Append("?");
                    sb.Append(System.Web.HttpContext.Current.Request.ServerVariables["QUERY_STRING"]);
                }
                return sb.ToString() ;
            }
        }
        /// <summary>
        /// 创建表
        /// </summary>
        public void CashTableInit()
        {    
            DataTable dt = new DataTable("OnlineTalbe");
            dt.Columns.Add("SessionID",typeof(string));
            dt.Columns.Add("VisitorName", typeof(string));
            dt.Columns.Add("VisitorLevel", typeof(int));
            dt.Columns.Add("LastActiveTime", typeof(DateTime));
            dt.Columns.Add("LoginTime", typeof(DateTime));
            dt.Columns.Add("VisitorIP", typeof(string));
            dt.Columns.Add("UserWhere", typeof(string));
            dt.Columns["SessionID"].Unique = true;
            dt.PrimaryKey = new DataColumn[]{dt.Columns["SessionID"]};
                        
            System.Web.HttpContext.Current.Application["OnlineTalbe"] = dt;
            System.Web.HttpContext.Current.Application["LastRemove"] = DateTime.Now.ToString();
            System.Web.HttpContext.Current.Application["Removing"] = "n";
        }    
    }
}