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>
    /// basedatalistAction 的摘要说明
    /// </summary>
    public class basedatalistAction : 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("basedataID");
            switch (action)
            {
                case "getbasedataList":
                    context.Response.Write(GetbasedatalistList(context, keyWord, GetbasedataId));
                    break;
                case "delete":
                    context.Response.Write(GetbasedataDel(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_DictionaryBase> organList = new BLL.T_Sys_DictionaryBase().GetModelList("1=1");
            object obj = GetNodeTreeData(organList);
            return obj.ToString();
        }

        private object GetNodeTreeData(List<Model.T_Sys_DictionaryBase> organList)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            foreach (var item in organList)
            {
                if (item.F_DictionaryFlag == "ZH")
                {
                    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_DictionaryBase item, StringBuilder jsonString, List<Model.T_Sys_DictionaryBase> organList)
        {
            //判断是否有下级节点,如果有子节点，输出子节点
            bool isLeaf = IsLeaf(item.F_DictionaryFlag);

            //添加根节点
            jsonString.Append("{text:\"" + item.F_DictionaryName + "\",id:\"" + item.F_DictionaryFlag + "\"");
            var n = organList.Where(p => p.F_DictionaryFlag == item.F_DictionaryFlag).Count();
            int temJ = 0;
            if (isLeaf)
            {
                jsonString.Append(",children:[");
                //...输出子节点        
                foreach (var child in organList.Where(p => p.F_Describe == item.F_DictionaryFlag))
                {
                    temJ++;
                    Test(child, jsonString, organList);
                }
                jsonString.Append("]},");
            }
            else
            {
                jsonString.Append("},");
            }
        }
       
        /// <summary>
        /// 判断有没有子节点
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private bool IsLeaf(string p)
        {
            bool fas = false;
            DataTable dt = DBUtility.DbHelperSQL.Query("select * from T_Sys_DictionaryBase where F_Describe='" + p + "'").Tables[0];
            if (dt.Rows.Count > 0)
            {
                fas = true;
            }
            return fas;
        }

        private string GetbasedataDel(HttpContext context, string taolCount)
        {
            int res = 0;
            string sql = "update T_Sys_DictionaryValue set F_State=1 where F_DictionaryValueId in(" + taolCount.Trim(',') + ")";
            if (!string.IsNullOrEmpty(taolCount))
            {

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



        /// <summary>
        /// 获取T_Sys_DictionaryValue的列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="keyWord"></param>
        /// <param name="GetbasedataId"></param>
        /// <returns></returns>
        private string GetbasedatalistList(HttpContext context, string keyWord, string GetbasedataId)
        {
            string result = "";
            DataTable dt = new DataTable();
            string keyWordCon = "";
            try
            {
                if (!string.IsNullOrEmpty(keyWord))
                {
                    keyWordCon += " and F_DictionaryFlag like '%" + keyWord + "%'";
                }
                if (!string.IsNullOrEmpty(GetbasedataId))
                {
                    if (GetbasedataId != "ZH")
                    {
                          keyWordCon += " and F_DictionaryFlag like '%" + 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_DictionaryValue> pageModel = new Model.PageData<Model.T_Sys_DictionaryValue>();

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

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

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