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 Share : DbBase, IShare
    {
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="Info">分享实体类</param>
        /// <returns>添加成功返回1</returns>
        public int Add(ShareInfo Info)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();
            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                SqlParameter[] param = getParameters(Info);
                string Sql = "Insert Into [NT_Share]" +
                             "([UserID],[Title],[Description],[ShareType],[URL],[CaseID],[IsLock],[PostTime],[PostIP],[Comments],[Privacy],[FriendIDGroup]) " +
                             "Values(@UserID,@Title,@Description,@ShareType,@URL,@CaseID,@IsLock,@PostTime,@PostIP,@Comments,@Privacy,@FriendIDGroup);" +
                             "Select @@IDENTITY";
                int ID = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, param));

                //添加私信表
                Sql = "Insert Into [NT_Mail]" +
                      "([Sender],[Receiver],[Title],[Content],[PostTime],[PostIP],[TopicID],[IsReply],[LtType],[RelativeID],[isRead])" +
                      "Values(@UserID,0,@Title,@Description,@PostTime,@PostIP,0,0,1," + ID + ",0);" +
                      "Select @@IDENTITY";
                int LetterID = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, param));

                //添加发件箱
                Sql = "Insert Into [NT_MailOutbox]" +
                      "([UserID],[LetterID]) " +
                      "Values(" + Info.UserID + "," + LetterID + ")";
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                string DynName = string.Empty;
                int bUserID = 0;
                switch (Info.ShareType)
                {
                    case EnumShareType.ShareAlbum:
                        DynName = "ShareAlbum";
                        break;
                    case EnumShareType.ShareBlog:
                        DynName = "ShareBlog";
                        break;
                    case EnumShareType.ShareViode:
                        DynName = "ShareViode";
                        break;
                    case EnumShareType.ShareMusic:
                        DynName = "ShareMusic";
                        break;
                    case EnumShareType.ShareOther:
                        DynName = "ShareOther";
                        break;
                    case EnumShareType.SharePhoto:
                        DynName = "SharePhoto";
                        break;
                    case EnumShareType.ShareNews:
                        DynName = "ShareNews";
                        break;
                    case EnumShareType.ShareWeb:
                        DynName = "ShareWeb";
                        break;
                    case EnumShareType.ShareFriend:
                        DynName = "ShareFriend";
                        //SqlParameter Param1 = new SqlParameter("@ID", ID);
                        //string sqlS = "select CaseID from NT_Share where ID=@ID";
                        //int CID = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, sqlS, Param1));
                        //bUserID = CID;
                        //ID = CID;
                        break;
                }
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, Info.UserID, "ActShareComment"))
                {
                   UserDyn(trans, 0, 0, DynName, Info.UserID, bUserID, ID, "分享", Info.CaseID.ToString());
                }
                trans.Commit();
                User us = new User();
                us.updateinte(Info.UserID, 2, 0, 0,"创建了分享");

                return n;
            }
            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>删除成功返回1</returns>
        public int Del(int ID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                string Sql = "Delete From [NT_Share] Where [ID]=" + ID;
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                if (n > 0)
                {
                    Sql = "delete From NT_Dyn where cID=" + ID + " and (dynType like '%Share%')";
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    //删除分享评论表
                    Sql = "Delete From [NT_ShareComment] Where [ShareID]=" + ID;
                    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="ID">分享编号</param>
        /// <param name="UserID">用户编号</param>
        /// <returns>删除成功返回1</returns>
        public int Del(int ID, int UserID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                string Sql = "Delete From [NT_Share] Where [UserID]=" + UserID + " And [ID]=" + ID;
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                if (n > 0)
                {
                    Sql = "delete From NT_Dyn where cID=" + ID + " and UserID=" + UserID + " and (dynType like '%Share%')";
                    DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                    //删除分享评论表
                    Sql = "Delete From [NT_ShareComment] Where [ShareID]=" + 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="ID">分享编号</param>
        /// <returns>返回评论总数</returns>
        public int CommentsCount(int ID)
        {
            string Sql = "Select count(id) From [NT_ShareComment] Where [ShareID]=" + ID;
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, Sql, null));
        }

        /// <summary>
        /// 添加评论次数
        /// </summary>
        /// <param name="ID">分享编号</param>
        public void AddComments(int ID)
        {
            string Sql = "Update [NT_Share] Set [Comments]=[Comments]+1 Where [ID]=" + ID;
            DbHelper.ExecuteNonQuery(CommandType.Text, Sql, null);
        }

        /// <summary>
        /// 取得分享信息
        /// </summary>
        /// <param name="ID">编号</param>
        /// <returns>返回分享实体类</returns>
        public ShareInfo Info(int ID)
        {
            ShareInfo info = new ShareInfo();
            string Sql = "Select [ID],[UserID],[Title]," +
                         "[Description],[ShareType],[Url],[CaseID],[IsLock],[PostTime],[PostIP],[Comments],[Privacy],[FriendIDGroup] " +
                         "From " +
                         "[NT_Share] " +
                         "Where [ID]=" + ID;
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, null);
            if (rd.Read())
            {
                info.ID = Convert.ToInt32(rd["ID"].ToString());
                info.UserID = Convert.ToInt32(rd["UserID"].ToString());
                if (rd["Title"] != DBNull.Value) info.Title = rd["Title"].ToString();
                if (rd["Url"] != DBNull.Value) info.Url = rd["Url"].ToString();
                if (rd["Description"] != DBNull.Value) info.Description = rd["Description"].ToString();
                //if (rd["FriendIDGroup"] != DBNull.Value) info.FriendIDGroup = rd["FriendIDGroup"].ToString();
                info.FriendIDGroup = Convert.ToInt32(rd["FriendIDGroup"].ToString());
                info.ShareType = (EnumShareType)Convert.ToInt32(rd["ShareType"].ToString());
                info.CaseID = Convert.ToInt32(rd["CaseID"].ToString());
                if (rd["IsLock"].ToString() == "1")
                {
                    info.IsLock = EnumIsLock.Lock;
                }
                else
                {
                    info.IsLock = EnumIsLock.UnLock;
                }
                info.PostTime = Convert.ToDateTime(rd["PostTime"].ToString());
                if (rd["PostIP"] != DBNull.Value) info.PostIP = rd["PostIP"].ToString();
                info.Comments = Convert.ToInt32(rd["Comments"].ToString());
                info.Privacy = (EnumPrivacy)Convert.ToInt32(rd["Privacy"].ToString());
            }
            rd.Close();
            return info;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Info">分享实体类</param>
        /// <returns>返回SQL参数</returns>
        private SqlParameter[] getParameters(ShareInfo Info)
        {
            SqlParameter[] param = new SqlParameter[13];

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

            param[3] = new SqlParameter("@Description", SqlDbType.NVarChar, 1000);
            param[3].Value = Info.Description;
            param[4] = new SqlParameter("@ShareType", SqlDbType.Int, 4);
            param[4].Value = Info.ShareType;
            param[5] = new SqlParameter("@CaseID", SqlDbType.Int, 4);
            param[5].Value = Info.CaseID;

            param[6] = new SqlParameter("@IsLock", SqlDbType.Bit);
            param[6].Value = Info.IsLock;
            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("@Comments", SqlDbType.Int, 4);
            param[9].Value = Info.Comments;
            param[10] = new SqlParameter("@Privacy", SqlDbType.Int, 4);
            param[10].Value = Info.Privacy;
            param[11] = new SqlParameter("@URL", SqlDbType.NVarChar, 200);
            param[11].Value = Info.Url;
            param[12] = new SqlParameter("@FriendIDGroup", SqlDbType.NVarChar, 500);
            param[12].Value = Info.FriendIDGroup;

            return param;
        }

        /// <summary>
        /// 得到相册照片数量
        /// </summary>
        /// <param name="ID">相册ID</param>
        /// <returns>相册图片数量</returns>
        public int AlbumCount(int ID)
        {
            SqlParameter param = new SqlParameter("@ID", ID);
            string sql = "select count(PhotoID) from [NT_Photo] where AlbumID=@ID and isLock=0";
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
        }

        /// <summary>
        /// 获得分享头像。///没用！
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public string AlbumIndexPic(int ID)
        {
            string IndexPicStr = "#0";
            SqlParameter param = new SqlParameter("@ID", ID);
            string sql = "select count(PhotoID) from [NT_Photo] where AlbumID=@ID and isLock=0";
            int TMPIndexPic = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
            if (TMPIndexPic > 0)
            {
                string asql = "select top 1 FilePath from [NT_Photo] where AlbumID=@ID order by PhotoID desc";
                IndexPicStr = Convert.ToString(DbHelper.ExecuteScalar(CommandType.Text, asql, param));
            }
            return IndexPicStr;
        }

        /// <summary>
        /// 获得头像图片  ///没用！
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public string PhotoURL(int ID)
        {
            SqlParameter param = new SqlParameter("@ID", ID);
            string sql = "select FilePath from [NT_Photo] where PhotoID=@ID";
            return Convert.ToString(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
        }


        /// <summary>
        /// 评论列表
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public IDataReader ShareCommentList(int ID)
        {
            SqlParameter param = new SqlParameter("@ID", ID);
            string sql = "select * from [NT_ShareComment] where ShareID=@ID";
            return DbHelper.ExecuteReader(CommandType.Text, sql, param);
        }

        /// <summary>
        /// 发表评论
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="UserID"></param>
        /// <param name="Content"></param>
        /// <param name="isLock"></param>
        public void PostComment(int ID, int UserID, string Content, int isLock)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {

                string sql = "insert into NT_shareComment (ShareID,UserID,Content,PostTime,PostIP,IsLock) values (" + ID + "," + UserID + ",'" + Content.ToString() + "','" + DateTime.Now + "','" + JuSNS.Common.Public.GetClientIP() + "'," + isLock + ");Select @@IDENTITY";
                int n = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, sql, null));
                if (n > 0)
                {
                    string gsql = "select UserID from NT_share where ID=" + ID;
                    int rID = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, gsql, null));
                    JUser ju = new JUser();
                    if (ju.CheckPrivacyInfo(trans, UserID, "ActShareComment"))
                    {
                        UserDyn(trans, 0, 0, "commentShare", UserID, 0, ID, "发表了分享评论", n.ToString());
                    }
                    int m = Notify(trans, EnumNotifyType.ShareComment, UserID, rID, "评论了你的分享", n);
                    trans.Commit();
                }
            }
            catch (SqlException e)
            {
                trans.Rollback();
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Userid"></param>
        public void DelComment(int ID, int Userid)
        {
            string sql = "delete from NT_shareComment where ID=" + ID + " and UserID=" + Userid + "";
            DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
        }

        /// <summary>
        /// 插入分享
        /// </summary>
        /// <param name="info"></param>
        public void AddShareTable(ShareInfo info)
        {

        }

        public string GetURLAddress(int Id)
        {
            SqlParameter Param = new SqlParameter("@ID", Id);
            string sql = "select URL from NT_Share where ID=@ID";
            return Convert.ToString(DbHelper.ExecuteScalar(CommandType.Text, sql, Param));
        }

        /// <summary>
        /// 得到用户ID
        /// </summary>
        /// <param name="id">分享的ID</param>
        /// <returns></returns>
        public int GetCaseID(int id)
        {
            SqlParameter Param = new SqlParameter("@ID", id);
            string sql = "select CaseID from NT_Share where ID=@ID";
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, Param));
        }
    }
}
