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

namespace JuSNS.SQLServer
{
    public class Mood : DbBase, IMood
    {
        /// <summary>
        /// 保存心情日记
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="Content">内容</param>
        /// <returns></returns>
        public int SaveMini(int userId, string content,string mType)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            SqlTransaction trans = cn.BeginTransaction();
            try
            {
                string sql = "insert into NT_Mood (UserID,Content,PostTime,PostIP,IsLock,mType,isRec) values (" + userId + ",@Content,'" + DateTime.Now.ToString() + "','" + JuSNS.Common.Public.GetClientIP() + "',0,'" + mType + "',0);SELECT @@IDENTITY";
                SqlParameter param = new SqlParameter("@Content", SqlDbType.NVarChar, 1000);
                param.Value = content;
                int id = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, sql, param));
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, userId, "ActLogComment"))
                {
                    UserDyn(trans, 0, 0, "mood", userId, 0, id, "发表心情日记", id.ToString());
                }
                trans.Commit();
                //增加积分
                User us = new User();
                us.updateinte(userId, 2, 0, 0, "发表心情日记");
                return id;
            }
            catch
            {
                trans.Rollback();
                throw;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 删除心情日记
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int DeleteMini(int userId, int miniId, bool isAdmin)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string Sql;
                if (!isAdmin)
                {
                    Sql = "select count(ID) from NT_Mood where ID=" + miniId + " and UserID=" + userId;
                    int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                    if (n < 1)
                    {
                        throw new Exception("对不起,你没有删除该心情日记的权限");
                    }
                }
                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    Sql = "delete from NT_Mood where ID=" + miniId;
                    int m = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    Sql = "delete from NT_MoodComment where MiniBlogID=" + miniId;
                    m += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    trans.Commit();
                    User us = new User();
                    us.updateinte(userId, 2, 0, 1,"删除心情日记");
                    return m;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 获取MiniBlogInfo实例
        /// </summary>
        /// <param name="MiniID"></param>
        /// <returns></returns>
        public MiniBlogInfo GetMiniInfo(int MiniID)
        {
            MiniBlogInfo MiniInfo = new MiniBlogInfo();
            MiniInfo.ID = MiniID;
            string sql = "select * from NT_Mood where ID=" + MiniID.ToString();
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, sql, null);
            if (rd.Read())
            {
                MiniInfo.UserID = Convert.ToInt32(rd["UserID"].ToString());
                MiniInfo.Content = Convert.ToString(rd["Content"].ToString());
                MiniInfo.PostTime = Convert.ToDateTime(rd["PostTime"].ToString());
                MiniInfo.PostIP = Convert.ToString(rd["PostIP"].ToString());
                MiniInfo.IsLock = Convert.ToBoolean(rd["IsLock"].ToString());
            }
            rd.Close();
            return MiniInfo;
        }
        /// <summary>
        /// 获取用户的最后发布的心情日记
        /// </summary>
        /// <param name="vistor"></param>
        /// <param name="owner"></param>
        /// <returns></returns>
        public MiniBlogInfo GetLastInfo(int vistor, int owner)
        {
            MiniBlogInfo info = new MiniBlogInfo();
            info.ID = -1;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                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, vistor, owner))
                    return info;
                Sql = "select ID,Content,PostTime from NT_Mood where UserID=" + owner + " and IsLock=0 order by PostTime Desc";
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                if (rd.Read())
                {
                    info.ID = rd.GetInt32(0);
                    info.Content = rd.GetString(1);
                    info.PostTime = rd.GetDateTime(2);
                }
                rd.Close();
                return info;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 检查是否有查看迷你日志的权限
        /// </summary>
        /// <param name="hostId"></param>
        /// <param name="guestId"></param>
        /// <returns></returns>
        public bool CheckAuthority(int hostId, int guestId)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                EnumPrivacy priv = EnumPrivacy.ForFriends;
                string Sql = "select PrivMiniBlog from NT_UserSetting where UserID=" + hostId;
                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, hostId);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 得到心情日记的评论
        /// </summary>
        /// <param name="Mid">心情日记的ID</param>
        /// <returns></returns>
        public IDataReader GetMiniComment(int Mid)
        {
            string sql = "select ID,Commentator,MiniBlogID,Content,CommentID,PostTime from NT_MoodComment where islock!=1 and MiniBlogID=" + Mid;
            return DbHelper.ExecuteReader(CommandType.Text, sql, null);
        }

        /// <summary>
        /// 得到迷你博客的评论数量
        /// </summary>
        /// <param name="mid">迷你博客ID</param>
        /// <returns></returns>
        public int GetMiniCount(int mid)
        {
            string sql = "select count(id) from NT_MoodComment where islock!=1 and MiniBlogID=" + mid;
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, null));
        }
        /// <summary>
        /// 保存心情日记评论
        /// </summary>
        /// <param name="mid">被评论的ID</param>
        /// <param name="Content">内容</param>
        /// <param name="UserID">用户</param>
        /// <param name="CommentID">父ID</param>
        public void SaveMiniComment(int mid, string Content, int UserID, int CommentID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();
            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                SqlParameter[] param = new SqlParameter[7];
                param[0] = new SqlParameter("@mid", SqlDbType.Int, 4);
                param[0].Value = mid;
                param[1] = new SqlParameter("@Content", SqlDbType.NVarChar, 100);
                param[1].Value = Content;
                param[2] = new SqlParameter("@UserID", SqlDbType.Int, 4);
                param[2].Value = UserID;
                param[3] = new SqlParameter("@CommentID", SqlDbType.Int, 4);
                param[3].Value = CommentID;
                param[4] = new SqlParameter("@PostTime", SqlDbType.DateTime, 8);
                param[4].Value = DateTime.Now;
                param[5] = new SqlParameter("@PostIP", SqlDbType.NVarChar, 15);
                param[5].Value = JuSNS.Common.Public.GetClientIP();
                param[6] = new SqlParameter("@isLock", SqlDbType.Bit);
                param[6].Value = 0;
                string sql = "insert into NT_MoodComment(Commentator,MiniBlogID,Content,CommentID,PostTime,PostIP,isLock) values (@UserID,@mid,@Content,@CommentID,@PostTime,@PostIP,@isLock);";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, param);

                sql = "update NT_Mood set Comments=Comments+1 where ID=" + mid;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, null);
                //根据博客ID找到主人
                string mSQL = "select UserID from NT_Mood where ID=@mid";
                int mUserID = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, mSQL, param));
                //这里插入主人的通知,不自己通知自己
                if (mUserID != UserID)
                {
                    Notify(trans, EnumNotifyType.MiniComment, UserID, mUserID, "评论了您的心情日记", mid);
                }
                trans.Commit();
                User us = new User();
                us.updateinte(UserID, 1, 0, 0,"发表心情日记评论");
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }
        /// <summary>
        /// 删除心情日记评论
        /// </summary>
        /// <param name="bid"></param>
        public void DelMiniComent(int bid)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();
            string Sql = "select MiniBlogID from NT_MoodComment where ID=" + bid;
            int blogid = (int)DbHelper.ExecuteScalar(Conn, CommandType.Text, Sql, null);
            string ubsql = "select Commentator from NT_MoodComment where ID=" + bid;
            int UserID = (int)DbHelper.ExecuteScalar(Conn, CommandType.Text, ubsql, null);
            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                string sql = "delete from NT_MoodComment where ID=" + bid;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, null);

                sql = "update NT_Mood set Comments=Comments-1 where ID=" + blogid;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, null);
                trans.Commit();
                User us = new User();
                us.updateinte(UserID, 1, 0, 1,"删除心情日记评论");
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }


        }
        #region 管理员后台
        /// <summary>
        /// 迷你博客搜索
        /// </summary>
        /// <param name="searchCondition">搜索条件:1.按作者姓名;2.按日志标题</param>
        /// <param name="keyword">搜索关键字</param>
        /// <param name="orderType">排序方式:1.按发表日期;2.按作者姓名;3.按评论数</param>
        /// <returns></returns>
        public DataTable Search(int searchCondition, string keyword, int orderType, int pageIndex, int pageSize, out int recordCount, out int pageCount)
        {
            string AllFields = "a.ID,a.UserID,a.Content,a.PostTime,a.IsLock,a.Comments,a.isRec,b.UserName";
            string TablesAndWhere = "NT_Mood a inner join NT_User b on a.UserID=b.UserID";
            if (keyword != null && keyword.Trim() != string.Empty)
            {
                string _key = keyword.Replace("'", "''");
                if (searchCondition == 1)
                    TablesAndWhere += " where b.UserName like '%" + _key + "%'";
                else if (searchCondition == 2)
                    TablesAndWhere += " where a.Content like '%" + _key + "%'";
            }
            string IndexField = "a.ID";
            string OrderFields = "order by a.ID Desc";
            switch (orderType)
            {
                case 1:
                    OrderFields = "order by a.PostTime Desc";
                    break;
                case 2:
                    OrderFields = "order by b.UserName Desc";
                    break;
                case 3:
                    OrderFields = "order by a.Comments Desc";
                    break;
            }
            return Pagination.ProcPage(AllFields, TablesAndWhere, IndexField, OrderFields, pageIndex, pageSize, out recordCount, out pageCount);
        }

        public void updateMiniRec(int ID, int NUM)
        {
            string sql = "update NT_Mood set isRec=" + NUM + " where ID=" + ID;
            DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
        }

        /// <summary>
        /// 锁定或解锁心情日记
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="blogId"></param>
        /// <param name="lockSate"></param>
        public int ChangeLock(int userId, int miniBlogId, bool lockSate)
        {
            int newLock = 0;
            if (lockSate)
                newLock = 1;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            SqlTransaction trans = cn.BeginTransaction();
            try
            {
                string Sql = "update NT_Mood set IsLock=" + newLock + " where ID=" + miniBlogId;
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                Sql = "update NT_MoodComment set IsLock=" + newLock + " where MiniBlogID=" + miniBlogId;
                n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                trans.Commit();
                return n;
            }
            catch
            {
                trans.Rollback();
                throw;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        #endregion
    }
}
