using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using DotNet.FrameWork.Data;
using System.Text;
/**************************************************************************************************************************
 * 作者;杨伟
 * 时间：2011-08-17
 * 描述：从数据库获取数据，构造json给前台
 * 
 * ************************************************************************************************************************/

namespace HteamDd.Web.ashx
{
    /// <summary>
    /// Dd_index 的摘要说明
    /// </summary>
    public class Dd_index : IHttpHandler
    {
        int initPageRowCount = 8;
        int pageRowCount = 5;
        int count=0;
        string mark = null;
        protected StringBuilder json = new StringBuilder();
        HaTeam.Dd.Model.Dd_Reply model = new HaTeam.Dd.Model.Dd_Reply();
        HaTeam.Dd.BLL.Dd_Reply bll = new HaTeam.Dd.BLL.Dd_Reply();
        HaTeam.Dd.BLL.Dd_Text textbll = new HaTeam.Dd.BLL.Dd_Text();
        HaTeam.Dd.BLL.Dd_Picture picbll = new HaTeam.Dd.BLL.Dd_Picture();
        HaTeam.Dd.BLL.Dd_Link linkbll = new HaTeam.Dd.BLL.Dd_Link();
        HaTeam.Dd.BLL.Dd_Video videobll = new HaTeam.Dd.BLL.Dd_Video();
        HaTeam.Dd.BLL.Dd_Reprint reprintbll = new HaTeam.Dd.BLL.Dd_Reprint();
        HaTeam.Dd.BLL.Dd_Like likebll = new HaTeam.Dd.BLL.Dd_Like();
        HaTeam.Dd.BLL.Dd_Music musicbll = new HaTeam.Dd.BLL.Dd_Music();
        HaTeam.Dd.Model.Dd_Like likemodel = new HaTeam.Dd.Model.Dd_Like();
        public void ProcessRequest(HttpContext context)
        {
            json.Append("[");
            context.Response.ContentType = "text/plain";

            if (context.Request["requestType"] == "1")
            {
                try
                {
                    pageInitDataToJson();
                }
                catch
                {
                    context.Response.Write("fuck");
                }
                context.Response.Write(json);
            }
            else if (context.Request["requestType"] == "2")
            {
                try
                {
                    nextPageDataToJson(context.Request["select_time"]);
                }
                catch
                {
                    context.Response.Write("fuck too");
                }
                context.Response.Write(json);
            }
            else if (context.Request["state"] == "replayALL")
            {
                if (context.Request["Type_Process"] == "relpy")
                {
                    model.Reply_UserID = Convert.ToInt32(context.Request["userID"]);
                    model.Reply_Content = context.Request["content"].ToString();
                    model.Reply_ArticleID = context.Request["typeID"].ToString();
                    model.Reply_Type = Convert.ToInt32(context.Request["typeOrder"].ToString());
                    model.Reply_Guid = Convert.ToString(Guid.NewGuid());
                    model.Reply_Datetime = DateTime.Now;
                    model.Reply_UpDatetime = DateTime.Now;
                    model.Reply_Verify = 0;
                    model.Reply_Lock = 0;
                    model.Reply_State = 0;
                    model.Reply_Delete = 0;
                    model.Reply_Count = 0;
                    model.Reply_Order = 0;
                    int _num = 0;
                    try
                    {
                        _num = bll.Add(model);
                    }
                    catch
                    {
                        _num = -1;
                    }
                    context.Response.Write("1" + "," + _num);
                }
            }
            //获取回应（）
            else if (context.Request["state"] == "replycontentALL")
            {
                if (context.Request["Type_Process"] == "replycontent")
                {
                    var id = context.Request["typeID"].ToString();
                    var order = context.Request["Orders"].ToString();
                    if (BandReplyContent(id, order) != null)
                    {
                        context.Response.Write("1" + "," + id + "," + BandReplyContent(id, order));
                    }
                    else { }
                }
            }
            else if (context.Request["state"] == "DelReply")
            {
                if (context.Request["Type_Process"] == "DelreplyContent")
                {
                    bool istrue = false;

                    try
                    {
                        int num = Convert.ToInt32(context.Request["TypeID"]);
                        istrue = bll.Delete(num);
                        context.Response.Write("true");
                    }
                    catch
                    {
                        istrue = false;
                    }
                }
            }
            else if (context.Request["state"] == "edit")
            {
                if (context.Request["Type_Process"] == "reContent")
                {
                    string val = "";
                    string ID = context.Request["id"];
                    string Orders = context.Request["orders"];
                    string sql = "select Title,Content,Lable from view_tables where typeID='" + ID + "' and Orders='" + Orders + "'";
                    try
                    {
                        DataSet ds = DbHelperSQL.GetDataSet(sql);
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            val = dr["Title"].ToString() + "|" + dr["Content"].ToString() + "|" + dr["Lable"].ToString();
                        }
                    }
                    catch
                    {
                        val = null;
                    }
                    context.Response.Write("1" + "," + val);
                }
            }
            else if (context.Request["state"] == "DeleteArticle")
            {
                if (context.Request["Type_Process"] == "Delete")
                {
                    var order = context.Request["Orders"].ToString();
                    var id = Convert.ToInt32(context.Request["ID"]);
                    var IsDel = false;
                    switch (order)
                    {
                        case "0":
                            try
                            {
                                IsDel = textbll.Delete(id);
                            }
                            catch { }
                            break;
                        case "1":
                            try
                            {
                                IsDel = picbll.Delete(id);
                            }
                            catch { }
                            break;
                        case"2":
                            try
                            {
                                IsDel = musicbll.Delete(id);
                            }
                            catch { }
                            break;
                        case "3":
                            try
                            {
                                IsDel = linkbll.Delete(id);
                            }
                            catch { }
                            break;
                        case "4":
                            try
                            {
                                IsDel = videobll.Delete(id);
                            }
                            catch { }
                            break;
                    }
                    context.Response.Write(IsDel);
                }
            }
            else if (context.Request["state"] == "favor")
            {
                var id = context.Request["ID"].ToString();
                var order = context.Request["Orders"].ToString();
                var userid = context.Request["UserID"];
                if (context.Request["Type_Process"] == "addfavor")
                {
                    if (IstrueFavor(id, order, userid) == 0)
                    {
                        likemodel.Like_UserID = Convert.ToInt32(userid);
                        likemodel.Like_ArticleID = Convert.ToInt32(id);
                        likemodel.Like_TypeID = Convert.ToInt32(order);
                        likemodel.Like_Datetime = DateTime.Now;
                        likemodel.Like_Guid = Convert.ToString(Guid.NewGuid());
                        likemodel.Like_UpDatetime = DateTime.Now;
                        likemodel.Like_Delete = 0;
                        likemodel.Like_Lock = 0;
                        likemodel.Like_State = 0;
                        likemodel.Like_Verify = 0;
                        likemodel.Like_Order = 0;
                        likemodel.Like_Remark = 0.ToString();
                        int num = -1;
                        try
                        {
                            num = likebll.Add(likemodel);
                        }
                        catch
                        {
                            num = -1;
                        }
                        context.Response.Write("1" + "," + num);
                    }
                    else
                    {
                        context.Response.Write("0" + "," + "您已添加过喜欢，请不要重复添加！");
                    }
                }
            }
            else if (context.Request["state"] == "fever")
            {
                if (context.Request["Type_Process"] == "addfever")
                {

                    string id = context.Request["ID"].ToString();
                    string order = context.Request["Orders"].ToString();
                    string username = context.Request["UserName"].ToString();
                    try
                    {
                        GetReplyContent(id, order,username);
                        GetFavorContent(id, order);
                        GetReshipContent(id, order,username);
                        
                    }
                    catch { }
                    context.Response.Write(json);

                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 获得回应内容的的个数
        /// </summary>
        /// <param name="Reply_ArticleID">对回应文章（视频、图片等）文本的ID</param>
        /// <returns>根据回应文章的ID返回查询到的个数</returns>
        public int BandReplyCount(string ID,string replytype)
        {
            string sql = "select rly_Count from view_fever where TypeID='"+ID+"' and Orders='"+replytype+"'";
            count = Convert.ToInt32(DbHelperSQL.GetSingle(sql.ToString()));
            return count;
        }
        //当点击某一个回应的时候显示所有回应的内容
        public string BandReplyContent(string ID,string Order)
        {
            string sql = "select distinct Reply_ArticleID,Reply_UserID,User_BlogName,Reply_Content,Reply_ID from Dd_Reply dr,view_fever vt,Dd_User du where dr.Reply_ArticleID=vt.TypeID and dr.Reply_UserID=du.User_ID and Orders= Reply_Type and TypeID=" + ID + " and Orders=" + Order;
            DataSet ds = DbHelperSQL.GetDataSet(sql);
            string mess = null;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                mess += dr["Reply_UserID"].ToString() + "#" + dr["User_BlogName"].ToString().Trim() + "#" + dr["Reply_Content"].ToString().Trim() + "#" + dr["Reply_ID"].ToString().Trim() + "#" + dr["Reply_ArticleID"].ToString().Trim() + "#".Trim() + "reply" + "*";
            }
            mark = "reply";
            return mess;
        } 
        //获取热度人数
        int feverCount = 0;
        public int GetFeverCount(string id, string orders) 
        {
            string sql = "select Fever from view_fever where TypeID='" + id + "' and Orders='" + orders + "'";
            feverCount = Convert.ToInt32(DbHelperSQL.GetSingle(sql.ToString()));
            return feverCount;
        }
        // 获取喜欢的内容 
       
        //获取转载的主要内容
        public string bandReshipContent(string ID, string Order)
        {
            string sql = "select distinct Reply_ArticleID,Reply_UserID,User_BlogName,Reply_Content,Reply_ID from Dd_Reply dr,view_fever vt,Dd_User du where dr.Reply_ArticleID=vt.TypeID and dr.Reply_UserID=du.User_ID and Orders= Reply_Type and TypeID=" + ID + " and Orders=" + Order;
            DataSet ds = DbHelperSQL.GetDataSet(sql);
            string mess = null;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                mess += dr["Reply_UserID"].ToString() + "#" + dr["User_BlogName"].ToString() + "#" + dr["Reply_Content"].ToString() + "#" + dr["Reply_ID"].ToString() + "#" + dr["Reply_ArticleID"].ToString() + "#" + "reship" + "*";
            }
            mark = "reship";
            return mess;
        }


