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

namespace HySoft.BaseCallCenter.Web.workordermanage.ajax
{
    /// <summary>
    /// WorkTypeManageAjax 的摘要说明
    /// </summary>
    public class WorkTypeManageAjax : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
     
            string action = CommonRequest.GetQueryString("action");
            switch (action)
            {
                case "getlist":
                    context.Response.Write(LoadList(context));
                    break;
                case "gettreelist":
                    context.Response.Write(LoadTree(context));
                    break;
                case "deletePanDuan":
                    context.Response.Write(DeletePanDuan(context));
                    break;
                case "delete":
                    context.Response.Write(Delete(context));
                    break;
            }
        }


 

        private string Delete(HttpContext context)
        {
            bool res = false;
            string arr = CommonRequest.GetQueryString("arrid");
            if (arr.IndexOf(",") == -1)
            {
                res = new BLL.T_Wo_WorkOrderType().Delete(Convert.ToInt32(arr));
            }
            else
            {
                res = new BLL.T_Wo_WorkOrderType().DeleteList(arr);
            }


            return res ? "success" : "field";
        }

        /// <summary>
        /// 判断是否删除信息
        /// </summary>
        /// <returns></returns>
        public int DeletePanDuan(HttpContext context) {
            int countArr = 0;
            string Arrstr = CommonRequest.GetQueryString("arrid");
            try{
            if (!string.IsNullOrEmpty(CommonRequest.GetQueryString("arrid"))){
                countArr = Convert.ToInt32(DBUtility.DbHelperSQL.GetSingle("select count(*) from T_Wo_WorkOrderType where F_ParentId in (" + Arrstr + ")").ToString());
            }
            }catch(Exception ex ){
                countArr = 0;
            }

            return countArr;
        }




        private string LoadList(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";

            try
            {
                string  str  = HttpUtility.UrlDecode(CommonRequest.GetQueryString("whereSql"));
                if (str != "0")
                 {
                     sql += " and  F_ParentId in (" + str + ")";
                 }
                sql += " and F_WorkOrderTypeId!=1";
                 

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

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

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

                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_Wo_WorkOrderType().GetList(" F_ParentId=0 and F_DeleteFlag=0").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)
            {
                System.Collections.Generic.List<Model.T_Wo_WorkOrderType> categorylist = new BLL.T_Wo_WorkOrderType().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_WorkOrderTypeId.ToString();//当前功能ID
                    model.id = currentID;
                    model.IconCls = categorylist[i].F_ParentId.ToString();//图标
                    model.text = categorylist[i].F_Name;
                    tab2 = new BLL.T_Wo_WorkOrderType().GetList("F_ParentId=" + currentID + " order by f_sort").Tables[0];
                    if (tab2 != null && tab2.Rows.Count > 0)
                    {
                        model.children = BindTree(tab2, currentID);
                    }
                    modelList.Add(model);
                }
                return modelList;

            }
            else
            {
                return null;
            }

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