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

namespace JuSNS.SQLServer
{
    public class Friend : DbBase, IFriend
    {
        /// <summary>
        /// 判断是否是好友
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendid"></param>
        /// <returns></returns>
        static internal bool IsFriends(SqlConnection cn, int userid, int friendid)
        {
            string Sql = "select count(ID) from NT_Friend where UserID=" + userid + " and FriendID=" + friendid;
            int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
            if (n < 1)
                return false;
            else
                return true;
        }
        /// <summary>
        /// 判断是否是好友
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendid"></param>
        /// <returns></returns>
        public bool IsFriends(int userid, int friendid)
        {
            using (SqlConnection cn = new SqlConnection(DBConfig.CnString))
            {
                cn.Open();
                return IsFriends(cn, userid, friendid);
            }
        }

        /// <summary>
        /// 得到好友分类
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public IDataReader GetFriendClass(int UserID)
        {
            SqlParameter param = new SqlParameter("@UserID", UserID);
            return DbHelper.ExecuteReader(CommandType.StoredProcedure, "JuSNS_FriendClass", param);
        }

        /// <summary>
        /// 发送交友请求
        /// </summary>
        /// <param name="proposer"></param>
        /// <param name="friend"></param>
        /// <returns></returns>
        int IFriend.Request(int proposer, int friend)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                if (IsFriends(cn, proposer, friend))
                {
                    return -1;
                }
                string Sql = "select count(ID) from NT_Request where RequestType=" + (int)EnumRequestType.MakeFriends + " and ((Receiver=" + proposer + " and Demander=" + friend + ") or (Receiver=" + friend + " and Demander=" + proposer + "))";
                int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                if (n > 0)
                    return -2;
                return SendRequest(null, EnumRequestType.MakeFriends, proposer, friend, null);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 回应好友请求
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="requestid"></param>
        /// <param name="reply"></param>
        /// <param name="classID"></param>
        /// <returns></returns>
        int IFriend.Response(int userid, int requestid, EnumReply reply, string classID)
        {
            if (reply == EnumReply.NoneReply)
                return -100;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {

                bool flag = true;
                int friendid = 0;
                int uid = 0;
                int reqtp = -1;
                string Sql = "select Demander,Receiver,RequestType from NT_Request where ID=" + requestid;
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                if (rd.Read())
                {
                    friendid = rd.GetInt32(0);
                    uid = rd.GetInt32(1);
                    reqtp = rd.GetInt32(2);
                    flag = false;
                }
                rd.Close();
                if (flag)
                    return -1;
                if (uid != userid)
                    return -2;
                if (reqtp != (int)EnumRequestType.MakeFriends)
                    return -3;
                if (IsFriends(cn, userid, friendid))
                    return -4;
                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    DateTime now = DateTime.Now;
                    int n = 0;
                    if (reply == EnumReply.Agree)
                    {
                        Sql = "insert into NT_Friend (UserID,FriendID,AddTime,FDegree,ClassID) values (" + userid + "," + friendid + ",'" + now + "',0," + Convert.ToInt32(classID) + ")";
                        n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                        Sql = "insert into NT_Friend (UserID,FriendID,AddTime,FDegree) values (" + friendid + "," + userid + ",'" + now + "',0)";
                        n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                        //写动态
                        JUser ju = new JUser();
                        if (ju.CheckPrivacyInfo(trans, userid, "ActAddFriend"))
                        {
                            UserDyn(trans, 0, 0, "friend", userid, friendid, friendid, "成为好友", friendid.ToString());
                        }
                        if (ju.CheckPrivacyInfo(trans, friendid, "ActAddFriend"))
                        {
                            UserDyn(trans, 0, 0, "friend", friendid, userid, userid, "成为好友", userid.ToString());
                        }
                        //写通知
                        n += Notify(trans, EnumNotifyType.AgreeBeFriends, userid, friendid, string.Empty);
                    }
                    Sql = "delete from NT_Request where ID=" + requestid;
                    n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    trans.Commit();
                    return n;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 删除好友
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendid"></param>
        /// <returns></returns>
        int IFriend.Diffidation(int userid, int friendid)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                if (!IsFriends(cn, userid, friendid))
                    return -1;
                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    string Sql = "delete from NT_Friend where UserID=" + userid + " and FriendID=" + friendid;
                    int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    Sql = "delete from NT_Friend where UserID=" + friendid + " and FriendID=" + userid;
                    n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    Sql = "delete from NT_FriendDesc where (Modifier=" + userid + " and Affirmant=" + friendid + ") or (Affirmant=" + userid + " and Modifier=" + friendid + ")";
                    n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    trans.Commit();
                    return n;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        #region 好友描述
        /*
        /// <summary>
        /// 获取好友描述信息
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendid"></param>
        /// <returns></returns>
        List<FriendDescInfo> IFriend.GetDetail(int userid, int friendid)
        {
            List<FriendDescInfo> list = new List<FriendDescInfo>();
            string Sql = "select Modifier,Affirmant,DescType,Reply,DescStartYear,DescEndYear,DescIsKnow,DescText from NT_FriendDesc";
            Sql += " where (Modifier=" + userid + " and Affirmant=" + friendid + ") or (Modifier=" + friendid + " and Affirmant=" + userid + ")";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, null);
            while (rd.Read())
            {
                FriendDescInfo info = new FriendDescInfo();
                info.Modifier = rd.GetInt32(0);
                info.Affirmant = rd.GetInt32(1);
                info.DescType = (EnumFriendDetailType)rd.GetInt32(2);
                info.Reply = rd.GetInt32(3);
                if (!rd.IsDBNull(4)) info.DescStartYear = rd.GetInt32(4); else info.DescStartYear = -1;
                if (!rd.IsDBNull(5)) info.DescEndYear = rd.GetInt32(5); else info.DescEndYear = -1;
                if (!rd.IsDBNull(6)) info.DescIsKnow = rd.GetInt32(6); else info.DescIsKnow = -1;
                if (!rd.IsDBNull(7)) info.DescText = rd.GetString(7); else info.DescText = string.Empty;
                list.Add(info);
            }
            rd.Close();
            return list;
        }
        
        /// <summary>
        /// 修改好友描述
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="detail"></param>
        /// <returns></returns>
        int IFriend.EditFriendsDetail(int userid, int friendid, List<FriendDescInfo> detail)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                if (!IsFriends(cn, userid, friendid))
                    return -1;
                string SqlWhere = " where (Modifier=" + userid + " and Affirmant=" + friendid + ") or (Affirmant=" + userid + " and Modifier=" + friendid + ")";
                string SqlDel = "delete from NT_FriendDesc " + SqlWhere;
                if (detail == null || detail.Count < 1)
                {
                    return DbHelper.ExecuteNonQuery(cn, CommandType.Text, SqlDel, null);
                }

                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, SqlDel, null);
                    foreach (FriendDescInfo info in detail)
                    {
                        string Sql = "insert into NT_FriendDesc (Modifier,Affirmant,DescType,Reply,DescStartYear,DescEndYear,DescIsKnow,DescText) values (";
                        Sql += userid + "," + friendid + ",0,@DescStartYear,@DescEndYear,@DescIsKnow,@DescText)";
                        SqlParameter[] param = new SqlParameter[4];
                        param[0] = new SqlParameter("@DescStartYear", SqlDbType.Int);
                        if (info.DescStartYear < 0)
                            param[0].Value = DBNull.Value;
                        else
                            param[0].Value = info.DescStartYear;
                        param[1] = new SqlParameter("@DescEndYear", SqlDbType.Int);
                        if (info.DescEndYear < 0)
                            param[1].Value = DBNull.Value;
                        else
                            param[1].Value = info.DescEndYear;
                        param[2] = new SqlParameter("@DescIsKnow", SqlDbType.Bit);
                        if (info.DescIsKnow < 0)
                            param[2].Value = DBNull.Value;
                        else
                            param[2].Value = info.DescIsKnow;
                        param[3] = new SqlParameter("@DescText", SqlDbType.NVarChar, 30);
                        if (info.DescText == null || info.DescText.Trim() == string.Empty)
                            param[3].Value = DBNull.Value;
                        else
                            param[3].Value = info.DescText.Trim();
                        n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, param);
                    }
                    //加一条请求
                    n += SendRequest(trans, EnumRequestType.FriendDetail, userid, friendid, null);
                    trans.Commit();
                    return n;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        
        /// <summary>
        /// 回复好友描述请求
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendid"></param>
        /// <param name="isconfirm"></param>
        /// <returns></returns>
        int IFriend.ReplyFriendDetail(int userid, int friendid, bool isconfirm)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            SqlTransaction trans = cn.BeginTransaction();
            try
            {
                string Sql = "update NT_FriendDesc set Reply=";
                if (isconfirm)
                    Sql += "1";
                else
                    Sql += "2";
                Sql += " where Modifier=" + friendid + " and Affirmant=" + userid;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                if (isconfirm)
                {
                    Notify(trans, EnumNotifyType.ConfirmFriendDetail, userid, friendid, string.Empty);
                }
                //加一条请求
                trans.Commit();
                return 0;
            }
            catch
            {
                trans.Rollback();
                throw;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        */
        #endregion
        /// <summary>
        /// 打招呼,非好友也可以打招呼
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendid"></param>
        /// <returns></returns>
        int IFriend.Greet(int userid, int friendid)
        {
            string Sql = "insert into NT_Greet (UserID,FriendID,PostTime,PostIP,IsRead) values (";
            Sql += userid + "," + friendid + ",'" + DateTime.Now + "','" + Public.GetClientIP() + "',0)";
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, null);
        }
        /// <summary>
        /// 是否在同一网络中
        /// </summary>
        /// <param name="cn"></param>
        /// <param name="userid"></param>
        /// <param name="friendid"></param>
        /// <returns></returns>
        static internal bool IsInSameNetwork(SqlConnection cn, int userid, int friendid)
        {
            string Sql = "select Province from NT_User where UserID=" + userid;
            object obj1 = DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
            Sql = "select Province from NT_User where UserID=" + friendid;
            object obj2 = DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
            if (obj1 != null && obj1 != DBNull.Value && obj1 == obj2)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #region 留言
        /// <summary>
        /// 发送留言
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendid"></param>
        /// <param name="word"></param>
        /// <returns></returns>
        int IFriend.SendLeaveword(int userid, int friendid, string word)
        {
            if (word == null || word.Trim() == string.Empty)
                return -2;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            string Sql = "select count(ID) from NT_Friend where UserID=" + userid + " and FriendID=" + friendid;
            int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
            if (n < 1)
            {
                return -1;
            }
            try
            {
                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    DateTime now = DateTime.Now;
                    Sql = "insert into NT_gbook (Sender,Receiver,Content,PostTime,PostIP) values (";
                    Sql += userid + "," + friendid + ",@Content,'" + now + "','" + Public.GetClientIP() + "');select @@IDENTITY";
                    SqlParameter Param = new SqlParameter("@Content", SqlDbType.NVarChar, 1000);
                    Param.Value = word;
                    int lid = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, Param));
                    int m = Notify(trans, EnumNotifyType.Leaveword, userid, friendid, string.Empty, lid);
                    trans.Commit();
                    return m;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 删除留言
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="wordid"></param>
        /// <returns></returns>
        int IFriend.DeleteLeaveword(int userid, int wordid)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string Sql = "select count(ID) from NT_gbook where ID=" + wordid + " and (Sender=" + userid + " or Receiver=" + userid + ")";
                int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                if (n < 1)
                {
                    return -1;
                }
                Sql = "delete from NT_gbook where ID=" + wordid;
                return DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        #endregion


        /// <summary>
        /// 判断是否在同一网络
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendid"></param>
        /// <returns></returns>
        bool IFriend.IsInSameNetwork(int userid, int friendid)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                return IsInSameNetwork(cn, userid, friendid);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 好友统计
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        Dictionary<NetworkInfo, int> Statistic(SqlConnection cn, int userid)
        {
            string Sql = "SELECT COUNT(a.FriendID) AS Total, b.Province, c.Name FROM NT_Friend a ";
            Sql += "INNER JOIN NT_User b ON a.FriendID = b.UserID INNER JOIN NT_Dict_Area c ";
            Sql += "ON b.Province = c.ID WHERE (a.UserID=" + userid + ") GROUP BY b.Province, c.Name";
            IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
            Dictionary<NetworkInfo, int> dctnet = new Dictionary<NetworkInfo, int>();
            while (rd.Read())
            {
                dctnet.Add(new NetworkInfo(Convert.ToInt32(rd["Province"]), rd["Name"].ToString()), Convert.ToInt32(rd["Total"]));
            }
            rd.Close();
            return dctnet;
        }
        /// <summary>
        /// 取得好友
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendname"></param>
        /// <returns></returns>
        Dictionary<int, string> IFriend.GetFriends(int userid, string friendname)
        {
            Dictionary<int, string> dct = new Dictionary<int, string>();
            string Sql = "select a.FriendID,b.UserName from NT_Friend a inner join NT_User b on a.FriendID=b.UserID where a.UserID=" + userid + " and b.UserName like @UserName";
            SqlParameter Param = new SqlParameter("@UserName", "%" + friendname + "%");
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, Param);
            while (rd.Read())
            {
                int id = rd.GetInt32(0);
                if (!dct.ContainsKey(id))
                    dct.Add(id, rd.GetString(1));
            }
            rd.Close();
            return dct;
        }

        /// <summary>
        /// 取得好友（群组）
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="friendname"></param>
        /// <returns></returns>
        Dictionary<int, string> IFriend.GetFriendsForGroup(int userid, int GroupID, string friendname)
        {
            Dictionary<int, string> dct = new Dictionary<int, string>();
            string Sql = "select a.FriendID,b.UserName from NT_Friend a inner join NT_User b on a.FriendID=b.UserID where a.UserID=" + userid + " and (a.FriendID Not In (Select JoinUserID From NT_GroupInvite Where Response=0 And GroupID=" + GroupID + ")) And (a.FriendID Not In(Select UserID From NT_GroupMember Where GroupID=" + GroupID + ")) and b.UserName like  @UserName";
            SqlParameter Param = new SqlParameter("@UserName", SqlDbType.NVarChar, 50);
            Param.Value = "%" + friendname + "%";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, Param);
            while (rd.Read())
            {
                int id = rd.GetInt32(0);
                if (!dct.ContainsKey(id))
                    dct.Add(id, rd.GetString(1));
            }
            rd.Close();
            return dct;
        }
        /// <summary>
        /// 查看两人关系
        /// </summary>
        /// <param name="myid"></param>
        /// <param name="otherid"></param>
        /// <returns>0无任何关系,1本人,2好友,3已发出好友申请,等待确认好友申请,4被申请</returns>
        int IFriend.GetRelation(int myid, int otherid)
        {
            if (myid == otherid)
                return 1;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                EnumReply rp = EnumReply.Agree;
                if (IsFriends(cn, myid, otherid))
                    return 2;
                string Sql = "select Receiver,Demander,ReplyResult from NT_Request where RequestType=" + (int)EnumRequestType.MakeFriends;
                Sql += " and ((Receiver=" + myid + " and Demander=" + otherid + ") or (Receiver=" + otherid + " and Demander=" + myid + "))";
                int n = 0;
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                if (rd.Read())
                {
                    if ((EnumReply)rd.GetInt32(2) == EnumReply.NoneReply)
                    {
                        if (rd.GetInt32(0) == myid)
                            n = 4;
                        else if (rd.GetInt32(1) == myid)
                            n = 3;
                    }

                }
                rd.Close();
                return n;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 邮件邀请好友
        /// </summary>
        /// <param name="userid">邀请者ID</param>
        /// <param name="emails">被邀请者的email</param>
        /// <param name="postscript">附言</param>
        /// <param name="isRepeat">是否重复邀请</param>
        /// <returns>0成功,1该邮箱已经注册,2该邮箱已被邀请,3写入数据库失败</returns>
        Dictionary<string, int> IFriend.InviteFriends(int userId, string userName, string[] emails, string postscript, bool isRepeat)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                Dictionary<string, int> dct = new Dictionary<string, int>();
                foreach (string eml in emails)
                {
                    string code = Rand.Str(11);
                    #region SqlParameter参数
                    SqlParameter[] Param = new SqlParameter[5];
                    Param[0] = new SqlParameter("@Email", SqlDbType.NVarChar, 100);
                    Param[0].Value = eml;
                    Param[1] = new SqlParameter("@Postscript", SqlDbType.NVarChar, 255);
                    if (postscript == null || postscript.Trim() == string.Empty)
                        Param[1].Value = DBNull.Value;
                    else
                        Param[1].Value = postscript;
                    Param[2] = new SqlParameter("@ValidCode", SqlDbType.Char, 11);
                    Param[2].Value = code;
                    #endregion
                    string Sql = "Select Count(UserID) from NT_User where Email=@Email";
                    int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, Param[0]);
                    Sql = "Select Count(ID) from NT_SpareEmail where Email=@Email";
                    n += (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, Param[0]);
                    if (n > 0)
                    {
                        dct.Add(eml, 1);
                        continue;
                    }
                    Sql = "select count(ID) from NT_FriendInvite where Invitee=@Email and Method=1 and UserID=" + userId;
                    n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, Param[0]);
                    if (!isRepeat && n > 0)
                    {
                        dct.Add(eml, 2);
                        continue;
                    }
                    if (isRepeat && n > 0)
                    {
                        Sql = "update NT_FriendInvite set Reply=0,Postscript=@Postscript,PostTime='" + DateTime.Now + "',PostIP='" + Public.GetClientIP() + "'";
                        Sql += ",ValidCode=@ValidCode where Invitee=@Email and Method=1 and UserID=" + userId;
                    }
                    else
                    {
                        Sql = "insert into NT_FriendInvite (UserID,Method,Invitee,Reply,Postscript,PostTime,PostIP,ValidCode) values (";
                        Sql += userId + ",1,@Email,0,@Postscript,'" + DateTime.Now + "','" + Public.GetClientIP() + "',@ValidCode)";
                    }
                    try
                    {
                        #region 发送邮件
                        JuSNS.Common.EMail em = JuSNS.Common.EMail.CreateInstance();
                        string body = EmailConfig.invite;
                        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 + "/InviteReg.aspx?r=" + code);
                        if (postscript == null || postscript.Trim() == string.Empty)
                            body = body.Replace("{Title}", "你的朋友" + userName + "邀请你去" + UiConfig.SiteName + "看看");
                        else
                            body = body.Replace("{Title}", postscript);
                        em.Body = body;
                        em.Subject = userName + "邀请您去" + UiConfig.SiteName;
                        em.To = eml;
                        em.From = userName + "<" + EmailConfig.from + ">";
                        em.Send();
                        #endregion

