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

namespace HySoft.BaseCallCenter.Web.sysmanage.ajax
{
    /// <summary>
    /// functionmanage 的摘要说明
    /// </summary>
    public class functionmanage : 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 "getlist":
                    context.Response.Write(LoadList(context));
                    break;
                case "getanniulist":
                    context.Response.Write(LoadAnniuList(context));
                    break;
                case "deletelist":
                    context.Response.Write(Delete(context));
                    break;
                case "deletetree":
                    context.Response.Write(DeleteById(CommonRequest.GetQueryString("id")));
                    break;
                case "clear":
                    break;
            }
        }
        #region 删除数据
        private string Delete(HttpContext context)
        {
            bool res = false;
            string arr = CommonRequest.GetQueryString("arrid");
            if (arr.IndexOf(",") == -1)
            {
                res = new BLL.T_Sys_ModuleFunctionsOpt().Delete(Convert.ToInt32(arr));
            }
            else
            {
                res = new BLL.T_Sys_ModuleFunctionsOpt().DeleteList(arr);
            }


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

        #endregion
        private string LoadAnniuList(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";

            try
            {
                string id = HttpUtility.UrlDecode(CommonRequest.GetQueryString("id"));

                string strpageindex = context.Request.Params["page"];
                int pageindex = 1;
                string strpagesize = context.Request.Params["pagesize"];
                int pagesize = 10;

                if (id.Trim() != "" && id != "undefined")
                {
                    sql += " and F_Id= '" + id.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_Sys_ModuleFunctionsOpt> pageModel = new Model.PageData<Model.T_Sys_ModuleFunctionsOpt>();

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

                System.Collections.Generic.List<Model.T_Sys_ModuleFunctionsOpt> modelList = new BLL.T_Sys_ModuleFunctionsOpt().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_Sys_ModuleFunctionsOpt>));

                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;
        }
        private string LoadList(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";

            try
            {
                //string flag = HttpUtility.UrlDecode(CommonRequest.GetQueryString("flag"));
                //string name = HttpUtility.UrlDecode(CommonRequest.GetQueryString("name"));
                string id = HttpUtility.UrlDecode(CommonRequest.GetQueryString("id"));

                string strpageindex = context.Request.Params["page"];
                int pageindex = 1;
                string strpagesize = context.Request.Params["pagesize"];
                int pagesize = 10;

                if (id.Trim() != "" && id != "undefined")
                {
                    sql += " and F_ParentId= '" + id.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_Sys_ModuleFunctions> pageModel = new Model.PageData<Model.T_Sys_ModuleFunctions>();

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

                System.Collections.Generic.List<Model.T_Sys_ModuleFunctions> modelList = new BLL.T_Sys_ModuleFunctions().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_Sys_ModuleFunctions>));

                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;
        }
        private string LoadTree(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";

            try
            {
                dt = new BLL.T_Sys_ModuleFunctions().GetList("F_ParentId=0 and F_StateFlag=1 order by F_Sort").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)
            {

                if (parentid == "0")
                {
                    System.Collections.Generic.List<Model.T_Sys_ModuleFunctions> categorylist = new BLL.T_Sys_ModuleFunctions().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_FunctionId.ToString();//当前功能ID
                        model.id = currentID;
                        model.IconCls = "1";//图标
                        model.text = categorylist[i].F_Name;
                        tab2 = new BLL.T_Sys_ModuleFunctions().GetList("F_ParentId=" + currentID + " and F_StateFlag=1  order by F_Sort").Tables[0];
                        if (tab2 != null && tab2.Rows.Count > 0)
                        {
                            model.children = BindTree(tab2, "0");
                        }
                        tab2 = new BLL.T_Sys_ModuleFunctionsOpt().GetList("F_FunctionId=" + currentID + " order by F_Id").Tables[0];
                        if (tab2 != null && tab2.Rows.Count > 0)
                        {
                            model.children = BindTree(tab2, "1");
                        }
                        modelList.Add(model);
                    }
                    return modelList;
                }
                else
                {
                    System.Collections.Generic.List<Model.T_Sys_ModuleFunctionsOpt> categorylist1 = new BLL.T_Sys_ModuleFunctionsOpt().DataTableToList(tab);
                    System.Collections.Generic.List<Model.TreeModel> modelList1 = new List<Model.TreeModel>(categorylist1.Count);
                    for (int i = 0; i < categorylist1.Count; i++)
                    {
                        Model.TreeModel model = new Model.TreeModel();
                        string currentID = categorylist1[i].F_Id.ToString();//当前功能ID
                        model.id = currentID;
                        model.IconCls = "4";//图标
                        model.text = categorylist1[i].F_OptName;
                        modelList1.Add(model);
                    }
                    return modelList1;
                }
             
            }
            else
            {
                return null;
            }

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