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;
using System.IO;
using GetCommand;

namespace HteamDd.Web.ashx
{
    /// <summary>
    /// Dd_private_index 的摘要说明
    /// </summary>
    public class Dd_private_index : IHttpHandler
    {
        string UserId ;
        int pageCount = 0;
        int pageRowCount = 4;
        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();
        public void ProcessRequest(HttpContext context)
        {   
            json.Append("[");
            context.Response.ContentType = "text/plain";
           
            if (context.Request["requestType"] == "1")
            {
                UserId = context.Request["userID"];
                try
                {
                    pageInitDataToJson();
                }
                catch
                {
                    context.Response.Write("Error");
                }
                context.Response.Write(json);

            }
            else if (context.Request["requestType"] == "2")
            {
                UserId = context.Request["userID"];
                try
                {
                    nextPageDataToJson(context.Request["select_time"]);
                }
                catch
                {
                    context.Response.Write("Error too");
                }
                context.Response.Write(json);
            }
            else if (context.Request["requestType"] == "rly_count")
            {
                string article_ID = context.Request["article_ID"].ToString();
                try
                {
                    string sql_replycout = "select COUNT(*) from Dd_Reply where Reply_ArticleID=@ID and Reply_Delete=0";
                    SqlParameter parmeter = new SqlParameter("@ID", article_ID);
                    int rly_count = Convert.ToInt32(DbHelperSQL.GetSingle(sql_replycout, parmeter));

                    context.Response.Write(rly_count.ToString());
                }
                catch
                {
                    context.Response.Write("cout_Error");
                }

            }

            else if (context.Request["state"] == "replayALL")
            {
                if (context.Request["Type_Process"] == "reply")
                {
                    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);
                        string type = model.Reply_Type.ToString();//类型ID（0 文章 1图片 3 链接 4 视频）
                        string type_ArticleId = model.Reply_ArticleID;//（文章、图片……）唯一标示符ID
                        string tables, typeFever, typeID;//类型的（表名,对应的热度，表中的主键，加1操作的标示）
                        switch (type)
                        {
                            case "0":
                                tables = "Dd_Text";
                                typeFever = "Text_Fever";
                                typeID = "Text_ID";
                                FeverProcess(type_ArticleId, tables, typeFever, typeID, "add");
                                break;
                            case "1":
                                tables = "Dd_Picture";
                                typeFever = "Picture_Fever";
                                typeID = "Picture_ID";
                                FeverProcess(type_ArticleId, tables, typeFever, typeID, "add");
                                break;
                            case "3":
                                tables = "Dd_Link";
                                typeFever = "Link_Fever";
                                typeID = "Link_ID";
                                FeverProcess(type_ArticleId, tables, typeFever, typeID, "add");
                                break;
                            case "4":
                                tables = "Dd_Video";
                                typeFever = "Video_Fever";
                                typeID = "Video_ID";
                                FeverProcess(type_ArticleId, tables, typeFever, typeID, "add");
                                break;
                        }
                    }
                    catch
                    {
                        _num = -1;
                    }
                    context.Response.Write("1" + "," + _num);
                }
                else if (context.Request["Type_Process"] == "dele")
                {
                    string ID = context.Request["reply_ArticleID"].ToString();//对应的文章、图片……的ID
                    DeleByID(ID);//调用方法进行删除
                    string style_order = context.Request["Order"].ToString();
                    bool isdele_Base = false;
                    switch (style_order)
                    {
                        //删除的对象（0文章1图片2音乐3链接4视频）
                        case "0":
                            HaTeam.Dd.Model.Dd_Text model = new HaTeam.Dd.Model.Dd_Text();
                            HaTeam.Dd.BLL.Dd_Text blltext = new HaTeam.Dd.BLL.Dd_Text();
                            isdele_Base = blltext.Delete(Convert.ToInt32(ID));
                            break;
                        case "1":
                            HaTeam.Dd.Model.Dd_Picture modelpic = new HaTeam.Dd.Model.Dd_Picture();
                            HaTeam.Dd.BLL.Dd_Picture bllpic = new HaTeam.Dd.BLL.Dd_Picture();

                            string del_images = "select Picture_Address from Dd_Picture where Picture_ID=@ID";
                            SqlParameter par_url = new SqlParameter("@ID",ID);
                            string [] imgages = DbHelperSQL.GetSingle(del_images, par_url).ToString().Split('|');
                            string[] image_head = imgages[0].Split('/');
                            for (int i = 0; i < imgages.Length-2; i++)
                            {
                                DeleImage.image_server_del(imgages[0],imgages[i+1]);
                                DeleImage.image_server_del("/" + image_head[1] + "/UploadPictures/" + image_head[3] + "/" + image_head[4], imgages[i + 1]);
                            }
                            isdele_Base = bllpic.Delete(Convert.ToInt32(ID));
                            break;
                        case "3":
                            HaTeam.Dd.Model.Dd_Link modelLink = new HaTeam.Dd.Model.Dd_Link();
                            HaTeam.Dd.BLL.Dd_Link bllLink = new HaTeam.Dd.BLL.Dd_Link();
                            isdele_Base = bllLink.Delete(Convert.ToInt32(ID));
                            break;
                        case "4":
                            HaTeam.Dd.Model.Dd_Video modelvideo = new HaTeam.Dd.Model.Dd_Video();
                            HaTeam.Dd.BLL.Dd_Video bllvideo = new HaTeam.Dd.BLL.Dd_Video();
                            isdele_Base = bllvideo.Delete(Convert.ToInt32(ID));
                            break;
                    }
                    if (isdele_Base == true)
                    {
                        context.Response.Write("1");
                    }
                    else
                    {
                        context.Response.Write("0");
                    }

                }
            }
            else if (context.Request["state"] == "replayDetails")//单个删除回应的信息
            {
                bool _delNum = bll.Delete(Convert.ToInt32(context.Request["reply_typeID"].ToString()));//执行删除单个回应的操作
                string del_divID = context.Request["div_id"].ToString();//每个表中的主键
                string del_leixing = context.Request["div_type"].ToString();//类型对象（0文章1图片2音乐3链接4视频）
                switch (del_leixing)
                {
                    case "0":
                        FeverProcess(del_divID, "Dd_Text", "Text_Fever", "Text_ID", "del");
                        break;
                    case "1":
                        FeverProcess(del_divID, "Dd_Picture", "Picture_Fever", "Picture_ID", "del");
                        break;
                    case "3":
                        FeverProcess(del_divID, "Dd_Link", "Link_Fever", "Link_ID", "del");
                        break;
                    case "4":
                        FeverProcess(del_divID, "Dd_Video", "Video_Fever", "Video_ID", "del");
                        break;
                }

                if (_delNum)
                {
                    context.Response.Write("1");
                }
                else
                {
                    context.Response.Write("0");
                }
            }
            ///对下拉列表的处理
            else if (context.Request["requestType"] == "rly_list")
            {
                string rly_Item_ID = context.Request["rly_Item_ID"].ToString();
                string rly_Item_type = context.Request["rly_item_type"].ToString();
                string rly_sql = "select Reply_ID,Reply_Content from Dd_Reply where Reply_ArticleID=" + rly_Item_ID + " and Reply_Type=" + rly_Item_type + " and Reply_Delete=0";
                // SqlParameter pam = new SqlParameter("@rly_ID", rly_Item_ID);
                SqlDataReader sdr = DbHelperSQL.ExecuteReader(rly_sql);
                string content = string.Empty;
                while (sdr.Read())
                {
                    if (content != "")
                    {
                        content += ";" + sdr["Reply_ID"].ToString() + "," + sdr["Reply_Content"].ToString();
                    }
                    else
                    {
                        content = sdr["Reply_ID"].ToString() + "," + sdr["Reply_Content"].ToString();
                    }
                }
                context.Response.Write(content);

            }