        //取得热度中的回应
        public void GetReplyContent(string ID, string Order, string username)
        {
            string mess = "";//标示是文本、图片、视频、还是链接
            string text = "";
            switch (Order)
            {
                case "0":
                    mess = "Text";
                    text = "文字";
                    break;
                case "1":
                    mess = "Picture";
                    text = "图片";
                    break;
                case "2":
                    mess = "Music";
                    text = "音乐";
                    break;
                case "3":
                    mess = "Link";
                    text = "链接";
                    break;
                case "4":
                    mess = "Video";
                    text = "视频";
                    break;
            }
            string sql = "select User_BlogName,Reply_Content,Reply_Guid,Reply_UserID  from  Dd_Reply dr,Dd_User du where dr.Reply_UserID=du.User_ID and Reply_ArticleID='" + ID + "' and Reply_Type='" + Order + "'";
            DataSet ds = DbHelperSQL.GetDataSet(sql);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                json.Append("{\"User_BlogName\":" + "\"" + dr["User_BlogName"].ToString() + "\",");
                json.Append("\"Reply_Content\":" + "\"" + dr["Reply_Content"].ToString() + "\",");
                json.Append("\"Reply_Guid\":" + "\"" + dr["Reply_Guid"].ToString()+"\",");
                json.Append("\"Reply_UserID\":" + "\"" + dr["Reply_UserID"].ToString()+"\",");
                json.Append("\"UserName\":" + "\"" + username + "\",");
                json.Append("\"Text\":" + "\"" + text + "\",");
                json.Append("\"Mark\":" + "\"" + "reply" + "\"},");
            }
        }
        //获取热度中的喜欢
        public void GetFavorContent(string ID, string Order)
        {
            string text = "";//标示是文本、图片、视频、还是链接
            switch (Order)
            {
                case "0":
                    text = "文字";
                    break;
                case "1":
                    text = "图片";
                    break;
                case "2":
                    text = "音乐";
                    break;
                case "3":
                    text = "链接";
                    break;
                case "4":
                    text = "视频";
                    break;
            }
            string sql = "select User_BlogName,Like_Guid,Like_UserID from Dd_Like dl,Dd_User du where dl.Like_UserID=du.User_ID and Like_ArticleID='" + ID + "' and Like_TypeID='" + Order + "'";
            DataSet ds = DbHelperSQL.GetDataSet(sql);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                json.Append("{\"User_BlogName\":" + "\"" + dr["User_BlogName"].ToString() + "\",");
                json.Append("\"Like_Guid\":" + "\"" + dr["Like_Guid"].ToString()+"\",");
                json.Append("\"Like_UserID\":" + "\"" + dr["Like_UserID"].ToString()+"\",");
                json.Append("\"Text\":" + "\"" + text + "\",");
                json.Append("\"Mark\":" + "\"" + "favor" + "\"},");
            }
        }
        //获取热度中的转载
        public void GetReshipContent(string ID, string Order,string username)
        {
            string mess = "";//标示是文本、图片、视频、还是链接
            string text = "";
            switch (Order)
            {
                case "0":
                    mess = "Text";
                    text = "文字";
                    break;
                case "1":
                    mess = "Picture";
                    text = "图片";
                    break;
                case "2":
                    mess = "Music";
                    text = "音乐";
                    break;
                case "3":
                    mess = "Link";
                    text = "链接";
                    break;
                case "4":
                    mess = "Video";
                    text = "视频";
                    break;
            }
            string sql = "select User_BlogName,dm.User_ID,Reprint_type,Reprint_Guid,Reprint_UserID  from Dd_Reprint dr,Dd_User du,Dd_" + mess + " dm where " + mess + "_ID=Reprint_CopyFrom and dr.Reprint_UserID=du.User_ID and Reprint_ArticleID='" + ID + "' and Reprint_type='" + Order + "'";
            DataSet ds = DbHelperSQL.GetDataSet(sql);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                json.Append("{\"User_BlogName\":" + "\"" + dr["User_BlogName"].ToString() + "\",");
                json.Append("\"User_ID\":" + "\"" + dr["User_ID"].ToString() + "\",");
                json.Append("\"Reprint_Guid\":" + "\"" + dr["Reprint_Guid"].ToString()+"\",");
                json.Append("\"Reprint_UserID\":" + "\"" + dr["Reprint_UserID"].ToString() + "\",");
                json.Append("\"UserName\":" + "\"" + username + "\",");
                json.Append("\"Text\":" + "\"" + text + "\",");
                json.Append("\"Mark\":" + "\"" + "reship" + "\"},");
            }
            json.Append("]");
        }

        //当点击喜欢时，判断是否已经添加喜欢 如果已经喜欢则不让进行再喜欢！
        int num = 0;
        public int IstrueFavor(string id, string orders, string userid)
        {
            string sql = "select COUNT(*) num from Dd_Like where Like_ArticleID='" + id + "' and Like_UserID='" + userid + "' and Like_TypeID='" + orders + "'";
            num = Convert.ToInt32(DbHelperSQL.GetSingle(sql));
            return num;
        }
        public void pageInitDataToJson()
        {
            string sql = "select top(" + initPageRowCount.ToString() + ") * from view_tables  order by Datetime desc";
            DataSet ds = DbHelperSQL.GetDataSet(sql);
            dataToJson(ds);
        }
        public void nextPageDataToJson(string current)
        {
            string sql = "select top(" + pageRowCount.ToString() + ") * from view_tables where Datetime < '" + current + "' order by Datetime desc";
            DataSet ds = DbHelperSQL.GetDataSet(sql);
            dataToJson(ds);
        }
        public void dataToJson(DataSet ds)
        {

            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                string type;
               // string copyFrom;
                switch (dr["Orders"].ToString())
                {
                        
                    case "0":
                        type = "text";
                        string Content;
                        //if (dr["Content"].ToString().Length > 200)
                        //    Content = dr["Content"].ToString().Substring(0, 199) + "....";
                        //else
                            Content = dr["Content"].ToString();

                        //if (dr["CopyFrom"].ToString() == "0")
                        //    copyFrom = "0";
                        //else
                        //    copyFrom = getBlogName(dr["CopyFrom"].ToString());
                        json.Append("{\"type\":" + "\"" + type + "\",");
                        json.Append("\"UserID\":" + "\"" + dr["User_ID"].ToString()+"\",");

                        json.Append("\"feverCount\":"+"\"" + GetFeverCount(dr["TypeID"].ToString(), dr["Orders"].ToString())+"\",");
                        json.Append("\"count\":"+"\"" + BandReplyCount(dr["TypeID"].ToString(),dr["Orders"].ToString())+ "\",");//回应的所有个数
                        json.Append("\"TypeID\":" + "\"" + dr["TypeID"].ToString() + "\",");//回应所对应的节点的ID
                        json.Append("\"blogName\":" + "\"" + getBlogName(dr["User_ID"].ToString()) + "\",");
                        json.Append("\"title\":" + "\"" + string2Json(dr["Title"].ToString()) + "\",");
                        json.Append("\"content\":" + "\"" + string2Json(Content) + "\",");
                        json.Append("\"fever\":" + "\"" + dr["Fever"].ToString() + "\",");
                        //json.Append("\"copyfrom\":" + "\"" + copyFrom + "\",");
                        json.Append("\"lable\":" + "\"" + string2Json(dr["Lable"].ToString()) + "\"},");
                        break;
                    case "1":
                        type = "picture";

                        json.Append("{\"type\":" + "\"" + type + "\",");
                        json.Append("\"UserID\":" + "\"" + dr["User_ID"].ToString() + "\",");
                        json.Append("\"feverCount\":" + "\"" + GetFeverCount(dr["TypeID"].ToString(), dr["Orders"].ToString()) + "\",");
                        json.Append("\"count\":" + "\"" + +BandReplyCount(dr["TypeID"].ToString(), dr["Orders"].ToString()) + "\",");
                        json.Append("\"TypeID\":" + "\"" + dr["TypeID"].ToString() + "\",");
                        json.Append("\"discript\":" + "\"" + string2Json(dr["Content"].ToString()) + "\",");
                        json.Append("\"blogName\":" + "\"" + getBlogName(dr["User_ID"].ToString()) + "\",");
                        json.Append("\"imageUrl\":" + "\"" + dr["Title"].ToString() + "\",");
                        json.Append("\"fever\":" + "\"" + dr["Fever"].ToString() + "\",");
                        json.Append("\"lable\":" + "\"" + string2Json(dr["Lable"].ToString()) + "\"},");
                        break;
                    case "2":
                        type = "music";
                        json.Append("{\"type\":" + "\"" + type + "\",");
                        json.Append("\"UserID\":" + "\"" + dr["User_ID"].ToString() + "\",");
                        json.Append("\"feverCount\":" + "\"" + GetFeverCount(dr["TypeID"].ToString(), dr["Orders"].ToString()) + "\",");
                        json.Append("\"count\":" + "\"" + +BandReplyCount(dr["TypeID"].ToString(), dr["Orders"].ToString()) + "\",");
                        json.Append("\"TypeID\":" + "\"" + dr["TypeID"].ToString() + "\",");
                        json.Append("\"blogName\":" + "\"" + getBlogName(dr["User_ID"].ToString()) + "\",");
                        json.Append("\"musicUrl\":" + "\"" + dr["Title"].ToString() + "\",");
                        json.Append("\"content\":" + "\"" + string2Json(dr["Content"].ToString()) + "\",");
                        json.Append("\"discript\":" + "\"" + string2Json(dr["Discript"].ToString()) + "\",");
                        json.Append("\"fever\":" + "\"" + dr["Fever"].ToString() + "\",");
                        json.Append("\"lable\":" + "\"" + string2Json(dr["Lable"].ToString()) + "\"},");
                        break;
                    case "3":
                        type = "link";
                        json.Append("{\"type\":" + "\"" + type + "\",");
                        json.Append("\"UserID\":" + "\"" + dr["User_ID"].ToString() + "\",");
                        json.Append("\"feverCount\":" + "\"" + GetFeverCount(dr["TypeID"].ToString(), dr["Orders"].ToString()) + "\",");
                        json.Append("\"count\":" + "\"" + +BandReplyCount(dr["TypeID"].ToString(), dr["Orders"].ToString()) + "\",");
                        json.Append("\"TypeID\":" + "\"" + dr["TypeID"].ToString() + "\",");
                        json.Append("\"blogName\":" + "\"" + getBlogName(dr["User_ID"].ToString()) + "\",");
                        json.Append("\"discript\":" + "\"" + string2Json(dr["Discript"].ToString()) + "\",");
                        json.Append("\"url\":" + "\"" + dr["Content"].ToString() + "\",");
                        json.Append("\"title\":" + "\"" + string2Json(dr["Title"].ToString()) + "\",");
                        json.Append("\"fever\":" + "\"" + dr["Fever"].ToString() + "\",");
                        json.Append("\"lable\":" + "\"" + string2Json(dr["Lable"].ToString()) + "\"},");
                        break;
                    case "4":
                        type = "video";
                        json.Append("{\"type\":" + "\"" + type + "\",");
                        json.Append("\"UserID\":" + "\"" + dr["User_ID"].ToString() + "\",");
                        json.Append("\"feverCount\":" + "\"" + GetFeverCount(dr["TypeID"].ToString(), dr["Orders"].ToString()) + "\",");
                        json.Append("\"count\":" + "\"" + +BandReplyCount(dr["TypeID"].ToString(), dr["Orders"].ToString()) + "\",");
                        json.Append("\"TypeID\":" + "\"" + dr["TypeID"].ToString() + "\",");
                        json.Append("\"blogName\":" + "\"" + getBlogName(dr["User_ID"].ToString()) + "\",");
                        json.Append("\"videoUrl\":" + "\"" + dr["Title"].ToString() + "\",");
                        json.Append("\"imageUrl\":" + "\"" + dr["Content"].ToString() + "\",");
                        json.Append("\"discript\":" + "\"" + string2Json(dr["Discript"].ToString()) + "\",");
                        json.Append("\"fever\":" + "\"" + dr["Fever"].ToString() + "\",");
                        json.Append("\"lable\":" + "\"" + string2Json(dr["Lable"].ToString()) + "\"},");
                        break;
                }
                if (dr == ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1])
                {
                    json.Append("{\"type\":" + "\"" + "time" + "\",");
                    json.Append("\"time\":" + "\"" + dr["Datetime"].ToString() + "\"}");
                }
            }
            json.Append("]");
        }

        public string getBlogName(string UserId)
        {
            try
            {
                string sql = "select User_BlogName from Dd_User where USER_ID = " + UserId;
                string Blogname = DbHelperSQL.GetSingle(sql).ToString();
                return Blogname;
            }
            catch
            {
                return "";
            }
        }
        public string string2Json(string s)
        {
            StringBuilder sb = new StringBuilder();

            char[] c = s.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                switch (c[i])
                {
                    case '\"':
                        sb.Append("\\\"");
                        break;
                    case '\\':
                        sb.Append("\\\\");
                        break;
                    case '/':
                        sb.Append("\\/");
                        break;
                    case '\b':
                        sb.Append("\\b");
                        break;
                    case '\f':
                        sb.Append("\\f");
                        break;
                    case '\n':
                        sb.Append("\\n");
                        break;
                    case '\r':
                        sb.Append("\\r");
                        break;
                    case '\t':
                        sb.Append("\\t");
                        break;
                    default:
                        sb.Append(c[i].ToString());
                        break;
                }
                StringBuilder show = sb;
            }
            return sb.ToString();
        }
    }
}