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>
    /// WorkalarmmangeAjax 的摘要说明
    /// </summary>
    public class WorkalarmmangeAjax : IHttpHandler
    {
        

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = CommonRequest.GetQueryString("action");
            string NodeId = CommonRequest.GetQueryString("ActionNodeIds");
            string childId = CommonRequest.GetQueryString("NodeChildid");
            
            switch (action)
            {
                case "getlist":
                    context.Response.Write(LoadList(context, NodeId));
                    break;
                case "gettreelist":
                    context.Response.Write(LoadTree(context));
                    break;
                case "getstatelist":
                    context.Response.Write(LoadState(context));
                    break;
                case "PanDuanChild":
                    context.Response.Write(LoadChildCount(context, childId));
                    break;
                
                //case "deletePanDuan":
                //    context.Response.Write(DeletePanDuan(context));
                //    break;
                //case "delete":
                //    context.Response.Write(Delete(context));
                //    break;
            }
        }
        public int LoadChildCount(HttpContext context,string ChildId) {
            int count = 0;
            if (!string.IsNullOrEmpty(ChildId)) {
                object obj = DBUtility.DbHelperSQL.GetSingle("select count(*) from T_Wo_WorkOrderType where F_ParentId='" + ChildId + "'");
                if (obj != null) {
                  count=  Convert.ToInt32(obj);
                }
            }
            return count;
        }
        private string LoadState(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
                    { }
                }
                sql += " and F_Deleteflag=0";

                //if (!string.IsNullOrEmpty(NodeId) && NodeId != "undefined" && NodeId != "1")
                //{
                //    sql += " and F_WorkOrderTypeId='" + NodeId + "'";
                //}
                int recordCount = 0;

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

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

                System.Collections.Generic.List<Model.T_Wo_WorkOrderState> modelList = getStateModel(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_WorkOrderState>));

                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 List<Model.T_Wo_WorkOrderState> getStateModel(DataTable tab)
        {
            BLL.T_Wo_StateAlarmDate bll_timeset = new BLL.T_Wo_StateAlarmDate();

            Model.T_Wo_StateAlarmDate model_time = new Model.T_Wo_StateAlarmDate();
            System.Collections.Generic.List<Model.T_Wo_WorkOrderState> modelList = new List<Model.T_Wo_WorkOrderState>();
            if (tab != null && tab.Rows.Count > 0)
            {
                modelList = new BLL.T_Wo_WorkOrderState().DataTableToList(tab);
                for (int i = 0; i < modelList.Count; i++)
                {
                    string currentID = modelList[i].F_WorkOrderStateId.ToString();//当前功能ID
                    try
                    {
                        List<Model.T_Wo_StateAlarmDate> mode_timeset = bll_timeset.GetModelList("  F_WorkOrderStateId='" + currentID + "'");
                        if (mode_timeset.Count > 0)
                        {
                            model_time = mode_timeset[0];
                            if (model_time != null)
                            {
                                modelList[i].F_ID = model_time.F_Id;//超时记录ID
                                modelList[i].GaoJingTime = (model_time.F_Gcount == null ? "" : model_time.F_Gcount.ToString()) + GetUnit(model_time.F_Gunit == null ? "" : model_time.F_Gunit.ToString());
                                modelList[i].ChaoShiTime = (model_time.F_Ccount == null ? "" : model_time.F_Ccount.ToString()) + GetUnit(model_time.F_Cunit == null ? "" : model_time.F_Cunit.ToString());
                                modelList[i].F_ISMAIN = model_time.F_IsMain;//是否是全局
                            }
                        }
                    }
                    catch (Exception)
                    {

                    }
                }
                return modelList;
            }
            return null;
        }
        private string LoadList(HttpContext context,string NodeId)
        {
            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
                    { }
                }
                sql += " and F_Deleteflag=0";
                if (!string.IsNullOrEmpty(NodeId) && NodeId != "undefined" && NodeId!="1")
                {
                    sql += " and F_WorkOrderTypeId='" + NodeId + "'";
                }

                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_WorkOrderTypeId desc",
                 pagesize,
                 pageindex,
                 true,
                 out recordCount);


                //System.Collections.Generic.List<Model.T_Wo_WorkOrderType> modelList = new BLL.T_Wo_WorkOrderType().DataTableToList(dt);
                System.Collections.Generic.List<Model.T_Wo_WorkOrderType> modelList = getModel(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;
        }


        public List<Model.T_Wo_WorkOrderType> getModel(DataTable tab)
        {
            BLL.T_Wo_TypeAlarmDate bll_timeset = new BLL.T_Wo_TypeAlarmDate();
            
            Model.T_Wo_TypeAlarmDate model_time = new Model.T_Wo_TypeAlarmDate();
            System.Collections.Generic.List<Model.T_Wo_WorkOrderType> modelList=new List<Model.T_Wo_WorkOrderType>();
            if (tab != null && tab.Rows.Count > 0)
            {
                 modelList = new BLL.T_Wo_WorkOrderType().DataTableToList(tab);
                for (int i = 0; i < modelList.Count; i++)
                {
                    string currentID = modelList[i].F_WorkOrderTypeId.ToString();//当前功能ID
                    try
                    {
                        List<Model.T_Wo_TypeAlarmDate> mode_timeset = bll_timeset.GetModelList("  F_WorkOrderTypeId='" + currentID + "'");
                        if (mode_timeset.Count > 0)
                        {
                            model_time = mode_timeset[0];
                            if (model_time != null) {
                                modelList[i].F_ID = model_time.F_Id;//超时记录ID
                                modelList[i].GaoJingTime = (model_time.F_Gcount == null ? "" : model_time.F_Gcount.ToString()) + GetUnit(model_time.F_Gunit == null ? "" : model_time.F_Gunit.ToString());
                                modelList[i].ChaoShiTime = (model_time.F_Ccount == null ? "" : model_time.F_Ccount.ToString()) + GetUnit(model_time.F_Cunit == null ? "" : model_time.F_Cunit.ToString());
                                modelList[i].F_ISMAIN = model_time.F_IsMain;//是否是全局
                            }
                        }
                    }
                    catch (Exception)
                    {

                    }
                }
                return modelList;
            }
            return null;
        }

        private string GetUnit(string number)
        {
            switch (number)
            {
                case "0":
                    return "分";
                case "1":
                    return "小时";
                case "2":
                    return "天";
                default:
                    return "";
            }
        }

        private string LoadTree(HttpContext context)
        {
            string res = "";
            DataTable dt = new DataTable();
            string sql = " ";
            try
            {
                dt = new BLL.T_Wo_WorkOrderType().GetList(" 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();
            }
            res="[{\"IconCls\":\"0\",\"children\":"+res+",  \"id\": \"1\",\"text\": \"类型信息\"}]";
            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
                    tab2 = new BLL.T_Wo_WorkOrderType().GetList("F_ParentId=" + currentID + " and F_WorkOrderTypeId!=1 order by f_sort").Tables[0];
                        if (tab2 == null || tab2.Rows.Count <= 0)
                    {
                        model.id = currentID;
                        model.IconCls = categorylist[i].F_ParentId.ToString();//图标
                        model.text = categorylist[i].F_Name;
                        modelList.Add(model);
                    }
                    }
               
                return modelList;

            }
            else
            {
                return null;
            }

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