using System;
using Whir.ezEIP.Web;
using Whir.Framework;
using Whir.Security;
using Whir.ezEIP.Web.HttpHandlers;
using Whir.Security.Service;
using Whir.Service;

public partial class whir_system_Handler_Security_User : SysHandlerPageBase
{
    private const string REMEMBER_USERNAME_COOKIEKEY = "{5E73B429-3E4A-43EB-9A34-05EFAE8C5DC1}";
    private const string LOGINTIME_COOKIEKEY = "{72943b2f-c150-4d4e-a9fb-0717c6f1b925 }";

    protected void Page_Load(object sender, EventArgs e)
    {
        var action = RequestUtil.Instance.GetFormString("_action");
        Exec(this, action);
    }

    /// <summary>
    /// 更换皮肤
    /// </summary>
    /// <returns></returns>
    public HandlerResult ModifySkin()
    {
        string systemSkin = RequestUtil.Instance.GetFormString("SystemSkin");

        if (CurrentUser.UserId == 0)
            return new HandlerResult { Status = false, Message = "当前用户不存在" };

        CurrentUser.SystemSkin = systemSkin;

         Whir.Security.ServiceFactory.UsersService.Update(CurrentUser);
       
        return new HandlerResult { Status = true, Message = "更换皮肤成功" };
    }
 

    #region  异步登录
    /// <summary>
    /// 异步登录
    /// </summary>
    public HandlerResult Login()
    {
        string loginName = Request.Form["UserName"];
        string password = Request.Form["Password"];
        string code = Request.Form["verifiyCode"];
        string isRemember = Request.Form["isRemember"];

        if (!string.IsNullOrEmpty(loginName) && !string.IsNullOrEmpty(password))
        {
            // 输入过滤验证.
            bool isSafe = StrExt.IsSafeSql(loginName);
            if (isSafe)
            {
                return new HandlerResult { Status = false, Message = "用户名含非法字符，请输入合法的用户名" };
            }

            if (this.VerifyCheckCode(code))
            {
                LoginService loginService = new LoginService();
                LoginStatus e = loginService.Login(loginName, password, AppSettingUtil.GetString("SystemPath"));
                HandlerResult hr;
                switch (e)
                {
                    case Whir.Security.LoginStatus.LicenseInvalid:
                        SetLoginTime();
                        hr= new HandlerResult { Status = false, Message = "-1" };//登录失败，未授权
                        break;
                    case Whir.Security.LoginStatus.AccountNotFound:
                        SetLoginTime();
                        hr= new HandlerResult { Status = false, Message = "登录失败，用户名或密码错误" };
                        break;
                    case Whir.Security.LoginStatus.AccountDisabled:
                        SetLoginTime();
                        hr= new HandlerResult { Status = false, Message = "登录失败，用户被禁用" };
                        break;
                    case Whir.Security.LoginStatus.InvalidPassword:
                        SetLoginTime();
                        hr= new HandlerResult { Status = false, Message = "登录失败，用户名或密码错误" };
                        break;
                    case Whir.Security.LoginStatus.Success:
                        Whir.Service.ServiceFactory.OperateLogService.Save(LogType.SystemRunLog, string.Format("【{0}】登录成功", loginName));
                        CookieUtil.Instance.RemoveCookie(LOGINTIME_COOKIEKEY);
                        RememberLoginName(isRemember == "1", loginName);
                        return new HandlerResult { Status = true, Message = "ok" };
                    default:
                        hr= new HandlerResult { Status = false, Message = "未知错误" };
                        break;

                }
                if (e != Whir.Security.LoginStatus.Success)
                {
                    Whir.Service.ServiceFactory.OperateLogService.Save(LogType.SystemRunLog, string.Format("后台-用户名:{0},密码:{1},登录失败", loginName, password));
                }
 
                return hr;
            }
            else
            {
                return new HandlerResult { Status = false, Message = "请输入正确的验证码" };
            }

        }
        return new HandlerResult { Status = false, Message = "请填写账号、密码" };
 
    }

    /// <summary>
    /// 获取记住的用户名
    /// </summary>
    public HandlerResult GetLoinName()
    {
        if (null != Request.Cookies[REMEMBER_USERNAME_COOKIEKEY] &&
                      !String.IsNullOrEmpty(Request.Cookies[REMEMBER_USERNAME_COOKIEKEY].Value))
        {
            return new HandlerResult { Status = true, Message =  Request.Cookies[REMEMBER_USERNAME_COOKIEKEY].Value};
        
        }
        return new HandlerResult { Status = false, Message = "" };
    }

     /// <summary>
    /// 获取记住的用户名
    /// </summary>
    public HandlerResult IsShowCode()
    {
        if (GetLoginTime() > 2)
        {
            return new HandlerResult { Status = true, Message = "请输入验证码" };

        }
        return new HandlerResult { Status = false, Message = "" };
    }


    #region 记住用户名
    /// <summary>
    /// 记住用户名
    /// </summary>
    private void RememberLoginName(bool isRemember, string loginName)
    {
        //选中记住用户名时设置COOKIE,用以登录的用户名.
        if (isRemember)
        {
            if (null != CookieUtil.Instance.GetCookie(REMEMBER_USERNAME_COOKIEKEY))
            {
                CookieUtil.Instance.RemoveCookie(REMEMBER_USERNAME_COOKIEKEY);
            }
            CookieUtil.Instance.AddCookie(REMEMBER_USERNAME_COOKIEKEY, loginName, DateTime.Now.AddMonths(1));//记住用户名有效时间1个月
        }
        else
        {
            if (null != CookieUtil.Instance.GetCookie(REMEMBER_USERNAME_COOKIEKEY))
                CookieUtil.Instance.RemoveCookie(REMEMBER_USERNAME_COOKIEKEY);
        }
    }
  
    #endregion

    /// <summary>
    /// 检查验证码是否正确.
    /// </summary>
    public bool VerifyCheckCode(string code)
    {
        if (GetLoginTime() > 2)
        {
            if (this.Session[CheckCodeHandler.CheckCode_Key] == null)
            {
                return false;
            }
            string checkCode = this.Session[CheckCodeHandler.CheckCode_Key].ToString();
            return checkCode.Equals(code, StringComparison.OrdinalIgnoreCase);
        }
        return true;
    }


    #region 登录次数

    /// <summary>
    /// 得到当前登陆失败的次数
    /// </summary>
    /// <returns></returns>
    private static int GetLoginTime()
    {
        return null != CookieUtil.Instance.GetCookie(LOGINTIME_COOKIEKEY) ? CookieUtil.Instance.GetCookie(LOGINTIME_COOKIEKEY).Value.ToInt() : 0;
    }

    /// <summary>
    /// 设置登陆次数的Cookies
    /// </summary>
    private void SetLoginTime()
    {
        if (CookieUtil.Instance.GetCookie(LOGINTIME_COOKIEKEY) == null)
        {
            CookieUtil.Instance.AddCookie(LOGINTIME_COOKIEKEY, "1", DateTime.Now.AddHours(1));
        }
        else
        {
            int newTimesValue = CookieUtil.Instance.GetCookie(LOGINTIME_COOKIEKEY).Value.ToInt() + 1;
            CookieUtil.Instance.RemoveCookie(LOGINTIME_COOKIEKEY);
            CookieUtil.Instance.AddCookie(LOGINTIME_COOKIEKEY, newTimesValue.ToStr(), DateTime.Now.AddHours(1)); //有效时间1小时
        }
    }
    #endregion

    #endregion

}