using System.Web;
using System.Web.Security;


namespace Stat.Security
{
    /// <summary>
    /// 用户 登录，退出，权限，等等
    /// </summary>
    class Security : ISecurity
    {
        Stat.Cache.IConfig config = Stat.Cache.CacheFatory.CreateConfig();
        Stat.IDAL.IUsers dalUser = Stat.DALFactory.AbstractFactory.GetInstance().CreateUsers();
        Stat.IDAL.IWebSites dalSite = Stat.DALFactory.AbstractFactory.GetInstance().CreateWebSites();

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="master"></param>
        /// <returns></returns>
        public bool Login(Stat.Model.Users master)
        {
            Model.Users model = dalUser.Get(master.UserName);
            if (model == null || model.UserId == 0)
            {
                Common.Alert("该用户不存在！");
                return false;
            }
            else
            {
                if (config.IsUserPwdMd5() || model.UserGroup == 1)
                {
                    master.UserPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(master.UserPwd, "MD5");
                }
                //
                if (model.UserPwd == master.UserPwd || model.UserPwd.ToLower() == master.UserPwd.ToLower())
                {
                    if (model.UserState == 1)
                    {
                        setupUserLogin(model);
                        return true;
                    }
                    else
                    {
                        Common.Alert("您被限制登录！");
                        return false;
                    }
                }
                else
                {
                    Common.Alert("密码有误！");
                    return false;
                }
            }
        }
        /// <summary>
        /// 检查 验证码
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool CheckCode(string name, string value)
        {
            string message = "";
            //检查浏览器是否打开Cookies
            if (HttpContext.Current.Request.Cookies[name] == null)
            {
                message = "您的浏览器设置已被禁用 Cookies，您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";
                Common.Alert(message);
                return false;
            }

            //检查验证码
            if (!HttpContext.Current.Request.Cookies[name].Value.ToLower().Equals(value.ToLower()))
            {
                message = "温馨提示：验证码错误";
                Common.Alert(message);
                return false;
            }
            return true;
        }


        /// <summary>
        /// 获取用户可以操作的 站点 ID 列表
        /// </summary>
        /// <returns></returns>
        public string GetUserWebsiteList()
        {
            string WebsiteList = string.Empty;
            string webidList = string.Empty;

            if (HttpContext.Current.Session == null) return string.Empty;

            if (HttpContext.Current.Session["UserPower"] != null)
            {
                WebsiteList = HttpContext.Current.Session["UserPower"].ToString();
            }
            string[] arr = WebsiteList.Split(',');
            foreach (string item in arr)
            {
                string webid = item.Trim();
                if (webid.Length > 0)
                {
                    webidList += webid + ",";
                }
            }
            //去掉最后 '
            if (webidList.Length > 1)
            {
                webidList = webidList.Substring(0, webidList.Length - 1);
            }
            return webidList;
        }

