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

namespace JuSNS.SQLServer
{
    /// <summary>
    /// 群组成员类
    /// </summary>
    public class GroupMember : DbBase, IGroupMember
    {
        /// <summary>
        /// 加入群组
        /// </summary>
        /// <param name="Info">群组成员实体类</param>
        /// <returns>加入成功返回1</returns>
        public int Join(GroupMemberInfo Info)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                int cID = 0;
                SqlParameter[] param = getParameters(Info);
                string checkSql = "Select Count([ID]) From [NT_GroupMember] Where [GroupID]=@GroupID And [UserID]=@UserID";
                int count = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, checkSql, param));
                if (count == 0)
                {
                    string Sql = "Insert Into [NT_GroupMember]([GroupID],[UserID],[JoinTime],[Grade]) " +
                                 "Values" +
                                 "(@GroupID,@UserID,@JoinTime,@Grade);Select @@IDENTITY";
                    cID = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, param));

                    Sql = "Update [NT_UserGroup] Set [Members]=[Members]+1 Where [GroupID]=@GroupID";
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, param);
                    JUser ju = new JUser();
                    if (ju.CheckPrivacyInfo(trans, Info.UserID, "ActDeliver"))
                    {
                         UserDyn(trans, 0, 0, "joingroup", Info.UserID, 0, Info.GroupID, "加入了群", cID.ToString());
                    }
                }
                trans.Commit();
                return cID;
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 退出一个群
        /// </summary>
        /// <param name="UserID">会员编号</param>
        /// <param name="GroupID">群编号</param>
        /// <returns></returns>
        public int Out(int UserID, int GroupID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                //删除群组成员表
                string Sql = "Delete From [NT_GroupMember] " +
                             "Where " +
                             "[GroupID]=" + GroupID + " And [UserID]=" + UserID + "";
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                if (n > 0)
                {
                    JUser ju = new JUser();
                    if (ju.CheckPrivacyInfo(trans, UserID, "ActDeliver"))
                    {
                        UserDyn(trans, 0, 0, "outgroup", UserID, 0, GroupID, "退出群", GroupID.ToString());
                    }
                    Sql = "delete from NT_dyn where cID=" + GroupID + " and (dynType='joingroup' or dynType='posttopic')";
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    //更新群组成员个数
                    Sql = "Update [NT_UserGroup] Set [Members]=[Members]-1 Where [GroupID]=" + GroupID;
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    //删除群组邀请表
                    Sql = "Delete From [NT_GroupInvite] " +
                          "Where [GroupID]=" + GroupID + " And ([UserID]=" + UserID + " Or [JoinUserID]=" + UserID + ")";
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    //删除群组讨论表
                    Sql = "Delete From [NT_GroupDiscuss] Where [UserID]=" + UserID + " And [GroupID]=" + GroupID + "";
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    //删除通知表
                    Sql = "Delete From [NT_Notice] Where [Receiver]=" + UserID + " " +
                          "And [MsgType]=" + (int)EnumNotifyType.GroupAdmin + " And [Correspond]=" + GroupID;
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                }
                trans.Commit();
                return n;
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 设置群成员为管理员
        /// </summary>
        /// <param name="GroupUserID">群成员编号</param>
        /// <param name="GroupID">组编号</param>
        /// <param name="UserID">群主编号</param>
        /// <returns>设置成功返回1</returns>
        public int SetAdmin(int GroupUserID, int GroupID, int UserID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                string Sql = "Update [NT_GroupMember] " +
                             "Set " +
                             "[Grade]=" + (int)EnumGroupGrade.Admin + " " +
                             "Where [UserID]=" + GroupUserID + " And " +
                                "[GroupID]=(Select [GroupID] From [NT_UserGroup] Where " +
                                    "[GroupID]=" + GroupID + " And [UserID]=" + UserID + ")";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);

                int n = Notify(trans, EnumNotifyType.GroupAdmin, UserID, GroupUserID, "成为了群管理员", GroupID);
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, GroupUserID, "ActDeliver"))
                {
                    UserDyn(trans, 0, 0, "groupAdmin", GroupUserID, UserID, GroupID, "成为了管理员", GroupID.ToString());
                }
                trans.Commit();
                return n;
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 删除群管理员
        /// </summary>
        /// <param name="GroupUserID">群成员编号</param>
        /// <param name="GroupID">组编号</param>
        /// <param name="UserID">群主编号</param>
        /// <returns>设置成功返回1</returns>
        public int DelAdmin(int GroupUserID, int GroupID, int UserID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                string Sql = "Update [NT_GroupMember] " +
                             "Set " +
                             "[Grade]=" + (int)EnumGroupGrade.Common + " " +
                             "Where [UserID]=" + GroupUserID + " And " +
                                "[GroupID]=(Select [GroupID] From [NT_UserGroup] Where " +
                                    "[GroupID]=" + GroupID + " And [UserID]=" + UserID + ")";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除通知表
                Sql = "Delete From [NT_Notice] Where [Receiver]=" + GroupUserID + " " +
                      "And [MsgType]=" + (int)EnumNotifyType.GroupAdmin + " And [Correspond]=" + GroupID + " And [Sender]=" + UserID;
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                trans.Commit();
                return n;
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 管理员辞职
        /// </summary>
        /// <param name="UserID">会员编号</param>
        /// <param name="GroupID">群组编号</param>
        /// <returns>辞职成功返回1</returns>
        public int QuitGroup(int UserID, int GroupID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                string Sql = "Update [NT_GroupMember] " +
                             "Set " +
                             "[Grade]=" + (int)EnumGroupGrade.Common + " " +
                             "Where [UserID]=" + UserID + " And " +
                                "[GroupID]=" + GroupID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除通知表
                Sql = "Delete From [NT_Notice] Where " +
                      "[MsgType]=" + (int)EnumNotifyType.GroupAdmin + " And [Correspond]=" + GroupID + " And [Receiver]=" + UserID;
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                trans.Commit();
                return n;
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 取得群组各等级类型的群员列表
        /// </summary>
        /// <param name="Grade">类型</param>
        /// <param name="GroupID">组编号</param>
        /// <returns></returns>
        public DataTable GroupMemberGradeList(int Grade, int GroupID)
        {
            string Sql = "";
            switch (Grade)
            {
                case 0:
                    Sql = "Select a.[UserID],a.[Grade],b.[UserName],c.[Name] From [NT_GroupMember] As a Inner Join NT_User As b " +
                          "On a.[UserID]=b.[UserID] Inner Join [NT_Dict_Area] As c On b.[Province]=c.[ID] Where " +
                          "a.[GroupID]=" + GroupID + " And a.[Grade]<>3 Order By a.[Grade] Asc";
                    break;
                case 1:
                    Sql = "Select a.[JoinUserID],b.[UserName],c.[Name] From " +
                          "[NT_GroupInvite] As a Inner Join [NT_User] As b On a.[JoinUserID]=b.[UserID]" +
                          "Inner Join [NT_Dict_Area] As c On b.[Province]=c.[ID] " +
                          "Where a.[Response]=0 And a.[GroupID]=" + GroupID;
                    break;
                case 2:
                    Sql = "Select a.[UserID],a.[Grade],b.[UserName],c.[Name] From [NT_GroupMember] As a Inner Join NT_User As b " +
                          "On a.[UserID]=b.[UserID] Inner Join [NT_Dict_Area] As c On b.[Province]=c.[ID] Where " +
                          "a.[GroupID]=" + GroupID + " And (a.[Grade]=0 Or a.[Grade]=1) Order By a.[Grade] Asc";
                    break;

                case 3:
                    Sql = "Select a.[UserID],a.[Grade],b.[UserName],c.[Name] From [NT_GroupMember] As a Inner Join " +
                          "[NT_User] As b On a.[UserID]=b.[UserID] Inner Join [NT_Dict_Area] As c On b.[Province]=c.[ID] " +
                          "Where a.[GroupID]=" + GroupID + " And a.[Grade]=3 Order By a.[ID] Desc";
                    break;
            }
            return DbHelper.ExecuteTable(CommandType.Text, Sql, null);
        }

        /// <summary>
        /// 取得最新六位成员
        /// </summary>
        /// <param name="GroupID">群组编号</param>
        /// <returns>返回数据表</returns>
        public DataTable Top6GroupMemberList(int GroupID)
        {
            string Sql = "Select top 10 a.[UserID],b.[UserName],c.[FilePath] From [NT_GroupMember] As a Inner Join [NT_User] " +
                         "As b On a.[UserID]=b.[UserID] Left Join [Nt_Photo] As c On b.[Portrait]=c.[PhotoID] " +
                         "And c.[IsLock]=0 Where a.[GroupID]=" + GroupID + " Order By [JoinTime] Desc";
            return DbHelper.ExecuteTable(CommandType.Text, Sql, null);
        }

        /// <summary>
        /// 检查会员是不是此组的成员
        /// </summary>
        /// <param name="UserID">会员编号</param>
        /// <param name="GroupID">群组编号</param>
        /// <returns>如果是返回true，否则返回false</returns>
        public bool IsGroupMember(int UserID, int GroupID)
        {
            bool tf = false;
            string Sql = "Select Count([ID]) From [NT_GroupMember] Where " +
                         "[GroupID]=" + GroupID + " And [UserID]=" + UserID + " And [Grade]<>3";
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, Sql, null));
            if (n > 0)
                tf = true;
            return tf;
        }

        /// <summary>
        /// 检查会员是不是此组的管理员
        /// </summary>
        /// <param name="UserID">会员编号</param>
        /// <param name="GroupID">群组编号</param>
        /// <returns>如果是返回true，否则返回false</returns>
        public bool IsGroupAdmin(int UserID, int GroupID)
        {
            bool tf = false;
            string Sql = "Select Count([ID]) From [NT_GroupMember] Where " +
                         "[GroupID]=" + GroupID + " And [UserID]=" + UserID + " And [Grade]=1";
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, Sql, null));
            if (n > 0)
                tf = true;
            return tf;
        }

        /// <summary>
        /// 取得群组是否有邀请
        /// </summary>
        /// <param name="UserID">会员编号</param>
        /// <returns>返回数据表</returns>
        public DataTable getGroupRequest(int UserID)
        {
            string Sql = "Select a.GroupID,a.GroupName,a.Portrait,b.Postscript,b.UserID,b.ID,c.UserName From " +
                         "NT_UserGroup as a inner Join NT_GroupInvite as b on a.GroupID=b.GroupID " +
                         "inner Join NT_User as c on b.UserID=c.UserID Where b.Response=0 And b.JoinUserID=" + UserID;
            return DbHelper.ExecuteTable(CommandType.Text, Sql, null);
        }

        /// <summary>
        /// 取得群组成员信息
        /// </summary>
        /// <param name="ID">记录编号</param>
        /// <returns></returns>
        public GroupMemberInfo Info(int ID)
        {
            GroupMemberInfo info = new GroupMemberInfo();

            string Sql = "Select [ID],[GroupID],[UserID],[JoinTime],[Grade] " +
                         "From " +
                         "[NT_UserGroup] " +
                         "Where [ID]=" + ID;
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, null);
            if (rd.Read())
            {
                info.ID = Convert.ToInt32(rd["ID"].ToString());
                info.GroupID = Convert.ToInt32(rd["GroupID"].ToString());
                info.UserID = Convert.ToInt32(rd["UserID"].ToString());
                info.JoinTime = Convert.ToDateTime(rd["JoinTime"].ToString());
                info.Grade = (EnumGroupGrade)Convert.ToInt32(rd["Grade"].ToString());
            }
            rd.Close();
            return info;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Info">群组实体类</param>
        /// <returns>返回SQL参数</returns>
        private SqlParameter[] getParameters(GroupMemberInfo Info)
        {
            SqlParameter[] param = new SqlParameter[5];

            param[0] = new SqlParameter("@ID", SqlDbType.Int, 4);
            param[0].Value = Info.ID;
            param[1] = new SqlParameter("@GroupID", SqlDbType.Int, 4);
            param[1].Value = Info.GroupID;
            param[2] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[2].Value = Info.UserID;

            param[3] = new SqlParameter("@JoinTime", SqlDbType.DateTime, 8);
            param[3].Value = Info.JoinTime;
            param[4] = new SqlParameter("@Grade", SqlDbType.Int, 4);
            param[4].Value = (int)Info.Grade;

            return param;
        }
    }
}
