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

namespace JuSNS.SQLServer
{
    public class Blog : DbBase, IBlog
    {
        #region 会员前台
        /// <summary>
        /// 取得某条日志或草稿
        /// </summary>
        /// <param name="blogid"></param>
        /// <param name="isdraft"></param>
        /// <returns></returns>
        BlogInfo IBlog.GetBlog(int blogid, bool isdraft)
        {
            BlogInfo info = new BlogInfo();
            string Sql = "select UserID,Title,Content,PicPath,Privacy,LastModTime,PostTime from NT_BlogDraft where ID=" + blogid;
            if (!isdraft)
                Sql = "select UserID,Title,Content,PicPath,Privacy,LastModTime,PostTime from NT_Blog where ID=" + blogid;
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, null);
            if (rd.Read())
            {
                info.ID = blogid;
                info.UserID = rd.GetInt32(0);
                if (!rd.IsDBNull(1)) info.Title = rd.GetString(1);
                if (!rd.IsDBNull(2)) info.Content = rd.GetString(2);
                if (!rd.IsDBNull(3)) info.PicPath = rd.GetString(3);
                info.Privacy = (EnumPrivacy)rd.GetInt32(4);
                if (!rd.IsDBNull(5)) info.PostTime = rd.GetDateTime(5);
                if (!rd.IsDBNull(6)) info.LastModTime = rd.GetDateTime(6);
            }
            rd.Close();
            return info;
        }
        /// <summary>
        /// 发表草稿
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="draftid"></param>
        /// <returns></returns>
        int IBlog.DeliverDraft(int userid, int draftid)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string Sql = "select count(ID) from NT_BlogDraft where UserID=" + userid + " and ID=" + draftid;
                int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                if (n < 1)
                    return -1;
                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    DateTime now = DateTime.Now;
                    Sql = "insert into NT_Blog (UserID,Title,Content,PicPath,PostTime,PostIP,Privacy,IsLock,Comments,LastModTime) select ";
                    Sql += "UserID,Title,Content,PicPath,'" + now + "','" + Public.GetClientIP() + "',Privacy,0,0,'" + now + "') from ";
                    Sql += "NT_BlogDraft where ID=" + draftid;
                    int m = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    Sql = "delete from NT_BlogDraft where ID=" + draftid;
                    m += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    trans.Commit();
                    return m;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }

        }
        /// <summary>
        /// 修改日志或草稿
        /// </summary>
        /// <param name="info"></param>
        /// <param name="draftSate">0修改日志，1保存草稿，2本来是草稿-保存为日志</param>
        /// <returns>返回新日志的ID</returns>
        int IBlog.Edit(BlogInfo info, int draftSate)
        {
            SqlParameter[] Param = new SqlParameter[3];
            Param[0] = new SqlParameter("@Title", SqlDbType.NVarChar, 40);
            Param[0].Value = info.Title;
            Param[1] = new SqlParameter("@Content", SqlDbType.NText);
            Param[1].Value = info.Content;
            Param[2] = new SqlParameter("@PicPath", SqlDbType.NVarChar, 255);
            if (info.PicPath == null || info.PicPath.Trim() == string.Empty)
                Param[2].Value = DBNull.Value;
            else
                Param[2].Value = info.PicPath;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string Sql = "select count(ID) from NT_BlogDraft where ID=" + info.ID + " and UserID=" + info.UserID;
                if (draftSate == 0)
                    Sql = "select count(ID) from NT_Blog where UserID=" + info.UserID + " and ID=" + info.ID;
                int r = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                if (r < 1)
                    throw new Exception("该日志不存在,或者你没有权力修改该日志");
                DateTime now = DateTime.Now;
                if (draftSate == 1)
                {
                    Sql = "update NT_BlogDraft set Title=@Title,Content=@Content,PicPath=@PicPath,LastModTime='" + now + "' where ID=" + info.ID;
                    return DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, Param);
                }
                else
                {
                    SqlTransaction trans = cn.BeginTransaction();
                    try
                    {
                        int n = 0;
                        if (draftSate == 0)
                        {
                            Sql = "update NT_Blog set Title=@Title,Content=@Content,PicPath=@PicPath,LastModTime='" + now + "' where ID=" + info.ID;
                            n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, Param);
                        }
                        else if (draftSate == 2)
                        {
                            Sql = "insert into NT_Blog (UserID,Title,Content,PicPath,PostTime,PostIP,Privacy,IsLock,Comments,LastModTime) values (";
                            Sql += info.UserID + ",@Title,@Content,@PicPath,'" + now + "','" + Public.GetClientIP() + "'," + (int)info.Privacy + ",0,0,'" + now + "');select @@IDENTITY";
                            n = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, Param));
                            JUser ju = new JUser();
                            if (ju.CheckPrivacyInfo(trans, info.UserID, "ActLogComment"))
                            {
                                UserDyn(trans, 0, 0, "blog", info.UserID, 0, n, "发表了新日志", n.ToString());
                            }
                            Sql = "delete from NT_BlogDraft where ID=" + info.ID;
                            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="info"></param>
        /// <param name="isdraft">是不是草稿</param>
        /// <returns></returns>
        int IBlog.Deliver(BlogInfo info, bool isdraft)
        {
            SqlParameter[] Param = new SqlParameter[3];
            Param[0] = new SqlParameter("@Title", SqlDbType.NVarChar, 40);
            Param[0].Value = info.Title;
            Param[1] = new SqlParameter("@Content", SqlDbType.NText);
            Param[1].Value = info.Content;
            Param[2] = new SqlParameter("@PicPath", SqlDbType.NVarChar, 255);
            if (info.PicPath == null || info.PicPath.Trim() == string.Empty)
                Param[2].Value = DBNull.Value;
            else
                Param[2].Value = info.PicPath;
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                DateTime now = DateTime.Now;
                if (isdraft)
                {
                    string Sql = "insert into NT_BlogDraft (UserID,Title,Content,PicPath,PostTime,PostIP,Privacy,IsLock,LastModTime) values (";
                    Sql += info.UserID + ",@Title,@Content,@PicPath,'" + now + "','" + Public.GetClientIP() + "'," + (int)info.Privacy + ",0,'" + now + "');SELECT @@IDENTITY";
                    return Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, Param));
                }
                else
                {
                    SqlTransaction trans = cn.BeginTransaction();
                    try
                    {
                        string Sql = "insert into NT_Blog (UserID,Title,Content,PicPath,PostTime,PostIP,Privacy,IsLock,Comments,LastModTime) values (";
                        Sql += info.UserID + ",@Title,@Content,@PicPath,'" + now + "','" + Public.GetClientIP() + "'," + (int)info.Privacy + ",0,0,'" + now + "');select @@IDENTITY";
                        int n = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, Param));
                        JUser ju = new JUser();
                        if (ju.CheckPrivacyInfo(trans, info.UserID, "ActLogComment"))
                        {
                            UserDyn(trans, 0, 0, "blog", info.UserID, 0, n, "发表新日志", n.ToString());
                        }
                        trans.Commit();
                        return n;
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 对日志发表评论
        /// </summary>
        /// <param name="blogid"></param>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        int IBlog.CommentsBlog(int blogid, int userid, string content)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string Sql = "select UserID from NT_BLog where ID=" + blogid;
                object uid = DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    //评论日志
                    Sql = "insert into NT_BLogComment (BlogID,UserID,Content,PostTime,PostIP,IsLock) values (";
                    Sql += blogid + "," + userid + ",@Content,'" + DateTime.Now + "','" + Public.GetClientIP() + "',0);select @@IDENTITY";
                    SqlParameter Param = new SqlParameter("@Content", SqlDbType.NVarChar, 300);
                    Param.Value = content;
                    int cid = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, Param));
                    //修改日志的评论条数
                    Sql = "update NT_BLog set Comments=Comments+1 where ID=" + blogid;
                    int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    //修改动态
                    JUser ju = new JUser();
                    if (ju.CheckPrivacyInfo(trans, userid, "ActLogComment"))
                    {
                        UserDyn(trans, 0, 0, "blogcomment", userid, 0, cid, "发表了日志评论", blogid.ToString());
                    }
                    //通知
                    if (Convert.ToInt32(uid) != userid)
                        n += Notify(trans, EnumNotifyType.CommentBlog, userid, (int)uid, null, blogid);
                    trans.Commit();
                    return n;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        /// <summary>
        /// 删除日志评论,只有评论者或日志发表者可删除
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="commentid"></param>
        /// <returns></returns>
        int IBlog.DelComment(int userid, int commentid)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string Sql = "select b.ID from NT_BLogComment a inner join NT_Blog b on a.BlogID=b.ID where a.ID=" + commentid;
                Sql += " and (a.UserID=" + userid + " or b.UserID=" + userid + ")";
                object obj = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                if (obj == null || obj == DBNull.Value)
                {
                    throw new Exception("对不起,你没有删除该日志评论的权限");
                }
                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    Sql = "delete from NT_BLogComment where ID=" + commentid;
                    int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    Sql = "delete from NT_BLogComment where CommentID=" + commentid;
                    n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    Sql = "update NT_Blog set Comments=Comments-1 where ID=" + (int)obj;
                    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="blogid"></param>
        /// <returns></returns>
        int IBlog.DelBlog(int userid, int blogid, bool isAdmin)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string Sql;
                if (!isAdmin)
                {
                    Sql = "select count(ID) from NT_BLog where ID=" + blogid + " and UserID=" + userid;
                    int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                    if (n < 1)
                    {
                        return 0;
                    }
                }
                SqlTransaction trans = cn.BeginTransaction();
                try
                {
                    Sql = "delete from NT_BLog where ID=" + blogid;
                    int m = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    Sql = "delete from NT_BLogComment where BlogID=" + blogid;
                    m += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    trans.Commit();
                    return m;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        public int Rec(int t, int blogId)
        {
            string sql = "update NT_Blog set isRec=" + t + " where ID=" + blogId;
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
        }
        /// <summary>
        /// 删除草稿
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="draftid"></param>
        /// <returns></returns>
        int IBlog.DelDraft(int userid, int draftid)
        {
            string Sql = "delete from NT_BlogDraft where ID=" + draftid + " and UserID=" + userid;
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, null);
        }
        /// <summary>
        /// 返回日志的所有信息
        /// </summary>
        /// <param name="userId">登录用户ID</param>
        /// <param name="blogId">id</param>
        /// <param name="blogInf">返回日志的信息</param>
        /// <param name="comment">返回评论的相关信息</param>
        /// <returns>返回该用户日志的总数</returns>
        int IBlog.GetAllInfo(int userId, int blogId, bool increaseReads, out BlogInfo blogInf, out List<BlogCommentInfo> comment)
        {
            blogInf = new BlogInfo();
            comment = new List<BlogCommentInfo>();
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                bool bex = false;
                string Sql = "select a.ID,a.UserID,a.Title,a.Content,a.PostTime,a.Comments,a.Privacy,a.PicPath,a.Reads,b.UserName,c.FilePath ";
                Sql += "from NT_BLog a inner join NT_User b on a.UserID=b.UserID left join NT_Photo c on (b.Portrait=c.PhotoID and c.IsLock=0) where a.IsLock=0 and a.ID=" + blogId;
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                if (rd.Read())
                {
                    blogInf.ID = rd.GetInt32(0);
                    blogInf.UserID = rd.GetInt32(1);
                    if (!rd.IsDBNull(2)) blogInf.Title = rd.GetString(2);
                    if (!rd.IsDBNull(3)) blogInf.Content = rd.GetString(3);
                    blogInf.PostTime = rd.GetDateTime(4);
                    blogInf.Comments = rd.GetInt32(5);
                    blogInf.Privacy = (EnumPrivacy)rd.GetInt32(6);
                    if (!rd.IsDBNull(7)) blogInf.PicPath = rd.GetString(7);
                    blogInf.Reads = rd.GetInt32(8);
                    blogInf.UserName = rd.GetString(9);
                    if (!rd.IsDBNull(10)) blogInf.UserPortrait = rd.GetString(10);
                    bex = true;
                }
                rd.Close();
                if (!bex)
                    throw new Exception("没有找到相关的日志");
                Sql = "select count(ID) from NT_BLog where UserID=" + blogInf.UserID;
                int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                if (n < 1)
                {
                    return n;
                }
                if (userId != blogInf.UserID && !CheckPrivacy(cn, blogInf.Privacy, userId, blogInf.UserID))
                {
                    throw new Exception("对不起,你没有查看该日志的权限");
                }
                Sql = "select a.ID,a.BlogID,a.UserID,a.Content,a.PostTime,b.UserName,c.Name,d.FilePath from NT_BLogComment a inner join NT_User b on a.UserID=b.UserID inner join NT_Dict_Area c on b.Province=c.ID left join NT_Photo d on (b.Portrait=d.PhotoID and d.IsLock=0) where a.IsLock=0 and a.BlogID=" + blogId;
                Sql += " order by a.ID Asc";
                rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                while (rd.Read())
                {
                    BlogCommentInfo cm = new BlogCommentInfo();
                    cm.ID = rd.GetInt32(0);
                    cm.BlogID = rd.GetInt32(1);
                    cm.UserID = rd.GetInt32(2);
                    if (!rd.IsDBNull(3)) cm.Content = rd.GetString(3);
                    cm.PostTime = rd.GetDateTime(4);
                    cm.UserName = rd.GetString(5);
                    cm.UserNetwork = rd.GetString(6);
                    if (!rd.IsDBNull(7)) cm.UserPortrait = rd.GetString(7);
                    comment.Add(cm);
                }
                rd.Close();
                if (increaseReads)
                {
                    Sql = "update NT_BLog set Reads=Reads+1 where ID=" + blogId;
                    DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
                    blogInf.Reads += 1;
                }
                return n;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        public void UpdateBlogFoot(int BlogID, int UserID)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                SqlParameter[] param = new SqlParameter[3];
                param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
                param[0].Value = UserID;
                param[1] = new SqlParameter("@BlogID", SqlDbType.Int, 4);
                param[1].Value = BlogID;
                param[2] = new SqlParameter("@Date", SqlDbType.DateTime, 8);
                param[2].Value = DateTime.Now;
                int isValue = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.StoredProcedure, "JuSNS_BlogFootIDValue", param));
                if (isValue == 0)
                {
                    DbHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, "JuSNS_UpdateBlogFoot", param);
                }
                else
                {
                    DbHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, "JuSNS_UpdateBlogFoot1", param);
                }
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        #endregion
        
        #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.Title,a.PostTime,a.IsLock,a.Comments,a.Privacy,b.UserName,a.isRec";
            string TablesAndWhere = "NT_Blog 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.Title 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);
        }
        /// <summary>
        /// 锁定或解锁日志
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="blogId"></param>
        /// <param name="lockSate"></param>
        public int ChangeLock(int userId, int blogId, 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_Blog set IsLock=" + newLock + " where ID=" + blogId;
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                Sql = "update NT_BlogComment set IsLock=" + newLock + " where BlogID=" + blogId;
                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
    }
}
