using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HySoft.Common;
using System.Data;
using System.Text;
namespace HySoft.BaseCallCenter.Web.sysmanage.ajax
{
    /// <summary>
    /// deptListAction 的摘要说明
    /// </summary>
    public class deptListAction : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = CommonRequest.GetQueryString("action");
            string taolCount = CommonRequest.GetQueryString("taolCount");
            string keyWord = CommonRequest.GetQueryString("keyWords");
            string GetbasedataId = CommonRequest.GetQueryString("deptId");
            switch (action)
            {
                case "getbasedataList":
                    context.Response.Write(GetdeptList(context, keyWord, GetbasedataId));
                    break;
                case "delete":
                    context.Response.Write(GetDeptmentDel(context, taolCount));
                    break;
                case "GetexDept":
                    context.Response.Write(GetexDept(context));
                    break;
                case "clear":
                    break;
            }
        }

        private string GetDeptmentDel(HttpContext context, string taolCount)
        {
            int res = 0;
            string sql = "update T_Sys_Department set F_state=1 where F_deptid in(" + taolCount.Trim(',') + ")";
            if (!string.IsNullOrEmpty(taolCount))
            {
                res = DBUtility.DbHelperSQL.ExecuteSql(sql);
            }
            if (res > 0)
            {
                return "success";
            }
            else
            {
                return "error";
            }
           
        }




        private string GetexDept(HttpContext context)
        {
            List<HySoft.BaseCallCenter.Model.T_Sys_Department> organList = new BLL.T_Sys_Department().GetModelList("F_State=0");
            object obj = GetNodeTreeData(organList);
            return obj.ToString();
        }


        private object GetNodeTreeData(List<Model.T_Sys_Department> organList)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            foreach (var item in organList)
            {
                if (item.F_ParentId == 0)
                {
                    Test(item, jsonString, organList);
                }
            }
            jsonString.Append("]");
            //....删除多余','号
            string[] test = jsonString.ToString().Split(']');
            jsonString.Clear();
            foreach (var item in test)
            {
                if (item != "")
                {
                    jsonString.Append(item.Remove(item.Length - 1, 1) + "]");
                }
            }
            return jsonString;
        }

        private void Test(Model.T_Sys_Department item, StringBuilder jsonString, List<Model.T_Sys_Department> organList)
        {
            //判断是否有下级节点,如果有子节点，输出子节点
            bool isLeaf = IsLeaf(item.F_DeptId);
            string deptId = getDeptIds(item.F_DeptId.ToString(), "");
            //添加根节点
            jsonString.Append("{text:\"" + item.F_DeptName + "\",id:\"" + item.F_DeptId + "\"");
            var n = organList.Where(p => p.F_ParentId == item.F_DeptId).Count();
            int temJ = 0;
            if (isLeaf)
            {
                jsonString.Append(",children:[");
                //...输出子节点        
                foreach (var child in organList.Where(p => p.F_ParentId == item.F_DeptId))
                {
                    temJ++;
                    Test(child, jsonString, organList);
                }
                jsonString.Append("]},");
            }
            else
            {
                jsonString.Append("},");
            }
        }

        private string getDeptIds(string deptId, string resstr)
        {
            string res = "";
            DataTable dt = new DataTable();
            if (!string.IsNullOrEmpty(deptId))
            {
                dt = DBUtility.DbHelperSQL.Query("select * from T_Sys_Department where F_ParentId in (" + deptId.Trim(',') + ")").Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        res += dt.Rows[i]["F_DeptId"].ToString() + ",";
                        resstr += dt.Rows[i]["F_DeptId"].ToString() + ",";
                    }
                    resstr+=getDeptIds(res, resstr);
                }
                
            }
            return resstr;
        }
        /// <summary>
        /// 判断有没有子节点
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private bool IsLeaf(int p)
        {
            bool fas = false;
            DataTable dt = DBUtility.DbHelperSQL.Query("select * from T_Sys_Department where F_ParentId='" + p + "'").Tables[0];
            if (dt.Rows.Count > 0)
            {
                fas = true;
            }
            return fas;
        }

        /// <summary>
        /// 部门信息list
        /// </summary>
        /// <param name="context"></param>
        /// <param name="keyWord"></param>
        /// <param name="GetbasedataId"></param>
        /// <returns></returns>
        private string GetdeptList(HttpContext context, string keyWord, string GetbasedataId)
        {
            string result = "";
            DataTable dt = new DataTable();
            string keyWordCon = "";
            try
            {
                if (!string.IsNullOrEmpty(keyWord))
                {
                    keyWordCon += " and F_DeptCode like '%" + keyWord + "%'";
                }
                if (!string.IsNullOrEmpty(GetbasedataId))
                {

                    if (!string.IsNullOrEmpty(getDeptIds(GetbasedataId, "")))
                    {
                        keyWordCon += " and F_DeptId in (" + GetbasedataId + "," + getDeptIds(GetbasedataId, "").Trim(',') + ") ";
                    }
                    else {
                        keyWordCon += " and F_DeptId in (" + GetbasedataId + ")";
                    }
                }

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


                int recordCount = 0;
                Model.PageData<Model.T_Sys_Department> pageModel = new Model.PageData<Model.T_Sys_Department>();

                dt = BLL.PagerBLL.GetListPager(
                    "T_Sys_Department ",
                    "F_DeptId",
                    "*",
                    " and F_State!=1 " + keyWordCon,
                    "ORDER BY F_DeptId desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

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

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

        

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