using System;
using System.Web.Security;

namespace ynhtm.Admin
{
    using Common;

    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var setting = new BLL.Setting();
            var settingItem = setting.Get();
            var s = settingItem.CreateDate.Year.ToString();
            if (DateTime.Now.Year > settingItem.CreateDate.Year) s += "-" + DateTime.Now.Year;
            this.lblCopy.Text = s + " " + settingItem.SiteName.IifNullOrWhiteSpace(this.Request.Url.Host).HtmlEncode();
            if (!this.IsPostBack)
            {
#if DEMO
                this.txtUserName.Text = "admin";
                this.txtPassWord.Text = "admin888";
#endif
                if (string.Equals(this.Request.QueryString["Action"], "Logout", StringComparison.OrdinalIgnoreCase))
                    FormsAuthentication.SignOut();
                else
                {
                    switch (this.Request.QueryString["ErrorCode"])
                    {
                        case "1":
                            this.ShowError("还未登录，请先登录");
                            break;
                        case "2":
                            this.ShowError("没有权限进行管理");
                            break;
                        case "3":
                            this.ShowError("帐号被锁定，无法进行操作");
                            break;
                    }
                }
            }
            this.Form.DefaultFocus = this.txtUserName.Text.IsNullOrWhiteSpace() ? this.txtUserName.ClientID : this.txtPassWord.ClientID;
            this.Form.DefaultButton = this.btnLogin.UniqueID;
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                var code = this.Session[BLL.Setting.AUTHCODEKEY];
                if (code == null || !string.Equals(this.txtAuthcode.Text, code.ToString()))
                    this.ShowError("验证码错误");
                else
                {
                    var user = new BLL.User();
                    var item = user.GetByUserNameAndPassWord(this.txtUserName.Text, this.txtPassWord.Text.HashMD5());
                    if (item == null)
                        this.ShowError("用户名或密码错误");
                    else if (item.IsLock == true)
                        this.ShowError("帐号被锁定，无法登陆");
                    else
                    {
                        user.Login(item, this.Request, this.Response);
                        this.Response.Redirect("./");
                    }
                }
            }
        }
    }
}