using System;
using System.Collections.Generic;
using System.Text;
using JuSNS.Factory;
using System.Data;
using System.Data.SqlClient;
using JuSNS.Profile;
using JuSNS.Config;
using JuSNS.Model;
using JuSNS.Common;

namespace JuSNS.SQLServer
{
    public class User : DbBase, IUser
    {
        /// <summary>
        /// 判断信箱是否已经注册
        /// </summary>
        /// <param name="UserEmail">用户Email</param>
        /// <returns></returns>
        public bool IsExist(string UserEmail)
        {
            SqlParameter param = new SqlParameter("@UserEmail", SqlDbType.NVarChar, 100);
            param.Value = UserEmail;
            string sql = "select count(UserID) from NT_User where Email=@UserEmail";
            int result = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, param).ToString());
            if (result == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="ui">用户对象</param>
        /// <returns>所影响的行数</returns>
        public EnumRegister Register(UserInfo ui, UserBasicInfo bi)
        {
            string verifyCode = Rand.Str(11);
            string RegVert = JuSNS.Common.Public.GetXMLValue("RegVer");
            bool isEmailVer = false;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                SqlParameter[] param = new SqlParameter[13];
                param[0] = new SqlParameter("@ReturnValue", SqlDbType.Int);
                param[0].Direction = ParameterDirection.ReturnValue;
                param[1] = new SqlParameter("@Email", SqlDbType.NVarChar, 100);
                param[1].Value = ui.Email;
                param[2] = new SqlParameter("@IP", SqlDbType.Char, 15);
                param[2].Value = Public.GetClientIP();
                param[3] = new SqlParameter("@Password", SqlDbType.NVarChar, 32);
                param[3].Value = JuSNS.Common.Input.MD5(ui.Password, false);
                param[4] = new SqlParameter("@Username", SqlDbType.NVarChar, 50);
                param[4].Value = ui.Username;
                param[5] = new SqlParameter("@State", SqlDbType.Int, 4);
                int isYanZhen = 0;
                if (RegVert == "1")
                {
                    isEmailVer = true;
                    isYanZhen = 0;
                }
                else
                {
                    isYanZhen = 2;
                }
                param[5].Value = isYanZhen;
                param[6] = new SqlParameter("@Province", SqlDbType.Int, 4);
                param[6].Value = ui.Province;
                param[7] = new SqlParameter("@City", SqlDbType.Int, 4);
                if (ui.City == 0)
                    param[7].Value = DBNull.Value;
                else
                    param[7].Value = ui.City;
                param[8] = new SqlParameter("@NowTime", SqlDbType.DateTime);
                param[8].Value = DateTime.Now;
                param[9] = new SqlParameter("@VerifyCode", SqlDbType.Char, 11);
                param[9].Value = verifyCode;
                param[10] = new SqlParameter("@EmailItem", SqlDbType.VarChar, 1000);
                param[10].Value = EnumClass.GetEmailNotifyStr();
                param[11] = new SqlParameter("@PrivDef", SqlDbType.Int);
                param[11].Value = (int)EnumPrivacy.ForWholeSite;
                param[12] = new SqlParameter("@Sex", SqlDbType.Int);
                param[12].Value = bi.Sex;
                DbHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, "JuSNS_Register", param);
                int retvalue = (int)param[0].Value;
                switch (retvalue)
                {
                    case 1:
                        #region 注册成功发送邮件
                        try
                        {
                            int actv = 0;
                            //插入默认好友
                            if (isYanZhen ==2)
                            {
                                string qsql = "select UserID from NT_User where Email='" + ui.Email + "'";
                                int UserID = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, qsql, param));
                                InserDefaultFriend(UserID);
                                actv = 0;
                            }
                            else
                            {
                                actv = 1;
                            }
                            if (isEmailVer)
                            {
                                JuSNS.Common.EMail em = JuSNS.Common.EMail.CreateInstance();
                                string body = EmailConfig.register;
                                body = body.Replace("{SiteName}", UiConfig.SiteName);
                                body = body.Replace("{UserName}", ui.Username);
                                body = body.Replace("{Domain}", UiConfig.Domain);
                                body = body.Replace("{Date}", DateTime.Now.ToString("yyyy年MM月dd日"));
                                body = body.Replace("{Url}", UiConfig.RootUrl + "/RegVerify.aspx?active=" + actv + "&r=" + verifyCode + "&e=" + JuSNS.Common.Input.URLEncode(ui.Email));
                                em.Body = body;
                                em.Subject = "亲爱的" + ui.Username + "，请确认你在" + UiConfig.SiteName + "的注册邮箱";
                                em.To = ui.Email;
                                em.From = UiConfig.SiteName + "<" + EmailConfig.from + ">";
                                em.Send();
                                return EnumRegister.Succeed;
                            }
                            else
                            {
                                return EnumRegister.SucceedNotMail;
                            }
                        }
                        catch
                        {
                            return EnumRegister.EmailMayNotSend;
                        }
                        #endregion
                    case 2:
                        return EnumRegister.EmailRepeat;
                    default:
                        return EnumRegister.UnexpectedError;

                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        public int InserDefaultFriend(int UserID)
        {
            int riCount = 0;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                DateTime now = DateTime.Now;
                string dfriend = JuSNS.Common.Public.GetXMLValue("defaultfriend");
                string[] dfriendARR = null;
                if (!string.IsNullOrEmpty(dfriend))
                {
                    if (dfriend.IndexOf(",") > -1)
                    {
                        dfriendARR = dfriend.Split(',');
                        string iSQL = string.Empty;
                        for (int j = 0; j < dfriendARR.Length; j++)
                        {
                            if (UserID.ToString() != dfriendARR[j].ToString())
                            {
                                iSQL = "insert into NT_Friend (UserID,FriendID,State,AddTime,FDegree,ClassID) values (" + UserID + "," + dfriendARR[j].ToString() + ",0,'" + now.ToString() + "',0,0)";
                                iSQL += "insert into NT_Friend (UserID,FriendID,State,AddTime,FDegree,ClassID) values (" + dfriendARR[j].ToString() + "," + UserID + ",0,'" + now.ToString() + "',0,0)";
                                riCount = DbHelper.ExecuteNonQuery(cn, CommandType.Text, iSQL, null);
                            }
                        }
                    }
                    else
                    {
                        if (UserID.ToString() != dfriend)
                        {
                            string reiSQL = "insert into NT_Friend (UserID,FriendID,State,AddTime,FDegree,ClassID) values (" + dfriend + "," + UserID + ",0,'" + now.ToString() + "',0,0)";
                            reiSQL += "insert into NT_Friend (UserID,FriendID,State,AddTime,FDegree,ClassID) values (" + UserID + "," + dfriend + ",0,'" + now.ToString() + "',0,0)";
                            riCount = DbHelper.ExecuteNonQuery(cn, CommandType.Text, reiSQL, null);
                        }
                    }
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
            return riCount;
        }
        /// <summary>
        /// 注册确认,验证后同时设置最后登录
        /// </summary>
        /// <param name="code"></param>
        /// <param name="userId"></param>
        /// <param name="email"></param>
        /// <param name="userName"></param>
        /// <param name="md5Password"></param>
        /// <returns>0成功,-1验证码不正确,-2该用户已通过验证,-3数据修改失败</returns>
        public int RegisterConfirm(string code, string email, out int userId, out string userName, out string md5Password)
        {
            userId = 0;
            userName = string.Empty;
            md5Password = string.Empty;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                EnumUserState state = EnumUserState.Normal;
                bool f = false;
                int inviter = 0;
                SqlParameter[] Param = new SqlParameter[2];
                Param[0] = new SqlParameter("@VerifyCode", SqlDbType.NVarChar, 12);
                Param[0].Value = code;
                Param[1] = new SqlParameter("@email", SqlDbType.NVarChar, 100);
                Param[1].Value = email;
                string Sql = "select UserID,UserName,Password,State,InviterID from NT_User where VerifyCode=@VerifyCode and Email=@email";
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, Param);
                if (rd.Read())
                {
                    userId = rd.GetInt32(0);
                    userName = rd.GetString(1);
                    md5Password = rd.GetString(2);
                    state = (EnumUserState)rd.GetInt32(3);
                    if (!rd.IsDBNull(4)) inviter = rd.GetInt32(4);
                    f = true;
                }
                rd.Close();
                if (!f)
                {
                    return -1;
                }
                if (state == EnumUserState.Normal)
                {
                    return -2;
                }
                bool isEmailNotSend = false;
                if (state == EnumUserState.NormalNotEmail)
                {
                    isEmailNotSend = true;
                }
                Sql = "select count(ID) from NT_Friend where (UserID=" + userId + " and FriendID=" + inviter + ") or (UserID=" + inviter + " and FriendID=" + userId + ")";
                int m = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                DateTime now = DateTime.Now;
                SqlTransaction trans = cn.BeginTransaction();
                JUser ju = new JUser();
                try
                {
                    Sql = "update NT_User set State=" + (int)EnumUserState.Normal + ",LastLoginTime='" + now + "',LastLoginIP='" + Public.GetClientIP() + "',ConfirmTime='" + now + "' where VerifyCode=@VerifyCode";
                    int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, Param);
                    if (!isEmailNotSend)
                    {
                        if (inviter > 0 && m == 0)
                        {
                            Sql = "insert into NT_Friend (UserID,FriendID,State,AddTime) values (" + userId + "," + inviter + ",0,'" + now + "')";
                            n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                            Sql = "insert into NT_Friend (UserID,FriendID,State,AddTime) values (" + inviter + "," + userId + ",0,'" + now + "')";
                            n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                            if (ju.CheckPrivacyInfo(trans, userId, "ActAddFriend"))
                            {
                                n += UserDyn(trans, 0, 0, "inviteJoin", userId, inviter, inviter, "邀请加入了", inviter.ToString());
                            }
                        }
                    }
                    else
                    {
                        if (ju.CheckPrivacyInfo(trans, userId, "ActUpdateData"))
                        {
                            n += UserDyn(trans, 0, 0, "vEmail", userId, userId, userId, "验证了电子邮件", userId.ToString());
                        }
                    }
                    trans.Commit();
                    if (n > 0)
                    {
                        if (state == 0)
                        {
                            InserDefaultFriend(userId);
                        }
                        return 0;
                    }
                    else
                        return -3;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        public int EmailActive(string email,UserInfo ui)
        {
            try
            {
                SqlParameter param = new SqlParameter("@email", email);
                //获取verifyCode
                string sql = "select VerifyCode,state from NT_user where email=@email";
                string verifyCode = string.Empty;
                int stat = 0;
                IDataReader dr = DbHelper.ExecuteReader(CommandType.Text, sql, param);
                if (dr.Read())
                {
                    verifyCode = dr["VerifyCode"].ToString();
                    stat = Convert.ToInt32(dr["state"].ToString());
                }
                dr.Close();
                if (stat == 5)
                {
                    return 2;
                }
                EMail em = EMail.CreateInstance();
                string body = EmailConfig.emailactive;
                body = body.Replace("{SiteName}", UiConfig.SiteName);
                body = body.Replace("{UserName}", email);
                body = body.Replace("{Domain}", UiConfig.Domain);
                body = body.Replace("{Date}", DateTime.Now.ToString("yyyy年MM月dd日"));
                body = body.Replace("{Url}", UiConfig.RootUrl + "/RegVerify.aspx?active=0&r=" + verifyCode + "&e=" + JuSNS.Common.Input.URLEncode(ui.Email));
                em.Body = body;
                em.Subject = "尊敬的用户，激活您在" + UiConfig.SiteName + "的邮件帐号";
                em.To = ui.Email;
                em.From = UiConfig.SiteName + "<" + EmailConfig.from + ">";
                em.Send();
                return 0;
            }
            catch
            {
                return 1;
            }
        }

        /// <summary>
        /// 邀请用户注册
        /// </summary>
        /// <param name="ui"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public EnumRegister InviterRegister(UserInfo ui, UserBasicInfo bi, EnumFriendInviteMode mode, string code, out int userId)
        {
            userId = 0;
            if (mode == EnumFriendInviteMode.Email)
                return EmailRegister(ui,bi, code, out userId);
            else
                return UrlRegister(ui,bi, int.Parse(code), out userId);
        }
        /// <summary>
        /// Url邀请注册
        /// </summary>
        /// <param name="ui"></param>
        /// <param name="code"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        EnumRegister UrlRegister(UserInfo ui, UserBasicInfo bi, int Inviter, out int userId)
        {
            string verifyCode = Rand.Str(11);
            userId = 0;
            string RegVert = JuSNS.Common.Public.GetXMLValue("RegVer");
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                SqlParameter[] param = new SqlParameter[15];
                param[0] = new SqlParameter("@ReturnValue", SqlDbType.Int);
                param[0].Direction = ParameterDirection.ReturnValue;
                param[1] = new SqlParameter("@InviterID", SqlDbType.Int);
                param[1].Value = Inviter;
                param[2] = new SqlParameter("@Email", SqlDbType.NVarChar, 100);
                param[2].Value = ui.Email;
                param[3] = new SqlParameter("@IP", SqlDbType.Char, 15);
                param[3].Value = Public.GetClientIP();
                param[4] = new SqlParameter("@Password", SqlDbType.NVarChar, 32);
                param[4].Value = JuSNS.Common.Input.MD5(ui.Password, false);
                param[5] = new SqlParameter("@Username", SqlDbType.NVarChar, 50);
                param[5].Value = ui.Username;
                param[6] = new SqlParameter("@State", SqlDbType.Int, 4);
                //param[6].Value = (int)EnumUserState.Register;
                if (RegVert == "1")
                {
                    param[6].Value = (int)EnumUserState.Register;
                }
                else
                {
                    param[6].Value = (int)EnumUserState.NormalNotEmail;
                }
                param[7] = new SqlParameter("@Province", SqlDbType.Int, 4);
                param[7].Value = ui.Province;
                param[8] = new SqlParameter("@City", SqlDbType.Int, 4);
                if (ui.City == 0)
                    param[8].Value = DBNull.Value;
                else
                    param[8].Value = ui.City;
                param[9] = new SqlParameter("@NowTime", SqlDbType.DateTime);
                param[9].Value = DateTime.Now;
                param[10] = new SqlParameter("@VerifyCode", SqlDbType.Char, 11);
                param[10].Value = verifyCode;
                param[11] = new SqlParameter("@EmailItem", SqlDbType.VarChar, 1000);
                param[11].Value = EnumClass.GetEmailNotifyStr();
                param[12] = new SqlParameter("@PrivDef", SqlDbType.Int);
                param[12].Value = (int)EnumPrivacy.ForWholeSite;
                param[13] = new SqlParameter("@NewUid", SqlDbType.Int);
                param[13].Direction = ParameterDirection.Output;
                param[14] = new SqlParameter("@Sex", SqlDbType.Int);
                param[14].Value = bi.Sex;
                DbHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, "NTP_UrlRegister", param);
                int retvalue = (int)param[0].Value;
                switch (retvalue)
                {
                    case 1:
                        #region 注册成功发送邮件
                        userId = (int)param[13].Value;
                        try
                        {
                           //插入默认好友
                            InserDefaultFriend(userId);
                            if (RegVert == "1")
                            {
                                JuSNS.Common.EMail em = JuSNS.Common.EMail.CreateInstance();
                                string body = EmailConfig.register;
                                body = body.Replace("{SiteName}", UiConfig.SiteName);
                                body = body.Replace("{UserName}", ui.Username);
                                body = body.Replace("{Domain}", UiConfig.Domain);
                                body = body.Replace("{Date}", DateTime.Now.ToString("yyyy年MM月dd日"));
                                body = body.Replace("{Url}", UiConfig.RootUrl + "/RegVerify.aspx?r=" + verifyCode);
                                em.Body = body;
                                em.Subject = "亲爱的" + ui.Username + "，请确认你在" + UiConfig.SiteName + "的注册邮箱";
                                em.To = ui.Email;
                                em.From = UiConfig.SiteName + "<" + EmailConfig.from + ">";
                                em.Send();
                            }
                            return EnumRegister.Succeed;
                        }
                        catch
                        {
                            return EnumRegister.EmailMayNotSend;
                        }
                        #endregion
                    case 2:
                        return EnumRegister.EmailRepeat;
                    default:
                        return EnumRegister.UnexpectedError;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// Email邀请注册
        /// </summary>
        /// <param name="ui"></param>
        /// <param name="code"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        EnumRegister EmailRegister(UserInfo ui, UserBasicInfo bi, string code, out int userId)
        {
            userId = 0;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                SqlParameter[] param = new SqlParameter[14];
                param[0] = new SqlParameter("@ReturnValue", SqlDbType.Int);
                param[0].Direction = ParameterDirection.ReturnValue;
                param[1] = new SqlParameter("@Email", SqlDbType.NVarChar, 100);
                param[1].Value = ui.Email;
                param[2] = new SqlParameter("@IP", SqlDbType.Char, 15);
                param[2].Value = Public.GetClientIP();
                param[3] = new SqlParameter("@Password", SqlDbType.NVarChar, 32);
                param[3].Value = JuSNS.Common.Input.MD5(ui.Password, false);
                param[4] = new SqlParameter("@Username", SqlDbType.NVarChar, 50);
                param[4].Value = ui.Username;
                param[5] = new SqlParameter("@State", SqlDbType.Int, 4);
                param[5].Value = (int)EnumUserState.Normal;
                param[6] = new SqlParameter("@Province", SqlDbType.Int, 4);
                param[6].Value = ui.Province;
                param[7] = new SqlParameter("@City", SqlDbType.Int, 4);
                if (ui.City == 0)
                    param[7].Value = DBNull.Value;
                else
                    param[7].Value = ui.City;
                param[8] = new SqlParameter("@NowTime", SqlDbType.DateTime);
                param[8].Value = DateTime.Now;
                param[9] = new SqlParameter("@EmailItem", SqlDbType.VarChar, 1000);
                param[9].Value = EnumClass.GetEmailNotifyStr();
                param[10] = new SqlParameter("@Code", SqlDbType.Char, 11);
                param[10].Value = code;
                param[11] = new SqlParameter("@PrivDef", SqlDbType.Int);
                param[11].Value = (int)EnumPrivacy.ForWholeSite;
                param[12] = new SqlParameter("@NewUid", SqlDbType.Int);
                param[12].Direction = ParameterDirection.Output;
                param[13] = new SqlParameter("@Sex", SqlDbType.Int);
                param[13].Value = bi.Sex;
                DbHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, "NTP_InviterRegister", param);
                int retvalue = (int)param[0].Value;
                switch (retvalue)
                {
                    case 1:
                        userId = (int)param[12].Value;
                        InserDefaultFriend(userId);
                        return EnumRegister.Succeed;
                    case 2:
                        return EnumRegister.InvalidCode;
                    case 3:
                        return EnumRegister.RegInviteCode;
                    case 4:
                        return EnumRegister.EmailRepeat;
                    default:
                        return EnumRegister.UnexpectedError;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 获取用户对象数据库参数数组
        /// </summary>
        /// <param name="ui">用户对象</param>
        /// <returns>用户对象数据库参数数组</returns>
        private SqlParameter[] GetParam(UserInfo ui)
        {
            SqlParameter[] param = new SqlParameter[7];
            param[0] = new SqlParameter("@Email", SqlDbType.NVarChar, 100);
            param[0].Value = ui.Email;
            param[1] = new SqlParameter("@Password", SqlDbType.NVarChar, 32);
            param[1].Value = ui.Password;
            param[2] = new SqlParameter("@Username", SqlDbType.NVarChar, 50);
            param[2].Value = ui.Username;
            param[3] = new SqlParameter("@State", SqlDbType.Int, 4);
            param[3].Value = ui.State;
            param[4] = new SqlParameter("@Province", SqlDbType.Int, 4);
            param[4].Value = ui.Province;
            param[5] = new SqlParameter("@City", SqlDbType.Int, 4);
            if (ui.City == 0)
                param[5].Value = DBNull.Value;
            else
                param[5].Value = ui.City;
            param[6] = new SqlParameter("@Portrait", SqlDbType.Int, 4);
            param[6].Value = ui.Portrait;
            return param;
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="Email">用户Email</param>
        /// <returns></returns>
        public int Exit(int userID)
        {
            return 1;
        }


        /// <summary>
        /// 修改Email
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="Email">新Email</param>
        /// <returns></returns>
        public int ChangeEmail(int UserID, string Email)
        {
            SqlConnection sqlConn = new SqlConnection(DBConfig.CnString);
            sqlConn.Open();
            SqlTransaction trans = sqlConn.BeginTransaction();
            try
            {
                SqlParameter param = new SqlParameter("@Email", SqlDbType.NVarChar, 100);
                param.Value = Email;
                string sql = "update NT_User set Email=@Email where UserID=" + UserID.ToString();
                int n =DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, param);
                trans.Commit();
                return n;
            }
            catch (SqlException sqlEx)
            {
                trans.Rollback();
                throw sqlEx;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="Password">新Password</param>
        /// <returns></returns>
        public int ChangePassword(int UserID, string Password)
        {
            SqlParameter param = new SqlParameter("@Password", SqlDbType.NChar, 32);
            param.Value = JuSNS.Common.Input.MD5(Password, false);
            string sql = "update NT_User set Password=@Password where UserID=" + UserID.ToString();
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
        }
        /// <summary>
        /// 修改所在地
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="Province">省份</param>
        /// <param name="City">城市</param>
        /// <returns></returns>
        public int ChangeAddr(int UserID, int Province, int City)
        {
            SqlConnection sqlConn = new SqlConnection(DBConfig.CnString);
            sqlConn.Open();
            SqlTransaction trans = sqlConn.BeginTransaction();
            try
            {
                string sql = "update NT_User set Province=" + Province.ToString() + ",City=" + City.ToString() + " where UserID=" + UserID.ToString();
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, null);
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, UserID, "ActUpdateData"))
                {
                    n += UserDyn(trans, 0, 0, "infoAddress", UserID, UserID, UserID, "修改了所在地", UserID.ToString());
                }
                trans.Commit();
                return n;
            }
            catch (SqlException sqlEx)
            {
                trans.Rollback();
                throw sqlEx;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }
        /// <summary>
        /// 保存MSN
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="MSN">MSN帐号</param>
        /// <returns></returns>
        public int ChangeMSN(int UserID, string MSN)
        {
            SqlConnection sqlConn = new SqlConnection(DBConfig.CnString);
            sqlConn.Open();
            SqlTransaction trans = sqlConn.BeginTransaction();
            try
            {
                SqlParameter param = new SqlParameter("@MSN", SqlDbType.NVarChar, 50);
                param.Value = MSN;
                string sql = "update NT_UserInfo set MSN=@MSN where UserID=" + UserID.ToString();
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, param);
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, UserID, "ActUpdateData"))
                {
                    n += UserDyn(trans, 0, 0, "infolink", UserID, UserID, UserID, "修改了联系方式(MSN)", UserID.ToString());
                }
                trans.Commit();
                return n;
            }
            catch (SqlException sqlEx)
            {
                trans.Rollback();
                throw sqlEx;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }
        /// <summary>
        /// 保存GTalk
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="MSN">GTalk帐号</param>
        /// <returns></returns>
        public int ChangeGTalk(int UserID, string GTalk)
        {
            SqlConnection sqlConn = new SqlConnection(DBConfig.CnString);
            sqlConn.Open();
            SqlTransaction trans = sqlConn.BeginTransaction();
            try
            {
                SqlParameter param = new SqlParameter("@GTalk", SqlDbType.NVarChar, 50);
                param.Value = GTalk;
                string sql = "update NT_UserInfo set GTalk=@GTalk where UserID=" + UserID.ToString();
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, param);
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, UserID, "ActUpdateData"))
                {
                    n += UserDyn(trans, 0, 0, "infolink", UserID, UserID, UserID, "修改了联系方式(GTalk)", UserID.ToString());
                }
                trans.Commit();
                return n;
            }
            catch (SqlException sqlEx)
            {
                trans.Rollback();
                throw sqlEx;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }
        /// <summary>
        /// 保存Mobile
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="MSN">Mobile帐号</param>
        /// <returns></returns>
        public int ChangeMobile(int UserID, string Mobile)
        {
            SqlConnection sqlConn = new SqlConnection(DBConfig.CnString);
            sqlConn.Open();
            SqlTransaction trans = sqlConn.BeginTransaction();
            try
            {
                SqlParameter param = new SqlParameter("@Mobile", SqlDbType.NChar, 15);
                param.Value = Mobile;
                string sql = "update NT_UserInfo set Mobile=@Mobile where UserID=" + UserID.ToString();
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, param);
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, UserID, "ActUpdateData"))
                {
                    n += UserDyn(trans, 0, 0, "infolink", UserID, UserID, UserID, "修改了联系方式(手机)", UserID.ToString());
                }
                trans.Commit();
                return n;
            }
            catch (SqlException sqlEx)
            {
                trans.Rollback();
                throw sqlEx;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }
        #region 检查登录
        /// <summary>
        /// 登录
        /// </summary>
        public EnumLoginState Login(string email, string password, out int userId, out string userName, out string portrait, out int loginNum)
        {
            userId = -1;
            userName = string.Empty;
            portrait = string.Empty;
            loginNum = 0;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string pwd = string.Empty;
                EnumUserState us = EnumUserState.Lock;
                SqlParameter param = new SqlParameter("@Email", email);
                bool exist = false;
                int headpic = 0;
                string Sql = "select UserID,UserName,Password,State,Portrait,loginTimes from NT_User where Email=@Email";
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, param);
                if (rd.Read())
                {
                    userId = rd.GetInt32(0);
                    userName = rd.GetString(1);
                    pwd = rd.GetString(2);
                    loginNum = rd.GetInt32(5);
                    us = (EnumUserState)rd.GetInt32(3);
                    if (!rd.IsDBNull(4)) headpic = rd.GetInt32(4);
                    exist = true;
                }
                rd.Close();
                if (!exist || pwd == string.Empty || pwd != JuSNS.Common.Input.MD5(password, false))
                {
                    return EnumLoginState.Err_NameOrPwdError;
                }
                if (us == EnumUserState.Register)
                {
                    return EnumLoginState.Err_UnActivation;
                }
                else if (us == EnumUserState.Lock)
                {
                    return EnumLoginState.Err_Locked;
                }
                if (headpic > 0)
                {
                    Sql = "select FilePath from NT_Photo where PhotoID=" + headpic;
                    portrait = Convert.ToString(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null));
                }
                Sql = "update NT_User set LastLoginTime='" + DateTime.Now + "',LastLoginIP='" + JuSNS.Common.Public.GetClientIP() + "',LoginTimes=LoginTimes+1 where UserID=" + userId;
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
                return EnumLoginState.Succeed;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 检查登录
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public EnumLoginState CheckLogin(int userId, string password, out int loginNum)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                int lNum = 0;
                string pwd = string.Empty;
                EnumUserState us = EnumUserState.Lock;
                bool exist = false;
                string Sql = "select Password,State,LoginTimes from NT_User where UserID=" + userId;
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                if (rd.Read())
                {
                    pwd = rd.GetString(0);
                    us = (EnumUserState)rd.GetInt32(1);
                    exist = true;
                    lNum = rd.GetInt32(2);
                }
                loginNum = lNum;
                rd.Close();
                if (!exist || pwd == string.Empty || pwd != password)
                    return EnumLoginState.Err_NameOrPwdError;
                if (us == EnumUserState.Register)
                    return EnumLoginState.Err_UnActivation;
                else if (us == EnumUserState.Lock)
                    return EnumLoginState.Err_Locked;
                return EnumLoginState.Succeed;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        #endregion
        /// <summary>
        /// 获取用户实体类
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public UserInfo GetUserInfo(int UserID)
        {
            UserInfo UInfo = new UserInfo();
            UInfo.UserID = UserID;
            string sql = "select a.*,b.FilePath from NT_User a left join NT_Photo b on a.Portrait=b.PhotoID and b.IsLock=0 where UserID=" + UserID;
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, sql, null);
            if (rd.Read())
            {
                UInfo.Email = rd["Email"].ToString();
                UInfo.Password = rd["Password"].ToString();
                UInfo.Username = rd["Username"].ToString();
                UInfo.State = (EnumUserState)(int)rd["State"];
                if (rd["LastLoginTime"] != DBNull.Value) UInfo.LastLoginTime = (DateTime)rd["LastLoginTime"];
                if (rd["LastLoginIp"] != DBNull.Value) UInfo.LastLoginIp = rd["LastLoginIp"].ToString();
                UInfo.LoginTimes = (int)rd["LoginTimes"];
                UInfo.Province = (int)rd["Province"];
                if (rd["City"] != DBNull.Value) UInfo.City = (int)rd["City"];
                UInfo.RegTime = (DateTime)rd["RegTime"];
                UInfo.RegIP = rd["RegIP"].ToString();
                if (rd["Portrait"] != DBNull.Value) UInfo.Portrait = (int)rd["Portrait"];
                if (rd["FilePath"] != DBNull.Value) UInfo.PortraitDir = (string)rd["FilePath"];
                if (rd["integral"] != DBNull.Value) UInfo.integral = (int)rd["integral"];
                if (rd["inteyb"] != DBNull.Value) UInfo.inteyb = (int)rd["inteyb"];
                if (rd["Click"] != DBNull.Value) UInfo.Click = (int)rd["Click"];
                if (rd["InviterID"] != DBNull.Value) UInfo.InviterID = (int)rd["InviterID"];
            }
            rd.Close();
            return UInfo;
        }

        /// <summary>
        /// 获取用户基本信息实体类
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public UserBasicInfo GetUserBasic(int UserID)
        {
            UserBasicInfo UBasicInfo = new UserBasicInfo();
            UBasicInfo.UserID = UserID;
            string sql = "select * from NT_UserInfo where UserID=" + UserID.ToString();
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, sql, null);
            if (rd.Read())
            {
                UBasicInfo.Sex = Convert.ToInt32(rd["Sex"]);
                if (rd["Birthday"] != DBNull.Value) UBasicInfo.Birthday = (DateTime)rd["Birthday"];
                if (rd["BirthidayDisplay"] != DBNull.Value) UBasicInfo.BirthidayDisplay = (int)rd["BirthidayDisplay"];
                if (rd["Constellation"] != DBNull.Value) UBasicInfo.Constellation = (int)rd["Constellation"];
                UBasicInfo.MSN = Convert.ToString(rd["MSN"]);
                UBasicInfo.GTalk = Convert.ToString(rd["GTalk"]);
                UBasicInfo.QQ = Convert.ToString(rd["QQ"]);
                UBasicInfo.Skype = Convert.ToString(rd["Skype"]);
                UBasicInfo.Mobile = Convert.ToString(rd["Mobile"]);
                if (rd["MobilePrivacy"] != DBNull.Value) UBasicInfo.MobilePrivacy = (int)rd["MobilePrivacy"];
                if (rd["EmailPrivacy"] != DBNull.Value) UBasicInfo.EmailPrivacy = (int)rd["EmailPrivacy"];
                UBasicInfo.Tel = Convert.ToString(rd["Tel"]);
                UBasicInfo.Addr = Convert.ToString(rd["Addr"]);
                UBasicInfo.WebSite = Convert.ToString(rd["WebSite"]);
                UBasicInfo.Favourite = Convert.ToString(rd["Favourite"]);
                UBasicInfo.FavMusics = Convert.ToString(rd["FavMusics"]);
                UBasicInfo.FavMovies = Convert.ToString(rd["FavMovies"]);
                UBasicInfo.FavCartoons = Convert.ToString(rd["FavCartoons"]);
                UBasicInfo.FavGames = Convert.ToString(rd["FavGames"]);
                UBasicInfo.FavSports = Convert.ToString(rd["FavSports"]);
                UBasicInfo.FavBooks = Convert.ToString(rd["FavBooks"]);
                UBasicInfo.FavAdages = Convert.ToString(rd["FavAdages"]);
                UBasicInfo.AppreciateMen = Convert.ToString(rd["AppreciateMen"]);
                UBasicInfo.Presetation = Convert.ToString(rd["Presentation"]);
                if (rd["Vocation"] != DBNull.Value) UBasicInfo.Vocation = (int)rd["Vocation"];
                if (rd["MSNPrivacy"] != DBNull.Value) UBasicInfo.MSNPrivacy = (int)rd["MSNPrivacy"];
                if (rd["GTalkPrivacy"] != DBNull.Value) UBasicInfo.GTalkPrivacy = (int)rd["GTalkPrivacy"];
                if (rd["QQPrivacy"] != DBNull.Value) UBasicInfo.QQPrivacy = (int)rd["QQPrivacy"];
                if (rd["SkypePrivacy"] != DBNull.Value) UBasicInfo.SkypePrivacy = (int)rd["SkypePrivacy"];
                if (rd["TelPrivacy"] != DBNull.Value) UBasicInfo.TelPrivacy = (int)rd["TelPrivacy"];
                if (rd["AddrPrivacy"] != DBNull.Value) UBasicInfo.AddrPrivacy = (int)rd["AddrPrivacy"];
                if (rd["WebSitePrivacy"] != DBNull.Value) UBasicInfo.WebSitePrivacy = (int)rd["WebSitePrivacy"];
                if (rd["HomeProv"] != DBNull.Value) UBasicInfo.HomeProv = (int)rd["HomeProv"];
                if (rd["HomeCity"] != DBNull.Value) UBasicInfo.HomeCity = (int)rd["HomeCity"];
            }
            rd.Close();
            return UBasicInfo;
        }
        #region
        //编辑（个人信息）
        /// <summary>
        /// 保存基本信息
        /// </summary>
        /// <param name="ubi">用户基本信息对象</param>
        /// <param name="Province">省份</param>
        /// <param name="City">城市</param>
        /// <returns></returns>
        public int SaveBasic(JuSNS.Model.UserBasicInfo ubi, int Province, int City)
        {
            SqlConnection sqlConn = new SqlConnection(DBConfig.CnString);
            sqlConn.Open();
            SqlTransaction trans = sqlConn.BeginTransaction();
            try
            {
                SqlParameter[] param = GetUserBasic(ubi, Province, City);
                string sql = "update NT_UserInfo set Sex=@Sex,Birthday=@Birthday,BirthidayDisplay=@BirthidayDisplay,Constellation=@Constellation,Province=@Province,City=@City where UserID=@UserID";
                int n = DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, ubi.UserID, "ActUpdateData"))
                {
                    n += UserDyn(trans, 0, 0, "info", ubi.UserID, ubi.UserID, ubi.UserID, "修改了个人信息", ubi.UserID.ToString());
                }
                trans.Commit();
                return n;
            }
            catch (SqlException sqlEx)
            {
                trans.Rollback();
                throw sqlEx;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }
        /// <summary>
        /// 获取用户基本信息数据库参数数组
        /// </summary>
        /// <param name="ubi">用户基本信息对象</param>
        /// <param name="Province">省份</param>
        /// <param name="City">城市</param>
        /// <returns></returns>
        private SqlParameter[] GetUserBasic(JuSNS.Model.UserBasicInfo ubi, int Province, int City)
        {
            SqlParameter[] param = new SqlParameter[7];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = ubi.UserID;
            param[1] = new SqlParameter("@Sex", SqlDbType.Bit, 1);
            param[1].Value = ubi.Sex;
            param[2] = new SqlParameter("@Birthday", SqlDbType.DateTime, 8);
            param[2].Value = ubi.Birthday;
            param[3] = new SqlParameter("@BirthidayDisplay", SqlDbType.Int, 4);
            param[3].Value = ubi.BirthidayDisplay;
            param[4] = new SqlParameter("@Constellation", SqlDbType.Int, 4);
            param[4].Value = ubi.Constellation;
            param[5] = new SqlParameter("@Province", SqlDbType.Int, 4);
            param[5].Value = Province;
            param[6] = new SqlParameter("@City", SqlDbType.Int, 4);
            param[6].Value = City;
            return param;
        }

        /// <summary>
        /// 获取个人爱好数据库参数数组
        /// </summary>
        /// <param name="ubi">用户基本信息对象</param>
        /// <returns></returns>
        private SqlParameter[] GetFavorite(JuSNS.Model.UserBasicInfo ubi)
        {
            SqlParameter[] param = new SqlParameter[11];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = ubi.UserID;
            param[1] = new SqlParameter("@Favourite", SqlDbType.NVarChar, 200);
            param[1].Value = ubi.Favourite;
            param[2] = new SqlParameter("@FavMusics", SqlDbType.NVarChar, 200);
            param[2].Value = ubi.FavMusics;
            param[3] = new SqlParameter("@FavMovies", SqlDbType.NVarChar, 200);
            param[3].Value = ubi.FavMovies;
            param[4] = new SqlParameter("@FavCartoons", SqlDbType.NVarChar, 200);
            param[4].Value = ubi.FavCartoons;
            param[5] = new SqlParameter("@FavGames", SqlDbType.NVarChar, 200);
            param[5].Value = ubi.FavGames;
            param[6] = new SqlParameter("@FavSports", SqlDbType.NVarChar, 200);
            param[6].Value = ubi.FavSports;
            param[7] = new SqlParameter("@FavBooks", SqlDbType.NVarChar, 200);
            param[7].Value = ubi.FavBooks;
            param[8] = new SqlParameter("@FavAdages", SqlDbType.NVarChar, 200);
            param[8].Value = ubi.FavAdages;
            param[9] = new SqlParameter("@AppreciateMen", SqlDbType.NVarChar, 200);
            param[9].Value = ubi.AppreciateMen;
            param[10] = new SqlParameter("@Presentation", SqlDbType.NVarChar, 200);
            param[10].Value = ubi.Presetation;
            return param;
        }

        /// <summary>
        /// 获取个人联系信息数据库参数数组
        /// </summary>
        /// <param name="ubi">用户基本信息对象</param>
        /// <returns></returns>
        private SqlParameter[] GetContact(JuSNS.Model.UserBasicInfo ubi)
        {
            SqlParameter[] param = new SqlParameter[7];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = ubi.UserID;
            param[0] = new SqlParameter("@QQ", SqlDbType.NVarChar, 20);
            param[0].Value = ubi.QQ;
            param[0] = new SqlParameter("@Skype", SqlDbType.NVarChar, 50);
            param[0].Value = ubi.Skype;
            param[0] = new SqlParameter("@Mobile", SqlDbType.Char, 15);
            param[0].Value = ubi.Mobile;
            param[0] = new SqlParameter("@Tel", SqlDbType.Char, 20);
            param[0].Value = ubi.Tel;
            param[0] = new SqlParameter("@Addr", SqlDbType.NVarChar, 100);
            param[0].Value = ubi.Addr;
            param[0] = new SqlParameter("@WebSite", SqlDbType.NVarChar, 50);
            param[0].Value = ubi.WebSite;
            return param;
        }
        /// <summary>
        /// 保存教育信息
        /// </summary>
        /// <param name="listEdu">教育信息对象数组</param>
        /// <returns></returns>
        public int SaveEducation(List<JuSNS.Model.UserEducationInfo> listEdu)
        {
            SqlParameter[] param = null;
            int num = 0;
            for (int i = 0; i < listEdu.Count; i++)
            {
                //判断是否已经有ID
                param = GetEducation(listEdu[i]);
                string sqlIsExist = "select ID from NT_UserEducation where ID=" + listEdu[i].ID.ToString();
                string result = Convert.ToString(DbHelper.ExecuteScalar(CommandType.Text, sqlIsExist, null));
                if (result == listEdu[i].ID.ToString())
                {
                    string sqlUpdate = "update NT_UserEducation set DegreeID=@DegreeID,SchoolID=@SchoolID,AcademyID=@AcademyID,MatriculationYear=@MatriculationYear,PostTime='" + DateTime.Now.ToString() + "',PostIP='" + JuSNS.Common.Public.GetClientIP() + "' where ID=@ID and  UserID=@UserID";
                    num = DbHelper.ExecuteNonQuery(CommandType.Text, sqlUpdate, param);
                }
                else
                {
                    string sqlInsert = "insert into NT_UserEducation (UserID,DegreeID,SchoolID,AcademyID,MatriculationYear,PostTime,PostIP,IsLock) values (@UserID,@DegreeID,@SchoolID,@AcademyID,@MatriculationYear,'" + DateTime.Now.ToString() + "','" + JuSNS.Common.Public.GetClientIP() + "',0)";
                    DbHelper.ExecuteNonQuery(CommandType.Text, sqlInsert, param);
                }
            }
            return num;
        }
        /// <summary>
        /// 删除学校
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int DelEducation(int ID)
        {
            SqlParameter param = new SqlParameter("@ID", ID);
            string sql = "DELETE FROM NT_UserEducation WHERE ID =@ID";
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
        }
        /// <summary>
        /// 获取教育信息数据库参数数组
        /// </summary>
        /// <param name="uEdu">教育信息对象</param>
        /// <returns></returns>
        private SqlParameter[] GetEducation(JuSNS.Model.UserEducationInfo uEdu)
        {
            SqlParameter[] param = new SqlParameter[6];
            param[0] = new SqlParameter("@ID", SqlDbType.Int, 4);
            param[0].Value = uEdu.ID;
            param[1] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[1].Value = uEdu.UserID;
            param[2] = new SqlParameter("@DegreeID", SqlDbType.Int, 4);
            param[2].Value = uEdu.DegreeID;
            param[3] = new SqlParameter("@SchoolID", SqlDbType.Int, 4);
            param[3].Value = uEdu.SchoolID;
            param[4] = new SqlParameter("@AcademyID", SqlDbType.Int, 4);
            param[4].Value = uEdu.AcademyID;
            param[5] = new SqlParameter("@MatriculationYear", SqlDbType.Int, 4);
            param[5].Value = uEdu.MatriculationYear;
            return param;
        }
        /// <summary>
        /// 保存工作信息
        /// </summary>
        /// <param name="listCareer">工作信息对象数组</param>
        /// <returns></returns>
        public int SaveCareer(List<JuSNS.Model.UserCareerInfo> listCareer)
        {
            SqlParameter[] param = null;
            int num = 0;
            for (int i = 0; i < listCareer.Count; i++)
            {
                //判断是否已经有ID
                param = GetCareer(listCareer[i]);
                string sqlIsExist = "select ID from NT_UserCareer where ID=" + listCareer[i].ID.ToString();
                string result = Convert.ToString(DbHelper.ExecuteScalar(CommandType.Text, sqlIsExist, null));
                if (result == listCareer[i].ID.ToString())
                {
                    string sqlUpdate = "update NT_UserCareer set Company=@Company,Description=@Description,IsStill=@IsStill,JoinYear=@JoinYear,JoinMonth=@JoinMonth,PostTime='" + DateTime.Now + "',PostIP='" + JuSNS.Common.Public.GetClientIP() + "' where ID=@ID and  UserID=@UserID";
                    num = DbHelper.ExecuteNonQuery(CommandType.Text, sqlUpdate, param);
                }
                else
                {
                    string sqlInsert = "insert into NT_UserCareer (UserID,Company,Description,IsStill,JoinYear,JoinMonth,PostTime,PostIP) values (@UserID,@Company,@Description,@IsStill,@JoinYear,@JoinMonth,'" + DateTime.Now + "','" + JuSNS.Common.Public.GetClientIP() + "')";
                    DbHelper.ExecuteNonQuery(CommandType.Text, sqlInsert, param);
                }
            }
            return num;
        }
        /// <summary>
        /// 删除工作信息
        /// </summary>
        /// <param name="ID">工作信息ID</param>
        /// <returns></returns>
        public int DelCareer(int ID)
        {
            SqlParameter param = new SqlParameter("@ID", ID);
            string sql = "DELETE FROM NT_UserCareer WHERE ID =@ID";
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
        }
        /// <summary>
        /// 获取工作信息数据库参数数组
        /// </summary>
        /// <param name="uEdu">工作信息对象</param>
        /// <returns></returns>
        private SqlParameter[] GetCareer(JuSNS.Model.UserCareerInfo uCar)
        {
            SqlParameter[] param = new SqlParameter[7];
            param[0] = new SqlParameter("@ID", SqlDbType.Int, 4);
            param[0].Value = uCar.ID;
            param[1] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[1].Value = uCar.UserID;
            param[2] = new SqlParameter("@Company", SqlDbType.NVarChar, 100);
            param[2].Value = uCar.Company;
            param[3] = new SqlParameter("@Description", SqlDbType.NVarChar, 1000);
            param[3].Value = uCar.Description;
            param[4] = new SqlParameter("@IsStill", SqlDbType.Bit, 1);
            param[4].Value = uCar.IsStill;
            param[5] = new SqlParameter("@JoinYear", SqlDbType.Int, 4);
            param[5].Value = uCar.JoinYear;
            param[6] = new SqlParameter("@JoinMonth", SqlDbType.Int, 4);
            param[6].Value = uCar.JoinMonth;
            return param;
        }
        /// <summary>
        /// 获取隐私及个人动态设置类实例
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public UserSettingInfo GetUSetInfo(int UserID)
        {
            SqlParameter param = new SqlParameter("@UserID", UserID);
            UserSettingInfo USetInfo = new UserSettingInfo();
            USetInfo.UserID = UserID;
            string sql = "select * from NT_UserSetting where UserID=@UserID";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, sql, param);
            if (rd.Read())
            {
                USetInfo.PrivSpace = Convert.ToInt32(rd["PrivSpace"]);
                USetInfo.PrivFavourite = Convert.ToInt32(rd["PrivFavourite"]);
                USetInfo.PrivEducate = Convert.ToInt32(rd["PrivEducate"]);
                USetInfo.PrivLasso = Convert.ToInt32(rd["PrivLasso"]);
                USetInfo.PrivFriends = Convert.ToInt32(rd["PrivFriends"]);
                USetInfo.PrivLeaveWord = Convert.ToInt32(rd["PrivLeaveWord"]);
                USetInfo.PrivMiniBlog = Convert.ToInt32(rd["PrivMiniBlog"]);
                USetInfo.PrivShare = Convert.ToInt32(rd["PrivShare"]);
                USetInfo.PrivGroup = Convert.ToInt32(rd["PrivGroup"]);
                USetInfo.PrivMovies = Convert.ToInt32(rd["PrivMovies"]);
                USetInfo.ActUpdateData = Convert.ToBoolean(rd["ActUpdateData"]);
                USetInfo.ActAddFriend = Convert.ToBoolean(rd["ActAddFriend"]);
                USetInfo.ActLeaveWord = Convert.ToBoolean(rd["ActLeaveWord"]);
                USetInfo.ActPicComment = Convert.ToBoolean(rd["ActPicComment"]);
                USetInfo.ActSecede = Convert.ToBoolean(rd["ActSecede"]);
                USetInfo.ActDeliver = Convert.ToBoolean(rd["ActDeliver"]);
                USetInfo.ActLogComment = Convert.ToBoolean(rd["ActLogComment"]);
                USetInfo.ActMovieComment = Convert.ToBoolean(rd["ActMovieComment"]);
                USetInfo.ActPhotoLasso = Convert.ToBoolean(rd["ActPhotoLasso"]);
                USetInfo.ActShareComment = Convert.ToBoolean(rd["ActShareComment"]);
                USetInfo.LastPostTime = Convert.ToDateTime(rd["LastPostTime"]);
                USetInfo.LastPostIP = Convert.ToString(rd["LastPostIP"]);
            }
            rd.Close();
            return USetInfo;
        }
        #endregion
        #region 取得用户一些相关的信息
        /// <summary>
        /// 取得用户的教育信息
        /// </summary>
        /// <param name="userid">查看者ID</param>
        /// <param name="friendid">被查看者ID</param>
        /// <returns></returns>
        public DataTable GetEducation(int userid, int friendid)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                SqlParameter[] param = new SqlParameter[2];
                param[0] = new SqlParameter("@userid", SqlDbType.Int, 4);
                param[0].Value = userid;
                param[1] = new SqlParameter("@friendid", SqlDbType.Int, 4);
                param[1].Value = friendid;

                EnumPrivacy pri = GetWorkAndEduPrivacy(cn, friendid);
                if (!CheckPrivacy(cn, pri, userid, friendid))
                    return null;
                string Sql = "select a.DegreeID,a.MatriculationYear,b.SchoolName,c.Name from NT_UserEducation a inner join NT_Dict_School b on a.SchoolID=b.SchoolID inner join NT_Dict_Academy c on a.AcademyID=c.ID where a.UserID=@friendid order by a.DegreeID Desc,a.MatriculationYear desc";
                return DbHelper.ExecuteTable(cn, CommandType.Text, Sql, param);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 取得工作相关的信息
        /// </summary>
        /// <param name="userid">查看者ID</param>
        /// <param name="friendid">被查看者ID</param>
        /// <returns></returns>
        public DataTable GetCareer(int userid, int friendid)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                EnumPrivacy pri = GetWorkAndEduPrivacy(cn, friendid);
                if (!CheckPrivacy(cn, pri, userid, friendid))
                    return null;
                string Sql = "select * from NT_UserCareer where UserID=" + friendid;
                return DbHelper.ExecuteTable(cn, CommandType.Text, Sql, null);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 取得教育和工作的隐私设置
        /// </summary>
        /// <param name="cn"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        private EnumPrivacy GetWorkAndEduPrivacy(SqlConnection cn, int userid)
        {
            SqlParameter param = new SqlParameter("@userid", userid);
            string Sql = "select PrivEducate from NT_UserSetting where UserID=@userid";
            return (EnumPrivacy)Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, param));
        }
        #endregion
        #region 取得用户教育相关信息
        /// <summary>
        /// 取得用户最高教育相关信息
        /// </summary>
        /// <param name="UserID">会员编号</param>
        /// <returns></returns>
        public UserEducationInfo LastEducInfo(int UserID)
        {
            SqlParameter param = new SqlParameter("@UserID", UserID);
            UserEducationInfo info = new UserEducationInfo();
            string Sql = "Select ID,UserID,DegreeID,SchoolID,AcademyID,MatriculationYear,PostTime,PostIP,IsLock From NT_UserEducation " +
                         "Where UserID=@UserID Order By DegreeID Desc";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, param);
            if (rd.Read())
            {
                info.ID = Convert.ToInt32(rd["ID"].ToString());
                info.UserID = Convert.ToInt32(rd["UserID"].ToString());
                info.DegreeID = Convert.ToInt32(rd["DegreeID"].ToString());
                info.SchoolID = Convert.ToInt32(rd["SchoolID"].ToString());
                info.AcademyID = Convert.ToInt32(rd["AcademyID"].ToString());
                info.MatriculationYear = Convert.ToInt32(rd["MatriculationYear"].ToString());
                info.PostTime = Convert.ToDateTime(rd["PostTime"].ToString());
                if (rd["PostIP"] != DBNull.Value) info.PostIP = rd["PostIP"].ToString();
                info.IsLock = Convert.ToBoolean(rd["IsLock"].ToString());
            }
            rd.Close();
            return info;
        }

        /// <summary>
        /// 取得学校信息
        /// </summary>
        /// <param name="SchoolID">学校编号</param>
        /// <returns></returns>
        public DictSchoolInfo GetSchoolInfo(int SchoolID)
        {
            SqlParameter param = new SqlParameter("@SchoolID", SchoolID);
            DictSchoolInfo info = new DictSchoolInfo();
            string Sql = "Select SchoolID,DegreeID,AreaID,SchoolName,IsLock From NT_Dict_School Where SchoolID=@SchoolID";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, param);
            if (rd.Read())
            {
                info.SchoolID = Convert.ToInt32(rd["SchoolID"].ToString());
                info.DegreeID = Convert.ToInt32(rd["DegreeID"].ToString());
                info.AreaID = Convert.ToInt32(rd["AreaID"].ToString());
                if (rd["SchoolName"] != DBNull.Value) info.SchoolName = rd["SchoolName"].ToString();
                info.IsLock = Convert.ToBoolean(rd["IsLock"].ToString());
            }
            rd.Close();
            return info;
        }

        /// <summary>
        /// 取得院系信息
        /// </summary>
        /// <param name="AcademyID">院系编号</param>
        /// <returns></returns>
        public DictAcademyInfo GetAcademyInfo(int AcademyID)
        {
            SqlParameter param = new SqlParameter("@AcademyID", AcademyID);
            DictAcademyInfo info = new DictAcademyInfo();
            string Sql = "Select ID,Name,SchoolID,IsLock From NT_Dict_Academy Where ID=@AcademyID";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, param);
            if (rd.Read())
            {
                info.ID = Convert.ToInt32(rd["ID"].ToString());
                if (rd["Name"] != DBNull.Value) info.Name = rd["Name"].ToString();
                info.SchoolID = Convert.ToInt32(rd["SchoolID"].ToString());
                info.IsLock = Convert.ToBoolean(Convert.ToInt32(rd["IsLock"]));
            }
            rd.Close();
            return info;
        }
        #endregion
        /// <summary>
        /// 随机取出某一网络的用户
        /// </summary>
        /// <param name="topNum"></param>
        /// <param name="networkId"></param>
        /// <returns></returns>
        DataTable IUser.GetUserByNetwork(int topNum, int networkId, int userId,int f)
        {
            using (SqlConnection cn = new SqlConnection(DBConfig.CnString))
            {
                string pc = " and a.City=" + networkId + "";
                if (f == 0)
                {
                    pc = " and a.Province=" + networkId + "";
                }

                string Sql = "select top " + topNum + " a.UserID,a.UserName,a.Province,b.Name,c.FilePath,MiniContent='',MiniTime=GETDATE(),";
                Sql += "WorkCompany='',WorkJoinYear=0,WorkJoinMonth=0,WorkLeaveYear=0,WorkLeaveMonth=0,SchlDegreeID=0,SchlMatriculationYear=0,SchoolName='',SchlAcdName=''";
                Sql += " from NT_User a inner join NT_Dict_Area b on a.Province=b.ID left join NT_Photo c on a.Portrait=c.PhotoID and c.IsLock=0 Where a.UserID<>" + userId + " " + pc + " and a.State<>" + (int)EnumUserState.Register + " order by newid()";
                DataTable dt = DbHelper.ExecuteTable(cn, CommandType.Text, Sql, null);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow r = dt.Rows[i];
                    int fid = (int)r[0];
                    Sql = "select PrivMiniBlog from NT_UserSetting where UserID=" + fid;
                    EnumPrivacy prv = (EnumPrivacy)Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null));
                    if (CheckPrivacy(cn, prv, userId, fid))
                    {
                        Sql = "select Content,PostTime from NT_Mood where UserID=" + fid + " and IsLock=0 order by PostTime Desc";
                        IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                        if (rd.Read())
                        {
                            r["MiniContent"] = rd.GetString(0);
                            r["MiniTime"] = rd.GetDateTime(1);
                        }
                        rd.Close();
                    }
                    EnumPrivacy pri = GetWorkAndEduPrivacy(cn, fid);
                    if (CheckPrivacy(cn, pri, userId, fid))
                    {
                        Sql = "select Company,JoinYear,JoinMonth,LeaveYear,LeaveMonth from NT_UserCareer where UserID=" + fid;
                        IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                        if (rd.Read())
                        {
                            r["WorkCompany"] = rd[0];
                            r["WorkJoinYear"] = rd[1];
                            r["WorkJoinMonth"] = rd[2];
                            r["WorkLeaveYear"] = rd[3];
                            r["WorkLeaveMonth"] = rd[4];
                        }
                        rd.Close();
                    }
                    EnumPrivacy prie = GetWorkAndEduPrivacy(cn, fid);
                    if (CheckPrivacy(cn, prie, userId, fid))
                    {
                        Sql = "select a.DegreeID,a.MatriculationYear,b.SchoolName,c.Name from NT_UserEducation a inner join NT_Dict_School b on a.SchoolID=b.SchoolID inner join NT_Dict_Academy c on a.AcademyID=c.ID where a.UserID=" + fid + " order by a.DegreeID Desc,a.MatriculationYear desc";
                        IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                        if (rd.Read())
                        {
                            r["SchlDegreeID"] = rd[0];
                            r["SchlMatriculationYear"] = rd[1];
                            r["SchoolName"] = rd[2];
                            r["SchlAcdName"] = rd[3];
                        }
                        rd.Close();
                    }
                }
                return dt;
            }
        }

        /// <summary>
        /// 取回密码
        /// </summary>
        /// <param name="Email">Email</param>
        /// <returns>0,成功,-2,邮箱无效,-3邮件发送失败</returns>
        int IUser.Retrieve(string email)
        {
            string userName = string.Empty;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string Sql = "select UserName from NT_User where Email=@Email";
                object obj = DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, new SqlParameter("@Email", email));
                if (obj == null || obj == DBNull.Value)
                {
                    return -2;
                }

                userName = (string)obj;
                string code = Rand.Str(32);
                while ((int)DbHelper.ExecuteScalar(cn, CommandType.Text, "select count(ID) from NT_RetrievePwd where ValidCode='" + code + "'", null) > 0)
                {
                    code = Rand.Str(32, true);
                }
                Sql = "insert into NT_RetrievePwd (Email,PostTime,PostIP,State,ValidCode) values (@Email,'" + DateTime.Now + "','" + JuSNS.Common.Public.GetClientIP() + "',0,@ValidCode)";
                SqlParameter[] Param = new SqlParameter[2];
                Param[0] = new SqlParameter("@Email", SqlDbType.NVarChar, 100);
                Param[0].Value = email;
                Param[1] = new SqlParameter("@ValidCode", SqlDbType.Char, 32);
                Param[1].Value = code;
                try
                {
                    #region 发送邮件
                    JuSNS.Common.EMail eml = JuSNS.Common.EMail.CreateInstance();
                    eml.To = email;
                    eml.Subject = "亲爱的" + userName + "，你申请了重设" + UiConfig.SiteName + "的账户密码";
                    string body = EmailConfig.retrieve;
                    body = body.Replace("{SiteName}", UiConfig.SiteName);
                    body = body.Replace("{UserName}", userName);
                    body = body.Replace("{Domain}", UiConfig.Domain);
                    body = body.Replace("{Date}", DateTime.Now.ToString("yyyy年MM月dd日"));
                    body = body.Replace("{Url}", UiConfig.RootUrl + "/restpwd.aspx?&email=" + email + "&r=" + code);
                    eml.Body = body;
                    eml.Send();
                    #endregion
                    DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, Param);
                    return 0;
                }
                catch
                {
                    return -3;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        /// <summary>
        /// 重设密码,并设为已录录状态
        /// </summary>
        /// <param name="newPwd"></param>
        /// <param name="code"></param>
        /// <returns>0成功，-1没有找到相关的申请记录,-2该申请已完成重设而无效,-3邮箱无效</returns>
        int IUser.ResetPwd(string newPwd, string code, out int userId, out string userName, out string userPortrait)
        {
            userId = 0;
            userName = string.Empty;
            userPortrait = string.Empty;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                bool f = false;
                int state = -1;
                int id = 0;
                string email = string.Empty;
                SqlParameter cd = new SqlParameter("@code", code);
                string Sql = "select ID,Email,State from NT_RetrievePwd where ValidCode=@code";
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, cd);
                if (rd.Read())
                {
                    id = rd.GetInt32(0);
                    email = rd.GetString(1);
                    state = rd.GetInt32(2);
                    f = true;
                }
                rd.Close();
                if (!f)
                {
                    return -1;
                }
                if (state != 0)
                    return -2;
                f = false;
                SqlParameter Param = new SqlParameter("@Email", email);
                Sql = "select a.UserID,a.UserName,b.FilePath from NT_User a left join NT_Photo b on a.Portrait=b.PhotoID where a.Email=@Email";
                rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, Param);
                if (rd.Read())
                {
                    userId = rd.GetInt32(0);
                    userName = rd.GetString(1);
                    if (!rd.IsDBNull(2)) userPortrait = rd.GetString(2);
                    f = true;
                }
                rd.Close();
                if (!f)
                    return -3;
                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    string pwd = JuSNS.Common.Input.MD5(newPwd, false);
                    Sql = "update NT_User set Password='" + pwd + "',LastLoginTime='" + DateTime.Now + "',LastLoginIP='" + Public.GetClientIP() + "',LoginTimes=LoginTimes+1 where Email=@Email";
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, Param);
                    Sql = "update NT_RetrievePwd set State=1,ConfirmTime='" + DateTime.Now + "',ConfirmIP='" + JuSNS.Common.Public.GetClientIP() + "' where ID=" + id;
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    trans.Commit();
                    return 0;
                }
                catch
                {
                    trans.Rollback();
                    return -3;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        public bool getRestPwdRecord(string r, string email)
        {
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@email", SqlDbType.NVarChar, 100);
            param[0].Value = email;
            param[1] = new SqlParameter("@code", SqlDbType.NVarChar, 32);
            param[1].Value = r;
            string Sql = "select count(ID) from NT_RetrievePwd where ValidCode=@code and email=@email";
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, Sql, param).ToString());
            if (n > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 取得隐私信息
        /// </summary>
        /// <param name="UserID">用户ID信息</param>
        /// <returns></returns>
        public PrivacyInfo GetPrivacy(int UserID)
        {
            string sql = "select UserID,PrivSpace,PrivFavourite,PrivEducate,PrivLasso,PrivFriends,PrivLeaveWord,PrivMiniBlog,PrivShare,PrivGroup,PrivMovies,ActUpdateData,ActAddFriend,ActLeaveWord,ActPicComment,ActSecede,ActDeliver,ActLogComment,ActMovieComment,ActPhotoLasso,ActShareComment,LastPostTime,LastPostIP from NT_UserSetting where UserID=" + UserID;
            PrivacyInfo pri = new PrivacyInfo();
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, sql, null);
            if (rd.Read())
            {
                pri.UserID = Convert.ToInt32(rd["UserID"]);
                pri.PrivacySpace = (EnumPrivacy)Convert.ToInt32(rd["PrivSpace"]);
                pri.PrivacyFavourite = (EnumPrivacy)Convert.ToInt32(rd["PrivFavourite"]);
                pri.PrivacyEducate = (EnumPrivacy)Convert.ToInt32(rd["PrivEducate"]);
                pri.PrivacyLasso = (EnumPrivacy)Convert.ToInt32(rd["PrivLasso"]);
                pri.PrivacyFriends = (EnumPrivacy)Convert.ToInt32(rd["PrivFriends"]);
                pri.PrivacyLeaveWord = (EnumPrivacy)Convert.ToInt32(rd["PrivLeaveWord"]);
                pri.PrivacyMiniBlog = (EnumPrivacy)Convert.ToInt32(rd["PrivMiniBlog"]);
                pri.PrivacyShare = (EnumPrivacy)Convert.ToInt32(rd["PrivShare"]);
                pri.PrivacyGroup = (EnumPrivacy)Convert.ToInt32(rd["PrivGroup"]);
                pri.PrivacyMovies = (EnumPrivacy)Convert.ToInt32(rd["PrivMovies"]);
                pri.ActUpdateData = Convert.ToBoolean(rd["ActUpdateData"]);
                pri.ActAddFriend = Convert.ToBoolean(rd["ActAddFriend"]);
                pri.ActLeaveWord = Convert.ToBoolean(rd["ActLeaveWord"]);
                pri.ActPicComment = Convert.ToBoolean(rd["ActPicComment"]);
                pri.ActSecede = Convert.ToBoolean(rd["ActSecede"]);
                pri.ActDeliver = Convert.ToBoolean(rd["ActDeliver"]);
                pri.ActLogComment = Convert.ToBoolean(rd["ActLogComment"]);
                pri.ActMovieComment = Convert.ToBoolean(rd["ActMovieComment"]);
                pri.ActPhotoLasso = Convert.ToBoolean(rd["ActPhotoLasso"]);
                pri.ActShareComment = Convert.ToBoolean(rd["ActShareComment"]);
                pri.LastPostTime = Convert.ToDateTime(rd["LastPostTime"]);
                pri.LastPostIP = Convert.ToString(rd["LastPostIP"]);
            }
            else
            {
                pri.UserID = UserID;
            }
            rd.Close();
            return pri;
        }

        /// <summary>
        /// 设置隐私信息
        /// 返回0表示失败
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="privacyinfo">隐私信息</param>
        /// <returns></returns>
        public int SetPrivacy(int UserID, PrivacyInfo privacyinfo)
        {
            if (UserID != privacyinfo.UserID)
            {
                return 0;
            }
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                SqlParameter[] param = GetPrivacyParm(privacyinfo);
                string sql = "select Count(*) from NT_UserSetting where UserID=" + UserID;
                if (Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, sql, null)) > 0)
                {
                    sql = "update NT_UserSetting set PrivSpace=@PrivSpace,PrivFavourite=@PrivFavourite,PrivEducate=@PrivEducate,PrivLasso=@PrivLasso,PrivFriends=@PrivFriends,PrivLeaveWord=@PrivLeaveWord,PrivMiniBlog=@PrivMiniBlog,"
                    + "PrivShare=@PrivShare,PrivGroup=@PrivGroup,PrivMovies=@PrivMovies,ActUpdateData=@ActUpdateData,ActAddFriend=@ActAddFriend,ActLeaveWord=@ActLeaveWord,ActPicComment=@ActPicComment,ActSecede=@ActSecede,ActDeliver=@ActDeliver,ActLogComment=@ActLogComment,"
                    + "ActMovieComment=@ActMovieComment,ActPhotoLasso=@ActPhotoLasso,ActShareComment=@ActShareComment,LastPostTime=@LastPostTime,LastPostIP=@LastPostIP where UserID=@UserID";
                }
                else
                {
                    sql = "insert into NT_UserSetting (PrivSpace,PrivFavourite,PrivEducate,PrivLasso,PrivFriends,PrivLeaveWord,PrivMiniBlog,PrivShare,PrivGroup,PrivMovies,ActUpdateData,ActAddFriend,ActLeaveWord,ActPicComment,ActSecede,ActDeliver,ActLogComment,ActMovieComment,ActPhotoLasso,ActShareComment,LastPostTime,LastPostIP,UserID) values(@PrivSpace,@PrivFavourite,@PrivEducate,@PrivLasso,@PrivFriends,@PrivLeaveWord,@PrivMiniBlog,@PrivShare,@PrivGroup,@PrivMovies,@ActUpdateData,@ActAddFriend,@ActLeaveWord,@ActPicComment,@ActSecede,@ActDeliver,@ActLogComment,@ActMovieComment,@ActPhotoLasso,@ActShareComment,@LastPostTime,@LastPostIP,@UserID)";
                }

                int rint = DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, param);
                trans.Commit();
                return rint;
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }
        /// <summary>
        /// 隐私信息参数
        /// </summary>
        /// <param name="pri">隐私信息</param>
        /// <returns>sql参数</returns>
        private SqlParameter[] GetPrivacyParm(PrivacyInfo pri)
        {
            SqlParameter[] param = new SqlParameter[23];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = pri.UserID;
            param[1] = new SqlParameter("@PrivSpace", SqlDbType.Int, 4);
            param[1].Value = pri.PrivacySpace;
            param[2] = new SqlParameter("@PrivFavourite", SqlDbType.Int, 4);
            param[2].Value = pri.PrivacyFavourite;
            param[3] = new SqlParameter("@PrivEducate", SqlDbType.Int, 4);
            param[3].Value = pri.PrivacyEducate;
            param[4] = new SqlParameter("@PrivLasso", SqlDbType.Int, 4);
            param[4].Value = pri.PrivacyLasso;
            param[5] = new SqlParameter("@PrivFriends", SqlDbType.Int, 4);
            param[5].Value = pri.PrivacyFriends;
            param[6] = new SqlParameter("@PrivLeaveWord", SqlDbType.Int, 4);
            param[6].Value = pri.PrivacyLeaveWord;
            param[7] = new SqlParameter("@PrivMiniBlog", SqlDbType.Int, 4);
            param[7].Value = pri.PrivacyMiniBlog;
            param[8] = new SqlParameter("@PrivShare", SqlDbType.Int, 4);
            param[8].Value = pri.PrivacyShare;
            param[9] = new SqlParameter("@PrivGroup", SqlDbType.Int, 4);
            param[9].Value = pri.PrivacyGroup;
            param[10] = new SqlParameter("@PrivMovies", SqlDbType.Int, 4);
            param[10].Value = pri.PrivacyMovies;
            param[11] = new SqlParameter("@ActUpdateData", SqlDbType.Bit, 1);
            param[11].Value = pri.ActUpdateData;
            param[12] = new SqlParameter("@ActAddFriend", SqlDbType.Bit, 1);
            param[12].Value = pri.ActAddFriend;
            param[13] = new SqlParameter("@ActLeaveWord", SqlDbType.Bit, 1);
            param[13].Value = pri.ActLeaveWord;
            param[14] = new SqlParameter("@ActPicComment", SqlDbType.Bit, 1);
            param[14].Value = pri.ActPicComment;
            param[15] = new SqlParameter("@ActSecede", SqlDbType.Bit, 1);
            param[15].Value = pri.ActSecede;
            param[16] = new SqlParameter("@ActDeliver", SqlDbType.Bit, 1);
            param[16].Value = pri.ActDeliver;
            param[17] = new SqlParameter("@ActLogComment", SqlDbType.Bit, 1);
            param[17].Value = pri.ActLogComment;
            param[18] = new SqlParameter("@ActMovieComment", SqlDbType.Bit, 1);
            param[18].Value = pri.ActMovieComment;
            param[19] = new SqlParameter("@ActPhotoLasso", SqlDbType.Bit, 1);
            param[19].Value = pri.ActPhotoLasso;
            param[20] = new SqlParameter("@ActShareComment", SqlDbType.Bit, 1);
            param[20].Value = pri.ActShareComment;
            param[21] = new SqlParameter("@LastPostTime", SqlDbType.DateTime, 8);
            param[21].Value = pri.LastPostTime;
            param[22] = new SqlParameter("@LastPostIP", SqlDbType.NChar, 15);
            param[22].Value = pri.LastPostIP;
            return param;
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="us">实例类</param>
        /// <param name="UserID">会员编号</param>
        /// <returns></returns>
        public int UpdateUser(JuSNS.Model.UserInfo us, int UserID)
        {
            SqlParameter[] param = GetParam(us);
            string sql = "update NT_User set Email=@Email,Password=@Password,UserName=@UserName,Province=@Province,City=@City,State=@State,Portrait=@Portrait where UserID=" + UserID;
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
        }

        public int UpdateBer(int UserID, int integral, int inteyb, int Click)
        {
            string sql = "update NT_User set integral=" + integral + ",inteyb=" + inteyb + ",Click=" + Click + " where UserID=" + UserID;
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
        }

        /// <summary>
        /// 删除会员
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public int DelUser(int UserID, int flag)
        {
            string sql = "";
            SqlParameter param = new SqlParameter("@UserID", UserID);
            if (flag == 0)
            {
                sql = "delete from NT_User where UserID=@UserID";
            }
            else if (flag == 1)//推荐
            {
                sql = "update NT_User set isRec=1 where UserID=@UserID";
            }
            else if (flag == 2)//取消推荐
            {
                sql = "update NT_User set isRec=0 where UserID=@UserID";
            }
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
        }

        /// <summary>
        /// 删除所有会员
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public int DelUserAll()
        {
            string sql =  "delete from NT_User";
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
        }

        /// <summary>
        /// 更新会员基本信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public int UpdateUserBase(UserBasicInfo info)
        {
            SqlParameter[] param = GetBaseParm(info);

            string sql = "select UserID from NT_UserInfo where UserID=@UserID";
            object dresult = DbHelper.ExecuteScalar(CommandType.Text, sql, param);//是否存在该会员记录

            if (!Convert.IsDBNull(dresult) && dresult != null)
            {
                sql = "update NT_UserInfo set Sex=@Sex,Birthday=@Brithday,Constellation=@Constellation,MSN=@MSN,GTalk=@GTalk,QQ=@QQ,Skype=@Skype,Mobile=@Mobile,Tel=@Tel,Addr=@Addr,WebSite=@WebSite,BirthidayDisplay=@birthPrivacy,Vocation=@Vocation,HomeProv=@HomeProv,HomeCity=@HomeCity where UserID=@UserID";
            }
            else
            {
                sql = "insert into NT_UserInfo(UserID,Favourite,FavMusics,FavMovies,FavCartoons,FavGames,FavSports,FavBooks,FavAdages,AppreciateMen,Presentation,Sex,Birthday,Constellation,MSN,GTalk,QQ,Skype,Mobile,Tel,Addr,WebSite,BirthidayDisplay,Vocation,HomeProv,HomeCity,EmailPrivacy,MobilePrivacy,MSNPrivacy,GTalkPrivacy,QQPrivacy,TelPrivacy,SkypePrivacy,WebSitePrivacy,AddrPrivacy) values (@UserID,'','','','','','','','','','',@Sex,@Brithday,@Constellation,@MSN,@GTalk,@QQ,@Skype,@Mobile,@Tel,@Addr,@WebSite,@birthPrivacy,@Vocation,@HomeProv,@HomeCity,0,0,0,0,0,0,0,0,0)";
            }
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
        }

        /// <summary>
        /// 会员联系信息参数设置
        /// </summary>
        /// <returns>sql参数</returns>
        private SqlParameter[] GetBaseParm(UserBasicInfo Basic)
        {
            SqlParameter[] param = new SqlParameter[16];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = Basic.UserID;
            param[1] = new SqlParameter("@Sex", SqlDbType.Int, 4);
            param[1].Value = Basic.Sex;
            param[2] = new SqlParameter("@Brithday", SqlDbType.DateTime, 4);
            param[2].Value = Basic.Birthday;
            param[3] = new SqlParameter("@Constellation", SqlDbType.Int, 4);
            param[3].Value = Basic.Constellation;
            param[4] = new SqlParameter("@MSN", SqlDbType.NVarChar, 50);
            param[4].Value = Basic.MSN;
            param[5] = new SqlParameter("@GTalk", SqlDbType.NVarChar, 50);
            param[5].Value = Basic.GTalk;
            param[6] = new SqlParameter("@QQ", SqlDbType.NVarChar, 20);
            param[6].Value = Basic.QQ;
            param[7] = new SqlParameter("@Skype", SqlDbType.NVarChar, 50);
            param[7].Value = Basic.Skype;
            param[8] = new SqlParameter("@Mobile", SqlDbType.Char, 15);
            param[8].Value = Basic.Mobile;
            param[9] = new SqlParameter("@Tel", SqlDbType.Char, 20);
            param[9].Value = Basic.Tel;
            param[10] = new SqlParameter("@Addr", SqlDbType.NVarChar, 100);
            param[10].Value = Basic.Addr;
            param[11] = new SqlParameter("@WebSite", SqlDbType.NVarChar, 50);
            param[11].Value = Basic.WebSite;
            param[12] = new SqlParameter("@birthPrivacy", SqlDbType.Int, 4);
            param[12].Value = Basic.BirthidayDisplay;
            param[13] = new SqlParameter("@Vocation", SqlDbType.Int, 4);
            param[13].Value = Basic.Vocation;
            param[14] = new SqlParameter("@HomeProv", SqlDbType.Int, 4);
            param[14].Value = Basic.HomeProv;
            param[15] = new SqlParameter("@HomeCity", SqlDbType.Int, 4);
            param[15].Value = Basic.HomeCity;
            return param;
        }

        /// <summary>
        /// 修改会员联系信息可见度
        /// </summary>
        /// <param name="ub"></param>
        /// <returns></returns>
        public int UpdateUserPrivacy(UserBasicInfo ub)
        {
            SqlParameter[] param = GetBasePrivacyParm(ub);

            string sql = "select UserID from NT_UserInfo where UserID=@UserID";
            object dresult = DbHelper.ExecuteScalar(CommandType.Text, sql, param);//是否存在该会员记录

            if (!Convert.IsDBNull(dresult) && dresult != null)
            {
                sql = "update NT_UserInfo set EmailPrivacy=@EmailPrivacy,MobilePrivacy=@MobilePrivacy,MSNPrivacy=@MSNPrivacy,GTalkPrivacy=@GTalkPrivacy,QQPrivacy=@QQPrivacy,TelPrivacy=@TelPrivacy,SkypePrivacy=@SkypePrivacy,WebSitePrivacy=@WebSitePrivacy,AddrPrivacy=@AddrPrivacy where UserID=@UserID";
            }
            else
            {
                sql = "insert into NT_UserInfo(UserID,Favourite,FavMusics,FavMovies,FavCartoons,FavGames,FavSports,FavBooks,FavAdages,AppreciateMen,Presentation,Sex,Birthday,Constellation,MSN,GTalk,QQ,Skype,Mobile,Tel,Addr,WebSite,BirthidayDisplay,Vocation,HomeProv,HomeCity,EmailPrivacy,MobilePrivacy,MSNPrivacy,GTalkPrivacy,QQPrivacy,TelPrivacy,SkypePrivacy,WebSitePrivacy,AddrPrivacy) values (@UserID,'','','','','','','','','','',0,'1900-1-1',0,'','','','','','','','',1,0,0,0,@EmailPrivacy,@MobilePrivacy,@MSNPrivacy,@GTalkPrivacy,@QQPrivacy,@TelPrivacy,@SkypePrivacy,@WebSitePrivacy,@AddrPrivacy)";
            }
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
        }

        /// <summary>
        /// 会员联系信息可见度参数设置
        /// </summary>
        /// <returns>sql参数</returns>
        private SqlParameter[] GetBasePrivacyParm(UserBasicInfo Basic)
        {
            SqlParameter[] param = new SqlParameter[13];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = Basic.UserID;
            param[1] = new SqlParameter("@EmailPrivacy", SqlDbType.Int, 4);
            param[1].Value = Basic.EmailPrivacy;
            param[2] = new SqlParameter("@MobilePrivacy", SqlDbType.Int, 4);
            param[2].Value = Basic.MobilePrivacy;
            param[3] = new SqlParameter("@MSNPrivacy", SqlDbType.Int, 4);
            param[3].Value = Basic.MSNPrivacy;
            param[4] = new SqlParameter("@GTalkPrivacy", SqlDbType.Int, 4);
            param[4].Value = Basic.GTalkPrivacy;
            param[5] = new SqlParameter("@QQPrivacy", SqlDbType.Int, 4);
            param[5].Value = Basic.QQPrivacy;
            param[6] = new SqlParameter("@TelPrivacy", SqlDbType.Int, 4);
            param[6].Value = Basic.TelPrivacy;
            param[7] = new SqlParameter("@WebSitePrivacy", SqlDbType.Int, 4);
            param[7].Value = Basic.WebSitePrivacy;
            param[8] = new SqlParameter("@SkypePrivacy", SqlDbType.Int, 4);
            param[8].Value = Basic.SkypePrivacy;
            param[9] = new SqlParameter("@AddrPrivacy", SqlDbType.Int, 4);
            param[9].Value = Basic.AddrPrivacy;
            return param;
        }

        /// <summary>
        /// 根据ID读取教育信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataTable getEducationByID(int id)
        {
            SqlParameter param = new SqlParameter("@id", id);
            string sql = "select a.ID,a.UserID,a.DegreeID,a.SchoolID,a.AcademyID,a.MatriculationYear,a.PostTime,SchoolName=(select SchoolName from NT_Dict_School where SchoolID=a.SchoolID) from  NT_UserEducation a where a.ID=@id";
            return DbHelper.ExecuteTable(CommandType.Text, sql, param);
        }

        /// <summary>
        /// 根据ID读取教育信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataTable getCareerByID(int id)
        {
            SqlParameter param = new SqlParameter("@id", id);
            string sql = "select UserID,ID,Company,Description,IsStill,JoinYear,JoinMonth,LeaveYear,LeaveMonth from NT_UserCareer where ID=@id";
            return DbHelper.ExecuteTable(CommandType.Text, sql, param);
        }

        /// <summary>
        /// 锁定、解锁教育信息
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int LockEducation(int ID, int value)
        {
            string sql = "update NT_UserEducation set IsLock=" + value + " where ID=" + ID;
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
        }

        /// <summary>
        /// 锁定、解锁、删除地区信息
        /// </summary>
        /// <param name="ID">地区编号</param>
        /// <param name="value"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public int LockDelArea(int ID, int value, int flag)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                SqlParameter param = new SqlParameter("@ID", ID);
                string sql = "";
                if (flag == 0)//删除
                {
                    //判断地区是否使用过
                    sql = "select Province,City from NT_User where Province=@ID or City=@ID";
                    string strsql = "select HomeProv,HomeCity from NT_UserInfo where HomeProv=@ID or HomeCity=@ID";
                    object obj = DbHelper.ExecuteScalar(cn, CommandType.Text, sql, param);
                    object objstr = DbHelper.ExecuteScalar(cn, CommandType.Text, strsql, param);

                    if (!Convert.IsDBNull(obj) && obj != null && !Convert.IsDBNull(objstr) && objstr != null)
                    {
                        //已经用过
                        return 2;
                    }
                    sql = "delete  from NT_Dict_Area where ID=@ID or ParentID=@ID";
                }
                else if (flag == 1)//锁定、解锁
                {
                    sql = "update NT_Dict_Area set IsLock=" + value + " where ID=@ID or ParentID=@ID";
                }
                return DbHelper.ExecuteNonQuery(cn, CommandType.Text, sql, param);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        /// <summary>
        /// 添加、修改地区信息
        /// </summary>
        /// <param name="ID">地区编号</param>
        /// <param name="name"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public int UpdateAddArea(int ID, int ParentID, string name, int flag)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                //判断名字是否重复
                string sql = null;
                SqlParameter[] param = new SqlParameter[3];
                param[0] = new SqlParameter("@ID", SqlDbType.Int, 4);
                param[0].Value = ID;
                param[1] = new SqlParameter("@ParentID", SqlDbType.Int, 4);
                param[1].Value = ParentID;
                param[2] = new SqlParameter("@name", SqlDbType.NVarChar, 50);
                param[2].Value = name;

                if (flag == 0)//添加
                {
                    sql = "select Name from NT_Dict_Area where Name=@name";
                    object obj = DbHelper.ExecuteScalar(cn, CommandType.Text, sql, param);//是否存在该会员记录
                    if (!Convert.IsDBNull(obj) && obj != null)
                    {
                        return 2;
                    }
                    else
                    {
                        sql = "insert into NT_Dict_Area(ParentID,Name,IsLock) values(@ParentID,@name,0)";
                    }
                }
                else if (flag == 1)//修改
                {
                    sql = "select Name from NT_Dict_Area where Name=@name and ID<>@ID";
                    object obj = DbHelper.ExecuteScalar(cn, CommandType.Text, sql, param);//是否存在该会员记录
                    if (!Convert.IsDBNull(obj) && obj != null)
                    {
                        return 2;
                    }
                    else
                    {
                        sql = "update NT_Dict_Area set Name=@name where ID=@ID";
                    }
                }
                return DbHelper.ExecuteNonQuery(cn, CommandType.Text, sql, param);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 判断地区有几级
        /// </summary>
        /// <param name="ParentID"></param>
        /// <returns></returns>
        public int getArea(int ParentID)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                SqlParameter param = new SqlParameter("@ParentID", ParentID);
                string sql = "select ParentID from NT_Dict_Area where ID=@ParentID";
                string n = Convert.ToString(DbHelper.ExecuteScalar(cn, CommandType.Text, sql, param));
                int k = 0;

                if (n == "0")//2级
                {
                    k = 1;
                }
                else
                {
                    sql = "select ParentID from NT_Dict_Area where ID=" + int.Parse(n);
                    n = Convert.ToString(DbHelper.ExecuteScalar(cn, CommandType.Text, sql, null));

                    if (n == "0")//3级
                    {
                        k = 2;
                    }
                    else
                    {
                        k = 1;
                    }
                }
                return k;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        #region 邀请用户注册相关
        /// <summary>
        /// 取得邀请相关信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        InviteInfo IUser.GetInviteInfo(string code, EnumFriendInviteMode mode, out Dictionary<string, string> friends)
        {
            InviteInfo info = new InviteInfo();
            friends = new Dictionary<string, string>();
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                int reply = 1;
                bool f = false;
                SqlParameter Param = new SqlParameter("@ValidCode", code);
                string Sql = "select a.ID,a.UserID,a.Invitee,a.Postscript,b.UserName,c.Name,d.FilePath,a.Reply from NT_FriendInvite a inner join NT_User b on a.UserID=b.UserID inner join NT_Dict_Area c on b.Province=c.ID left join NT_Photo d on b.Portrait=d.PhotoID and d.IsLock=0 where a.Method=1 and a.ValidCode=@ValidCode";
                if (mode == EnumFriendInviteMode.URL)
                    Sql = "select 0,a.UserID,null,null,a.UserName,b.Name,c.FilePath,0 from NT_User a inner join NT_Dict_Area b on a.Province=b.ID left join NT_Photo c on a.Portrait=c.PhotoID and c.IsLock=0 where a.UserID=@ValidCode";
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, Param);
                if (rd.Read())
                {
                    info.ID = rd.GetInt32(0);
                    info.UserID = rd.GetInt32(1);
                    if (!rd.IsDBNull(2)) info.Invitee = rd.GetString(2);
                    if (!rd.IsDBNull(3)) info.Postscript = rd.GetString(3);
                    info.UserName = rd.GetString(4);
                    info.Network = rd.GetString(5);
                    if (!rd.IsDBNull(6)) info.HeaPic = rd.GetString(6);
                    reply = rd.GetInt32(7);
                    f = true;
                }
                rd.Close();
                if (!f)
                {
                    throw new Exception("没有找到相关信息,无效的邀请信息");
                }
                if (reply != 0)
                {
                    throw new Exception("该用户已经注册");
                }
                #region 开始统计
                //好友数
                Sql = "select count(ID) from NT_Friend where UserID=" + info.UserID;
                info.FriendCount = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                //照片数
                Sql = "select count(PhotoID) from NT_Photo where UploadUser=" + info.UserID;
                info.PhotoCount = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                //日志数
                Sql = "select count(ID) from NT_Blog where UserID=" + info.UserID;
                info.BlogCount = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                //留言数
                Sql = "select count(ID) from NT_gbook where RecID=" + info.UserID;
                info.NoteCount = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                //分享
                Sql = "select count(ID) from NT_Share where UserID=" + info.UserID;
                info.ShareCount = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                //电影
                Sql = "select count(ID) from NT_MovieComment where UserID=" + info.UserID;
                info.MovieCount = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                //群组
                Sql = "select count(ID) from NT_GroupMember where UserID=" + info.UserID;
                info.GroupCount = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                #endregion
                #region 得到好友列表
                Sql = "select top 8 a.FriendID,b.UserName,c.FilePath from NT_Friend a inner join NT_User b on a.FriendID=b.UserID left join NT_Photo c on b.Portrait=c.PhotoID and c.IsLock=0 where a.UserID=" + info.UserID + " order by b.LastLoginTime DESC";
                rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                while (rd.Read())
                {
                    string unm = rd.GetString(1);
                    string uhp = string.Empty;
                    if (!rd.IsDBNull(2)) uhp = rd.GetString(2);
                    friends.Add(unm, uhp);
                }
                rd.Close();
                #endregion
                return info;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        #endregion

        /// <summary>
        /// 判断用户是否存在
        /// </summary>
        /// <param name="UserId"></param>
        public bool CheckUser(int UserId)
        {
            SqlParameter param = new SqlParameter("@UserId", UserId);
            string sql = "select count(userID) from NT_User where userID=@UserId and State!=0";
            object obj = DbHelper.ExecuteScalar(CommandType.Text, sql, param);//是否存在该会员记录

            if (Convert.ToInt32(obj) > 0)
            {
                return true;//存在
            }
            else
            {
                return false;//不存在
            }
        }

        public int GetUserCity(int UserID)
        {
            string sql = "select City From NT_User where UserID=" + UserID;
            object obj = DbHelper.ExecuteScalar(CommandType.Text, sql, null);
            if (obj != null && obj != DBNull.Value)
            {
                return (int)obj;
            }
            else
            {
                return 0;
            }
        }


        /// <summary>
        /// 取得最大的USerID
        /// </summary>
        /// <returns></returns>
        public int GetMaxUserID()
        {
            string sql = "select top 1 userid from nt_user order by userid desc";
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, null));
        }

        /// <summary>
        /// 为邀请注册者增加积分
        /// </summary>
        /// <param name="UserID"></param>
        public void GetInvReg(int UserID)
        {
            string sql = "select InviterID from NT_User where UserID=" + UserID;
            IDataReader dr = DbHelper.ExecuteReader(CommandType.Text, sql, null);
            if (dr.Read())
            {
                string InvID = dr["InviterID"].ToString();
                if (JuSNS.Common.Input.IsInteger(InvID) && InvID!="0")
                {
                    updateinte(Convert.ToInt32(InvID), 200, 0, 0,"邀请用户加入");
                }
            }
            dr.Close();
        }

        /// <summary>
        /// 增加积分或者金币
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="Point">增加数量单位</param>
        /// <param name="Flag">0增加积分，1增加金币</param>
        /// <param name="ifoat">0增加，1减少</param>
        /// <param name="Content">描述</param>
        public void updateinte(int UserID, int Point, int Flag, int ifoat, string Content)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string sql = string.Empty;
                int iPoint = 0;
                int gPoint = 0;
                int bNum = Convert.ToInt32(JuSNS.Common.Public.GetXMLValue("intel")) * Point;
                if (bNum != 0)
                {
                    switch (Flag)
                    {
                        case 0:
                            if (ifoat == 0)
                            {
                                sql = "update NT_User set integral=integral+" + bNum + " where UserID=" + UserID;
                            }
                            else
                            {
                                sql = "update NT_User set integral=integral-" + bNum + " where UserID=" + UserID;
                            }
                            iPoint = bNum;
                            break;
                        case 1:
                            if (ifoat == 0)
                            {
                                sql = "update NT_User set inteyb=inteyb+" + bNum + " where UserID=" + UserID;
                            }
                            else
                            {
                                sql = "update NT_User set inteyb=inteyb-" + bNum + " where UserID=" + UserID;
                            }
                            gPoint = bNum;
                            break;
                    }
                    DateTime GetDate = DateTime.Now;
                    string iSQL = "insert into NT_UserPointHistory(UserID,Point,GPoint,UTF,CreatTime,Content) values(" + UserID + "," + iPoint + "," + gPoint + "," + ifoat + ",'" + GetDate + "','" + Content + "')";
                    if (Content == "登录")
                    {
                        //判断今天是否登录了 。
                        string gSQL = "select count(*) from NT_User where UserID=" + UserID + " and Convert(varchar(10),LastLoginTime,120) = Convert(varchar(10),getDate(),120)";
                        int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, gSQL, null).ToString());
                        if (n == 0)
                        {
                            //插入数据库
                            DbHelper.ExecuteNonQuery(cn, CommandType.Text, iSQL, null);
                            DbHelper.ExecuteNonQuery(cn, CommandType.Text, sql, null);
                        }
                    }
                    else
                    {
                        //插入数据库
                        DbHelper.ExecuteNonQuery(cn, CommandType.Text, iSQL, null);
                        DbHelper.ExecuteNonQuery(cn, CommandType.Text, sql, null);
                    }
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                {
                    cn.Close();
                }
            }
        }

        public IDataReader GetUserPoint(int UserID)
        {
            string sql = "select integral,inteyb from NT_User where UserID=" + UserID;
            return DbHelper.ExecuteReader(CommandType.Text, sql, null);
        }

        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="sTime">开始时间</param>
        /// <param name="eTime">结束时间</param>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">每页显示多少条</param>
        /// <param name="RecordCount">记录总数</param>
        /// <param name="PageCount">页数</param>
        /// <returns>返回数据表</returns>
        public DataTable SearchPointHistoryPage(int UserID,string sTime, string eTime, int PageIndex, int PageSize, out int RecordCount, out int PageCount)
        {
            string allFields = "*";
            string tablesAndWhere = " NT_UserPointHistory Where UserID=" + UserID + "";
            if (JuSNS.Common.Input.IsDate(sTime) && JuSNS.Common.Input.IsDate(eTime))
            {
                tablesAndWhere += " and CreatTime BETWEEN '" + sTime + "' AND '" + eTime + "'";
            }           
            string indexField = "ID";
            string orderField = "Order By ID Desc";
            return DbHelper.ExecutePage(allFields, tablesAndWhere, indexField, orderField, PageIndex, PageSize, out RecordCount, out PageCount, null);
        }
        /// <summary>
        /// 取得用户名
        /// </summary>
        /// <param name="userid">用户ID</param>
        /// <returns></returns>
        public string GetUserName(int userid)
        {
            SqlParameter param = new SqlParameter("@UserID", userid);
            string sql = "select UserName from Nt_User where UserID=@UserID";
            string str = string.Empty;
            try
            {
                str = Convert.ToString(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
            }
            catch { }
            return str;
        }
        /// <summary>
        /// 取得用户性别
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public int GetUserSex(int userid)
        {
            SqlParameter param = new SqlParameter("@UserID", userid);
            string sql = "select Sex from Nt_UserInfo where UserID=@UserID";
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
        }
        /// <summary>
        /// 取得头像名称
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string GetUserHeadPic(int userid)
        {
            SqlParameter param = new SqlParameter("@UserID", userid);
            string sql = "select FilePath from Nt_Photo where PhotoID=(Select Portrait from Nt_User where UserID=@UserID)";
            string filepath = string.Empty;
            try
            {
                filepath=Convert.ToString(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
            }
            catch { }
            return filepath;
        }

        public int DelUserAdv(int UserID, string Type)
        {
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = UserID;
            param[1] = new SqlParameter("@Type", SqlDbType.NVarChar, 50);
            param[1].Value = Type;
            return DbHelper.ExecuteNonQuery(CommandType.StoredProcedure, "JuSNS_DelUserAdv", param);
        }

        public int DelUserCommAdv(int UserID, string Type)
        {
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = UserID;
            param[1] = new SqlParameter("@Type", SqlDbType.NVarChar, 50);
            param[1].Value = Type;
            return DbHelper.ExecuteNonQuery(CommandType.StoredProcedure, "JuSNS_DelUserCommAdv", param);
        }
        public int DelAllAdv(string Type)
        {
            SqlParameter param = new SqlParameter("@Type", Type);
            return DbHelper.ExecuteNonQuery(CommandType.StoredProcedure, "JuSNS_DelAllAdv", param);
        }
    }
}
