using System;
using System.Data;
using System.Configuration;
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;
using SQLHelper;
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic;
/// <summary>
/// UserInfo 的摘要说明
/// </summary>
namespace BLL
{
    public class UserInfo
    {
        #region DAL

        #region 增

        /// <summary>
        /// 创建一个新用户
        /// </summary>
        /// <param name="username">用户名称</param>
        /// <param name="password">用户密码</param>
        /// <param name="email">电子邮件</param>
        /// <param name="question">密码问题</param>
        /// <param name="answer">问题答案</param>
        /// <returns></returns>
        public int createUser(string username, string password, int power, string email, string question, string answer)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("insert into UserInfo ([UserName],[Password],[Power],[Email],[Question],[Answer]) values ");
            sb.Append(" (@UserName,@Password,@Power,@Email,@Question,@Answer)");
            SqlParameter[] param = 
                                    {
                                        DBHelper.GetParameter("@UserName",SqlDbType.NVarChar,50,"[UserName]",username),
                                        DBHelper.GetParameter("@Password",SqlDbType.NVarChar,50,"[Password]",password),
                                        DBHelper.GetParameter("@Power",SqlDbType.Int,4,"[Power]",power),
                                        DBHelper.GetParameter("@Email",SqlDbType.NVarChar,50,"[Email]",email),
                                        DBHelper.GetParameter("@Question",SqlDbType.NVarChar,50,"[Question]",question),
                                        DBHelper.GetParameter("@Answer",SqlDbType.NVarChar,50,"[Answer]",answer)
                                    };
            return DBHelper.ExecuteSql(sb.ToString(), param);
        }

        #endregion
        #region 删