            //对热度下拉列表内容的处理
            else if (context.Request["fever_proc"] == "fever")
            {
                string fever_id = context.Request["fever_ID"].ToString();//对应本篇(0文章 1图片 3 链接 4视频)的ID
                string fev_num = context.Request["fever_leixing"].ToString();//(0文章 1图片 3 链接 4视频)
                //对转载的处理
                ReprintPrc(fever_id, fev_num);
                //对回应的处理 
                rly_info(fever_id, fev_num);
                //对喜欢的处理
                like_info(fever_id, fev_num);
                context.Response.Write(json);
            }
        }

        //对转载的处理
        private void ReprintPrc(string fever_id,string fever_num)
        {
            string Reprint = "select Reprint_UserID,Reprint_CopyFrom from Dd_Reprint where Reprint_OriginID=(select Reprint_OriginID from Dd_Reprint  where Reprint_ArticleID=" + fever_id + " and Reprint_type=" + fever_num + ") and Reprint_Delete=0";
            DataSet ds = DbHelperSQL.GetDataSet(Reprint);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                json.Append("{\"user_Name\":" + "\"" + getBlogName(dr["Reprint_UserID"].ToString()) + "\",");
                json.Append("\"copy_from\":" + "\"" + getBlogName(dr["Reprint_CopyFrom"].ToString()) + "\",");
                json.Append("\"fever_type\":" + "\"" + "reprint" + "\"},");  
            }
            
        }

        //对回应的处理
        private void rly_info(string fever_id,string fev_num)
        {
            string rly_proc = "select Reply_UserID,Reply_Content from Dd_Reply where Reply_ArticleID=" + fever_id + "and Reply_Type=" + fev_num + "and Reply_Delete=0";
            DataSet ds = DbHelperSQL.GetDataSet(rly_proc);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                json.Append("{\"rly_userName\":" + "\"" + getBlogName(dr["Reply_UserID"].ToString()) + "\",");
                json.Append("\"rly_content\":" + "\"" + dr["Reply_Content"].ToString() + "\",");
                json.Append("\"fever_type\":" + "\"" + "response" + "\"},");
            }
            
        }

        //对喜欢的处理
        private void like_info(string fever_id,string fev_num)
        {
            string like_proc = "select Like_UserID from Dd_Like where Like_ArticleID=" + fever_id + "and Like_TypeID=" + fev_num + " and Like_Delete=0";
            DataSet ds = DbHelperSQL.GetDataSet(like_proc);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                json.Append("{\"like_userName\":" + "\"" + getBlogName(dr["Like_UserID"].ToString()) + "\",");
                json.Append("\"fever_type\":" + "\"" + "like" + "\"},");
            }
            
            json.Append("]");
        }

        /// <summary>
        /// 对热度条数的处理
        /// </summary>
        /// <param name="type_ArticleId"></param>
        /// <param name="tables"></param>
        /// <param name="typeFever"></param>
        /// <param name="typeID"></param>
        private static void FeverProcess(string type_ArticleId, string tables, string typeFever, string typeID,string method)
        {
            string sqlsearch = "select " + typeFever + " from " + tables + " where " + typeID + "=" + type_ArticleId + "";
            SqlDataReader sdr = DbHelperSQL.ExecuteReader(sqlsearch);
            string count = string.Empty;
            while (sdr.Read())
            {
                count = sdr["" + typeFever + ""].ToString();
            }
            if (method == "add")
            {
                count = (Convert.ToInt32(count) + 1).ToString();//发布回应，对热度进行加一操作
            }
            else if (method == "del")
            {
                count = (Convert.ToInt32(count) - 1).ToString();//删除单个回应，对热度进行减一操作，确保热度个数的准确性
            }
            string sqlupdate = "update " + tables + " set " + typeFever + "=@fever where " + typeID + "=@ID";
            SqlParameter[] parmeters = { 
                                        new SqlParameter("@fever",count),
                                        new SqlParameter("@ID",type_ArticleId)
                                        };
            DbHelperSQL.ExecuteSql(sqlupdate, parmeters);
        }

        /// <summary>
        /// 删除回应表中对本篇文章（图片、链接、视频）的所有回应信息
        /// </summary>
        /// <param name="ID">对本篇文章（图片、链接、视频）的唯一标示id</param>
        /// <returns></returns>
        private int DeleByID(string ID)
        {
            string sql = "delete Dd_Reply where Reply_ArticleID =@Reply_ArticleID";
            SqlParameter parameters = new SqlParameter("@Reply_ArticleID", ID);
            return DbHelperSQL.ExecuteSql(sql.ToString(), parameters);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void pageInitDataToJson()
        {          
            string sql = "select  top(4)* from view_fever where USER_ID = " + UserId + " order by Datetime desc";
            DataSet ds = DbHelperSQL.GetDataSet(sql);
            dataToJson(ds);
        }
        public void nextPageDataToJson(string current)
        {          
            string sql = "select top(" + pageRowCount.ToString() + ") * from view_fever where USER_ID = " + UserId + " and 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("{\"typeID\":"+"\""+dr["TypeID"].ToString()+"\",");
                        json.Append("\"type\":" + "\"" + type + "\",");
                        json.Append("\"title\":"+"\""+string2Json(dr["Title"].ToString())+"\",");
                        json.Append("\"content\":" + "\"" + string2Json(dr["Content"].ToString()) + "\",");
                        json.Append("\"fever\":"+"\""+dr["Fever"].ToString()+"\",");
                        //json.Append("\"copyfrom\":" + "\"" + copyFrom + "\",");
                        json.Append("\"lable\":" + "\"" + string2Json(dr["Lable"].ToString()) + "\",");
                        json.Append("\"Orders\":"+"\""+dr["Orders"].ToString()+"\",");
                        json.Append("\"rly_Count\":"+"\""+ dr["rly_Count"].ToString()+"\"},");
                        break;
                    case "1":
                        type = "picture";
                        
                        //if (dr["CopyFrom"].ToString() == "0")
                        //    copyFrom = "0";
                        //else
                        //    copyFrom = getBlogName(dr["CopyFrom"].ToString());
                        json.Append("{\"typeID\":" + "\"" + dr["TypeID"].ToString() + "\",");
                        json.Append("\"type\":" + "\"" + type + "\",");
                        json.Append("\"discript\":"+"\""+string2Json(dr["Content"].ToString())+"\",");
                        json.Append("\"imageUrl\":"+"\""+dr["Title"].ToString()+"\",");
                        json.Append("\"fever\":"+"\""+dr["Fever"].ToString()+"\",");
                        //json.Append("\"copyfrom\":" + "\"" + copyFrom + "\",");
                        json.Append("\"lable\":" + "\"" + string2Json(dr["Lable"].ToString()) + "\",");
                        json.Append("\"Orders\":"+"\""+dr["Orders"].ToString()+"\",");
                        json.Append("\"rly_Count\":"+"\""+ dr["rly_Count"].ToString()+"\"},");
                        break;

                    case "2":
                        type = "music";
                        json.Append("{\"typeID\":" + "\"" + dr["TypeID"].ToString() + "\",");
                        json.Append("\"type\":" + "\"" + type + "\",");
                        json.Append("\"discript\":" + "\"" + string2Json(dr["Content"].ToString()) + "\",");
                        json.Append("\"music_url\":"+"\""+dr["Title"].ToString()+"\",");
                        json.Append("\"fever\":"+"\""+dr["Fever"].ToString()+"\",");
                        json.Append("\"lable\":" + "\"" + string2Json(dr["Lable"].ToString()) + "\",");
                        json.Append("\"Orders\":"+"\""+dr["Orders"].ToString()+"\",");
                        json.Append("\"rly_Count\":"+"\""+ dr["rly_Count"].ToString()+"\"},");
                        break;
                    case "3":
                        type = "link";
                        //if (dr["CopyFrom"].ToString() == "0")
                        //    copyFrom = "0";
                        //else
                        //    copyFrom = getBlogName(dr["CopyFrom"].ToString());
                        json.Append("{\"typeID\":" + "\"" + dr["TypeID"].ToString() + "\",");
                        json.Append("\"type\":" + "\"" + type + "\",");
                        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("\"copyfrom\":" + "\"" + copyFrom + "\",");
                        json.Append("\"lable\":" + "\"" + string2Json(dr["Lable"].ToString()) + "\",");
                        json.Append("\"Orders\":"+"\""+dr["Orders"].ToString()+"\",");
                        json.Append("\"rly_Count\":"+"\""+ dr["rly_Count"].ToString()+"\"},");
                        break;
                    case "4":
                        type = "video";
                        //if (dr["CopyFrom"].ToString() == "0")
                        //    copyFrom = "0";
                        //else
                        //    copyFrom = getBlogName(dr["CopyFrom"].ToString());
                        json.Append("{\"typeID\":" + "\"" + dr["TypeID"].ToString() + "\",");
                        json.Append("\"type\":" + "\"" + type + "\",");
                        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()) + "\",");
                        json.Append("\"Orders\":"+"\""+dr["Orders"].ToString()+"\",");
                        json.Append("\"rly_Count\":"+"\""+ dr["rly_Count"].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();
        }
    }
}