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>
    /// UserAjaxList 的摘要说明
    /// </summary>
    public class UserAjaxList : 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 deptId = CommonRequest.GetQueryString("deptId");
            switch (action)
            {
                case "getUserList":
                    context.Response.Write(GetUserList(context));
                    break;
                case "getUserListFinish":
                    context.Response.Write(GetUserListFinish(context));
                    break;
                case "getAssignUserList":
                    context.Response.Write(GetAssignUserList(context));
                    break;
                case "delete":
                    context.Response.Write(GetUserDel(context, taolCount));
                    break;
                case "Getexpstate":
                    context.Response.Write(Deptexpstate(context));
                    break;
                case "clear":
                    break;
            }
        }

        public string Deptexpstate(HttpContext context) {
            List<HySoft.BaseCallCenter.Model.T_Sys_Department> organList = new BLL.T_Sys_Department().GetModelList("1=1");
            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);
            //组合节点id;

            string deptId = getDeptIds(item.F_DeptId.ToString(),"").Trim(',');

            //添加根节点
            if (!string.IsNullOrEmpty(deptId))
            {
                jsonString.Append("{text:\"" + item.F_DeptName + "\",id:\"" + item.F_DeptId +","+deptId +"\"");
            }
            else {
                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 res)
        {
            string reslut = "";
            DataTable 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++)
                {
                    reslut += "," + dt.Rows[i]["F_DeptId"];
                    res += "," + dt.Rows[i]["F_DeptId"];
                }
               res+= getDeptIds(reslut,res);
            }
            return res;
        }

        /// <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>
        /// 删除user信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="countUser"></param>
        /// <returns></returns>
        public string GetUserDel(HttpContext context,string countUser)
        {
            int res = 0;
            string type = CommonRequest.GetQueryString("type");
            string sql = "update T_Sys_UserAccount set F_DeleteFlag=" + type + " where F_UserId in(" + countUser.Trim(',') + ")";
            if (!string.IsNullOrEmpty(countUser)) {

                res = DBUtility.DbHelperSQL.ExecuteSql(sql);
            }
            if (res>0)
            {
                return "success";
            }
            else {
                return "error";
            }
        }



        public string GetAssignUserList(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";

            try
            {
                string id = HttpUtility.UrlDecode(CommonRequest.GetQueryString("id"));
                int pageindex = 1;
                int pagesize = 10;

                if (id.Trim() != "")
                {
                    sql += " and F_UserId in (" + id.Trim() + ")";
                }
                else 
                {
                    return res;
                }

                int recordCount = 0;

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

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

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

                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;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetUserListFinish(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";

            try
            {
                string id = HttpUtility.UrlDecode(CommonRequest.GetQueryString("id"));
                string name = HttpUtility.UrlDecode(CommonRequest.GetQueryString("name"));
                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_DeptId=" + id.Trim() + "";
                }
                if (name != "")
                {
                    sql += " and F_UserName like '%" + name.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.UserAccount> pageModel = new Model.PageData<Model.UserAccount>();

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

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

                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;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetUserList(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";

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

                if (id.Trim() != "" && id.Trim() != "undefined")
                {
                    sql += " and F_DeptId=" + id.Trim() + "";
                }
                if (key != "")
                {
                    sql = "";
                    string str = string.Format(" and (F_UserCode like '%{0}%' or F_UserName like '%{1}%')", key, key);
                    sql += str;
                }
                if (strpageindex.Trim() != "")
                {
                    try
                    {
                        pageindex = Convert.ToInt32(strpageindex);
                    }
                    catch
                    { }
                }

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

                int recordCount = 0;

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

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

                System.Collections.Generic.List<Model.UserAccount> modelList = new BLL.UserAccount().DataTableToList(dt);
                #region MyRegion
                //System.Collections.Generic.List<Model.UserAccount> newmodelList = new List<Model.UserAccount>();
                //foreach (Model.T_Sys_UserAccount tsu in modelList)
                //{
                //    newmodelList.Add(new Model.UserAccount()
                //    {
                //        F_UserId = tsu.F_UserId,
                //        F_UserCode = tsu.F_UserCode,
                //        F_WorkNumber = tsu.F_WorkNumber,
                //        F_UserName = tsu.F_UserName,
                //        F_Telephone = tsu.F_Telephone,
                //        F_Mobile = tsu.F_Mobile,
                //        F_SeatFlag = tsu.F_SeatFlag,
                //        F_DeptName = new BLL.T_Sys_Department().GetModel(tsu.F_DeptId).F_DeptName,
                //        F_RoleName = new BLL.T_Sys_RoleInfo().GetModel(tsu.F_RoleId).F_RoleName
                //    });
                //} 
                #endregion
                pageModel.Rows = modelList;
                pageModel.Total = recordCount;
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = 
                    new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Model.PageData<Model.UserAccount>));

                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;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}