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>
    /// rolelist 的摘要说明
    /// </summary>
    public class rolelist : 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 "deletelist":
                    context.Response.Write(Delete(CommonRequest.GetQueryString("id")));
                    break;
                case "save":
                    context.Response.Write(LoadSave(context));
                    break;
            }
        }

        #region 获取数据
        private string LoadList(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";

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


                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_RoleInfo> pageModel = new Model.PageData<Model.T_Sys_RoleInfo>();

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

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

                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 Delete(string id)
        {
            bool res = false;
            res = new BLL.T_Sys_RoleInfo().Delete(Convert.ToInt32(id));
            return res ? "success" : "field";
        }

        #endregion

        #region 保存角色权限
        private string LoadSave(HttpContext context)
        {
            bool res = false;
            string F_FunctionId = CommonRequest.GetQueryString("F_FunctionId");
            string F_ModuleId = CommonRequest.GetQueryString("F_ModuleId");
            string RoleID = CommonRequest.GetQueryString("RoleID");
            Model.T_Sys_RoleFunction RoleModel = new Model.T_Sys_RoleFunction();
            BLL.T_Sys_RoleFunction RoleBll = new BLL.T_Sys_RoleFunction();
            Model.T_Sys_RoleOpt RoleOptModel = new Model.T_Sys_RoleOpt();
            BLL.T_Sys_RoleOpt RoleOptBll = new BLL.T_Sys_RoleOpt();

            if (RoleID == "0")
            {
                DataTable dt = DBUtility.DbHelperSQL.Query("select F_RoleId from T_Sys_RoleInfo order by F_RoleId desc").Tables[0];
                if (dt.Rows.Count > 0)
                {
                    RoleID = dt.Rows[0]["F_RoleId"].ToString();
                    new BLL.T_Sys_RoleFunction().Delete1(Convert.ToInt32(RoleID));
                    string[] arr = F_FunctionId.Split(',');
                    for (int i = 0; i < arr.Length - 1; i++)
                    {
                        RoleModel.F_RoleId = Convert.ToInt32(RoleID);
                        RoleModel.F_FunctionId = Convert.ToInt32(arr[i]);
                        res = RoleBll.Add(RoleModel);
                    }
                    new BLL.T_Sys_RoleOpt().Delete1(Convert.ToInt32(RoleID));
                    string[] arropt = F_ModuleId.Split(',');
                    for (int i = 0; i < arropt.Length - 1; i++)
                    {
                        RoleOptModel.F_RoleId = Convert.ToInt32(RoleID);
                        RoleOptModel.F_Id = Convert.ToInt32(arropt[i].Replace("s", ""));
                        res = RoleOptBll.Add(RoleOptModel);
                    }

                }
            }
            else
            {
                new BLL.T_Sys_RoleFunction().Delete1(Convert.ToInt32(RoleID));
                string[] arr = F_FunctionId.Split(',');
                for (int i = 0; i < arr.Length - 1; i++)
                {
                    RoleModel.F_RoleId = Convert.ToInt32(RoleID);
                    RoleModel.F_FunctionId = Convert.ToInt32(arr[i]);
                    res = RoleBll.Add(RoleModel);
                }
                new BLL.T_Sys_RoleOpt().Delete1(Convert.ToInt32(RoleID));
                string[] arropt = F_ModuleId.Split(',');
                for (int i = 0; i < arropt.Length - 1; i++)
                {
                    RoleOptModel.F_RoleId = Convert.ToInt32(RoleID);
                    RoleOptModel.F_Id = Convert.ToInt32(arropt[i].Replace("s", ""));
                    res = RoleOptBll.Add(RoleOptModel);
                }
            }
            return res ? "success" : "field";
        }
        #endregion

        #region
        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;
        }
        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 + "s";
                        model.IconCls = "4";//图标
                        model.text = categorylist1[i].F_OptName;
                        modelList1.Add(model);
                    }
                    return modelList1;
                }

            }
            else
            {
                return null;
            }

        }
        #endregion

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