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 Group : DbBase, IGroup
    {
        /// <summary>
        /// 添加新主题
        /// </summary>
        /// <param name="Info">群讨论实体类</param>
        /// <returns>添加成功返回1</returns>
        public int Add(GroupDiscussInfo Info)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                try
                {
                    SqlParameter[] param = getParameters(Info);
                    string Sql = "Insert Into [NT_GroupDiscuss]([GroupID]," +
                                 "[UserID],[Topic],[Content],[DiscussType],[BelongTopic],[PostTime],[PostIP],[Replys]," +
                                 "[State],[TopNum],[SeriesNum])Values" +
                                 "(@GroupID,@UserID,@Topic,@Content,@DiscussType,@BelongTopic,@PostTime,@PostIP,@Replys,@State," +
                                 "@TopNum,@SeriesNum)" +
                                 "Select @@IDENTITY";
                    int ID = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, param));
                    JUser ju = new JUser();
                    if (ju.CheckPrivacyInfo(trans, Info.UserID, "ActDeliver"))
                    {
                        UserDyn(trans, 0, 0, "posttopic", Info.UserID, 0, ID, "发表了新主题", Info.GroupID.ToString());
                    }
                    trans.Commit();
                    User us = new User();
                    us.updateinte(Info.UserID, 2, 0, 0, "群组发表主题");
                    return ID;
                }
                catch (SqlException e)
                {
                    trans.Rollback();
                    throw e;
                }
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 修改主题信息
        /// </summary>
        /// <param name="Content">内容</param>
        /// <param name="UserID">会员编号</param>
        /// <param name="ID">回复编号</param>
        /// <returns>修改成功返回1</returns>
        public int Edit(string Content, int UserID, int ID)
        {
            SqlParameter[] param = new SqlParameter[5];
            param[0] = new SqlParameter("@Content", SqlDbType.NText);
            param[0].Value = Content;
            param[1] = new SqlParameter("@UserID", SqlDbType.Int, 4);
            param[1].Value = UserID;
            param[2] = new SqlParameter("@ID", SqlDbType.Int, 4);
            param[2].Value = ID;
            param[3] = new SqlParameter("@LastModifyTime", SqlDbType.DateTime, 8);
            param[3].Value = DateTime.Now;
            param[4] = new SqlParameter("@LastModifyIP", SqlDbType.VarChar, 15);
            param[4].Value = JuSNS.Common.Public.GetClientIP();

            string Sql = "Update [NT_GroupDiscuss] " +
                         "Set " +
                         "[Content]=@Content,[LastModifyTime]=@LastModifyTime,[LastModifyIP]=@LastModifyIP " +
                         "Where " +
                         "[ID]=@ID And [UserID]=@UserID";
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, param);
        }

        /// <summary>
        /// 删除(后台)
        /// </summary>
        /// <param name="ID">编号</param>
        /// <returns>删除成功返回1</returns>
        public int Del(int ID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                GroupDiscussInfo Info = new GroupDiscussInfo();
                Group discuss = new Group();
                Info = discuss.Info(ID);
                string Sql = "delete from NT_Dyn where cid=" + ID + " and (dynType='posttopic' or dynType='replytopic')";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                if (ID == Info.BelongTopic)
                    Sql = "Delete From [NT_GroupDiscuss]  Where [BelongTopic]=" + ID;
                else
                    Sql = "Update [NT_GroupDiscuss] Set [State]=3 Where [ID]=" + ID;
                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();
            }
        }

        /// <summary>
        /// 删除(前台)
        /// </summary>
        /// <param name="ID">编号</param>
        /// <param name="UserID">会员编号</param>
        /// <returns>返回影响记录数</returns>
        public int Del(int ID, int UserID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                GroupDiscussInfo Info = new GroupDiscussInfo();
                Group discuss = new Group();
                Info = discuss.Info(ID);
                string Sql = "";
                int n = 0;
                bool tf = false;
                if (Info.BelongTopic == 0)
                {
                    tf = true;
                    Sql = "Delete From [NT_GroupDiscuss]  Where [ID]=" + ID;
                }
                else
                {
                    Sql = "Update [NT_GroupDiscuss] Set [State]=3 Where [ID]=" + ID + " And [UserID]=" + UserID;
                }
                n = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, null));
                if (n > 0)
                {
                    Sql = "delete from NT_Dyn where cid=" + ID + " and (dynType='posttopic' or dynType='replytopic')";
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    if (tf)
                    {
                        //删除主题
                        Sql = "Delete From [NT_GroupDiscuss] " +
                              "Where " +
                              "[BelongTopic]=" + ID;
                        DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    }
                }
                trans.Commit();
                User us = new User();
                us.updateinte(UserID, 2, 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 Replay(GroupDiscussInfo Info)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                GroupDiscussInfo tempinfo = this.Info(Info.BelongTopic);

                SqlParameter[] param = getParameters(Info);
                string Sql = "Insert Into [NT_GroupDiscuss]([GroupID],[Topic]," +
                             "[UserID],[Content],[DiscussType],[BelongTopic],[PostTime],[PostIP]," +
                             "[SeriesNum],[Replys],[State],[ReplyTack])" +
                             "Values" +
                             "(@GroupID,@Topic,@UserID,@Content,@DiscussType,@BelongTopic,@PostTime,@PostIP," +
                             "@SeriesNum,@Replys,@State,@ReplyTack)" +
                             "Select @@IDENTITY";
                int m = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, param));

                Sql = "Update [NT_GroupDiscuss] Set [LastPostTime]=@LastPostTime,[LastPostIP]=@LastPostIP," +
                      "[LastPoster]=@UserID,[Replys]=[Replys]+1 Where ID=@BelongTopic";
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, param);

                //判断是否是自已发表的主题，不是则添加通知
                if (tempinfo.UserID != Info.UserID)
                {
                    Notify(trans, EnumNotifyType.ReGroupTopic, Info.UserID, tempinfo.UserID, "回复了你的主题", Info.BelongTopic);
                }
                //相关ID改为插入贴子本身的ID，因为还要获取帖子的内容，这样开销比较小
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, Info.UserID, "ActDeliver"))
                {
                    UserDyn(trans, 0, 0, "replytopic", Info.UserID, 0,m, "回复主题", Info.GroupID.ToString());
                }
                trans.Commit();
                User us = new User();
                us.updateinte(Info.UserID, 1, 0, 0,"回复主题");
                return (n+m);
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 锁定主题
        /// </summary>
        /// <param name="ID">主题编号</param>
        /// <returns>锁定成功返回1</returns>
        public int Lock(int ID)
        {
            string Sql = "Update [NT_GroupDiscuss] " +
                         "Set [State]=" + EnumIsLock.Lock + " Where [BelongTopic]=" + ID;
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, null);
        }

        /// <summary>
        /// 解锁主题
        /// </summary>
        /// <param name="ID">主题编号</param>
        /// <returns>解锁成功返回1</returns>
        public int UnLock(int ID)
        {
            string Sql = "Update [NT_GroupDiscuss] " +
                         "Set [State]=" + EnumIsLock.UnLock + " Where [BelongTopic]=" + ID;
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, null);
        }

        /// <summary>
        /// 置顶主题
        /// </summary>
        /// <param name="ID">主题编号</param>
        /// <returns>置顶成功返回1</returns>
        public int Top(int ID)
        {
            string Sql = "Update [NT_GroupDiscuss] " +
                         "Set [TopNum]=1 Where [ID]=" + ID;
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, null);
        }

        /// <summary>
        /// 取消置顶
        /// </summary>
        /// <param name="ID">主题编号</param>
        /// <returns>取消置顶成功返回1</returns>
        public int UnTop(int ID)
        {
            string Sql = "Update [NT_GroupDiscuss] " +
                         "Set [TopNum]=0 Where [ID]=" + ID;
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, null);
        }

        /// <summary>
        /// 取得讨论信息
        /// </summary>
        /// <param name="ID">贴子编号</param>
        /// <returns>返回群讨论实体类</returns>
        public GroupDiscussInfo Info(int ID)
        {
            GroupDiscussInfo info = new GroupDiscussInfo();
            string Sql = "Select [ID],[GroupID],[UserID],[Topic],[Content],[DiscussType]," +
                         "[LastModifyTime],[BelongTopic],[PostTime],[PostIP],[LastPostTime],[LastPostIP],[LastPoster],[Replys],[State]," +
                         "[LastModifyIP],[ReplyID],[ReplyTack],[SeriesNum],[TopNum]" +
                         "From " +
                         "[NT_GroupDiscuss] " +
                         "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());
                if (rd["Topic"] != DBNull.Value) info.Topic = rd["Topic"].ToString();
                if (rd["Content"] != DBNull.Value) info.Content = rd["Content"].ToString();
                info.DiscussType = Convert.ToInt32(rd["DiscussType"].ToString());
                if (rd["LastModifyTime"] != DBNull.Value) info.LastModifyTime = Convert.ToDateTime(rd["LastModifyTime"].ToString());
                info.BelongTopic = Convert.ToInt32(rd["BelongTopic"].ToString());
                info.PostTime = Convert.ToDateTime(rd["PostTime"].ToString());
                if (rd["PostIP"] != DBNull.Value) info.PostIP = rd["PostIP"].ToString();
                if (rd["LastPostTime"] != DBNull.Value) info.LastPostTime = Convert.ToDateTime(rd["LastPostTime"].ToString());
                if (rd["LastPostIP"] != DBNull.Value) info.LastPostIP = rd["LastPostIP"].ToString();
                if (rd["LastPoster"] != DBNull.Value) info.LastPoster = Convert.ToInt32(rd["LastPoster"].ToString());
                info.Replys = Convert.ToInt32(rd["Replys"].ToString());
                info.State = Convert.ToInt32(rd["State"].ToString());
                if (rd["LastModifyIP"] != DBNull.Value) info.LastModifyIP = rd["LastModifyIP"].ToString();
                if (rd["ReplyID"] != DBNull.Value) info.ReplyID = Convert.ToInt32(rd["ReplyID"].ToString());
                if (rd["ReplyTack"] != DBNull.Value) info.ReplyTack = rd["ReplyTack"].ToString();
                if (rd["SeriesNum"] != DBNull.Value) info.SeriesNum = Convert.ToInt32(rd["SeriesNum"].ToString());
                info.TopNum = Convert.ToInt32(rd["TopNum"].ToString());
            }
            rd.Close();
            return info;
        }

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

            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("@Topic", SqlDbType.NVarChar, 40);
            param[3].Value = Info.Topic;
            param[4] = new SqlParameter("@Content", SqlDbType.NVarChar, 4000);
            param[4].Value = Info.Content;
            param[5] = new SqlParameter("@DiscussType", SqlDbType.Int, 4);
            param[5].Value = Info.DiscussType;

            param[6] = new SqlParameter("@BelongTopic", SqlDbType.Int, 4);
            param[6].Value = Info.BelongTopic;
            param[7] = new SqlParameter("@PostTime", SqlDbType.DateTime, 8);
            param[7].Value = Info.PostTime;
            param[8] = new SqlParameter("@PostIP", SqlDbType.VarChar, 15);
            param[8].Value = Info.PostIP;

            param[9] = new SqlParameter("@LastPostTime", SqlDbType.DateTime, 8);
            param[9].Value = Info.LastPostTime;
            param[10] = new SqlParameter("@LastPostIP", SqlDbType.VarChar, 15);
            param[10].Value = Info.LastPostIP;
            param[11] = new SqlParameter("@LastPoster", SqlDbType.Int, 4);
            param[11].Value = Info.LastPoster;

            param[12] = new SqlParameter("@Replys", SqlDbType.Int, 4);
            param[12].Value = Info.Replys;
            param[13] = new SqlParameter("@State", SqlDbType.Int, 4);
            param[13].Value = Info.State;
            param[14] = new SqlParameter("@LastModifyTime", SqlDbType.DateTime, 8);
            param[14].Value = Info.LastModifyTime;

            param[15] = new SqlParameter("@LastModifyIP", SqlDbType.VarChar, 15);
            param[15].Value = Info.LastModifyIP;
            param[16] = new SqlParameter("@ReplyID", SqlDbType.Int, 4);
            param[16].Value = Info.ReplyID;
            param[17] = new SqlParameter("@ReplyTack", SqlDbType.NVarChar, 100);
            param[17].Value = Info.ReplyTack;

            param[18] = new SqlParameter("@SeriesNum", SqlDbType.Int, 4);
            param[18].Value = Info.SeriesNum;
            param[19] = new SqlParameter("@TopNum", SqlDbType.Int, 4);
            param[19].Value = Info.TopNum;
            return param;
        }
    }
}
