using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    public class InfoController : BaseController
    {
        private BLL.T_Bus_WorkOrder workOrderBLL = new BLL.T_Bus_WorkOrder();
        private BLL.T_Call_CallRecords callBLL = new BLL.T_Call_CallRecords();
        private BLL.T_Sys_DictionaryValue dicValueBLL = new BLL.T_Sys_DictionaryValue();
        private BLL.T_Sys_Department departmentBLL = new BLL.T_Sys_Department();

        #region no user
        #region  获取数据
        //来源渠道情况
        public ActionResult GetSourceInfo()
        {
            var obj = new
            {
                a = GetSourcePercent(),
                b = GetAreaCount(),
                c = GetAreaCount24()
            };

            return Success("加载成功", obj);
        }

        //接单部门情况
        public ActionResult GetDeptInfo()
        {
            var obj = new
            {
                a = GetStateCountMonth(),
                b = GetDeptCount(),
                c = GetDealCount24()
            };

            return Success("加载成功", obj);
        }

        //投诉举报情况
        public ActionResult GetTypeInfo()
        {
            var obj = new
            {
                a = GetTypeCountMonth(),
                b = GetTypeCount(),
                c = GetKeyCount(),
                d = GetDeptCount()
            };

            return Success("加载成功", obj);
        }
        //话务数量情况
        public ActionResult GetTelInfo()
        {
            var obj = new
            {
                a = GetTelCount24(),
                b = GetUserStateCount24(),
                c = GetTelCount()
            };

            return Success("加载成功", obj);
        }
        //中心大数据
        public ActionResult GetCenterInfo()
        {
            var obj = new
            {
                a = GetTypeCount(),
                b = GetTelRate24(),
                c = GetAvgTelTime24(),
                d = GetAreaCount(),
                e = GetCenterTypeCount()
            };

            return Success("加载成功", obj);
        }
        //服务知识
        #endregion

        #region 1.来源渠道情况
        //受理渠道24小时实时统计
        private object GetSourceCount()
        {
            string sql = " select F_Value Source,(select COUNT(1) from T_Bus_WorkOrder where datediff(day,F_CreateTime,getdate())=0 and F_IsDelete=0 "
                + " and  F_InfoSource=F_ValueId) Count from  dbo.T_Sys_DictionaryValue where F_ItemId=1 and F_State=0 ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            return dt;
        }
        private object GetSourcePercent()
        {
            int n = Int32.Parse(DbHelperSQL.GetSingle("select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 and datediff(day,F_CreateTime,getdate())=0").ToString());
            var sourceList = dicValueBLL.GetModelList(" F_ItemId=1 and F_State=0 ");

            var obj = sourceList.Select(p =>
            {
                var sql = " select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0  and datediff(day,F_CreateTime,getdate())=0"
                        + " and F_InfoSource=" + p.F_ValueId;
                var cl = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                return new
                {
                    source = p.F_Value,
                    percent = n > 0 ? Math.Round(((double)cl * 100 / n), 2) : 0
                };
            });

            return obj;
        }
        //受理区域统计
        private object GetAreaCount()
        {
            //string sql = " select F_AreaName AreaName,(select COUNT(1) from T_Bus_WorkOrder where datediff(day,F_CreateTime,getdate())=0 and F_IsDelete=0 "
            //    + "and F_SourceArea=F_AreaId) Count from dbo.T_Sys_Area where F_PrentId=0 and F_State=0 ";

            string sql = " select F_AreaId,F_AreaName AreaName,(select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 and isnull(F_IsResult,0)=0"
                + "and F_SourceArea=F_AreaId) Count from dbo.T_Sys_Area where F_PrentId=0 and F_State=0 ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            DataRow dr = dt.NewRow();
            dr["F_AreaId"] = "0";
            dr["AreaName"] = "当即办理";

            string sqlzb = "select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 and isnull(F_IsResult,0)=1";
            dr["Count"] = DbHelperSQL.GetSingle(sqlzb).ToString();

            dt.Rows.Add(dr);
            //dt.Columns.Add("Item", typeof(object));
            //foreach (DataRow drnew in dt.Rows)
            //{
            //    string where = " and isnull(F_IsResult,0)=1 ";
            //    string straid = drnew["F_AreaId"].ToString();
            //    if (straid != "0")
            //    {
            //        where = " and isnull(F_IsResult,0)=0 and F_SourceArea='" + straid + "' ";
            //    }
            //    string sqltype = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 " + where
            //    + " and F_InfoType=F_ValueId) Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
            //    DataTable dttype = DbHelperSQL.Query(sqltype).Tables[0];

            //    drnew["Item"] = dttype;
            //}

            return dt;
        }
        //受理区域统计(按小时统计)
        private object GetAreaCount24()
        {
            var areaList = new BLL.T_Sys_Area().GetModelList(" F_PrentId=0 and F_State=0 ");

            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };

            var obj = new
            {
                hours = hours,
                cols = areaList.Select(p => p.F_AreaName),
                counts = new List<int[]>()
            };

            foreach (var area in areaList)
            {
                int[] count = new int[24];
                for (int i = 0; i < hours.Length; i++)
                {
                    string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 and F_SourceArea='" + area.F_AreaId + "'"
                        + " and datediff(day, F_CreateTime, getdate()) = 0 and datepart(hh, F_CreateTime)=" + hours[i];
                    count[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                }
                obj.counts.Add(count);
            }

            return obj;
        }

        #endregion

        #region 2.接单部门情况
        //接单情况汇总(月份)
        private object GetStateCountMonth()
        {
            int[] stateList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            string[] nameList = { "新工单", "待交办", "待查收", "退回审核中", "办理中", "延时审核中", "已办理", "已回访", "重办中", "已结案" };
            int[] ints = new int[12];
            string[] months = new string[12];
            for (int i = 12; i > 0; i--)
            {
                var date = DateTime.Now.AddMonths(1 - i);
                string mon = date.ToString("yyyyMM");
                months[12 - i] = mon;
                ints[12 - i] = date.Month;
            }

            var obj = new
            {
                months = months,
                cols = nameList,
                counts = new List<int[]>()
            };

            foreach (var state in stateList)
            {
                int[] count = new int[12];
                for (int i = 0; i < ints.Length; i++)
                {
                    string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 and F_WorkState=" + state
                        + " and datediff(month,F_CreateTime,getdate())<=12 and datepart(month, F_CreateTime)=" + ints[i];
                    count[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                }
                obj.counts.Add(count);
            }

            return obj;
        }

        //各部门受理工单情况
        //private object GetDeptCount()
        //{
        //    var list = departmentBLL.GetModelList(" 1=1 ");
        //    var obj = new
        //    {
        //        cols = list.Select(p => p.F_DeptName),
        //        totals = new List<int[]>(),
        //        counts = new List<int[]>(),
        //        percents = new List<string[]>()
        //    };

        //    int[] total = new int[list.Count];
        //    int[] count = new int[list.Count];
        //    string[] percent = new string[list.Count];

        //    for (int i = 0; i < list.Count; i++)
        //    {
        //        string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 "
        //                + " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo where F_IsSure!=3 "
        //                + " and F_State=1 and F_IsDelete = 0 and F_MainDeptId=" + list[i].F_DeptId + ")";
        //        var tl = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
        //        sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 "
        //                + " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo where F_IsSure=1 "
        //                + " and F_State=1 and F_IsDelete = 0 and F_MainDeptId=" + list[i].F_DeptId + " and F_FeedbackTime is not null)";
        //        var cl = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

        //        total[i] = tl;
        //        count[i] = cl;
        //        percent[i] = tl > 0 ? ((double)cl / tl).ToString("0.00%") : "-";
        //    }

        //    obj.totals.Add(total);
        //    obj.counts.Add(count);
        //    obj.percents.Add(percent);

        //    return obj;
        //}
        private object GetDeptPercent()
        {
            var list = departmentBLL.GetModelList(" F_DeptNameSpell='3' ");

            var obj = list.Select(p =>
            {
                string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 "
                        + " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo where F_State=1 and F_IsDelete = 0  "
                        + " and F_IsSure !=3 and F_MainDeptId=" + p.F_DeptId + ")";
                var tl = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 "
                        + " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo where F_State=1 and F_IsDelete = 0 "
                        + " and F_IsSure=1 and F_MainDeptId=" + p.F_DeptId + "  and F_FeedbackTime is not null)";
                var cl = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                return new
                {
                    deptname = p.F_DeptName,
                    percent = tl > 0 ? Math.Round(((double)cl * 100 / tl), 2) : 0
                };
            });

            return obj;
        }

        //工单处理时间分布（小时）
        private object GetDealCount24()
        {
            //int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            //int[] acounts = new int[24];
            //int[] fcounts = new int[24];
            int[] hours = { 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
            int[] acounts = new int[12];
            int[] fcounts = new int[12];

            for (int i = 0; i < hours.Count(); i++)
            {
                string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 "
                        + " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo where F_IsSure!=3 and datediff(day,F_CreateTime,getdate())=0 "
                        + " and datepart(hh, F_CreateTime)=" + hours[i] + " and F_IsDelete = 0 and F_State=1 )";
                var al = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 "
                        + " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo where F_IsSure=1 and datediff(day,F_FeedbackTime,getdate())=0 "
                        + " and datepart(hh, F_FeedbackTime)=" + hours[i] + " and F_IsDelete = 0 and F_State=1 )";
                var fl = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                acounts[i] = al;
                fcounts[i] = fl;
            }

            var obj = new
            {
                hours = hours,
                acounts = acounts,
                fcounts = fcounts
            };

            return obj;
        }
        //受理单位统计
        private object GetDeptCount()
        {
            var list = departmentBLL.GetModelList(" F_DeptNameSpell='3' ");

            var obj = list.Select(p =>
            {
                string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 "
                        + " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo where F_IsDelete = 0 and F_State=1  "
                        + " and F_MainDeptId=" + p.F_DeptId + " and F_IsSure!=3)";
                var tl = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                return new
                {
                    deptname = p.F_DeptName,
                    count = tl
                };
            });

            return obj;
        }
        #endregion

        #region 3.投诉举报情况
        //工单类型各数量
        private object GetTypeCount()
        {
            var typelist = dicValueBLL.GetModelList(" F_ItemId=2 ");
            int[] counts = new int[typelist.Count];

            for (int i = 0; i < typelist.Count; i++)
            {
                string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 and F_InfoType=" + typelist[i].F_ValueId;
                counts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
            }
            var obj = new
            {
                cols = typelist.Select(p => p.F_Value),
                counts = counts
            };
            return obj;
        }
        //投诉类型统计(月份)
        private object GetTypeCountMonth()
        {
            int[] ints = new int[12];
            string[] months = new string[12];
            for (int i = 12; i > 0; i--)
            {
                var date = DateTime.Now.AddMonths(1 - i);
                string mon = date.ToString("yyyyMM");
                months[12 - i] = mon;
                ints[12 - i] = date.Month;
            }

            var typelist = dicValueBLL.GetModelList(" F_ItemId=2 ");
            var obj = new
            {
                months = months,
                cols = typelist.Select(p => p.F_Value),
                counts = new List<int[]>(),
            };

            foreach (var l in typelist)
            {
                int[] count = new int[12];
                for (int i = 0; i < ints.Length; i++)
                {
                    string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 and F_InfoType=" + l.F_ValueId
                        + " and datediff(month,F_CreateTime,getdate())<=12 and datepart(month, F_CreateTime)=" + ints[i];
                    count[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                }
                obj.counts.Add(count);
            }

            return obj;
        }
        //工单处理时间分布（小时）
        private object GetTypeCount24()
        {
            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            var typelist = dicValueBLL.GetModelList(" F_ItemId=2 ");
            var obj = new
            {
                hours = hours,
                cols = typelist.Select(p => p.F_Value),
                counts = new List<int[]>()
            };

            foreach (var l in typelist)
            {
                int[] count = new int[24];
                for (int i = 0; i < hours.Length; i++)
                {
                    string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 and F_InfoType=" + l.F_ValueId
                       + " and datediff(day,F_CreateTime,getdate())=0 and datepart(hh, F_CreateTime)=" + hours[i];
                    count[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                }
                obj.counts.Add(count);
            }

            return obj;
        }
        //投诉关键字统计
        private object GetKeyCount()
        {
            //var typelist = dicValueBLL.GetModelList(" F_ItemId=3 ");

            //int[] counts = new int[typelist.Count];

            //for (int i = 0; i < typelist.Count; i++)
            //{
            //    string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 and ','+F_Key+',' like '%,"+ typelist[i].F_ValueId + ",%'" ;
            //    counts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
            //}
            //var obj = new
            //{
            //    cols = typelist.Select(p => p.F_Value),
            //    counts = counts
            //};
            string sql = "select * from (select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 "
                       + "and ','+F_Key+',' like '%,'+CONVERT(varchar(100),F_ValueId)+',%') Count "
                       + "from dbo.T_Sys_DictionaryValue where F_ItemId = 3 and F_State = 0) a order by a.Count desc ";
            return DbHelperSQL.Query(sql).Tables[0];
        }
        //举报单位/个人统计
        //投诉单位统计
        //举报关键字统计
        #endregion

        #region 4.话务数量情况
        //话务量实时数据统计
        private object GetTelCount24()
        {
            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            int[] tcounts = new int[24];//来电数量
            int[] ccounts = new int[24];//接通数量
            int[] wjtcounts = new int[24];//未接通数量
            int[] lcounts = new int[24];//留言数量
            int[] gcounts = new int[24];//放弃数量
            int[] scounts = new int[24];//骚扰数量

            for (int i = 0; i < hours.Length; i++)
            {
                string sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, getdate()) = 0  "
                        + " and datepart(hh,BeginTime)=" + hours[i];
                tcounts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, getdate()) = 0  "
                        + " and CallState=1 and datepart(hh,BeginTime)=" + hours[i];
                ccounts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, getdate()) = 0  "
                        + " and CallState=0 and isnull(usercode,'')<>'' and datepart(hh,BeginTime)=" + hours[i];
                wjtcounts[i] = 0;

                //sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, getdate()) = 0  "
                //        + " and DealType=4 and datepart(hh,BeginTime)=" + hours[i];
                sql = " select count(1) from dbo.T_Call_LeaveRecord where datediff(day, F_LeaveTime, getdate()) = 0  "
                        + "and datepart(hh,F_LeaveTime)=" + hours[i];
                lcounts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, getdate()) = 0  "
                        + " and callstate=2  and datepart(hh,BeginTime)=" + hours[i];
                scounts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                gcounts[i] = tcounts[i] - ccounts[i] - wjtcounts[i] - scounts[i];
                //gcounts[i] = tcounts[i] - ccounts[i] - lcounts[i] - scounts[i];

            }

            var obj = new
            {
                hours = hours,
                rcounts = tcounts,
                ccounts = ccounts,
                //lcounts = lcounts,
                wjtcounts = wjtcounts,
                gcounts = gcounts,
                scounts = scounts
            };

            return obj;
        }
        //管辖区域来话量统计
        //坐席闲忙比例
        private object GetUserStateCount24()
        {
            //DataTable dt = DbHelperSQL.Query(" select datepart(hh,OccurTime) hor,State, count(1) con from rep_agent_state where datediff(day, OccurTime, getdate()) = 0 group by datepart(hh,OccurTime),State ").Tables[0];
            //select datepart(hh,TimeStart) hor,type, count(1) con   from rep_agentState_Detail   where datediff(day, TimeStart, getdate()) = 0 and TimeEnd is null  group by datepart(hh,TimeStart),type
            //DataTable dt = DbHelperSQL.Query("select datepart(hh,TimeStart) hor,type, count(1) con   from rep_agentState_Detail   where datediff(day, TimeStart, getdate()) = 0 and TimeEnd is null  group by datepart(hh,TimeStart),type").Tables[0];
            DataTable dt = DbHelperSQL.Query("select hor,type,COUNT(1) con from (select datepart(hh, TimeStart) hor, type, agentid, count(1) con   from rep_agentState_Detail   where datediff(day, TimeStart, getdate()) = 0   group by datepart(hh, TimeStart), type, agentid ) t group by hor, type").Tables[0];
            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            double[] kxpercents = new double[24];
            double[] thpercents = new double[24];
            double[] zmpercents = new double[24];

            for (int i = 0; i < hours.Length; i++)
            {

                var list = dt.Select(" hor=" + hours[i]);
                int con = 0;//总量
                foreach (var l in list)
                {
                    con = con + Int32.Parse(l["con"].ToString());
                }
                //var con = list.Count() > 0 ? list[0]["con"].ToString() : "0";//总量
                var kxlist = dt.Select(" hor=" + hours[i] + " and type=2 ");
                var kxcon = kxlist.Count() > 0 ? kxlist[0]["con"].ToString() : "0";//空闲
                var thlist = dt.Select(" hor=" + hours[i] + " and type=3 ");
                var thcon = thlist.Count() > 0 ? thlist[0]["con"].ToString() : "0"; ;//通话中
                var hhcllist = dt.Select(" hor=" + hours[i] + " and type=4 ");
                var hhclcon = hhcllist.Count() > 0 ? hhcllist[0]["con"].ToString() : "0"; ;//话后处理中
                var xxlist = dt.Select(" hor=" + hours[i] + " and type=5 ");
                var xxcon = xxlist.Count() > 0 ? xxlist[0]["con"].ToString() : "0"; ;//小休
                var zllist = dt.Select(" hor=" + hours[i] + " and type=6 ");
                var zlcon = zllist.Count() > 0 ? zllist[0]["con"].ToString() : "0"; ;//被请求
                if (con == 0)
                {
                    kxpercents[i] = 0;
                    thpercents[i] = 0;
                    zmpercents[i] = 0;
                }
                else
                {
                    //kxpercents[i] = (double.Parse(kxcon) / double.Parse(con)).ToString("0.00%");
                    //thpercents[i] = (double.Parse(thcon) / double.Parse(con)).ToString("0.00%");
                    //zmpercents[i] = (double.Parse(xxcon) / double.Parse(con)).ToString("0.00%");
                    kxpercents[i] = Math.Round((double.Parse(kxcon) * 100 / con), 2);
                    thpercents[i] = Math.Round((double.Parse(thcon) * 100 / con), 2);
                    zmpercents[i] = Math.Round((double.Parse(xxcon) * 100 / con), 2);
                }

            }
            var obj = new
            {
                hours = hours,
                kxpercents = kxpercents,
                thpercents = thpercents,
                zmpercents = zmpercents
            };

            return obj;
        }
        //话务量总体统计
        private object GetTelCount()
        {
            //话务量
            DataTable dt = DbHelperSQL.Query(" select count(1) con from T_Call_CallRecords where datediff(day, BeginTime, getdate()) = 0 ").Tables[0];

            var hwcon = dt.Rows[0]["con"].ToString();//话务量

            //来话量
            DataTable dt1 = DbHelperSQL.Query(" select count(1) con from T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, getdate()) = 0 ").Tables[0];
            var lhcon = dt1.Rows[0]["con"].ToString();//话务量

            //接通量,通话时长
            DataTable dt2 = DbHelperSQL.Query(" select count(1) con,sum(TalkLongTime) tltimes from T_Call_CallRecords where CallState=1 and datediff(day, BeginTime, getdate()) = 0 ").Tables[0];
            var jtcon = dt2.Rows[0]["con"].ToString();//接通量
            var ths = dt2.Rows[0]["tltimes"];//通话时长
            var thtimes = "0";
            if (ths != null && ths.ToString() != "")
            {
                thtimes = ths.ToString();
            }
            string jtl = "-";//接通率
            if (hwcon != "0")
            {
                jtl = (double.Parse(jtcon) / double.Parse(hwcon)).ToString("0.00%");
            }
            double pjthtimes = 0.00;//平均通话时长
            if (jtcon != "0")
            {
                pjthtimes = Math.Round(double.Parse(thtimes) / double.Parse(jtcon));
            }

            var obj = new
            {
                hwcon = hwcon,
                lhcon = lhcon,
                jtcon = jtcon,
                pjthtimes = pjthtimes,
                jtl = jtl
            };
            return obj;
        }
        #endregion

        #region 5.中心大数据
        //工单类型各数量
        private object GetCenterTypeCount()
        {
            string sql = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 "
                + "and F_InfoType=F_ValueId) Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];
            DataRow dr = dt.NewRow();
            dr["TypeName"] = "总计";

            string sqlzj = "select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 ";
            dr["Count"] = DbHelperSQL.GetSingle(sqlzj).ToString();

            dt.Rows.InsertAt(dr, 0);

            DataRow dr1 = dt.NewRow();
            dr1["TypeName"] = "今日";

            string sqlday = "select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 and datediff(day,F_CreateTime,getdate())=0 ";
            dr1["Count"] = DbHelperSQL.GetSingle(sqlday).ToString();

            dt.Rows.InsertAt(dr1, 1);

            return dt;
        }
        //接通率统计源
        //投诉举报关键话题排名
        //通话数量统计
        //接通率统计
        private object GetTelRate24()
        {
            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            //string[] rates = new string[24];
            double[] rates = new double[24];

            for (int i = 0; i < hours.Length; i++)
            {
                string sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and CallState=1 and UserCode is not null and datediff(day, BeginTime, getdate()) = 0  "
                        + " and datepart(hh,BeginTime)=" + hours[i];
                var c = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and UserCode is not null and datediff(day, BeginTime, getdate()) = 0  "
                        + " and datepart(hh,BeginTime)=" + hours[i];
                var t = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                //rates[i]= t > 0 ? ((double)c / t).ToString("0.00%") : "-";
                rates[i] = t > 0 ? Math.Round(((double)c * 100 / t), 2) : 0;
            }

            var obj = new
            {
                hours = hours,
                rates = rates
            };

            return obj;
        }
        //平均通话时长统计
        private object GetAvgTelTime24()
        {
            //接通量，通话时长
            DataTable dt = DbHelperSQL.Query(" select datepart(hh,BeginTime) hor,count(1) con,sum(TalkLongTime) tltimes from T_Call_CallRecords where CallState=1 and datediff(day, BeginTime, getdate()) = 0 group by datepart(hh,BeginTime) ").Tables[0];

            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            double[] avgtimes = new double[24];
            for (int i = 0; i < hours.Length; i++)
            {
                var jtlist = dt.Select(" hor=" + hours[i] + " ");
                var jtcon = jtlist.Count() > 0 ? jtlist[0]["con"].ToString() : "0";
                var thtimes = jtlist.Count() > 0 ? jtlist[0]["tltimes"].ToString() : "0";

                double avgtime = 0.00;
                if (jtcon != "0")
                {
                    if (thtimes == "") { thtimes = "0"; }
                    avgtime = Math.Round(double.Parse(thtimes) / double.Parse(jtcon), 2);
                }

                avgtimes[i] = avgtime;
            }
            var obj = new
            {
                hours = hours,
                avgtimes = avgtimes
            };

            return obj;
        }
        #endregion

        #region 6.服务知识
        //工单处理时间统计和分布
        //群众咨询知识库情况统计
        //工单处理时间统计和分布
        #endregion
        #endregion

        #region 来源渠道

        /// <summary>
        /// 获取来源数量
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetSourceCountByDate(DateTime? start, DateTime? end)
        {
            string where = " and F_IsDelete=0";
            if (start == null && end == null)
            {
                where += " and datediff(day,F_CreateTime,getdate())=0";
            }
            else
            {
                if (start == null) { start = DateTime.Now; }
                if (end == null) { end = DateTime.Now; }
                where += $" and datediff(day,F_CreateTime,'{start.Value.ToString("yyyy-MM-dd")}')<=0 and datediff(day,F_CreateTime,'{end.Value.ToString("yyyy-MM-dd")}')>=0 ";
            }

            string sql = " select F_ValueId Id,F_Value Source,(select COUNT(1) from T_Bus_WorkOrder where  F_InfoSource=F_ValueId " + where
                + ") Count from  dbo.T_Sys_DictionaryValue where F_ItemId=1 and F_State=0 ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            dt.Columns.Add("Item", typeof(object));
            foreach (DataRow drnew in dt.Rows)
            {
                string straid = drnew["Id"].ToString();
                string strwhere = where + " and F_InfoSource='" + straid + "' ";

                string sqltype = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_InfoType=F_ValueId " + strwhere
                + ") Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
                DataTable dttype = DbHelperSQL.Query(sqltype).Tables[0];

                drnew["Item"] = dttype;
            }

            return Success("加载成功", dt);
        }

        /// <summary>
        /// 获取来源百分比
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetSourcePercentByDate(DateTime? start, DateTime? end)
        {
            string where = " and F_IsDelete=0";
            if (start == null && end == null)
            {
                where += " and datediff(day,F_CreateTime,getdate())=0";
            }
            else
            {
                if (start == null) { start = DateTime.Now; }
                if (end == null) { end = DateTime.Now; }
                where += $" and datediff(day,F_CreateTime,'{start.Value.ToString("yyyy-MM-dd")}')<=0 and datediff(day,F_CreateTime,'{end.Value.ToString("yyyy-MM-dd")}')>=0 ";
            }
            string sql = " select F_ValueId Id,F_Value Source,(select COUNT(1) from T_Bus_WorkOrder where  F_InfoSource=F_ValueId " + where
                + ") Count from  dbo.T_Sys_DictionaryValue where F_ItemId=1 and F_State=0 ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            int n = Int32.Parse(DbHelperSQL.GetSingle("select COUNT(1) from T_Bus_WorkOrder where 1=1 " + where).ToString());

            dt.Columns.Add("Percent", typeof(object));
            dt.Columns.Add("Item", typeof(object));
            foreach (DataRow drnew in dt.Rows)
            {
                if (n > 0)
                {
                    drnew["Percent"] = Math.Round((double.Parse(drnew["Count"].ToString()) * 100 / n), 2);
                }
                string straid = drnew["Id"].ToString();
                string strwhere = where + " and F_InfoSource='" + straid + "' ";

                string sqltype = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_InfoType=F_ValueId " + strwhere
                + ") Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
                DataTable dttype = DbHelperSQL.Query(sqltype).Tables[0];

                drnew["Item"] = dttype;
            }

            return Success("加载成功", dt);
        }

        /// <summary>
        /// 获取受理区域数量
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetAreaCountByDate(DateTime? start, DateTime? end)
        {
            string where = " and F_IsDelete=0";
            if (start == null && end == null)
            {
                where += " and datediff(day,F_CreateTime,getdate())=0";
            }
            else
            {
                if (start == null) { start = DateTime.Now; }
                if (end == null) { end = DateTime.Now; }
                where += $" and datediff(day,F_CreateTime,'{start.Value.ToString("yyyy-MM-dd")}')<=0 and datediff(day,F_CreateTime,'{end.Value.ToString("yyyy-MM-dd")}')>=0 ";
            }
            string sql = " select F_AreaId,F_AreaName AreaName,(select COUNT(1) from T_Bus_WorkOrder where isnull(F_IsResult,0)=0 " + where
                + "and F_SourceArea=F_AreaId) Count from dbo.T_Sys_Area where F_PrentId=0 and F_State=0 ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            DataRow dr = dt.NewRow();
            dr["F_AreaId"] = "0";
            dr["AreaName"] = "当即办理";

            string sqlzb = "select COUNT(1) from T_Bus_WorkOrder where isnull(F_IsResult,0)=1" + where;
            dr["Count"] = DbHelperSQL.GetSingle(sqlzb).ToString();
            dt.Rows.Add(dr);
            dt.Columns.Add("Item", typeof(object));
            foreach (DataRow drnew in dt.Rows)
            {
                string strwhere = where;
                string straid = drnew["F_AreaId"].ToString();
                if (straid != "0")
                {
                    strwhere += " and isnull(F_IsResult,0)=0 and F_SourceArea='" + straid + "' ";
                }
                else
                {
                    strwhere += " and isnull(F_IsResult,0)=1 ";
                }

                string sqltype = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_InfoType=F_ValueId " + strwhere
                + ") Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
                DataTable dttype = DbHelperSQL.Query(sqltype).Tables[0];

                drnew["Item"] = dttype;
            }

            return Success("加载成功", dt);
        }

        /// <summary>
        /// 获取受理区域数量
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetAreaCount24ByDate(DateTime? date)
        {
            string where = " and F_IsDelete=0";
            if (date != null)
            {
                where += $" and datediff(day,F_CreateTime,'{date.Value.ToString("yyyy-MM-dd")}')=0 ";
            }
            else
            {
                where += " and datediff(day,F_CreateTime,getdate())=0";
            }

            var areaList = new BLL.T_Sys_Area().GetModelList(" F_PrentId=0 and F_State=0 ");

            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };

            var obj = new
            {
                hours = hours,
                cols = areaList.Select(p => p.F_AreaName),
                counts = new List<int[]>(),
                tcounts = new int[areaList.Count],
                items = new List<object>()
            };
            int n = 0;
            foreach (var area in areaList)
            {
                int t = 0;
                string strwhere = where;
                strwhere += " and F_SourceArea='" + area.F_AreaId + "'";
                int[] count = new int[24];
                for (int i = 0; i < hours.Length; i++)
                {
                    string sql = " select count(1) from dbo.T_Bus_WorkOrder where datepart(hh, F_CreateTime)=" + hours[i] + strwhere;
                    count[i] = Int32.Parse(DbHelperSQL.GetSingle(sql).ToString());
                    t = t + count[i];
                }
                obj.counts.Add(count);

                obj.tcounts[n]= t;
                n += 1;

                string sqltype = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_InfoType=F_ValueId " + strwhere
                + ") Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
                DataTable dttype = DbHelperSQL.Query(sqltype).Tables[0];
                obj.items.Add(dttype);
            }

            return Success("加载成功", obj);
        }

        #endregion

        #region 接单部门

        /// <summary>
        /// 接单情况汇总(月份)
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetStateCountMonthByDate()
        {
            int[] stateList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            string[] nameList = { "新工单", "待交办", "待查收", "退回审核中", "办理中", "延时审核中", "已办理", "已回访", "重办中", "已结案" };
            int[] ints = new int[12];
            string[] months = new string[12];
            for (int i = 12; i > 0; i--)
            {
                var date = DateTime.Now.AddMonths(1 - i);
                string mon = date.ToString("yyyyMM");
                months[12 - i] = mon;
                ints[12 - i] = date.Month;
            }

            var obj = new
            {
                months = months,
                cols = nameList,
                counts = new List<int[]>()
            };

            foreach (var state in stateList)
            {
                int[] count = new int[12];
                for (int i = 0; i < ints.Length; i++)
                {
                    string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 and F_WorkState=" + state
                        + " and datediff(month,F_CreateTime,getdate())<=12 and datepart(month, F_CreateTime)=" + ints[i];
                    count[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                }
                obj.counts.Add(count);
            }

            return Success("加载成功", obj);
        }

        /// <summary>
        /// 单位受理处理时间分布（小时）
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetDealCount24ByDate(DateTime? date)
        {
            int[] hours = { 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
            int[] acounts = new int[12];
            int[] fcounts = new int[12];

            string where = " and F_IsDelete= 0 and F_State=1 ";
            if (date == null)
            {
                date = DateTime.Now;
            }

            for (int i = 0; i < hours.Count(); i++)
            {
                string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 "
                        + " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo where F_IsSure!=3 " + where
                        + $" and datediff(day,F_CreateTime,'{date.Value.ToString("yyyy-MM-dd")}')=0 and datepart(hh, F_CreateTime)=" + hours[i] + ")";
                var al = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 "
                        + " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo where F_IsSure=1 and isnull(F_FeedbackTime,'')<>''" + where
                        + $" and datediff(day,F_FeedbackTime,'{date.Value.ToString("yyyy-MM-dd")}')=0 and datepart(hh, F_FeedbackTime)=" + hours[i] + ")";
                var fl = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                acounts[i] = al;
                fcounts[i] = fl;
            }

            var obj = new
            {
                hours = hours,
                acounts = acounts,
                fcounts = fcounts
            };

            return Success("加载成功", obj);
        }

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDeptList()
        {
            DataTable dt = new DataTable();
            dt = departmentBLL.GetList(0, "F_State=0 and F_DeptNameSpell='3'", " F_Sort").Tables[0];
            return Success("加载成功", dt);
        }

        /// <summary>
        /// 获取承办单位数量
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetDeptCountByDate(DateTime? start, DateTime? end,int deptid=0)
        {
            string where = " and F_IsDelete=0";
            if (start == null && end == null)
            {
                where += " and datediff(day,F_CreateTime,getdate())=0";
            }
            else
            {
                if (start == null) { start = DateTime.Now; }
                if (end == null) { end = DateTime.Now; }
                where += $" and datediff(day,F_CreateTime,'{start.Value.ToString("yyyy-MM-dd")}')<=0 and datediff(day,F_CreateTime,'{end.Value.ToString("yyyy-MM-dd")}')>=0 ";
            }
            string sql = " select F_DeptId Id,F_DeptName AreaName,(select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkOrderID in "
                +"(select F_WorkOrderID from T_Bus_AssignedInfo where F_IsSure!=3 " + where
                + " and F_MainDeptId=F_DeptId)) Count from dbo.T_Sys_Department where F_DeptNameSpell='3' ";
            if (deptid > 0)
            {
                sql += " and F_DeptId='" + deptid + "'";
            }
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            dt.Columns.Add("Item", typeof(object));
            foreach (DataRow drnew in dt.Rows)
            {
                string strwhere = where;
                string straid = drnew["Id"].ToString();
                strwhere += " and F_MainDeptId='" + straid + "' ";

                string sqltype = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 and F_InfoType=F_ValueId and F_WorkOrderID in"
                    + "(select F_WorkOrderID from T_Bus_AssignedInfo where F_IsSure!=3 " + strwhere
                + ")) Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
                DataTable dttype = DbHelperSQL.Query(sqltype).Tables[0];

                drnew["Item"] = dttype;
            }

            return Success("加载成功", dt);
        }

        #endregion

        #region 投诉举报

        /// <summary>
        /// 获取类型数量
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetTypeCountByDate(DateTime? start, DateTime? end)
        {
            string where = " and F_IsDelete=0";
            if (start == null && end == null)
            {
                where += " and datediff(day,F_CreateTime,getdate())=0";
            }
            else
            {
                if (start == null) { start = DateTime.Now; }
                if (end == null) { end = DateTime.Now; }
                where += $" and datediff(day,F_CreateTime,'{start.Value.ToString("yyyy-MM-dd")}')<=0 and datediff(day,F_CreateTime,'{end.Value.ToString("yyyy-MM-dd")}')>=0 ";
            }
            string sql = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_InfoType=F_ValueId " + where
                + ") Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            return Success("加载成功", dt);
        }

        /// <summary>
        /// 接单情况汇总(月份)
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetTypeCountMonthByDate()
        {
            int[] ints = new int[12];
            string[] months = new string[12];
            for (int i = 12; i > 0; i--)
            {
                var date = DateTime.Now.AddMonths(1 - i);
                string mon = date.ToString("yyyyMM");
                months[12 - i] = mon;
                ints[12 - i] = date.Month;
            }

            var typelist = dicValueBLL.GetModelList(" F_ItemId=2 ");
            var obj = new
            {
                months = months,
                cols = typelist.Select(p => p.F_Value),
                counts = new List<int[]>(),
            };

            foreach (var l in typelist)
            {
                int[] count = new int[12];
                for (int i = 0; i < ints.Length; i++)
                {
                    string sql = " select count(1) from dbo.T_Bus_WorkOrder where F_IsDelete = 0 and F_InfoType=" + l.F_ValueId
                        + " and datediff(month,F_CreateTime,getdate())<=12 and datepart(month, F_CreateTime)=" + ints[i];
                    count[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());
                }
                obj.counts.Add(count);
            }

            return Success("加载成功", obj);
        }

        /// <summary>
        /// 获取关键词数量
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetKeyCountByDate(DateTime? start, DateTime? end)
        {
            string where = " and F_IsDelete=0";
            if (start == null && end == null)
            {
                where += " and datediff(day,F_CreateTime,getdate())=0";
            }
            else
            {
                if (start == null) { start = DateTime.Now; }
                if (end == null) { end = DateTime.Now; }
                where += $" and datediff(day,F_CreateTime,'{start.Value.ToString("yyyy-MM-dd")}')<=0 and datediff(day,F_CreateTime,'{end.Value.ToString("yyyy-MM-dd")}')>=0 ";
            }
            string sql = "select * from (select F_ValueId Id,F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 "+ where
                       + "and ','+F_Key+',' like '%,'+CONVERT(varchar(100),F_ValueId)+',%') Count "
                       + "from dbo.T_Sys_DictionaryValue where F_ItemId = 3 and F_State = 0) a order by a.Count desc ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            dt.Columns.Add("Item", typeof(object));
            foreach (DataRow drnew in dt.Rows)
            {
                string strwhere = where;
                string straid = drnew["Id"].ToString();
                strwhere += " and ','+F_Key+',' like '%," + straid + ",%' ";

                string sqltype = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_InfoType=F_ValueId " + strwhere
                + ") Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
                DataTable dttype = DbHelperSQL.Query(sqltype).Tables[0];

                drnew["Item"] = dttype;
            }

            return Success("加载成功", dt);
        }

        #endregion

        #region 话务数量

        /// <summary>
        /// 话务量实时数据统计
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetTelCount24ByDate(DateTime? date)
        {
            if (date == null)
            {
                date = DateTime.Now;
            }

            string strdate = date.Value.ToString("yyyy-MM-dd");

            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            int[] tcounts = new int[24];//来电数量
            int[] ccounts = new int[24];//接通数量
            int[] lcounts = new int[24];//留言数量
            int[] gcounts = new int[24];//放弃数量
            int[] scounts = new int[24];//骚扰数量

            for (int i = 0; i < hours.Length; i++)
            {
                string sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, '" + strdate + "') = 0  "
                        + " and datepart(hh,BeginTime)=" + hours[i];
                tcounts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, '" + strdate + "') = 0  "
                        + " and CallState=1 and datepart(hh,BeginTime)=" + hours[i];
                ccounts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and datediff(day, BeginTime,'" + strdate + "') = 0  "
                        + " and DealType=4 and datepart(hh,BeginTime)=" + hours[i];
                lcounts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, '" + strdate + "') = 0  "
                        + " and DealType=1  and datepart(hh,BeginTime)=" + hours[i];
                scounts[i] = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                gcounts[i] = tcounts[i] - ccounts[i] - lcounts[i] - scounts[i];

            }

            var obj = new
            {
                hours = hours,
                rcounts = tcounts,
                ccounts = ccounts,
                //lcounts = lcounts,
                gcounts = gcounts,
                scounts = scounts
            };

            return Success("加载成功", obj);
        }

        /// <summary>
        /// 获取通话数量
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetTelCountByDate(DateTime? start, DateTime? end)
        {
            string where = " ";
            if (start == null && end == null)
            {
                where += " and datediff(day,BeginTime,getdate())=0";
            }
            else
            {
                if (start == null) { start = DateTime.Now; }
                if (end == null) { end = DateTime.Now; }
                where += $" and datediff(day,BeginTime,'{start.Value.ToString("yyyy-MM-dd")}')<=0 and datediff(day,BeginTime,'{end.Value.ToString("yyyy-MM-dd")}')>=0 ";
            }

            //话务量
            DataTable dt = DbHelperSQL.Query(" select count(1) con from T_Call_CallRecords where 1=1 " + where).Tables[0];

            var hwcon = dt.Rows[0]["con"].ToString();//话务量

            //来话量
            DataTable dt1 = DbHelperSQL.Query(" select count(1) con from T_Call_CallRecords where CallType=0 " + where).Tables[0];
            var lhcon = dt1.Rows[0]["con"].ToString();//话务量

            //接通量,通话时长
            DataTable dt2 = DbHelperSQL.Query(" select count(1) con,sum(TalkLongTime) tltimes from T_Call_CallRecords where CallState=1 " + where).Tables[0];
            var jtcon = dt2.Rows[0]["con"].ToString();//接通量
            var ths = dt2.Rows[0]["tltimes"];//通话时长
            var thtimes = "0";
            if (ths != null && ths.ToString() != "")
            {
                thtimes = ths.ToString();
            }
            //string jtl = "-";//接通率
            //if (hwcon != "0")
            //{
            //    jtl = (double.Parse(jtcon) / double.Parse(hwcon)).ToString("0.00%");
            //}
            double jtl = 0;//接通率
            if (hwcon != "0")
            {
                jtl = Math.Round((double.Parse(jtcon) * 100 / double.Parse(hwcon)), 2); 
            }
            double pjthtimes = 0.00;//平均通话时长
            if (jtcon != "0")
            {
                pjthtimes = Math.Round(double.Parse(thtimes) / double.Parse(jtcon));
            }

            var obj = new
            {
                hwcon = hwcon,
                lhcon = lhcon,
                jtcon = jtcon,
                pjthtimes = pjthtimes,
                jtl = jtl
            };

            return Success("加载成功", obj);
        }

        /// <summary>
        /// 话务量实时数据统计
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetUserStateCount24ByDate(DateTime? date)
        {
            if (date == null)
            {
                date = DateTime.Now;
            }

            string strdate = date.Value.ToString("yyyy-MM-dd");

            string sql = "select hor,type,COUNT(1) con from (select datepart(hh, TimeStart) hor, type, agentid, count(1) con  "
                + " from rep_agentState_Detail   where datediff(day, TimeStart, '" + strdate + "') = 0 "
                + "  group by datepart(hh, TimeStart), type, agentid ) t group by hor, type";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            double[] kxpercents = new double[24];
            double[] thpercents = new double[24];
            double[] zmpercents = new double[24];

            for (int i = 0; i < hours.Length; i++)
            {

                var list = dt.Select(" hor=" + hours[i]);
                int con = 0;//总量
                foreach (var l in list)
                {
                    con = con + Int32.Parse(l["con"].ToString());
                }
                //var con = list.Count() > 0 ? list[0]["con"].ToString() : "0";//总量
                var kxlist = dt.Select(" hor=" + hours[i] + " and type=2 ");
                var kxcon = kxlist.Count() > 0 ? kxlist[0]["con"].ToString() : "0";//空闲
                var thlist = dt.Select(" hor=" + hours[i] + " and type=3 ");
                var thcon = thlist.Count() > 0 ? thlist[0]["con"].ToString() : "0"; ;//通话中
                var hhcllist = dt.Select(" hor=" + hours[i] + " and type=4 ");
                var hhclcon = hhcllist.Count() > 0 ? hhcllist[0]["con"].ToString() : "0"; ;//话后处理中
                var xxlist = dt.Select(" hor=" + hours[i] + " and type=5 ");
                var xxcon = xxlist.Count() > 0 ? xxlist[0]["con"].ToString() : "0"; ;//小休
                var zllist = dt.Select(" hor=" + hours[i] + " and type=6 ");
                var zlcon = zllist.Count() > 0 ? zllist[0]["con"].ToString() : "0"; ;//被请求
                if (con == 0)
                {
                    kxpercents[i] = 0;
                    thpercents[i] = 0;
                    zmpercents[i] = 0;
                }
                else
                {
                    kxpercents[i] = Math.Round((double.Parse(kxcon) * 100 / con), 2);
                    thpercents[i] = Math.Round((double.Parse(thcon) * 100 / con), 2);
                    zmpercents[i] = Math.Round((double.Parse(xxcon) * 100 / con), 2);
                }

            }
            var obj = new
            {
                hours = hours,
                kxpercents = kxpercents,
                thpercents = thpercents,
                zmpercents = zmpercents
            };
            return Success("加载成功", obj);
        }

        #endregion

        #region 中心大数据

        /// <summary>
        /// 工单类型各数量
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetCenterTypeCountByDate()
        {
            string sql = " select F_Value TypeName,(select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 "
                + "and F_InfoType=F_ValueId) Count from dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];
            DataRow dr = dt.NewRow();
            dr["TypeName"] = "总计";

            string sqlzj = "select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 ";
            dr["Count"] = DbHelperSQL.GetSingle(sqlzj).ToString();

            dt.Rows.InsertAt(dr, 0);

            DataRow dr1 = dt.NewRow();
            dr1["TypeName"] = "今日";

            string sqlday = "select COUNT(1) from T_Bus_WorkOrder where F_IsDelete=0 and datediff(day,F_CreateTime,getdate())=0 ";
            dr1["Count"] = DbHelperSQL.GetSingle(sqlday).ToString();

            dt.Rows.InsertAt(dr1, 1);

            return Success("加载成功", dt);
        }

        /// <summary>
        /// 接通率统计
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetTelRate24ByDate(DateTime? date)
        {
            if (date == null)
            {
                date = DateTime.Now;
            }

            string strdate = date.Value.ToString("yyyy-MM-dd");

            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            //string[] rates = new string[24];
            double[] rates = new double[24];

            for (int i = 0; i < hours.Length; i++)
            {
                string sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and CallState=1 and UserCode is not null "
                    + " and datediff(day, BeginTime, '" + strdate + "') = 0  and datepart(hh,BeginTime)=" + hours[i];
                var c = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                sql = " select count(1) from dbo.T_Call_CallRecords where CallType=0 and UserCode is not null "
                    + "and datediff(day, BeginTime,  '" + strdate + "') = 0 and datepart(hh,BeginTime)=" + hours[i];
                var t = Int32.Parse(DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString());

                //rates[i]= t > 0 ? ((double)c / t).ToString("0.00%") : "-";
                rates[i] = t > 0 ? Math.Round(((double)c * 100 / t), 2) : 0;
            }

            var obj = new
            {
                hours = hours,
                rates = rates
            };
            return Success("加载成功", obj);
        }

        /// <summary>
        /// 平均通话时长统计
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetAvgTelTime24ByDate(DateTime? date)
        {
            if (date == null)
            {
                date = DateTime.Now;
            }

            string strdate = date.Value.ToString("yyyy-MM-dd");

            //接通量，通话时长
            string sql = " select datepart(hh,BeginTime) hor,count(1) con,sum(TalkLongTime) tltimes from T_Call_CallRecords where "
                + "CallState=1 and datediff(day, BeginTime, '" + strdate + "') = 0 group by datepart(hh,BeginTime) ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            int[] hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
            double[] avgtimes = new double[24];
            for (int i = 0; i < hours.Length; i++)
            {
                var jtlist = dt.Select(" hor=" + hours[i] + " ");
                var jtcon = jtlist.Count() > 0 ? jtlist[0]["con"].ToString() : "0";
                var thtimes = jtlist.Count() > 0 ? jtlist[0]["tltimes"].ToString() : "0";

                double avgtime = 0.00;
                if (jtcon != "0")
                {
                    if (thtimes == "") { thtimes = "0"; }
                    avgtime = Math.Round(double.Parse(thtimes) / double.Parse(jtcon), 2);
                }

                avgtimes[i] = avgtime;
            }
            var obj = new
            {
                hours = hours,
                avgtimes = avgtimes
            };
            return Success("加载成功", obj);
        } 

        #endregion

    }
}