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

namespace JuSNS.SQLServer
{
    public class HomeIndex : DbBase, IHomeIndex
    {

        /// <summary>
        /// 打招呼
        /// </summary>
        /// <param name="UserID">被打招呼的人</param>
        public IDataReader GetPoke(int UserID)
        {
            SqlParameter param = new SqlParameter("@UserID", UserID);
            string sql = "select DISTINCT  top 5 a.UserID,a.ID,b.UserName,a.gType,a.poketo,a.pokefrom,a.IsPub from NT_Greet a inner join NT_User b on a.UserID=b.UserID where a.IsRead=0 and a.FriendID=" + UserID+" order by a.ID desc";
            return DbHelper.ExecuteReader(CommandType.Text, sql, null);
        }

        /// <summary>
        /// 更新打招呼状态
        /// </summary>
        /// <param name="fID">好友ID</param>
        /// <param name="uID">用户ID</param>
        /// <param name="Flag">0回复，1忽略</param>
        public void UpdatePoke(int fID, int uID, int Flag)
        {
            string sql = string.Empty;
            if (Flag == 0)
            {
                sql = "update NT_Greet set isRead=0,UserID=" + uID + ", FriendID=" + fID + " where UserID=" + fID + " and FriendID=" + uID + "";
            }
            else
            {
                sql = "delete from NT_Greet where UserID=" + fID + " and FriendID=" + uID + "";
            }
            DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
        }

        /// <summary>
        /// 回复招呼状态
        /// </summary>
        /// <param name="fID">好友ID</param>
        /// <param name="uID">用户ID</param>
        public void updateRePoke(int fID, int uID)
        {
            SqlConnection Conn = new SqlConnection(DBConfig.CnString);
            Conn.Open();
            SqlTransaction trans = Conn.BeginTransaction();
            try
            {
                //删除以前的
                string sql = "delete from NT_Greet where FriendID=" + fID + " and UserID=" + uID + "";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, sql, null);
                //插入最新的
                string insertSQL = "insert into NT_Greet (UserID,FriendID,PostTime,PostIP,IsRead) values(" + fID + "," + uID + ",'" + DateTime.Now + "','" + JuSNS.Common.Public.GetClientIP() + "',0)";
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, insertSQL, null);

