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 Album : DbBase, IAlbum
    {
        /// <summary>
        /// 添加相册
        /// </summary>
        /// <param name="Info">相册实体类</param>
        /// <returns>添加成功返回1</returns>
        public int Add(AlbumInfo Info)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();
            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                SqlParameter[] param = getParameters(Info);
                string Sql = "Insert Into [NT_Album]" +
                             "([UserID],[Title],[Description],[ImagesCount],[CreateTime],[Privacy],[GroupID]) " +
                             "Values(@UserID,@Title,@Description,@ImagesCount,@CreateTime,@Privacy,@GroupID);" +
                             "Select @@IDENTITY";
                int AlbumID = Convert.ToInt32(DbHelper.ExecuteScalar(trans, CommandType.Text, Sql, param));
                JUser ju = new JUser();
                if (ju.CheckPrivacyInfo(trans, Info.UserID, "ActPicComment"))
                {
                    UserDyn(trans, 0, 0, "creatlbum", Info.UserID, 0, AlbumID, "创建相册", "" + AlbumID + "");
                }
                trans.Commit();
                User us = new User();
                us.updateinte(Info.UserID, 5, 0, 0,"创建相册");
                return AlbumID;
            }
            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 Edit(AlbumInfo Info)
        {
            SqlParameter[] param = getParameters(Info);
            string Sql = "Update [NT_Album] " +
                         "Set " +
                         "[Title]=@Title,[Description]=@Description,[Privacy]=@Privacy " +
                         "Where [AlbumID]=@AlbumID and [UserID]=@UserID";
            return DbHelper.ExecuteNonQuery(CommandType.Text, Sql, param);
        }

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

            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                string Sql = "delete from NT_Dyn where cID=" + AlbumID + "";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);

                //删除通知表
                Sql = "Delete From [NT_Notice] Where [MsgType]=" + (int)EnumNotifyType.PhotoComm + " And " +
                      "[Correspond] In(Select [PhotoID] From [NT_Photo] Where [AlbumID]=" + AlbumID + ")";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除相册表
                Sql = "Delete From [NT_Album] Where [AlbumID]=" + AlbumID;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除相片评论表
                Sql = "Delete From [NT_PhotoComment] Where " +
                      "[PhotoID] In(Select [PhotoID] From [NT_Photo] Where [AlbumID]=" + AlbumID + ")";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除相片圈人表
                Sql = "Delete From [NT_PhotoLasso] Where " +
                      "[PhotoID] In(Select [PhotoID] From [NT_Photo] Where [AlbumID]=" + AlbumID + ")";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除相片表
                Sql = "Delete From [NT_Photo] Where [AlbumID]=" + AlbumID;
                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="AlbumID">相册编号</param>
        /// <param name="UserID">会员编号</param>
        /// <returns>删除成功返回1</returns>
        public int Del(int AlbumID, int UserID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();
            if (!Check(Conn, UserID, AlbumID))
                return -1;

            SqlTransaction trans = Conn.BeginTransaction();

            try
            {
                string gNameSQL = "select Title from NT_Album where AlbumID=" + AlbumID;
                string Title = Convert.ToString(DbHelper.ExecuteScalar(trans, CommandType.Text, gNameSQL, null));
                //int n = UserDyn(trans, 0, 0, "dellbum", UserID, 0, AlbumID,"删除相册：" + Title + "", AlbumID.ToString());
                string Sql = "delete from NT_Dyn where cID=" + AlbumID + " and UserID=" + UserID + " and dynType='dellbum'";
                int n = DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除通知表
                Sql = "Delete From [NT_Notice] where [MsgType]=" + (int)EnumNotifyType.PhotoComm + " And " +
                      "[Correspond] In(Select [PhotoID] From [NT_Photo] Where [AlbumID]=" + AlbumID + ")";
                n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除相册表
                Sql = "Delete From [NT_Album] Where [AlbumID]=" + AlbumID;
                n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                User us = new User();
                us.updateinte(UserID, 5, 0, 1,"删除相册");
                //删除相片评论表
                Sql = "Delete From [NT_PhotoComment] Where " +
                      "[PhotoID] In(Select [PhotoID] From [NT_Photo] Where [AlbumID]=" + AlbumID + ")";
                n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除相片圈人表
                Sql = "Delete From [NT_PhotoLasso] Where " +
                      "[PhotoID] In(Select [PhotoID] From [NT_Photo] Where [AlbumID]=" + AlbumID + ")";
                n += DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                //删除相片表
                Sql = "Delete From [NT_Photo] Where [AlbumID]=" + AlbumID;
                n += 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="AlbumID">相册编号</param>
        /// <returns>返回照片记录数</returns>
        public int Count(int AlbumID)
        {
            string Sql = "Select [ImagesCount] From [NT_Album] Where [AlbumID]=" + AlbumID;
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, Sql, null));
        }

        /// <summary>
        /// 检查数据库是否存在此记录
        /// </summary>
        /// <param name="Conn">SQL联接对象</param>
        /// <param name="UserID">会员编号</param>
        /// <param name="AlbumID">相册编号</param>
        /// <returns>存在返回true,否则返回false</returns>
        private bool Check(SqlConnection Conn, int UserID, int AlbumID)
        {
            bool tf = false;
            string Sql = "Select Count([AlbumID]) From [NT_Album] Where [UserID]=" + UserID + " And [AlbumID]=" + AlbumID;
            int i_Cnt = Convert.ToInt32(DbHelper.ExecuteScalar(Conn, CommandType.Text, Sql, null));
            if (i_Cnt > 0)
                tf = true;
            return tf;
        }

        /// <summary>
        /// 取得相册下属相册所有相片路径，以做BLL层删除之用
        /// </summary>
        /// <param name="AlubmID">相册编号</param>
        /// <returns>返回编号</returns>
        public string A_s_PPath(int AlubmID)
        {
            string s_Path = "";
            string Sql = "Select [FilePath] From [NT_Photo] Where [AlbumID]=" + AlubmID;
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, null);
            if (rd.Read())
            {
                s_Path += rd["FilePath"].ToString() + ",";
            }
            rd.Close();
            if (s_Path != "")
                s_Path = s_Path.TrimEnd(',');
            return s_Path;
        }

        /// <summary>
        /// 相册信息
        /// </summary>
        /// <param name="AlbumID">相册编号</param>
        /// <returns>返回相册实体类</returns>
        public AlbumInfo Info(int AlbumID)
        {
            AlbumInfo info = new AlbumInfo();
            string Sql = "Select [AlbumID],[UserID],[Title]," +
                         "[Description],[ImagesCount],[CreateTime],[Privacy],[GroupID] " +
                         "From " +
                         "[NT_Album] " +
                         "Where [AlbumID]=" + AlbumID;
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, Sql, null);
            if (rd.Read())
            {
                info.AlbumID = Convert.ToInt32(rd["AlbumID"].ToString());
                info.UserID = Convert.ToInt32(rd["UserID"].ToString());
                if (rd["Title"] != DBNull.Value) info.Title = rd["Title"].ToString();
                if (rd["Description"] != DBNull.Value) info.Description = rd["Description"].ToString();
                info.ImagesCount = Convert.ToInt32(rd["ImagesCount"].ToString());
                info.CreateTime = Convert.ToDateTime(rd["CreateTime"].ToString());
                info.Privacy = (EnumPrivacy)Convert.ToInt32(rd["Privacy"].ToString());
                try
                {
                    info.GroupID = Convert.ToInt32(rd["GroupID"].ToString());
                }
                catch { }
            }
            rd.Close();
            return info;
        }

        /// <summary>
        /// 获取指定用户相册集
        /// </summary>
        /// <param name="UserID">用户编号</param>
        /// <returns>返回相册实体类集合</returns>
        public List<AlbumInfo> AlbumList(int UserID)
        {
            List<AlbumInfo> InfoList=new List<AlbumInfo>();
            string sql = "Select [AlbumID],[UserID],[Title]," +
                         "[Description],[ImagesCount],[CreateTime],[Privacy],[GroupID] " +
                         "From " +
                         "[NT_Album] " +
                         "Where [UserID]=" + UserID+" order by AlbumID desc";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, sql, null);
            while (rd.Read())
            {
                AlbumInfo info = new AlbumInfo();
                info.AlbumID = Convert.ToInt32(rd["AlbumID"].ToString());
                info.UserID = Convert.ToInt32(rd["UserID"].ToString());
                if (rd["Title"] != DBNull.Value) info.Title = rd["Title"].ToString();
                if (rd["Description"] != DBNull.Value) info.Description = rd["Description"].ToString();
                info.ImagesCount = Convert.ToInt32(rd["ImagesCount"].ToString());
                info.CreateTime = Convert.ToDateTime(rd["CreateTime"].ToString());
                info.Privacy = (EnumPrivacy)Convert.ToInt32(rd["Privacy"].ToString());
                try
                {
                    info.GroupID = Convert.ToInt32(rd["GroupID"].ToString());
                }
                catch { }
                InfoList.Add(info);
            }
            rd.Close();
            return InfoList;
        }
        /// <summary>
        /// 取得好友最新相册
        /// </summary>
        /// <param name="UserID">用户名</param>
        /// <returns></returns>
        public List<AlbumInfo> FriendAlbumList(int UserID)
        {
            List<AlbumInfo> InfoList = new List<AlbumInfo>();
            string sql = "Select [AlbumID],[UserID],[Title]," +
                         "[Description],[ImagesCount],[CreateTime],[Privacy],[GroupID] " +
                         "From " +
                         "[NT_Album] " +
                         "Where [UserID] in (select FriendID from [NT_Friend] where UserID=" + UserID + ") order by AlbumID desc";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, sql, null);
            while (rd.Read())
            {
                AlbumInfo info = new AlbumInfo();
                info.AlbumID = Convert.ToInt32(rd["AlbumID"].ToString());
                info.UserID = Convert.ToInt32(rd["UserID"].ToString());
                if (rd["Title"] != DBNull.Value) info.Title = rd["Title"].ToString();
                if (rd["Description"] != DBNull.Value) info.Description = rd["Description"].ToString();
                info.ImagesCount = Convert.ToInt32(rd["ImagesCount"].ToString());
                info.CreateTime = Convert.ToDateTime(rd["CreateTime"].ToString());
                info.Privacy = (EnumPrivacy)Convert.ToInt32(rd["Privacy"].ToString());
                try
                {
                    info.GroupID = Convert.ToInt32(rd["GroupID"].ToString());
                }
                catch { }
                InfoList.Add(info);
            }
            rd.Close();
            return InfoList;
        }

        /// <summary>
        /// 获取指定用户最新相册ID
        /// </summary>
        /// <param name="UserID">用户编号</param>
        /// <returns>相册ID</returns>
        public int LastAlbumID(int UserID)
        {
            string sql = "Select [AlbumID]" +
                         "From " +
                         "[NT_Album] " +
                         "Where [UserID]=" + UserID+" order by AlbumID desc";
            object o = DbHelper.ExecuteScalar(CommandType.Text, sql, null);
            return Convert.ToInt32(o);
        }

        /// <summary>
        /// 指定相册封面图片地址
        /// </summary>
        /// <param name="AlbumID">相册ID</param>
        /// <returns>图片路径</returns>
        public string CoverPath(int AlbumID)
        {
            string sql = "Select a.[FilePath] " +
                         " From " +
                         "[NT_Photo] a" +
                         " inner join [NT_Photo] b on b.AlbumID=a.AlbumID Where a.AlbumID=" + AlbumID + " and a.IsCover=1"; 
            object o = DbHelper.ExecuteScalar(CommandType.Text, sql, null);
            return Convert.ToString(o);
        }

        /// <summary>
        /// 取得群组最新相册
        /// </summary>
        /// <param name="UserID">群组ID</param>
        /// <returns></returns>
        public List<AlbumInfo> GroupAlbumList(int GroupID)
        {
            List<AlbumInfo> InfoList = new List<AlbumInfo>();
            string sql = "Select [AlbumID],[UserID],[Title]," +
                         "[Description],[ImagesCount],[CreateTime],[Privacy],[GroupID] " +
                         "From " +
                         "[NT_Album] " +
                         "Where [GroupID]=" + GroupID + " order by AlbumID desc";
            IDataReader rd = DbHelper.ExecuteReader(CommandType.Text, sql, null);
            while (rd.Read())
            {
                AlbumInfo info = new AlbumInfo();
                info.AlbumID = Convert.ToInt32(rd["AlbumID"].ToString());
                info.UserID = Convert.ToInt32(rd["UserID"].ToString());
                if (rd["Title"] != DBNull.Value) info.Title = rd["Title"].ToString();
                if (rd["Description"] != DBNull.Value) info.Description = rd["Description"].ToString();
                info.ImagesCount = Convert.ToInt32(rd["ImagesCount"].ToString());
                info.CreateTime = Convert.ToDateTime(rd["CreateTime"].ToString());
                info.Privacy = (EnumPrivacy)Convert.ToInt32(rd["Privacy"].ToString());
                try
                {
                    info.GroupID = Convert.ToInt32(rd["GroupID"].ToString());
                }
                catch { }
                InfoList.Add(info);
            }
            rd.Close();
            return InfoList;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Info">群组实体类</param>
        /// <returns>返回SQL参数</returns>
        private SqlParameter[] getParameters(AlbumInfo Info)
        {
            SqlParameter[] param = new SqlParameter[8];

            param[0] = new SqlParameter("@AlbumID", SqlDbType.Int, 4);
            param[0].Value = Info.AlbumID;
            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, 255);
            param[3].Value = Info.Description;
            if (Info.Description == null)
            {
                param[3].Value = "";
            }
            param[4] = new SqlParameter("@ImagesCount", SqlDbType.Int, 4);
            param[4].Value = Info.ImagesCount;
            param[5] = new SqlParameter("@CreateTime", SqlDbType.DateTime, 8);
            param[5].Value = Info.CreateTime;

            param[6] = new SqlParameter("@Privacy", SqlDbType.Int, 4);
            param[6].Value = (int)Info.Privacy;

            param[7] = new SqlParameter("@GroupID", SqlDbType.Int, 4);
            param[7].Value = Info.GroupID;

            return param;
        }
    }
}
