using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HySoft.Common;
using System.Data;

namespace HySoft.BaseCallCenter.Web.knowledgemanage.ajax
{
    /// <summary>
    /// knowledge 的摘要说明
    /// </summary>
    public class knowledge : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //取得处事类型
            string action = CommonRequest.GetQueryString("action");
            switch (action)
            {
                case "gettreelist":
                    context.Response.Write(LoadTree(context));
                    break;
                case "delete":
                    context.Response.Write(DeleteById(CommonRequest.GetQueryString("id")));
                    break;
                case "getKnowledgeList":
                    context.Response.Write(LoadList(context));
                    break;
                case "del":
                    context.Response.Write(DelById(CommonRequest.GetQueryString("singleclick")));
                    break;
            }
        }

        #region 加载知识库分类
        private string LoadTree(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();

            try
            {

                dt = new BLL.T_RepositoryCategory().GetList("F_ParentId=0 and F_DeleteFlag=0").Tables[0];

                System.Collections.Generic.List<Model.TreeModel> modelList = BindTree(dt, "0");
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<Model.TreeModel>));

                using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                {
                    //JSON序列化
                    serializer.WriteObject(stream, modelList);
                    res = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                }
            }
            catch (Exception err)
            {
                //res = err.ToString(); 
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
            }
            return res;
        }
        /// <summary>
        /// 递归获取树形结构
        /// </summary>
        /// <param name="tab">数据源</param>
        /// <param name="parentid">父节点ID</param>
        /// <returns></returns>
        public List<Model.TreeModel> BindTree(DataTable tab, string parentid)
        {
            DataTable tab2 = new DataTable();

            if (tab != null && tab.Rows.Count > 0)
            {
                System.Collections.Generic.List<Model.T_RepositoryCategory> categorylist = new BLL.T_RepositoryCategory().DataTableToList(tab);
                System.Collections.Generic.List<Model.TreeModel> modelList = new List<Model.TreeModel>(categorylist.Count);
                for (int i = 0; i < categorylist.Count; i++)
                {
                    Model.TreeModel model = new Model.TreeModel();
                    string currentID = categorylist[i].F_CategoryId.ToString();//当前功能ID
                    model.id = currentID;
                    model.IconCls = "";//图标
                    model.text = categorylist[i].F_CategoryName;
                    tab2 = new BLL.T_RepositoryCategory().GetList("F_ParentId=" + currentID + " and F_DeleteFlag=0 order by F_Sort").Tables[0];
                    if (tab2 != null && tab2.Rows.Count > 0)
                    {
                        model.children = BindTree(tab2, currentID);
                    }
                    modelList.Add(model);
                }
                return modelList;

            }
            else
            {
                return null;
            }

        } 
        #endregion

        #region 删除知识库分类

        /// <summary>
        /// 删除知识库分类
        /// </summary>
        /// <returns></returns>
        public string DeleteById(string id)
        {
            bool res = false;
            DataTable dt = new BLL.T_RepositoryInformation().GetList("F_CategoryId=" + Convert.ToInt32(id)).Tables[0];
            string rid = string.Empty;

            if (dt.Rows.Count > 0)
            {
                //先删除知识库信息再删除知识库分类
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    rid = dt.Rows[i]["F_RepositoryId"].ToString();
                    if (!string.IsNullOrEmpty(rid))
                    {
                        new BLL.T_RepositoryInformation().Delete(Convert.ToInt32(rid));
                    }
                }
            }

            res = new BLL.T_RepositoryCategory().Delete(Convert.ToInt32(id));

            return res ? "success" : "field";

        }

        #endregion

        #region 加载知识库
        private string LoadList(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";

            try
            {
                string keywords = HttpUtility.UrlDecode(CommonRequest.GetQueryString("keyWords"));
                string categoryid = HttpUtility.UrlDecode(CommonRequest.GetQueryString("categoryId"));
                string strpageindex = context.Request.Params["page"];
                int pageindex = 1;
                string strpagesize = context.Request.Params["pagesize"];
                int pagesize = 10;

                if (categoryid.Trim() != "")
                {
                    sql += " and F_CategoryId=" + categoryid.Trim();
                }
                if (keywords.Trim() != "")
                {
                    sql = "";
                    sql += " and (F_Content like '%" + keywords.Trim() + "%' or F_Title like '%"
                        + keywords.Trim() + "%' or F_KeyWords like '%" + keywords.Trim() + "%')";
                }
                if (strpageindex.Trim() != "")
                {
                    try
                    {
                        pageindex = Convert.ToInt32(strpageindex);
                    }
                    catch
                    { }
                }

                if (strpagesize.Trim() != "")
                {
                    try
                    {
                        pagesize = Convert.ToInt32(strpagesize);
                    }
                    catch
                    { }
                }

                int recordCount = 0;

                Model.PageData<Model.T_RepositoryInformation> pageModel = new Model.PageData<Model.T_RepositoryInformation>();

                dt = BLL.PagerBLL.GetListPager(
                    "T_RepositoryInformation",
                    "F_RepositoryId",
                    "*",
                    sql,
                    "ORDER BY F_RepositoryId desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

                System.Collections.Generic.List<Model.T_RepositoryInformation> modelList = new BLL.T_RepositoryInformation().DataTableToList(dt);
                pageModel.Rows = modelList;
                pageModel.Total = recordCount;
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
                    new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Model.PageData<Model.T_RepositoryInformation>));

                using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                {
                    //JSON序列化
                    serializer.WriteObject(stream, pageModel);
                    res = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                }
            }
            catch (Exception err)
            {
                //res = err.ToString(); 
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
            }
            return res;
        } 
        #endregion

        #region 删除知识库

        /// <summary>
        /// 删除知识库
        /// </summary>
        /// <returns></returns>
        public string DelById(string id)
        {
            bool res = false;
            res = new BLL.T_RepositoryInformation().Delete(Convert.ToInt32(id));
            return res ? "success" : "field";
        }

        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}