                trans.Commit();
            }
            catch (SqlException e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
            }
        }

        /// <summary>
        /// 获取好友请求数量
        /// </summary>
        /// <param name="UserID">被请求的用户ID</param>
        /// <returns></returns>
        public int FriendRequest(int UserID, int Type)
        {
            string sql = string.Empty;
            switch (Type)
            {
                case 1:
                    sql = "select count(id) from NT_Request where RequestType=1 and Receiver=" + UserID + " and isLock=0 and isDel=0 and ReplyResult=0";
                    break;
                //邀请
                case 3:
                    sql = "select count(id) from NT_GroupInvite where InviteFlag=1 and JoinUserID=" + UserID + " and Response=0";
                    break;
            }
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, null));
        }


        /// <summary>
        /// 获取通知数量（未读）
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public int NoticeInfo(int UserID)
        {
            string sql = "select count(id) from NT_Notice where Receiver=" + UserID + " and IsLock=0 and IsDel=0 and IsRead=0";
            return Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, null));
        }

        /// <summary>
        /// 获取10天内即将过生日的好友
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public DataTable FriendBirthday(int UserID)
        {
            SqlParameter param = new SqlParameter("@UserID", UserID);
            return DbHelper.ExecuteTable(CommandType.StoredProcedure, "JuSNS_GetFriendBirthday", param);
        }

        /// <summary>
        /// 得到电影图片
        /// </summary>
        /// <param name="MovieID"></param>
        /// <returns></returns>
        public string GetMoviePic(int MovieID)
        {
            string sql = "select PosterFile from NT_Movie where MovieID=" + MovieID;
            return Convert.ToString(DbHelper.ExecuteScalar(CommandType.Text, sql, null));
        }

        /// <summary>
        /// 拜访与被拜访
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="boundNum">必须大于这个数量才返回相应的数据</param>
        /// <param name="topNum">获取数量</param>
        /// <returns></returns>
        public List<VisitInfo>[] Visit(int userId, int boundNum, int topNum)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                string sql = "select count(id) from NT_visit where VisitorID=" + userId;
                int n = (int)DbHelper.ExecuteScalar(cn, CommandType.Text, sql, null);
                if (n <= boundNum)
                    return null;
                List<VisitInfo>[] list = new List<VisitInfo>[2] { new List<VisitInfo>(), new List<VisitInfo>() };
                string sql0 = "select DISTINCT top " + topNum + " a.MasterID,a.VisitorID,b.UserName,a.LastVisitTime,c.FilePath from NT_visit a inner join NT_User b ";

                sql = sql0 + "on a.VisitorID=b.UserID left join NT_Photo c on b.Portrait=c.PhotoID and c.IsLock=0 where MasterID=" + userId + " order by LastVisitTime desc";
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, sql, null);
                while (rd.Read())
                {
                    VisitInfo f = new VisitInfo();
                    f.UserID = rd.GetInt32(1);
                    f.UserName = rd.GetString(2);
                    f.VisitTime = rd.GetDateTime(3);
                    if (!rd.IsDBNull(4))
                        f.Portrait = rd.GetString(4);
                    else
                        f.Portrait = string.Empty;
                    list[0].Add(f);
                }
                rd.Close();
                sql = sql0 + "on a.MasterID=b.UserID left join NT_Photo c on b.Portrait=c.PhotoID and c.IsLock=0 where VisitorID=" + userId + " order by LastVisitTime desc";
                rd = DbHelper.ExecuteReader(cn, CommandType.Text, sql, null);
                while (rd.Read())
                {
                    VisitInfo f = new VisitInfo();
                    f.UserID = rd.GetInt32(0);
                    f.UserName = rd.GetString(2);
                    f.VisitTime = rd.GetDateTime(3);
                    if (!rd.IsDBNull(4))
                        f.Portrait = rd.GetString(4);
                    else
                        f.Portrait = string.Empty;
                    list[1].Add(f);
                }
                rd.Close();
                return list;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        public List<UserInfo>[] FindFriend(int userId,int Sex)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                List<UserInfo>[] list = new List<UserInfo>[3];
                #region 同城
                string Sql = "select City from NT_User where UserID=" + userId;
                object obj = DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                if (obj == null || obj == DBNull.Value)
                {
                    list[0] = null;
                }
                else
                {
                    list[0] = new List<UserInfo>();
                    SqlParameter[] Param = new SqlParameter[4];
                    Param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
                    Param[0].Value = userId;
                    Param[1] = new SqlParameter("@City", SqlDbType.Int, 4);
                    Param[1].Value = Convert.ToInt32(obj.ToString());
                    Param[2] = new SqlParameter("@Num", SqlDbType.Int, 4);
                    Param[2].Value = 6;
                    Param[3] = new SqlParameter("@Sex", SqlDbType.Int, 4);
                    Param[3].Value = Sex;

                    IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.StoredProcedure, "JuSNS_GetIndexFriendCity", Param);
                    while (rd.Read())
                    {
                        UserInfo us = new UserInfo();
                        us.UserID = rd.GetInt32(0);
                        us.Username = rd.GetString(1);
                        if (!rd.IsDBNull(2)) us.City = rd.GetInt32(2);
                        if (!rd.IsDBNull(3)) us.PortraitDir = rd.GetString(3);
                        list[0].Add(us);
                    }
                    rd.Close();
                }
                #endregion
                #region 随机
                list[1] = new List<UserInfo>();
                SqlParameter[] paramnewid = new SqlParameter[2];
                paramnewid[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
                paramnewid[0].Value = userId;
                paramnewid[1] = new SqlParameter("@Num", SqlDbType.Int, 4);
                paramnewid[1].Value = 6;
                Sql = "select top 6 a.UserID,a.UserName,b.Name,c.FilePath from NT_User a inner join NT_Dict_Area b on a.Province=b.ID inner join NT_Photo c on a.Portrait=c.PhotoID and c.IsLock=0 where a.State!=0 and a.UserID not in (select FriendID from NT_Friend where UserID=" + userId + ") and a.UserID!=" + userId + "  order by newid()";
                IDataReader dr = DbHelper.ExecuteReader(cn, CommandType.StoredProcedure, "JuSNS_GetIndexFriendRam", paramnewid);
                while (dr.Read())
                {
                    UserInfo us = new UserInfo();
                    us.UserID = dr.GetInt32(0);
                    us.Username = dr.GetString(1);
                    if (!dr.IsDBNull(2)) us.ProvinceName = dr.GetString(2);
                    if (!dr.IsDBNull(3)) us.PortraitDir = dr.GetString(3);
                    list[1].Add(us);
                }
                dr.Close();
                #endregion
                #region 推荐
                list[2] = new List<UserInfo>();
                Sql = "select top 6 a.UserID,a.UserName,b.FilePath from NT_User a inner join NT_Photo b on a.Portrait=b.PhotoID and b.IsLock=0 where a.isRec=1 and a.State!=0 and a.UserID!=" + userId + " order by newid()";
                dr = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                while (dr.Read())
                {
                    UserInfo us = new UserInfo();
                    us.UserID = dr.GetInt32(0);
                    us.Username = dr.GetString(1);
                    if (!dr.IsDBNull(2)) us.PortraitDir = dr.GetString(2);
                    list[2].Add(us);
                }
                dr.Close();
                #endregion
                return list;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        public List<UserInfo>[] FindNewReg(int userId, int Sex,int Num)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                List<UserInfo>[] list = new List<UserInfo>[1];
                #region 新注册
                list[0] = new List<UserInfo>();
                SqlParameter[] Param = new SqlParameter[3];
                Param[0] = new SqlParameter("@UserID", SqlDbType.Int, 4);
                Param[0].Value = userId;
                Param[1] = new SqlParameter("@Num", SqlDbType.Int, 4);
                Param[1].Value = Num;
                Param[2] = new SqlParameter("@Sex", SqlDbType.Int, 4);
                Param[2].Value = Sex;

                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.StoredProcedure, "JuSNS_GetIndexNewUserReg", Param);
                while (rd.Read())
                {
                    UserInfo us = new UserInfo();
                    us.UserID = rd.GetInt32(0);
                    us.Username = rd.GetString(1);
                    if (!rd.IsDBNull(2)) us.City = rd.GetInt32(2);
                    if (!rd.IsDBNull(3)) us.PortraitDir = rd.GetString(3);
                    list[0].Add(us);
                }
                rd.Close();
                #endregion
                return list;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        
        /// <summary>
        /// 取得动态
        /// </summary>
        /// <param name="UserId">用户ＩＤ</param>
        /// <param name="daynum">多少天内</param>
        /// <param name="num">最多条数</param>
        /// <param name="dynType">动态类型</param>
        /// <returns></returns>
        public List<UserLogInfo> DynList(int UserId,int num, string dynType,int Flag)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CnString);
            cn.Open();
            try
            {
                SqlParameter param = new SqlParameter("@UserID", UserId);
                string whereStr = string.Empty;
                if (!string.IsNullOrEmpty(dynType))
                {
                    switch (dynType)
                    {
                        case "logs":
                            whereStr = " and (a.DynType='blog' or a.DynType='blogcomment')";
                            break;
                        case "album":
                            whereStr = " and (a.DynType='creatlbum' or a.DynType='dellbum' or a.DynType='updatealbum' or a.DynType='quanren')";
                            break;
                        case "mood":
                            whereStr = " and (a.DynType='mood')";
                            break;
                        case "share":
                            whereStr = " and (a.DynType like 'Share%' or a.DynType='commentShare')";
                            break;
                        case "group":
                            whereStr = " and (a.DynType='creatgroup' or a.DynType='joingroup' or a.DynType='outgroup' or a.DynType='posttopic' or a.DynType='replytopic' or a.DynType='groupAdmin')";
                            break;
                        case "movie":
                            whereStr = " and (a.DynType='addmovie' or a.DynType='commentmovie')";
                            break;
                        case "info":
                            whereStr = " and (a.DynType='login' or a.DynType='info' or a.DynType='infolink' or a.DynType='infofav' or a.DynType='infoName' or a.DynType='infoAddress' or a.DynType='headpic' or a.DynType='inviteJoin')";
                            break;
                        case "friend":
                            whereStr = " and (a.DynType='friend' or a.DynType='inviteJoin')";
                            break;
                        case "app":
                            whereStr = " and (a.DynType='AddApp' or a.DynType='OutApp')";
                            break;
                        case "0day":
                            whereStr = "  and datediff(d,CreatTime,getdate())=0";
                            break;
                        case "1day":
                            whereStr = "  and datediff(d,CreatTime,getdate())=1";
                            break;
                        case "3day":
                            whereStr = "  and datediff(d,CreatTime,getdate())=2";
                            break;
                        case "7day":
                            whereStr = " and datediff(d,CreatTime,getdate())<=7";
                            break;
                        case "30day":
                            whereStr = " and datediff(d,CreatTime,getdate())<=30";
                            break;
                        case "90day":
                            whereStr = "  and datediff(d,CreatTime,getdate())<=90";
                            break;
                        case "all":
                            whereStr = "";
                            break;
                    }
                }
                string userXML = string.Empty;
                string endStr = string.Empty;
                if (UserId > 0)
                {
                    userXML = "~/user/config/xml/" + UserId.ToString() + ".xml";
                    endStr = JuSNS.Common.Public.LostDot(JuSNS.Common.Public.getXML(userXML, "cleardyn", "0", 1));
                    if (!string.IsNullOrEmpty(endStr))
                    {
                        whereStr += " and a.UserID not in (" + Convert.ToInt32(endStr) + ")";
                        //if (endStr.IndexOf(",") > -1)
                        //{
                        //    string[] endStrARR = endStr.Split(',');
                        //    for (int j = 0; j < endStrARR.Length; j++)
                        //    {
                        //        if (!string.IsNullOrEmpty(endStrARR[j]))
                        //        {
                        //            whereStr += " and a.UserID!=" + Convert.ToInt32(endStrARR[j]) + "";
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    if (JuSNS.Common.Input.IsInteger(endStr))
                        //    {
                        //        whereStr += " and a.UserID!=" + Convert.ToInt32(endStr) + "";
                        //    }
                        //}
                    }
                }
                string topStr = string.Empty;
                if (num != 0)
                {
                    topStr = " top " + num + " "; 
                }
                List<UserLogInfo> list = new List<UserLogInfo>();
                string sql = "select " + topStr + " a.ID,a.UserID,b.UserName,a.dynType,a.CreatTime,a.Descript,a.infoarr,";
                sql += "a.bUserID,a.cID,c.UserName from NT_dyn";
                if (UserId > 0)
                {
                    if (Flag == 0)
                    {
                        sql += " a inner join NT_User b on a.UserID=b.UserID left join NT_User c on a.bUserID=c.UserID inner join NT_Friend d on d.FriendID=a.UserID where d.UserID=@UserID  " + whereStr + " order by a.CreatTime desc,a.ID desc";
                    }
                    else
                    {
                        sql += " a inner join NT_User b on a.UserID=b.UserID left join NT_User c on a.bUserID=c.UserID where a.UserID=@UserID  " + whereStr + " order by a.CreatTime desc,a.ID desc";
                    }
                }
                else
                {
                    sql += " a inner join NT_User b on a.UserID=b.UserID left join NT_User c on a.bUserID=c.UserID where 1=1  " + whereStr + " order by a.CreatTime desc,a.ID desc";
                }
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, sql, param);
                while (rd.Read())
                {
                    UserLogInfo Dyn = new UserLogInfo(); //新行的信息
                    Dyn.ID = Convert.ToInt32(rd["ID"].ToString());
                    Dyn.cID = Convert.ToInt32(rd["cID"].ToString());
                    Dyn.User = new UserCurtInfo(Convert.ToInt32(rd["UserID"].ToString()), rd["UserName"].ToString());
                    Dyn.DynType = rd["dynType"].ToString();
                    Dyn.LogTime = Convert.ToDateTime(rd["CreatTime"].ToString());
                    Dyn.Description = rd["Descript"].ToString();
                    Dyn.bUserID = new UserCurtInfo(Convert.ToInt32(rd["bUserID"].ToString()), rd["UserName"].ToString());
                    Dyn.infoarr = rd["infoarr"].ToString();
                    #region 相关项信息
                    if (!string.IsNullOrEmpty(rd["cID"].ToString()))
                    {
                        int CorId = Convert.ToInt32(rd["cID"]);
                        Dyn.aboutID = new int[] { CorId };
                    }
                    #endregion
                    #region 重复
                    int n = list.Count;
                    if (n > 0)
                    {
                        n--;
                        UserLogInfo prevs = list[n];
                        if (prevs.DynType == Dyn.DynType && prevs.User.UserID == Dyn.User.UserID && (Dyn.DynType == "friend" || Dyn.DynType == "joingroup" || Dyn.DynType == "updatealbum" || Dyn.DynType == "outgroup"))
                        {
                            if (Dyn.aboutID.Length > 0)
                            {
                                int[] ar = prevs.aboutID;
                                int m = ar.Length;
                                Array.Resize<int>(ref ar, m + 1);
                                ar[m] = Dyn.aboutID[0];
                                prevs.aboutID = ar;
                            }
                            prevs.RepeatNum++;
                            continue;
                        }
                    }
                    #endregion
                    list.Add(Dyn);
                }
                rd.Close();
                return list;
            }
            finally
            {
                if (cn.State == ConnectionState.Open) cn.Close();
            }
        }
    }
}
