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 UserGroup : DbBase, IUserGroup
    {
        /// <summary>
        /// 添加群组
        /// </summary>
        /// <param name="Info">群组实体类</param>
        /// <returns>添加成功返回群编号</returns>
        public int Add(UserGroupInfo Info)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                SqlParameter[] param = getParameters(Info);
                string Sql = "Insert Into [NT_UserGroup]([GroupName]," +
                             "[UserID],[Members],[Bulletin],[NetWork],[Portrait],[Publicity],[State],[PostTime],[PostIP]) " +
                             "Values" +
                             "(@GroupName,@UserID,@Members,@Bulletin,@NetWork,@Portrait,@Publicity,@State,@PostTime,@PostIP);" +
                             "Select @@IDENTITY";
                int GroupID = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, param));

                Sql = "Insert Into [NT_GroupMember]([GroupID],[UserID],[JoinTime],[Grade]) " +
                      "Values" +
                      "(" + GroupID + ",@UserID,@PostTime," + (int)EnumGroupGrade.Master + ")";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, param);
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, Info.UserID, "ActDeliver"))
                {
                    UserDyn(trans, 0, 0, "creatgroup", Info.UserID, Info.UserID, GroupID, "创建了一个群", GroupID.ToString());
                }
                trans.Commit();
                User us = new User();
                us.updateinte(Info.UserID, 5, 0, 0, "创建群");
                return GroupID;
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 删除群组(后台)
        /// </summary>
        /// <param name="GroupID">群组编号</param>
        /// <returns>删除成功返回1</returns>
        public int Del(int GroupID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();
            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                string Sql = string.Empty;
                Sql = "delete from NT_Dyn where infoarr='" + GroupID + "' and dyntype='posttopic' or dyntype='replytopic'";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                Sql = "delete from NT_Dyn where cID=" + GroupID + " and (DynType='creatgroup' or DynType='joingroup')";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除通知表
                Sql = "Delete From [NT_Notice] Where " +
                      "[MsgType]=" + (int)EnumNotifyType.GroupAdmin + " And [Correspond]=" + GroupID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除群组邀请表
                Sql = "Delete From [NT_GroupInvite] Where [GroupID]=" + GroupID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除群组讨论表
                Sql = "Delete From [NT_GroupDiscuss] Where [GroupID]=" + GroupID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除群组成员表S
                Sql = "Delete From [NT_GroupMember] Where [GroupID]=" + GroupID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除群组表
                Sql = "Delete From [NT_UserGroup] Where [GroupID]=" + GroupID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除请求表
                Sql = "Delete From [NT_Request] " +
                      "Where " +
                      "[CorrespondInfo]=" + GroupID + " And " +
                      "([RequestType]=" + (int)EnumRequestType.InviteGroup + " Or [RequestType]=" + (int)EnumRequestType.ApplyGroup + ")";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);

                trans.Commit();
                return 1;
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }


        public int isRec(int GroupId, int st)
        {
            string sql = "update NT_userGroup set isRec=" + st + " where GroupID=" + GroupId;
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
        }

        /// <summary>
        ///  删除群组(前台)
        /// </summary>
        /// <param name="GroupID">群组编号</param>
        /// <param name="UserID">群主编号</param>
        /// <returns>删除成功返回1,否则返回-1</returns>
        public int Del(int GroupID, int UserID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();
            if (!Check(Conn, UserID, GroupID))
                return -1;

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                int n=1;
                string Sql = "delete from NT_Dyn where cID=" + GroupID + " and UserID=" + UserID + " and (DynType='creatgroup' or DynType='joingroup')";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                Sql = "delete from NT_Dyn where infoarr='" + GroupID + "' and dyntype='posttopic' or dyntype='replytopic'";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除群组邀请表
                Sql = "Delete From [NT_GroupInvite] Where [GroupID]=" + GroupID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除群组讨论表
                Sql = "Delete From [NT_GroupDiscuss] Where [GroupID]=" + GroupID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除群组成员表
                Sql = "Delete From [NT_GroupMember] Where [GroupID]=" + GroupID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除群组表
                Sql = "Delete From [NT_UserGroup] Where [GroupID]=" + GroupID + " And [UserID]=" + UserID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除请求表
                Sql = "Delete From [NT_Request] " +
                      "Where " +
                      "[CorrespondInfo]=" + GroupID + " And " +
                      "([RequestType]=" + (int)EnumRequestType.InviteGroup + " Or [RequestType]=" + (int)EnumRequestType.ApplyGroup + ")";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);

                trans.Commit();
                User us = new User();
                us.updateinte(UserID, 5, 0, 1,"删除群");

                return n;
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 修改群组基本信息
        /// </summary>
        /// <param name="Info">群组实体类</param>
        /// <returns>修改成功返回1</returns>
        public int EditInfo(UserGroupInfo Info)
        {
            SqlParameter[] param = getParameters(Info);
            string Sql = "Update [NT_UserGroup] " +
                         "Set [GroupName]=@GroupName,[Bulletin]=@Bulletin,[NetWork]=@NetWork,[Publicity]=@Publicity " +
                         "Where [GroupID]=@GroupID And [UserID]=@UserID";
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, param);
        }

        /// <summary>
        /// 修改群组头像
        /// </summary>
        /// <param name="Info">群组实体类</param>
        /// <returns>修改成功返回1</returns>
        public int EditHead(UserGroupInfo Info)
        {
            SqlParameter[] param = getParameters(Info);
            string Sql = "Update [NT_UserGroup] " +
                         "Set [Portrait]=@Portrait " +
                         "Where [GroupID]=@GroupID And [UserID]=@UserID";
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, param);
        }

        /// <summary>
        /// 取得会员总共加入的群组数
        /// </summary>
        /// <param name="UserID">会员编号</param>
        /// <param name="a">join & creat</param>
        /// <returns></returns>
        public int Count(int UserID,string a)
        {
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[0].Value = UserID;
            param[1] = new SqlParameter("@a", SqlDbType.NVarChar, 6);
            param[1].Value = a;
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.StoredProcedure, "JuSNS_GroupCount", param));
        }

        /// <summary>
        /// 检查是否是自已的群组
        /// </summary>
        /// <param name="GroupID">群组编号</param>
        /// <param name="UserID">会员编号</param>
        /// <returns></returns>
        public bool IsMyGroup(int GroupID, int UserID)
        {
            bool tf = false;
            string Sql = "Select Count([GroupID]) From [NT_UserGroup] Where [GroupID]=" + GroupID + " And [UserID]=" + UserID;
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, Sql, null));
            if (n > 0)
                tf = true;
            return tf;
        }

        /// <summary>
        /// 群组信息
        /// </summary>
        /// <param name="GroupID">群组编号</param>
        /// <returns>返回群组实体类</returns>
        public UserGroupInfo Info(int GroupID)
        {
            UserGroupInfo info = new UserGroupInfo();

            string Sql = "Select [GroupID],[GroupName],[UserID]," +
                         "[Members],[Bulletin],[NetWork],[Portrait],[Publicity],[State],[PostTime],[PostIP] " +
                         "From " +
                         "[NT_UserGroup] " +
                         "Where [GroupID]=" + GroupID;
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, null);
            if (rd.Read())
            {
                info.GroupID = Convert.ToInt32(rd["GroupID"].ToString());
                if (rd["GroupName"] != DBNull.Value) info.GroupName = rd["GroupName"].ToString();
                info.UserID = Convert.ToInt32(rd["UserID"].ToString());
                info.Members = Convert.ToInt32(rd["Members"].ToString());
                if (rd["Bulletin"] != DBNull.Value) info.Bulletin = rd["Bulletin"].ToString();
                info.NetWork = Convert.ToInt32(rd["NetWork"].ToString());
                if (rd["Portrait"] != DBNull.Value) info.Portrait = rd["Portrait"].ToString();
                info.Publicity = (EnumGroupPrivacy)Convert.ToInt32(rd["Publicity"].ToString());
                info.State = Convert.ToInt32(rd["State"].ToString());
                info.PostTime = Convert.ToDateTime(rd["PostTime"].ToString());
                if (rd["PostIP"] != DBNull.Value) info.PostIP = rd["PostIP"].ToString();
            }
            rd.Close();
            return info;
        }

        /// <summary>
        /// 检查数据库是否存在此记录
        /// </summary>
        /// <param name="Conn">SQL联接对象</param>
        /// <param name="UserID">会员编号</param>
        /// <param name="GroupID">群编号</param>
        /// <returns>存在返回true,否则返回false</returns>
        private bool Check(SqlConnection Conn, int UserID, int GroupID)
        {
            bool tf = false;
            string Sql = "Select Count([GroupID]) From [NT_UserGroup] Where [UserID]=" + UserID + " And GroupID=" + GroupID;
            int i_Cnt = Convert.ToInt32(DbHelper.ExecuteScalar(Conn, CommandType.Text, Sql, null));
            if (i_Cnt > 0)
                tf = true;
            return tf;
        }
        /// <summary>
        /// 取得指定用户群组
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public List<UserGroupInfo> GetUserGroup(int UserID)
        {
            List<UserGroupInfo> grouplist = new List<UserGroupInfo>();
            SqlParameter param = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param.Value = UserID;
            string sql = "Select [GroupID],[GroupName],[UserID],[Members],[Bulletin],[NetWork],[Portrait],[Publicity],[State],[PostTime],[PostIP] From [NT_UserGroup] Where [GroupID] in (select GroupID from NT_GroupMember where UserID=@UserID)";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, sql, param);
            while (rd.Read())
            {
                UserGroupInfo info = new UserGroupInfo();
                info.GroupID = Convert.ToInt32(rd["GroupID"].ToString());
                if (rd["GroupName"] != DBNull.Value) info.GroupName = rd["GroupName"].ToString();
                info.UserID = Convert.ToInt32(rd["UserID"].ToString());
                info.Members = Convert.ToInt32(rd["Members"].ToString());
                if (rd["Bulletin"] != DBNull.Value) info.Bulletin = rd["Bulletin"].ToString();
                info.NetWork = Convert.ToInt32(rd["NetWork"].ToString());
                if (rd["Portrait"] != DBNull.Value) info.Portrait = rd["Portrait"].ToString();
                info.Publicity = (EnumGroupPrivacy)Convert.ToInt32(rd["Publicity"].ToString());
                info.State = Convert.ToInt32(rd["State"].ToString());
                info.PostTime = Convert.ToDateTime(rd["PostTime"].ToString());
                if (rd["PostIP"] != DBNull.Value) info.PostIP = rd["PostIP"].ToString();
                grouplist.Add(info);
            }
            return grouplist;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Info">群组实体类</param>
        /// <returns>返回SQL参数</returns>
        private SqlParameter[] getParameters(UserGroupInfo Info)
        {
            SqlParameter[] param = new SqlParameter[11];

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

            param[3] = new SqlParameter("@Members", SqlDbType.Int, 4);
            param[3].Value = Info.Members;
            param[4] = new SqlParameter("@Bulletin", SqlDbType.NVarChar, 255);
            param[4].Value = Info.Bulletin;
            param[5] = new SqlParameter("@NetWork", SqlDbType.Int, 4);
            param[5].Value = Info.NetWork;

            param[6] = new SqlParameter("@Portrait", SqlDbType.NVarChar, 255);
            param[6].Value = Info.Portrait;
            param[7] = new SqlParameter("@Publicity", SqlDbType.Int, 4);
            param[7].Value = Info.Publicity;
            param[8] = new SqlParameter("@State", SqlDbType.Int, 4);
            param[8].Value = Info.State;

            param[9] = new SqlParameter("@PostTime", SqlDbType.DateTime, 8);
            param[9].Value = Info.PostTime;
            param[10] = new SqlParameter("@PostIP", SqlDbType.VarChar, 15);
            param[10].Value = Info.PostIP;

            return param;
        }

        public DataTable GetUserGroupDis(int GroupID, int TopNum)
        {
            string sql = "select top " + TopNum + " ID,Topic,GroupID from NT_groupdiscuss where GroupID=" + GroupID + " and BelongTopic=0 and len(Topic)>5 order by LastPostTime desc,id desc";
            return DbHelper.ExecuteTable(CommandType.Text, sql, null);
        }

    }
}