        /// <summary>
        /// 是否 用户 可以操作该站点
        /// </summary>
        /// <param name="webID">站点ID</param>
        /// <returns></returns>
        public bool IsOperateWebSite(int webID)
        {
            if (IsMaster())
            {
                return true;
            }
            /*--------------------------------------------------------*/
            string WebSiteIDList = "," + GetUserWebsiteList() + ",";
            if (WebSiteIDList.IndexOf("," + webID + ",") > -1)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 用户是否 已经登录
        /// </summary>
        /// <returns></returns>
        public bool IsUserLogin()
        {
            /*-----------------------------------------------------------------------------------*/
            if (GetCurrentUserID() < 0)
            {
                HttpContext.Current.Session.Abandon();
                return false;
            }
            else
            {

            }
            return true;
        }
        /// <summary>
        /// 检查 当前用户 是否 是用户组
        /// </summary>
        /// <returns></returns>
        public bool IsUser()
        {
            if (HttpContext.Current.Session["UserGroup"] != null)
            {
                if (HttpContext.Current.Session["UserGroup"].ToString() == "0")
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 检查 当前用户 是否 是管理员组
        /// </summary>
        /// <returns></returns>
        public bool IsMaster()
        {
            
           

            if (HttpContext.Current.Session == null) return false;

            if (HttpContext.Current.Session["UserGroup"] != null)
            {
                if (HttpContext.Current.Session["UserGroup"].ToString() == "1")
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 检查管理员 是否登录
        /// </summary>
        public bool IsMasterLogin()
        {
            if (HttpContext.Current.Session["Userid"] == null || HttpContext.Current.Session["UserGroup"] == null)
            {
                return false;
            }
            else
            {
                if (HttpContext.Current.Session["UserGroup"].ToString() == "1")
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 重新加载 当前用户 登录信息
        /// </summary>
        /// <returns></returns>
        public void ReloadCurrentUser()
        {
            Model.Users model = dalUser.GetUserInfo(GetCurrentUserID());
            setupUserLogin(model);
        }

        /// <summary>
        /// 获取当前用户的 ID（-1：表示当前无用户，0：查看者）
        /// </summary>
        /// <returns></returns>
        public int GetCurrentUserID()
        {
            if (HttpContext.Current.Session["Userid"] != null)
            {
                return int.Parse(HttpContext.Current.Session["Userid"].ToString());
            }
            return -1;
        }

        /// <summary>
        /// 退出 登录（用户主动触发）
        /// </summary>
        public void LogOut()
        {
            HttpContext.Current.Session.Abandon();
        }
        /// <summary>
        ///从 Session 获取 登录名
        /// </summary>
        /// <returns></returns>
        public string GetCurrentUserName()
        {
            if (HttpContext.Current.Session["UserName"] != null)
            {
                return HttpContext.Current.Session["UserName"].ToString();
            }
            else
            {
                return "";
            }

        }

        public string GetMasterPowerList(string admin_power)
        {
            return new Menu().GetMasterHtml(admin_power);
        }

        #region ISecurity 成员：管理员权限检查

        public bool CheckMasterPower(string pageName)
        {
            if (pageName.ToLower() == "main.aspx") { return true; }

            string[, ,] power = new Menu().PowerItem();

            int iCount = power.GetLength(0);
            for (int i = 0; i < iCount; i++)
            {
                int jCount = power.GetLength(2);
                for (int j = 1; j < jCount; j++)
                {
                    if (power[i, 0, j] == null) { break; }
                    if (power[i, 0, j].ToLower().IndexOf(pageName.ToLower()) > -1)
                    {
                        if (IsHaveSysPower(i.ToString() + j.ToString()))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
            return false;
        }

        #endregion
        #region ISecurity 成员


        public bool CheckReportPower(int webid, string pageName)
        {
            string[, ,] power = new OpenItem().PowerItem();

            int iCount = power.GetLength(0);
            for (int i = 0; i < iCount; i++)
            {
                int jCount = power.GetLength(2);
                for (int j = 1; j < jCount; j++)
                {
                    if (power[i, 0, j] == null) { break; }
                    if (power[i, 0, j].ToLower().IndexOf(pageName.ToLower()) > -1)
                    {
                        if (IsHaveReportPower(webid, (i.ToString() + j.ToString())))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
            return false;
        }

        #endregion
        /*-私有成员---------------------------------------------------------------------*/

        /// <summary>
        /// 是否拥有某项权限
        /// </summary>
        /// <param name="power"></param>
        /// <returns></returns>
        private bool IsHaveSysPower(string power)
        {
            if (HttpContext.Current.Session["UserPower"] != null)
            {
                string userPower = "," + HttpContext.Current.Session["UserPower"].ToString() + ",";
                if (userPower.IndexOf("," + power + ",") > -1)
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 是否拥有某项报表权限
        /// </summary>
        /// <param name="power"></param>
        /// <returns></returns>
        private bool IsHaveReportPower(int webid, string power)
        {
            Stat.Model.WebSites siteModel = GetWebSiteInfo(webid);
            if (siteModel != null)
            {
                if (siteModel.OpenItem != null)
                {
                    siteModel.OpenItem = "," + siteModel.OpenItem + ",";
                    if (siteModel.OpenItem.IndexOf("," + power + ",") > -1)
                        return true;
                }
            }
            else
            {
                return false;
            }
            return false;
        }
        /// <summary>
        /// 重新 设置 用户的 登录信息
        /// </summary>
        private void setupUserLogin(Model.Users model)
        {
            if (model != null && model.UserName != null)
            {
                HttpContext.Current.Session["UserPower"] = model.UserPower;//设置拥有站点权限
                HttpContext.Current.Session["UserGroup"] = model.UserGroup.ToString();
                HttpContext.Current.Session["Userid"] = model.UserId.ToString();
                HttpContext.Current.Session["UserName"] = model.UserName;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        private Stat.Model.WebSites GetWebSiteInfo(int webid)
        {
            string cName = "Website_" + webid.ToString();
            if (HttpContext.Current.Cache.Get(cName) == null)
            {
                Stat.Model.WebSites list = dalSite.Get(webid);
                if (list != null)
                {
                    HttpContext.Current.Cache.Insert(cName, list, null, System.DateTime.UtcNow.AddMinutes(10), System.TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Low, null);
                }
                return list;
            }
            return (Stat.Model.WebSites)(HttpContext.Current.Cache.Get(cName));
        }
        /*----------------------------------------------------------------------*/



        #region ISecurity 成员：站点报表公开权限集合


        public string GetWebsitePowerList(string website_power)
        {
            return new OpenItem().GetWebsitePowerList(website_power);
        }

        #endregion



        #region ISecurity 成员


        public void CheckReportPower(int webid)
        {           
            bool isView = false;
            string strPage = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
            if (CheckReportPower(webid, strPage.Substring(strPage.LastIndexOf("/") + 1))) { isView = true; }
            if (IsOperateWebSite(webid)) { isView = true; }
            if (!isView)
            {
                HttpContext.Current.Response.Write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");

                if (strPage.Substring(strPage.LastIndexOf("/") + 1).ToLower().IndexOf("main.aspx") > -1)
                {


                    Common.Alert("Sorry! 您没有查看此项报表【权限】！", "http://" + HttpContext.Current.Request.Url.Host + "");
                }
                else
                {
                    Common.Alert("Sorry! 您没有查看此项报表【权限】！");
                    Common.HistoryGo(-1);
                }
                HttpContext.Current.Response.Write("</body></html>");
                HttpContext.Current.Response.End();
            }   

        }

        #endregion
    }
}