        /// <summary>
        /// 删除一个用户
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns></returns>
        public int deleteUser(int userid)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("delete from UserInfo where [UserID]=@UserID");
            SqlParameter[] param = { DBHelper.GetParameter("@UserID", SqlDbType.Int, 4, "[UserID]", userid) };
            return DBHelper.ExecuteSql(sb.ToString(), param);
        }

        #endregion
        #region 改

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <param name="newpassword">新密码</param>
        /// <returns></returns>
        public int updateUserPassword(int userid, string newpassword)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("update UserInfo set [Password]=@newpassword where [UserID]=@UserID");
            SqlParameter[] param = 
                                   { 
                                       DBHelper.GetParameter("@UserID", SqlDbType.Int, 4, "[UserID]", userid) ,
                                       DBHelper.GetParameter("@newpassword",SqlDbType.NVarChar,50,"[Password]",newpassword)
                                   };
            return DBHelper.ExecuteSql(sb.ToString(), param);
        }
        /// <summary>
        /// 修改用户资料
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <param name="password">用户密码</param>
        /// <param name="email">电子邮件</param>
        /// <param name="question">密码问题</param>
        /// <param name="answer">问题答案</param>
        /// <returns></returns>
        public int updateUser(int userid, string password, string email, string question, string answer)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("update UserInfo set [Password]=@Password,[Email]=@Email,[Question]=@Question,");
            sb.Append("[Answer]=@Answer where [UserID]=@UserID");
            SqlParameter[] param = 
                                    {
                                        DBHelper.GetParameter("@UserID",SqlDbType.Int,4,"[UserID]",userid),
                                        DBHelper.GetParameter("@Password",SqlDbType.NVarChar,50,"[Password]",password),
                                        DBHelper.GetParameter("@Email",SqlDbType.NVarChar,50,"[Email]",email),
                                        DBHelper.GetParameter("@Question",SqlDbType.NVarChar,50,"[Question]",question),
                                        DBHelper.GetParameter("@Answer",SqlDbType.NVarChar,50,"[Answer]",answer)
                                    };
            return DBHelper.ExecuteSql(sb.ToString(), param);
        }

        #endregion
        #region 查
        /*  1.返回DataTable
         *  采用StringBuilder构造SQL语句,注意不可少了空格.
         *  构造输入参数SqlParameter数组,使用DBHelper.GetParmaeter()
         *  返回DBHelper.ExecuteDt()
         *      参考getUser()
         *  2.返回单值(字符串)
         *  判断(table.Rows.Count > 0),返回table.Rows[0]["Password"].ToString()或空字符串.
         *      参考researchPassword()
         *  3.返回单值(布尔)
         *  选择一个单值即可.
         *      参考validateUser()
         *  4.特例一:动态添加参数.用参数数组.
         *      参考getUserlist()
         *  List<SqlParameter> List 类是 ArrayList 类的泛型等效类。该类使用大小可按需动态增加的数组实现.
         *  这里简单当然动态数组使用.
         *  list.ToArray()转化为数组.
         */

        /// <summary>
        /// 找回用户密码
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="question">密码问题</param>
        /// <param name="answer">问题答案</param>
        /// <returns></returns>
        public string researchPassword(string username, string question, string answer)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select [Password] from UserInfo where [UserName]=@UserName ");
            sb.Append("and [Question]=@Question and [Answer]=@Answer");
            SqlParameter[] param = 
                                    {
                                        DBHelper.GetParameter("@UserName",SqlDbType.NVarChar,50,"[UserName]",username),
                                        DBHelper.GetParameter("@Question",SqlDbType.NVarChar,50,"[Question]",question),
                                        DBHelper.GetParameter("@Answer",SqlDbType.NVarChar,50,"[Answer]",answer)
                                    };
            DataTable table = DBHelper.ExecuteDt(sb.ToString(), param);
            if (table.Rows.Count > 0)
            {
                return table.Rows[0]["Password"].ToString();
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 获得一个用户资料
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public DataTable getUser(int userid)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select [UserID],[UserName],[Password],[Power],[Email],[Question],[Answer] ");
            sb.Append("from UserInfo where [UserID]=@UserID");
            SqlParameter[] param = { DBHelper.GetParameter("@UserID", SqlDbType.Int, 4, "[UserID]", userid) };
            return DBHelper.ExecuteDt(sb.ToString(), param);
        }
        /// <summary>
        /// 获得一个用户资料
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public DataTable getUser(string username)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select [UserID],[Password],[UserName],[Power],[Email],[Question],[Answer] ");
            sb.Append("from UserInfo where [UserName]=@UserName");
            SqlParameter[] param = { DBHelper.GetParameter("@UserName", SqlDbType.NVarChar, 50, "[UserName]", username) };
            return DBHelper.ExecuteDt(sb.ToString(), param);
        }
        /// <summary>
        /// 验证用户登陆
        /// </summary>
        /// <param name="username">用户名称</param>
        /// <param name="password">用户密码</param>
        /// <returns></returns>
        public bool validateUser(string username, string password, int power)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select [UserName] from UserInfo where [UserName]=@UserName ");
            sb.Append("and [Password]=@Password and [Power]=@Power");
            SqlParameter[] param = 
                                    {
                                        DBHelper.GetParameter("@UserName",SqlDbType.NVarChar,50,"[UserName]",username),
                                        DBHelper.GetParameter("@Password",SqlDbType.NVarChar,50,"[Password]",password),
                                        DBHelper.GetParameter("@Power",SqlDbType.Int,4,"[Power]",power)
                                    };
            DataTable table = DBHelper.ExecuteDt(sb.ToString(), param);
            if (table.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 用户名是否已经存在
        /// </summary>
        /// <param name="username">用户名称</param>
        /// <returns></returns>
        public bool IsExist(string username)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select [UserName] from UserInfo where [UserName]=@UserName ");
            SqlParameter[] param = 
                                    {
                                        DBHelper.GetParameter("@UserName",SqlDbType.NVarChar,50,"[UserName]",username),
                                    };
            DataTable table = DBHelper.ExecuteDt(sb.ToString(), param);
            if (table.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 获得一般用户或者管理员用户列表
        /// </summary>
        /// <param name="power"></param>
        /// <returns></returns>
        public DataTable getUserlist(string name, int power)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select [UserID],[UserName],[Password] from UserInfo where [Power]=@Power");
            List<SqlParameter> list = new List<SqlParameter>();
            list.Add(DBHelper.GetParameter("@Power", SqlDbType.Int, 4, "[Power]", power));

            if (name != "")
            {
                sb.Append(" and [UserName] like '%' + @UserName + '%'");
                list.Add(DBHelper.GetParameter("@UserName", SqlDbType.NVarChar, 50, "[UserName]", name));
            }

            return DBHelper.ExecuteDt(sb.ToString(), list.ToArray());
        }

        public DataSet getUserTest()
        {
            return DBHelper.ExecuteDs("select * from UserInfo");
        }

        #endregion

        #endregion

        #region BLL

        /*FormsAuthenticationTicket用于 Forms 身份验证对用户进行标识
         * 构造方法:(版本,用户名,票证发出日期,过期日期,是否跨浏览器,保存的数据,cookie路径)
         * 
         * FormsAuthentication提供了相应的方法和属性，您可以在需对用户进行身份验证的应用程序中使用它们
         * FormsCookiePath该属性取得cookie路径,
         * FormsCookieName名字cookie
         * Encrypt创建一个字符串，其中包含适用于 HTTP Cookie 的加密的 Forms 身份验证票证。
         */

        /// <summary>
        /// 设置COOKIE
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public void SetCookie(string username,int day)
        {
            DataTable table = getUser(username);
            if (table.Rows.Count > 0)
            {
                int userID = int.Parse(table.Rows[0]["UserID"].ToString());
                int power = int.Parse(table.Rows[0]["Power"].ToString());
                string userData = username.Replace(@"\", @"\\") + "#" + power.ToString();
                
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(60), false, userData, FormsAuthentication.FormsCookiePath);
                string encTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie newCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                //设置过期时间
                if (day > 0)
                {
                    newCookie.Expires = DateTime.Now.AddDays(day);//这里可以用AddDays(1d)
                }
                HttpContext.Current.Response.Cookies.Add(newCookie);
            }
        }
        /// <summary>
        /// 设置COOKIE
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public void SetCookie(string username)
        {
            DataTable table = getUser(username);
            if (table.Rows.Count > 0)
            {
                int userID = int.Parse(table.Rows[0]["UserID"].ToString());
                int power = int.Parse(table.Rows[0]["Power"].ToString());
                string userData = username.Replace(@"\", @"\\") + "#" + power.ToString();

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(60), false, userData, FormsAuthentication.FormsCookiePath);
                string encTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie newCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                HttpContext.Current.Response.Cookies.Add(newCookie);
            }
        }
        /// <summary>
        /// 判断用户是否登录
        /// </summary>
        /// <returns>已登录返回true</returns>
        public bool IsLogin()
        {
            return HttpContext.Current.User.Identity.IsAuthenticated;
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        public void Logout()
        {
            FormsAuthentication.SignOut();
        }
        /// <summary>
        /// 获取登录的用户ID
        /// </summary>
        /// <returns></returns>
        public int getUserID()
        {
            if (IsLogin())
            {
                return Convert.ToInt32(HttpContext.Current.User.Identity.Name);
            }
            else
            {
                return -1;
            }
        }
        /// <summary>
        /// 获得用户名
        /// </summary>
        /// <returns></returns>
        public string getUserName()
        {
            if (IsLogin())
            {
                string strUserData = ((FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData;
                string[] UserData = strUserData.Split(new string[] { @"#" }, StringSplitOptions.RemoveEmptyEntries);
                if (UserData.Length > 0)
                {
                    return UserData[0].Replace(@"\\", @"\");
                }
                else
                    return "";
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 返回用户的角色
        /// </summary>
        /// <returns></returns>
        public int getUserRole()
        {
            if (IsLogin())
            {
                string strUserData = ((FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData;
                string[] UserData = strUserData.Split(new string[] { @"#" }, StringSplitOptions.RemoveEmptyEntries);
                if (UserData.Length > 0)
                {
                    return Int32.Parse(UserData[1]);
                }
                else
                    return -1;
            }
            else
            {
                return -1;
            }
        }

        #endregion
        public UserInfo()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
    }
}