                        DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, Param);
                        dct.Add(eml, 0);
                    }
                    catch (Exception e)
                    {
                        dct.Add(eml, 4);
                    }
                }
                return dct;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 好友邀请统计
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="confirmed">确认了的</param>
        /// <param name="pending">还未确认的</param>
        void IFriend.InviteStat(int userId, out int confirmed, out int pending)
        {
            confirmed = 0;
            pending = 0;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string Sql = "select count(ID) from NT_FriendInvite where Reply=0 and Method=1 and UserID=" + userId;
                pending = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                Sql = "select count(ID) from NT_FriendInvite where Reply=1 and Method=1 and UserID=" + userId;
                confirmed = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 查看是否具有查看好友列表的权限
        /// </summary>
        /// <param name="guestId"></param>
        /// <param name="masterId"></param>
        /// <returns></returns>
        bool IFriend.CheckListAuthority(int guestId, int masterId)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                EnumPrivacy priv = EnumPrivacy.ForFriends;
                string Sql = "select PrivFriends from NT_UserSetting where UserID=" + masterId;
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                if (rd.Read())
                {
                    if (!rd.IsDBNull(0)) priv = (EnumPrivacy)rd.GetInt32(0);
                }
                rd.Close();
                return CheckPrivacy(cn, priv, guestId, masterId);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        /// <summary>
        /// 寻找MSN,Gtalk好友
        /// </summary>
        /// <param name="eamil">邮件列表</param>
        /// <returns>返回数据表</returns>
        public DataTable FindFriend(string eamil)
        {
            SqlParameter Param = new SqlParameter("@Email", SqlDbType.NText);
            Param.Value = eamil;
            string Sql = "Select a.UserID,a.UserName,b.FilePath,c.[Name] " +
                         "From NT_User As a Inner join NT_Dict_Area c on a.Province=c.ID " +
                         "Inner Join NT_UserInfo as d On a.UserID=d.UserID " +
                         "Left Join NT_Photo b on a.Portrait=b.PhotoID and b.IsLock=0 " +
                         "Where a.Email In(" + eamil + ") Or d.MSN In(" + eamil + ") Or d.GTalk In(" + eamil + ")";
            return DbHelper.ExecuteTable(CommandType.Text, Sql, Param);
        }

        public IList<FriendInfo> GetList(int pageIndex, int pageSize, out int recordCount, out int pageCount, int userId, int network, string searchName,string c, out Dictionary<NetworkInfo, int> stat)
        {
            IList<FriendInfo> list = new List<FriendInfo>();
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                stat = Statistic(cn, userId);
                string TablesAndWhere = "NT_Friend a inner join NT_User b on a.FriendID=b.UserID where b.State!=0 and a.UserID=" + userId;
                if (network > 0)
                {
                    TablesAndWhere += " and b.Province=" + network;
                }
                else if (searchName != null && searchName.Trim() != string.Empty)
                {
                    TablesAndWhere += " and b.UserName like '%" + searchName.Replace("'", "''") + "%'";
                }
                if (c != "#0")
                {
                    if (c == "#1")
                    {
                        TablesAndWhere += " and (a.ClassID=0 or a.ClassID=null)";
                    }
                    else
                    {
                        TablesAndWhere += " and a.ClassID=" + Convert.ToInt32(c);
                    }
                }
                string AllFields = "a.ID,a.FriendID,b.UserName,a.FDegree";
                string IndexField = "a.ID";
                string OrderFields = " order by b.LastLoginTime desc";
                DataTable dt = Pagination.ProcPage(cn, AllFields, TablesAndWhere, IndexField, OrderFields, pageIndex, pageSize, out  recordCount, out  pageCount);
                if (dt != null)
                {
                    foreach (DataRow r in dt.Rows)
                    {
                        FriendInfo info = new FriendInfo();
                        int owner = info.UserId = (int)r[1];
                        info.ID = (int)r[0];
                        info.UserName = (string)r[2];
                        info.FDegree = Convert.ToInt32(r[3]);
                        string Sql = "select PrivMiniBlog from NT_UserSetting where UserID=" + owner;
                        EnumPrivacy prv = (EnumPrivacy)Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null));
                        if (!CheckPrivacy(cn, prv, userId, owner))
                            continue;
                        Sql = "select ID,Content,PostTime from NT_Mood where UserID=" + owner + " and IsLock=0 order by PostTime Desc";
                        IDataReader dr = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                        if (dr.Read())
                        {
                            info.LastMiniBlog = dr.GetString(1);
                            info.LastMiniBlogTime = dr.GetDateTime(2);
                        }
                        dr.Close();
                        list.Add(info);
                    }
                    dt.Dispose();
                    dt = null;
                }
                return list;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        public int UpdateFriendClass(int sUserID, string CName, int ID)
        {
            SqlParameter[] param = new SqlParameter[3];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = sUserID;
            param[1] = new SqlParameter("@ID", SqlDbType.Int, 4);
            param[1].Value = ID;
            param[2] = new SqlParameter("@CName", SqlDbType.NVarChar, 50);
            param[2].Value = CName;
            return DbHelper.ExecuteNonQuery(CommandType.StoredProcedure, "JuSNS_UpdateFriendClass", param);
        }

        public int SetFriendClassID(int UserID, int ClassID,int ID)
        {
            string sql = "update NT_Friend SET ClassID=" + ClassID + " where ID=" + ID + " and UserID=" + UserID;
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
        }


        public int GetUnClassFriend(int UserID)
        {
            SqlParameter param = new SqlParameter("@UserID", UserID);
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.StoredProcedure, "JuSNS_GetUnClassFriend", param));
        }

        public void DelFriendClass(int ID, int UserID)
        {    
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string sql = "delete NT_FriendClass where ID=" + ID + " and UserID=" + UserID;
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, sql, null);

                string sql1 = "update NT_Friend set ClassID=0 where ClassID=" + ID;
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, sql1, null);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        public void AddFriendClass(string CName, int UserID)
        {
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = UserID;
            param[1] = new SqlParameter("@CName", SqlDbType.NVarChar, 50);
            param[1].Value = CName;
            string sql = "insert into NT_FriendClass(CName,UserID) values (@CName,@UserID)";
            DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
        }

        public int GetUserIDFromEmail(string sEmail)
        {
            SqlParameter param = new SqlParameter("@Email", sEmail);
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.StoredProcedure, "JuSNS_GetUserIDFromEmail", param));
        }
    }
}
