using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.IO;
using System.Timers;
using System.Text.RegularExpressions;
using DataPumpWindowsService.Entity;
using System.Net;
using Newtonsoft.Json;

namespace DataPumpWindowsService
{
    public partial class ServiceDatapump : ServiceBase
    {
        #region 属性变量
        Timer timer = new Timer();
        Timer timer2 = new Timer();
        Timer timer3 = new Timer();

        Timer timer4 = new Timer();
        Timer timer5 = new Timer();
        Timer timer6 = new Timer();

        Timer timer7 = new Timer();


        private string ccm_db_string { get; set; }
        private string aecc_db_string { get; set; }

        /// <summary>
        /// 呼入室组织ID
        /// </summary>
        private string InboundOrgID { get; set; }
        /// <summary>
        /// 深圳组织ID
        /// </summary>
        private string SZOrgID { get; set; }
        /// <summary>
        /// 济南组织ID
        /// </summary>
        private string JNOrgID { get; set; }
        /// <summary>
        /// 呼入室VDNID
        /// </summary>
        private string VDNInboundOrgID { get; set; }
        /// <summary>
        /// 深圳VDNID
        /// </summary>
        private string VDNSZOrgID { get; set; }
        /// <summary>
        /// 济南VDNID
        /// </summary>
        private string VDNJNOrgID { get; set; }
        /// <summary>
        /// 呼入室编码
        /// </summary>
        private string InboundCityCode { get; set; }
        /// <summary>
        /// 深圳编码
        /// </summary>
        private string SouthCityCode { get; set; }
        /// <summary>
        /// 济南编码
        /// </summary>
        private string NorthCityCode { get; set; }
        /// <summary>
        /// 所有呼入室VDN号
        /// </summary>
        private string ALLVDNIDS { get; set; }
        /// <summary>
        /// 所有呼入室监控的技能组
        /// </summary>
        private string AllSkillIds { get; set; }

        /// <summary>
        /// mcc满意度同步开始日期
        /// </summary>
        private string mcc_start_date { get; set; }

        private int iHour { get; set; }
        private int iMinute { get; set; }
        private int iSecond { get; set; }

        private string SZVDNIDS { get; set; }
        private string JNVDNIDS { get; set; }

        #endregion

        #region 事件

        public ServiceDatapump()
        {
            InitializeComponent();

            pushCallLossData();

            //定时间隔时间
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["interval"]))
                timer.Interval = int.Parse(ConfigurationManager.AppSettings["interval"]);

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["interval2"]))
                timer2.Interval = int.Parse(ConfigurationManager.AppSettings["interval2"]);

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["interval3"]))
                timer3.Interval = int.Parse(ConfigurationManager.AppSettings["interval3"]);

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["interval4"]))
                timer4.Interval = int.Parse(ConfigurationManager.AppSettings["interval4"]);

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["interval5"]))
                timer5.Interval = int.Parse(ConfigurationManager.AppSettings["interval5"]);

            //--------
            //数据库连接-CCMDB,寿险数据类型为sqlserver
            ccm_db_string = ConfigurationManager.AppSettings["ccmdb_string"];
            //数据库连接-CCMDB,寿险数据类型为aecc
            aecc_db_string = ConfigurationManager.AppSettings["aecc_string"];

            InboundOrgID = ConfigurationManager.AppSettings["InboundOrgID"];
            SZOrgID = ConfigurationManager.AppSettings["SouthOrgID"];
            JNOrgID = ConfigurationManager.AppSettings["NorthOrgID"];

            InboundCityCode = ConfigurationManager.AppSettings["InboundCityCode"];
            SouthCityCode = ConfigurationManager.AppSettings["SouthCityCode"];
            NorthCityCode = ConfigurationManager.AppSettings["NorthCityCode"];

            VDNInboundOrgID = ConfigurationManager.AppSettings["VDNInboundOrgID"];
            VDNSZOrgID = ConfigurationManager.AppSettings["VDNSZOrgID"];
            VDNJNOrgID = ConfigurationManager.AppSettings["VDNJNOrgID"];

            ALLVDNIDS = ConfigurationManager.AppSettings["ALLVDNIDS"];
            SZVDNIDS = ConfigurationManager.AppSettings["SZVDNIDS"];
            JNVDNIDS = ConfigurationManager.AppSettings["JNVDNIDS"];

            AllSkillIds = ConfigurationManager.AppSettings["ALLSkillIDS"];

            mcc_start_date = ConfigurationManager.AppSettings["MCC_START_DATE"];

            iHour = 3;
            iMinute = 20;
            iSecond = 00;

            //重算前一天数据时间
            string ReCaculate_Time = ConfigurationManager.AppSettings["ReCaculate_Time"];
            if (!string.IsNullOrEmpty(ReCaculate_Time))
            {
                try
                {
                    string[] strs = ReCaculate_Time.Split(new char[] { ':' });
                    if (strs.Length >= 3)
                    {
                        iHour = int.Parse(strs[0]);
                        iMinute = int.Parse(strs[1]);
                        iSecond = int.Parse(strs[2]);
                    }
                }
                catch { }
            }


        }

        protected override void OnStart(string[] args)
        {
            //服务启动执行代码
            Log.Debug("Start.");
            // Set up a timer that triggers every minute. 设置定时器

            timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
            timer.Enabled = true;
            timer.Start();

            //timer2.Elapsed += new ElapsedEventHandler(this.OnTimer2);
            //timer2.Enabled = true;
            //timer2.Start();

            //timer3.Elapsed += new ElapsedEventHandler(this.OnTimer3);
            //timer3.Enabled = true;
            //timer3.Start();


            //timer4.Elapsed += new ElapsedEventHandler(this.OnTimer4);
            //timer4.Enabled = true;
            //timer4.Start();

            //timer5.Elapsed += new ElapsedEventHandler(this.OnTimer5);
            //timer5.Enabled = true;
            //timer5.Start();

            timer6.Elapsed += new ElapsedEventHandler(this.OnTimer6);
            timer6.Enabled = true;
            timer6.Interval = 1000;//执行时间间隔，单位：毫秒
            timer6.Start();


            timer7.Elapsed += new ElapsedEventHandler(this.OnTimer7);
            timer7.Enabled = true;
            timer7.Interval = int.Parse(ConfigurationManager.AppSettings["interval7"]);//执行时间间隔，单位：毫秒
            timer7.Start();
        }

        protected override void OnStop()
        {
            //服务停止执行代码
            timer.Stop();
            //timer2.Stop();
            //timer3.Stop();

            //timer4.Stop();

            //timer5.Stop();
            timer6.Stop();
            timer7.Stop();
            Log.Debug("Stop.");
        }

        protected override void OnPause()
        {
            //服务暂停执行代码
            base.OnPause();
        }

        protected override void OnContinue()
        {
            //服务恢复执行代码
            base.OnContinue();
        }

        protected override void OnShutdown()
        {
            //系统即将关闭执行代码
            base.OnShutdown();
        }

        /// <summary>
        /// 定时器中定时执行的任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void OnTimer(object sender, ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.

            Log.Debug("开始大屏数据运算。");
            timer.Stop();

            //大屏数据
            PumpDashboard();

            Log.Debug("结束大屏数据运算。");
            timer.Start();
        }

        /// <summary>
        /// 大屏工时利用率
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void OnTimer2(object sender, ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.

            Log.Debug("开始大屏工时利用率运算。");
            timer2.Stop();

            PumpUtilizationRate();

            Log.Debug("结束大屏工时利用率运算。");
            timer2.Start();
        }

        public void OnTimer3(object sender, ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.

            Log.Debug("开始大屏非工时率时段数据运算。");
            timer3.Stop();

            PumpHourlySpanData();

            Log.Debug("结束大屏非工时率时段数据运算。");
            timer3.Start();
        }

        ///// <summary>
        ///// mcc满意度数据同步
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="args"></param>
        //public void OnTimer4(object sender, ElapsedEventArgs args)
        //{
        //    // TODO: Insert monitoring activities here.

        //    Log.Debug("开始mcc满意度数据同步。");
        //    timer4.Stop();

        //    PumpSatisfyData();

        //    Log.Debug("结束mcc满意度数据同步。");
        //    timer4.Start();
        //}

        public void OnTimer5(object sender, ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.

            Log.Debug("开始时段工时率计算。");
            timer5.Stop();

            PumpHourlyUtilizationRate();

            Log.Debug("结束时段工时率计算。");
            timer5.Start();
        }

        public void OnTimer6(object sender, ElapsedEventArgs args)
        {
            // 得到 hour minute second  如果等于某个值就开始执⾏某个程序。
            int intHour = args.SignalTime.Hour;
            int intMinute = args.SignalTime.Minute;
            int intSecond = args.SignalTime.Second;
            // 定制时间；⽐如在10：30 ：00 的时候执⾏某个函数
            //int iHour = 16;
            //int iMinute = 55;
            //int iSecond = 00;

            //// 设置　每秒钟的开始执⾏⼀次
            //if (intSecond == iSecond)
            //{
            //    Log.Debug("每秒钟的开始执⾏一次");
            //}
            //// 设置　每个⼩时的30分钟开始执⾏
            //if (intMinute == iMinute && intSecond == iSecond)
            //{
            //    Log.Debug(string.Format("每个⼩时的{0}:{1}开始执⾏一次", iMinute.ToString(), iSecond.ToString()));
            //}
            // 设置　每天的10：30：00开始执⾏程序
            if (intHour == iHour && intMinute == iMinute && intSecond == iSecond)
            {
                timer6.Stop();
                Log.Debug(string.Format("在每天{0}:{1}:{2}重算前一天数据", iHour.ToString(), iMinute.ToString(), iSecond.ToString()));
                FixYesterdayData();
                timer6.Start();
            }
        }

        public void OnTimer7(object sender, ElapsedEventArgs args)
        {
            Log.Debug("开始检测呼损数据。");
            timer7.Stop();
            
            pushCallLossData();

            Log.Debug("结束检测呼损数据。");
            timer7.Start();
            
        }

            #endregion

            #region 方法

            #region 大屏即时数据

            private void PumpDashboard()
        {
            SQLHelper ccm_db = null;
            SQLHelper aecc_db = null;
            try
            {
                string reportDate = DateTime.Now.ToString("yyyy-MM-dd");
                ccm_db = new SQLHelper(ccm_db_string);
                aecc_db = new SQLHelper(aecc_db_string);
                PumpDashboard(ccm_db, aecc_db, reportDate);
            }
            catch (Exception exp)
            {
                Log.Debug(exp);
            }
            finally
            {
                bool flag = ccm_db != null;
                if (flag)
                {
                    ccm_db.CloseConnection();
                    ccm_db = null;
                }
                flag = aecc_db != null;
                if (flag)
                {
                    aecc_db.CloseConnection();
                    aecc_db = null;
                }
            }
        }

        /// <summary>
        /// 聚合大屏的数据：单值
        /// </summary>
        /// <param name="ccm_db"></param>
        /// <param name="aecc_db"></param>
        private void PumpDashboard(SQLHelper ccm_db, SQLHelper aecc_db, string reportDate)
        {
            try
            {
                string ReportDate = reportDate.Replace("-", "");
                //黄亮2022056，要求统计数据去掉转留言，去掉进线前挂断
                //转留言：split='841007'
                //进线前挂断：split='' or split is null
                DataTable dtAll = CallsAllData(ReportDate, aecc_db);
                if (dtAll == null)
                    return;

                List<DataRow> lstJiSuan = dtAll.Rows.Cast<DataRow>().ToList();
                List<string> lstVDNAll = new List<string>();
                List<string> lstVDNSZ = new List<string>();
                List<string> lstVDNJN = new List<string>();
                string str = ConfigurationManager.AppSettings["ALLVDNIDS"];
                var strs = Regex.Split(str, "','");
                foreach (string s in strs)
                {
                    lstVDNAll.Add(s.Replace("\'", ""));
                }

                str = ConfigurationManager.AppSettings["SZVDNIDS"];
                strs = Regex.Split(str, "','");
                foreach (string s in strs)
                {
                    lstVDNSZ.Add(s.Replace("\'", ""));
                }

                str = ConfigurationManager.AppSettings["JNVDNIDS"];
                strs = Regex.Split(str, "','");
                foreach (string s in strs)
                {
                    lstVDNJN.Add(s.Replace("\'", ""));
                }

                //总的
                Entity.InboundAllEntity inbound = new Entity.InboundAllEntity();
                inbound.ReportDate = ReportDate;
                //深圳
                Entity.InboundAllEntity sz = new Entity.InboundAllEntity();
                sz.ReportDate = ReportDate;
                //济南
                Entity.InboundAllEntity jn = new Entity.InboundAllEntity();
                jn.ReportDate = ReportDate;

                inbound.CityCode = InboundCityCode;
                inbound.CityName = "两地";

                sz.CityCode = SouthCityCode;
                sz.CityName = "深圳";

                jn.CityCode = NorthCityCode;
                jn.CityName = "济南";
                //呼叫总量
                inbound.CallsTotal = CallsTotal(lstJiSuan, lstVDNAll, VDNInboundOrgID);
                //呼叫总量
                sz.CallsTotal = CallsTotal(lstJiSuan, lstVDNSZ, VDNSZOrgID);
                //呼叫总量
                jn.CallsTotal = CallsTotal(lstJiSuan, lstVDNJN, VDNJNOrgID);

                //放弃量
                inbound.GiveUpTotal = GiveUpTotal(lstJiSuan, lstVDNAll, VDNInboundOrgID);
                //放弃量
                sz.GiveUpTotal = GiveUpTotal(lstJiSuan, lstVDNSZ, VDNSZOrgID);
                //放弃量
                jn.GiveUpTotal = GiveUpTotal(lstJiSuan, lstVDNJN, VDNJNOrgID);

                //In20STotal
                decimal ALLIn20STotal = In20STotal(lstJiSuan, lstVDNAll, VDNInboundOrgID);
                //In20STotal
                decimal SZIn20STotal = In20STotal(lstJiSuan, lstVDNSZ, VDNSZOrgID);
                //In20STotal
                decimal JNIn20STotal = In20STotal(lstJiSuan, lstVDNJN, VDNJNOrgID);

                //接通量
                inbound.CompletionTotal = CompletionTotal(lstJiSuan, lstVDNAll, VDNInboundOrgID);
                //接通量
                sz.CompletionTotal = CompletionTotal(lstJiSuan, lstVDNSZ, VDNSZOrgID);
                //接通量
                jn.CompletionTotal = CompletionTotal(lstJiSuan, lstVDNJN, VDNJNOrgID);

                //人均通话时长
                inbound.CallTimeAverage = CallTimeAverage(lstJiSuan, lstVDNAll, VDNInboundOrgID);
                sz.CallTimeAverage = CallTimeAverage(lstJiSuan, lstVDNSZ, VDNSZOrgID);
                jn.CallTimeAverage = CallTimeAverage(lstJiSuan, lstVDNJN, VDNJNOrgID);

                //小休时长
                inbound.BreakTinmeAverage = BreakTinmeAverage(ReportDate, InboundOrgID, aecc_db);
                sz.BreakTinmeAverage = BreakTinmeAverage(ReportDate, SZOrgID, aecc_db);
                jn.BreakTinmeAverage = BreakTinmeAverage(ReportDate, JNOrgID, aecc_db);

                //人均后处理时长
                inbound.AfterCallTImeAverage = AfterCallTImeAverage(ReportDate, InboundOrgID, aecc_db);
                sz.AfterCallTImeAverage = AfterCallTImeAverage(ReportDate, SZOrgID, aecc_db);
                jn.AfterCallTImeAverage = AfterCallTImeAverage(ReportDate, JNOrgID, aecc_db);

                inbound.CompletionRate = inbound.CallsTotal == 0 ? 1 : inbound.CompletionTotal / inbound.CallsTotal;
                inbound.SLAIn20S = inbound.CallsTotal == 0 ? 1 : ALLIn20STotal / inbound.CallsTotal;
                inbound.GiveUpRate = inbound.CallsTotal == 0 ? 0 : inbound.GiveUpTotal / inbound.CallsTotal;

                sz.CompletionRate = sz.CallsTotal == 0 ? 1 : sz.CompletionTotal / sz.CallsTotal;
                sz.SLAIn20S = sz.CallsTotal == 0 ? 1 : SZIn20STotal / sz.CallsTotal;
                sz.GiveUpRate = sz.CallsTotal == 0 ? 0 : sz.GiveUpTotal / sz.CallsTotal;

                jn.CompletionRate = jn.CallsTotal == 0 ? 1 : jn.CompletionTotal / jn.CallsTotal;
                jn.SLAIn20S = jn.CallsTotal == 0 ? 1 : JNIn20STotal / jn.CallsTotal;
                jn.GiveUpRate = jn.CallsTotal == 0 ? 0 : jn.GiveUpTotal / jn.CallsTotal;

                //工时利用率在原来的方法去计算
                //string curTimeString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //DataTable dtAgentAll = GetAgentIDs(InboundOrgID,aecc_db);
                //DataTable dtAgentSZ = GetAgentIDs(SZOrgID, aecc_db);
                //DataTable dtAgentJN = GetAgentIDs(JNOrgID, aecc_db);

                //List<string> lstAgentAll = dtAgentAll.Rows.Cast<DataRow>().Select(i => i["Agent"].ToString()).ToList<string>();
                //List<string> lstAgentSZ = dtAgentSZ.Rows.Cast<DataRow>().Select(i => i["Agent"].ToString()).ToList<string>();
                //List<string> lstAgentJN1 = dtAgentJN.Rows.Cast<DataRow>().Select(i => i["Agent"].ToString()).ToList<string>();
                //List<string> lstAgentJN = lstAgentJN1.Where(i => lstAgentSZ.Contains(i) == false).ToList();//排除在深圳的坐席

                //List<DataRow> dtLoginAll = GetLoginDataDt(curTimeString, aecc_db);
                //List<DataRow> dtAUXAll = GetAUXDataDt(curTimeString, aecc_db);
                //List<DataRow> dtIdleAll = GetIdleDataDt(curTimeString, aecc_db);

                //List<DataRow> lstLoginZong = dtLoginAll.Where(i => lstAgentAll.Contains(i["AgentID"].ToString().Trim())).ToList();
                //List<DataRow> lstLoginSZ = dtLoginAll.Where(i => lstAgentSZ.Contains(i["AgentID"].ToString().Trim())).ToList();
                //List<DataRow> lstLoginJN = dtLoginAll.Where(i => lstAgentJN.Contains(i["AgentID"].ToString().Trim())).ToList();

                //List<DataRow> lstAUXZong = dtAUXAll.Where(i => lstAgentAll.Contains(i["AgentID"].ToString().Trim())).ToList();
                //List<DataRow> lstAUXSZ = dtAUXAll.Where(i => lstAgentSZ.Contains(i["AgentID"].ToString().Trim())).ToList();
                //List<DataRow> lstAUXJN = dtAUXAll.Where(i => lstAgentJN.Contains(i["AgentID"].ToString().Trim())).ToList();

                //List<DataRow> lstIdleZong = dtIdleAll.Where(i => lstAgentAll.Contains(i["AgentID"].ToString().Trim())).ToList();
                //List<DataRow> lstIdleSZ = dtIdleAll.Where(i => lstAgentSZ.Contains(i["AgentID"].ToString().Trim())).ToList();
                //List<DataRow> lstIdleJN = dtIdleAll.Where(i => lstAgentJN.Contains(i["AgentID"].ToString().Trim())).ToList();

                UpdateInboundData(ReportDate, inbound, ccm_db);
                UpdateInboundData(ReportDate, sz, ccm_db);
                UpdateInboundData(ReportDate, jn, ccm_db);
            }
            catch (Exception ex)
            {
                Log.Debug(ex);
            }
        }

        private string UpdateInboundData(String ReportDate, Entity.InboundAllEntity inbound, SQLHelper ccm_db)
        {
            string sql = string.Format(@"select * from ccm_inbound_all where reportdate='{0}' and citycode='{1}'", ReportDate, inbound.CityCode);
            DataTable dt = ccm_db.GetDataTable(sql);
            //存在更新
            if (dt != null && dt.Rows.Count > 0)
            {
                sql = @"update ccm_inbound_all set CallsTotal={3},
CompletionTotal={4},
CompletionRate={5},
GiveUpTotal={6},
GiveUpRate={7},
SLAIn20S={9},
CallTimeAverage={10},
BreakTinmeAverage={11},
AfterCallTImeAverage={12},
TimeStamp=getdate() where ReportDate='{2}' and CityCode='{0}'
";
                sql = string.Format(sql,
                    inbound.CityCode,
                    inbound.CityName,
                    inbound.ReportDate,
                    inbound.CallsTotal,
                    inbound.CompletionTotal,
                    inbound.CompletionRate,
                    inbound.GiveUpTotal,
                    inbound.GiveUpRate,
                    inbound.UtilizationRate,
                    inbound.SLAIn20S,
                    inbound.CallTimeAverage,
                    inbound.BreakTinmeAverage,
                    inbound.AfterCallTImeAverage,
                    dt.Rows[0]["CurrentQueue"],
                    dt.Rows[0]["CheckIn"],
                    dt.Rows[0]["CheckOut"]);
                ccm_db.ExecuteNonQuery(sql);
            }
            else
            {
                //不存在插入
                sql = @"insert into ccm_inbound_all(
ID,
CityCode,
CityName,
ReportDate,
CallsTotal,
CompletionTotal,
CompletionRate,
GiveUpTotal,
GiveUpRate,
UtilizationRate,
SLAIn20S,
CallTimeAverage,
BreakTinmeAverage,
AfterCallTImeAverage,
CurrentQueue,
CheckIn,
CheckOut,
TimeStamp
)
values(
newid(),-- ID,
'{0}',--CityCode,
'{1}',--CityName,
'{2}',--ReportDate,
{3},-- CallsTotal,
{4},-- CompletionTotal,
{5},-- CompletionRate,
{6},-- GiveUpTotal,
{7},-- GiveUpRate,
{8},-- UtilizationRate,
{9},-- SLAIn20S,
{10},-- CallTimeAverage,
{11},-- BreakTinmeAverage,
{12},-- AfterCallTImeAverage,
{13},-- CurrentQueue,
{14},-- CheckIn,
{15},-- CheckOut,
getdate()-- TimeStamp
)";
                sql = string.Format(sql,
                    inbound.CityCode,
                    inbound.CityName,
                    inbound.ReportDate,
                    inbound.CallsTotal,
                    inbound.CompletionTotal,
                    inbound.CompletionRate,
                    inbound.GiveUpTotal,
                    inbound.GiveUpRate,
                    inbound.UtilizationRate,
                    inbound.SLAIn20S,
                    inbound.CallTimeAverage,
                    inbound.BreakTinmeAverage,
                    inbound.AfterCallTImeAverage,
                    inbound.CurrentQueue,
                    inbound.CheckIn,
                    inbound.CheckOut);
                ccm_db.ExecuteNonQuery(sql);
            }
            return sql;
        }

        private DataTable CallsAllData(String rptDate, SQLHelper aecc_db)
        {
            DataTable dt = null;
            string sql = "", whereOrg = "";
            whereOrg = ALLVDNIDS;
            sql = string.Format(SQLEntity.SQL_GetCallsTotal_All, rptDate, whereOrg);
            dt = aecc_db.GetDataTable(sql);
            return dt;
        }

        /// <summary>
        /// 呼叫总量
        /// </summary>
        /// <param name="lstJiSuan"></param>
        /// <param name="lstVDNs"></param>
        /// <param name="parentOrgID"></param>
        /// <returns></returns>
        private decimal CallsTotal(List<DataRow> lstJiSuan, List<string> lstVDNs, string parentOrgID)
        {
            if (lstJiSuan == null || lstJiSuan.Count == 0)
                return 0;
            if (parentOrgID == VDNInboundOrgID)
            {
                return lstJiSuan.Count();
            }
            else
            {
                if (lstVDNs != null)
                {
                    var rt = lstJiSuan.Count(i => lstVDNs.Contains(i["VDN"].ToString().Trim()));
                    return rt;
                }
            }

            return 0;
        }

        /// <summary>
        /// 放弃量
        /// </summary>
        /// <param name="lstJiSuan"></param>
        /// <param name="lstVDNs"></param>
        /// <param name="parentOrgID"></param>
        /// <returns></returns>
        private decimal GiveUpTotal(List<DataRow> lstJiSuan, List<string> lstVDNs, string parentOrgID)
        {
            if (lstJiSuan == null || lstJiSuan.Count == 0)
                return 0;
            if (parentOrgID == VDNInboundOrgID)
            {
                return lstJiSuan.Count(i => i["Estab_time"].GetType().FullName == "System.DBNull");
            }
            else
            {
                if (lstVDNs != null)
                {
                    var rt = lstJiSuan.Count(i => i["Estab_time"].GetType().FullName == "System.DBNull" && lstVDNs.Contains(i["VDN"].ToString().Trim()));
                    return rt;
                }
            }

            return 0;
        }

        /// <summary>
        /// 20S服务水平
        /// </summary>
        /// <param name="lstJiSuan"></param>
        /// <param name="lstVDNs"></param>
        /// <param name="parentOrgID"></param>
        /// <returns></returns>
        private decimal In20STotal(List<DataRow> lstJiSuan, List<string> lstVDNs, string parentOrgID)
        {
            //原方法取全部计算，现改为取end_reason<>7的数据
            if (lstJiSuan == null || lstJiSuan.Count == 0)
                return 0;
            if (parentOrgID == VDNInboundOrgID)
            {
                return lstJiSuan.Count(i => i["Estab_time"].GetType().FullName != "System.DBNull" && (Convert.ToDecimal(i["Queue_Dur"].ToString()) + Convert.ToDecimal(i["Ring_Dur"].ToString())) <= 20);
            }
            else
            {
                if (lstVDNs != null)
                {
                    var rt = lstJiSuan.Count(i => i["Estab_time"].GetType().FullName != "System.DBNull" && (Convert.ToDecimal(i["Queue_Dur"].ToString()) + Convert.ToDecimal(i["Ring_Dur"].ToString())) <= 20 && lstVDNs.Contains(i["VDN"].ToString().Trim()));
                    return rt;
                }
            }

            return 0;
        }

        /// <summary>
        /// 接通量
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        private decimal CompletionTotal(List<DataRow> lstJiSuan, List<string> lstVDNs, string parentOrgID)
        {
            if (lstJiSuan == null || lstJiSuan.Count == 0)
                return 0;
            if (parentOrgID == VDNInboundOrgID)
            {
                return lstJiSuan.Count(i => i["Estab_time"].GetType().FullName != "System.DBNull");
            }
            else
            {
                if (lstVDNs != null)
                {
                    var rt = lstJiSuan.Count(i => i["Estab_time"].GetType().FullName != "System.DBNull" && lstVDNs.Contains(i["VDN"].ToString().Trim()));
                    return rt;
                }
            }

            return 0;
        }

        /// <summary>
        /// 人均通话时长
        /// </summary>
        /// <param name="lstJiSuan"></param>
        /// <param name="lstVDNs"></param>
        /// <param name="parentOrgID"></param>
        /// <returns></returns>
        private decimal CallTimeAverage(List<DataRow> lstJiSuan, List<string> lstVDNs, string parentOrgID)
        {
            //原方法取全部计算，现改为取end_reason<>7的数据
            if (lstJiSuan == null || lstJiSuan.Count == 0)
                return 0;

            decimal tmpCount = 0;
            decimal tmpTalkdur = 0;
            if (parentOrgID == VDNInboundOrgID)
            {
                tmpCount = lstJiSuan.Count(i => i["Estab_time"].GetType().FullName != "System.DBNull" && i["AgentID"].ToString().Trim() != "");
                foreach (var item in lstJiSuan)
                {
                    if (item["Estab_time"].GetType().FullName != "System.DBNull" && item["AgentID"].ToString().Trim() != "")
                    {
                        tmpTalkdur += Convert.ToDecimal(item["Talk_dur"].ToString());
                    }
                }
                return tmpCount == 0 ? 0 : tmpTalkdur / tmpCount;
            }
            else
            {
                if (lstVDNs != null)
                {
                    tmpCount = lstJiSuan.Count(i => i["Estab_time"].GetType().FullName != "System.DBNull" && i["AgentID"].ToString().Trim() != "" && lstVDNs.Contains(i["VDN"].ToString().Trim()));
                    foreach (var item in lstJiSuan)
                    {
                        if (item["Estab_time"].GetType().FullName != "System.DBNull" && item["AgentID"].ToString().Trim() != "" && lstVDNs.Contains(item["VDN"].ToString().Trim()))
                        {
                            tmpTalkdur += Convert.ToDecimal(item["Talk_dur"].ToString());
                        }
                    }
                    return tmpCount == 0 ? 0 : tmpTalkdur / tmpCount;
                }
            }

            return 0;
        }

        /// <summary>
        /// 人均小休时长
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        private decimal BreakTinmeAverage(string rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string whereOrg = "", sql = "";
            //whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + OrgCode + @"')";
            whereOrg = "'" + OrgCode + @"'";
            sql = string.Format(SQLEntity.SQL_BreakTimeAverage, rptDate, whereOrg);

            DataTable dt = aecc_db.GetDataTable(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                if (dt.Rows[0][0].GetType().FullName == "System.DBNull")
                    return 0;
                return Convert.ToDecimal(dt.Rows[0][0].ToString());
            }

            return 0;
        }

        /// <summary>
        /// 人均后处理时长
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        private decimal AfterCallTImeAverage(string rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string whereOrg = "", sql = "";
            if (OrgCode == JNOrgID)
            {
                //whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + OrgCode + @"')";
                whereOrg = "'" + OrgCode + @"'";
                sql = string.Format(SQLEntity.SQL_AfterCallTImeAverage, rptDate, whereOrg) + " and AgentID not in (select AgentID from v_Agent_Special) ";
            }
            else
            {
                //whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + OrgCode + @"')";
                whereOrg = "'" + OrgCode + @"'";
                sql = string.Format(SQLEntity.SQL_AfterCallTImeAverage, rptDate, whereOrg);
            }

            DataTable dt = aecc_db.GetDataTable(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                if (dt.Rows[0][0].GetType().FullName == "System.DBNull")
                    return 0;
                return Convert.ToDecimal(dt.Rows[0][0].ToString());
            }

            return 0;
        }

        ///// <summary>
        ///// 工时利用率 benson
        ///// </summary>
        ///// <param name="rptDate">当前时间</param>
        ///// <param name="orgID">组织ID</param>
        ///// <returns></returns>
        //private decimal UtilizationRate(string rptDate, string orgID, SQLHelper aecc_db)
        //{
        //    //公式改为：（登入时长-小休时长-空闲时长)/登入时长  ------------------新
        //    //（登入时长-小休时长-空闲时长)/(登入时长-小休时长)-----------------旧
        //    string sql = string.Format("exec [UtilizationRate] '{0}','{1}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), orgID);
        //    Log.Debug(sql);
        //    DataTable dt = aecc_db.GetDataTable(sql);
        //    if (dt != null && dt.Rows.Count > 0)
        //    {
        //        if (dt.Rows[0][0].GetType().FullName == "System.DBNull")
        //            return 0;
        //        return Convert.ToDecimal(dt.Rows[0][0].ToString());
        //    }

        //    return 0;
        //}

        #endregion        

        #region mcc满意度数据同步
        private void PumpSatisfyData()
        {
            OracleHelper mcc_db = null;
            SQLHelper aecc_db = null;
            try
            {
                string ReportDate = DateTime.Now.ToString("yyyyMMdd");
                mcc_db = new OracleHelper(ccm_db_string);
                aecc_db = new SQLHelper(aecc_db_string);
                PumpSatisfyData(mcc_db, aecc_db);
            }
            catch (Exception exp)
            {
                Log.Debug(exp);
            }
            finally
            {
                bool flag = mcc_db != null;
                if (flag)
                {
                    mcc_db.CloseConnection();
                    mcc_db = null;
                }
                flag = aecc_db != null;
                if (flag)
                {
                    aecc_db.CloseConnection();
                    aecc_db = null;
                }
            }
        }

        private void PumpSatisfyData(OracleHelper mcc_db, SQLHelper aecc_db)
        {
            try
            {
                //获取寿险库最后的同步时间
                string sql = "select max(CONNECTEDTIME) CONNECTEDTIME from rpt_mcc";
                string lastDate = "";
                DataTable dt;
                //DataTable dt = _ECCDB.GetDataTable(sql);
                //if (dt != null && dt.Rows.Count > 0)
                //{
                //    lastDate = Convert.ToDateTime(dt.Rows[0]["CONNECTEDTIME"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                //}

                //结束
                lastDate = Convert.ToDateTime(mcc_start_date).AddMinutes(30).ToString("yyyy-MM-dd HH:mm:ss");
                DateTime curTime = DateTime.Now;

                //当天的数据获取当前时间点半小时前的数据，以免产险库的数据还未同步过来
                if (Convert.ToDateTime(lastDate) >= curTime)
                {
                    lastDate = curTime.ToString("yyyy-MM-dd HH:mm:ss");
                    mcc_start_date = curTime.AddMinutes(-30).ToString("yyyy-MM-dd HH:mm:ss");
                }

                //取产险库的数据
                sql = string.Format(@"
with m1 as
(
select t1.user_code,max(t1.Updated_Date) Updated_Date,max(t1.created_date) created_date
from MCC_AGENT_INFO t1 where t1.agent_status='Y'
and t1.user_code is not null
group by t1.user_code
),
m2 as
(
select t2.user_code,t2.agent_code from MCC_AGENT_INFO t2
inner join m1 on t2.user_code=m1.user_code
and t2.Updated_Date=m1.Updated_Date
and t2.created_date=m1.created_date
)
select MC.IVR_KEY_INFO VDN,
MU.USER_NAME NAME,
LTRIM(MAI.AGENT_CODE,'a') AGENT,
MC.ANI,
mr.uuid UCID,
'是' ISCONNECTED,
to_char(MC.Connect_Time,'YYYY-MM-DD HH24:MI:SS') CONNECTEDTIME,
ROUND(TO_NUMBER(MC.DISCONNECT_TIME-MC.Connect_Time)*24*60*60) CALLDUR,
'是' ISTRANSFERSATISY,
to_char(MC.Satisfaction_Time,'YYYY-MM-DD HH24:MI:SS') TRANSFERSATISYTINE,
case when MC.Cust_Eval_Time is not null then '是' else '否' end as ISEVAL,
to_char(MC.Cust_Eval_Time,'YYYY-MM-DD HH24:MI:SS') EVALTIME,
CASE MC.SATIAFACTION_SCORE when '1' then '非常满意' when '2' then '满意' when '3' then '不满意' when '4' then '非常不满意' else null end as EVALRESULT,
mr.uuid UUID,
to_char(MC.DISCONNECT_TIME,'YYYY-MM-DD HH24:MI:SS') HANGOFFTIME,
NULL ROWNUM_
 from MCC_RECORD MR
INNER JOIN MCC_CALL MC ON MC.CALL_ID=MR.CALL_ID
INNER JOIN   MCC_USER  MU ON  MU.USER_CODE=MC.USER_CODE
INNER JOIN m2 MAI ON MC.USER_CODE=MAI.USER_CODE
where MC.Connect_Time>=to_date('{0}','YYYY-MM-DD HH24:MI:SS')
and MC.Connect_Time<to_date('{1}','YYYY-MM-DD HH24:MI:SS')
and MC.Satisfaction_Time is not null
order by MC.Connect_Time asc", mcc_start_date, lastDate);
                dt = mcc_db.GetDataTable(sql);

                mcc_start_date = lastDate;

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        sql = string.Format(@"
if not exists(
select * from rpt_mcc where 1=1 and UCID={4}
)
insert into rpt_mcc(
VDN,
NAME,
AGENT,
ANI,
UCID,
ISCONNECTED,
CONNECTEDTIME,
CALLDUR,
ISTRANSFERSATISY,
TRANSFERSATISYTINE,
ISEVAL,
EVALTIME,
EVALRESULT,
HANGOFFTIME,
UUID,
ROWNUM_)values(
{0},
{1},
{2},
{3},
{4},
{5},
{6},
{7},
{8},
{9},
{10},
{11},
{12},
{13},
{14},null
)", SetFieldItemValue(dr["VDN"].ToString()),
      SetFieldItemValue(dr["NAME"].ToString()),
      SetFieldItemValue(dr["AGENT"].ToString()),
      SetFieldItemValue(dr["ANI"].ToString()),
      SetFieldItemValue(dr["UCID"].ToString()),
      SetFieldItemValue(dr["ISCONNECTED"].ToString()),
      SetFieldItemValue(dr["CONNECTEDTIME"].ToString()),
      SetFieldItemValue(dr["CALLDUR"].ToString()),
      SetFieldItemValue(dr["ISTRANSFERSATISY"].ToString()),
      SetFieldItemValue(dr["TRANSFERSATISYTINE"].ToString()),
      SetFieldItemValue(dr["ISEVAL"].ToString()),
      SetFieldItemValue(dr["EVALTIME"].ToString()),
      SetFieldItemValue(dr["EVALRESULT"].ToString()),
      SetFieldItemValue(dr["HANGOFFTIME"].ToString()),
      SetFieldItemValue(dr["UUID"].ToString())
      );
                        aecc_db.ExecuteResult(sql);
                    }
                }

                Log.Debug("当前已同步数据时间：" + mcc_start_date + ",同步行数：" + dt.Rows.Count);
            }
            catch (Exception ex)
            {
                Log.Debug(ex);
            }
        }

        private string SetFieldItemValue(string content)
        {
            return content.Trim() == "" ? "null" : "'" + content + "'";
        }

        #endregion

        #region 单值工时利用率
        /// <summary>
        /// 单值工时利用率
        /// </summary>
        private void PumpUtilizationRate()
        {
            //执行时间久，单独执行
            SQLHelper ccm_db = null;
            SQLHelper aecc_db = null;
            try
            {
                string reportDate = DateTime.Now.ToString("yyyy-MM-dd");
                ccm_db = new SQLHelper(ccm_db_string);
                aecc_db = new SQLHelper(aecc_db_string);
                PumpUtilizationRate(ccm_db, aecc_db, reportDate);
            }
            catch (Exception exp)
            {
                Log.Debug(exp);
            }
            finally
            {
                bool flag = ccm_db != null;
                if (flag)
                {
                    ccm_db.CloseConnection();
                    ccm_db = null;
                }
                flag = aecc_db != null;
                if (flag)
                {
                    aecc_db.CloseConnection();
                    aecc_db = null;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void PumpUtilizationRate(SQLHelper ccm_db, SQLHelper aecc_db, string reportDate)
        {
            string ReportDate = reportDate.Replace("-", "");

            string tmp = GetUtilizationRateByDay(reportDate, "ALL", aecc_db).ToString();
            Log.Debug("总工时利用率：" + tmp);

            string sql = @"update ccm_inbound_all set UtilizationRate={0} where ReportDate='{1}' and CityCode='{2}'";
            sql = string.Format(sql, tmp, ReportDate, "ALL");
            Log.Debug(sql);
            ccm_db.ExecuteNonQuery(sql);

            tmp = GetUtilizationRateByDay(reportDate, "SZ", aecc_db).ToString();
            Log.Debug("深圳工时利用率：" + tmp);
            sql = @"update ccm_inbound_all set UtilizationRate={0} where ReportDate='{1}' and CityCode='{2}'";
            sql = string.Format(sql, tmp, ReportDate, "SZ");
            Log.Debug(sql);
            ccm_db.ExecuteNonQuery(sql);

            tmp = GetUtilizationRateByDay(reportDate, "JN", aecc_db).ToString();
            Log.Debug("济南工时利用率：" + tmp);
            sql = @"update ccm_inbound_all set UtilizationRate={0} where ReportDate='{1}' and CityCode='{2}'";
            sql = string.Format(sql, tmp, ReportDate, "JN");
            Log.Debug(sql);
            ccm_db.ExecuteNonQuery(sql);
        }

        /// <summary>
        /// 工时利用率 benson
        /// </summary>
        /// <param name="rptDate">当前时间</param>
        /// <param name="cityCode">区域码</param>
        /// <returns></returns>
        private decimal GetUtilizationRateByDay(string rptDate, string cityCode, SQLHelper aecc_db)
        {
            //公式：（通话时长(95535来电)+话后时长)/登入时长  ----------------新
            //公式：（登入时长-小休时长-空闲时长)/登入时长  ------------------旧
            string sql = string.Format("exec UtilizationRateByTime '{0}','{1}'", rptDate, cityCode);
            Log.Debug(sql);
            DataTable dt = aecc_db.GetDataTable(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                if (dt.Rows[0][0].GetType().FullName == "System.DBNull")
                    return 0;
                return Convert.ToDecimal(dt.Rows[0][0].ToString());
            }

            return 0;
        }

        #endregion

        #region 时段工时率数据

        private void PumpHourlyUtilizationRate()
        {
            SQLHelper ccm_db = null;
            SQLHelper aecc_db = null;
            try
            {
                string reportDate = DateTime.Now.ToString("yyyy-MM-dd");
                ccm_db = new SQLHelper(ccm_db_string);
                aecc_db = new SQLHelper(aecc_db_string);
                PumpHourlyUtilizationRate(ccm_db, aecc_db, reportDate);
            }
            catch (Exception exp)
            {
                Log.Debug(exp);
            }
            finally
            {
                bool flag = ccm_db != null;
                if (flag)
                {
                    ccm_db.CloseConnection();
                    ccm_db = null;
                }
                flag = aecc_db != null;
                if (flag)
                {
                    aecc_db.CloseConnection();
                    aecc_db = null;
                }
            }
        }

        /// <summary>
        /// 时段工时率
        /// </summary>
        public void PumpHourlyUtilizationRate(SQLHelper ccm_db, SQLHelper aecc_db, string reportDate)
        {
            //string sql = "select convert(varchar(10), getdate(),120) nowdate";
            //DataTable dtdate = aecc_db.GetDataTable(sql);
            //string reportData = System.DateTime.Now.ToString("yyyy-MM-dd");//获取数据库当前时间
            //if (dtdate != null && dtdate.Rows.Count > 0)
            //    reportData = dtdate.Rows[0][0].ToString();

            string ReportDate = reportDate.Replace("-", "");

            //两地
            string sql = string.Format("exec UtilizationRateByHour '{0}','{1}'", reportDate, CityCode.ALL.Code);
            DataTable dtAll = aecc_db.GetDataTable(sql);
            if (dtAll != null || dtAll.Rows.Count > 0)
            {
                UpdateHoulyData(dtAll, CityCode.ALL.Code, CityCode.ALL.Name, ReportDate, ccm_db);
            }

            sql = string.Format("exec UtilizationRateByHalfHour '{0}','{1}'", reportDate, CityCode.ALL.Code);
            dtAll = aecc_db.GetDataTable(sql);
            if (dtAll != null || dtAll.Rows.Count > 0)
            {
                UpdateHalfHoulyData(dtAll, CityCode.ALL.Code, CityCode.ALL.Name, ReportDate, ccm_db);
            }
            //深圳
            sql = string.Format("exec UtilizationRateByHour '{0}','{1}'", reportDate, CityCode.SZ.Code);
            dtAll = aecc_db.GetDataTable(sql);
            if (dtAll != null || dtAll.Rows.Count > 0)
            {
                UpdateHoulyData(dtAll, CityCode.SZ.Code, CityCode.SZ.Name, ReportDate, ccm_db);
            }

            sql = string.Format("exec UtilizationRateByHalfHour '{0}','{1}'", reportDate, CityCode.SZ.Code);
            dtAll = aecc_db.GetDataTable(sql);
            if (dtAll != null || dtAll.Rows.Count > 0)
            {
                UpdateHalfHoulyData(dtAll, CityCode.SZ.Code, CityCode.SZ.Name, ReportDate, ccm_db);
            }

            //济南
            sql = string.Format("exec UtilizationRateByHour '{0}','{1}'", reportDate, CityCode.JN.Code);
            dtAll = aecc_db.GetDataTable(sql);
            if (dtAll != null || dtAll.Rows.Count > 0)
            {
                UpdateHoulyData(dtAll, CityCode.JN.Code, CityCode.JN.Name, ReportDate, ccm_db);
            }

            sql = string.Format("exec UtilizationRateByHalfHour '{0}','{1}'", reportDate, CityCode.JN.Code);
            dtAll = aecc_db.GetDataTable(sql);
            if (dtAll != null || dtAll.Rows.Count > 0)
            {
                UpdateHalfHoulyData(dtAll, CityCode.JN.Code, CityCode.JN.Name, ReportDate, ccm_db);
            }
        }

        private void UpdateHoulyData(DataTable dtHoulyData, string cityCode, string cityName, string ReportDate, SQLHelper ccm_db)
        {
            string sql = string.Format(@"merge into ccm_hourly_stat a
using (
select newid() ID,
'{24}' CityCode,
'{25}' CityName,
'{26}' ReportDate,
'{27}' KPICode,
'{28}' KPIName,
{0} Data00,
{1} Data01,
{2} Data02,
{3} Data03,
{4} Data04,
{5} Data05,
{6} Data06,
{7} Data07,
{8} Data08,
{9} Data09,
{10} Data10,
{11} Data11,
{12} Data12,
{13} Data13,
{14} Data14,
{15} Data15,
{16} Data16,
{17} Data17,
{18} Data18,
{19} Data19,
{20} Data20,
{21} Data21,
{22} Data22,
{23} Data23,
getdate() TimeStamp
) b on a.CityCode=b.CityCode and a.ReportDate=b.ReportDate and a.KPICode=b.KPICode
when matched then 
update set a.Data00=b.Data00,
a.Data01=b.Data00,
a.Data02=b.Data02,
a.Data03=b.Data03,
a.Data04=b.Data04,
a.Data05=b.Data05,
a.Data06=b.Data06,
a.Data07=b.Data07,
a.Data08=b.Data08,
a.Data09=b.Data09,
a.Data10=b.Data10,
a.Data11=b.Data11,
a.Data12=b.Data12,
a.Data13=b.Data13,
a.Data14=b.Data14,
a.Data15=b.Data15,
a.Data16=b.Data16,
a.Data17=b.Data17,
a.Data18=b.Data18,
a.Data19=b.Data19,
a.Data20=b.Data20,
a.Data21=b.Data21,
a.Data22=b.Data22,
a.Data23=b.Data23,
a.TimeStamp=b.TimeStamp
when not matched then
insert (ID,
CityCode,
CityName,
ReportDate,
KPICode,
KPIName,
Data00,
Data01,
Data02,
Data03,
Data04,
Data05,
Data06,
Data07,
Data08,
Data09,
Data10,
Data11,
Data12,
Data13,
Data14,
Data15,
Data16,
Data17,
Data18,
Data19,
Data20,
Data21,
Data22,
Data23,
TimeStamp) values(
newid(),
'{24}',--CityCode
'{25}',--CityName
'{26}',--ReportDate
'{27}',--KPICode
'{28}',--KPIName
b.Data00,
b.Data01,
b.Data02,
b.Data03,
b.Data04,
b.Data05,
b.Data06,
b.Data07,
b.Data08,
b.Data09,
b.Data10,
b.Data11,
b.Data12,
b.Data13,
b.Data14,
b.Data15,
b.Data16,
b.Data17,
b.Data18,
b.Data19,
b.Data20,
b.Data21,
b.Data22,
b.Data23,
getdate());",
dtHoulyData.Rows[0]["UtilizationRate00"],
dtHoulyData.Rows[0]["UtilizationRate01"],
dtHoulyData.Rows[0]["UtilizationRate02"],
dtHoulyData.Rows[0]["UtilizationRate03"],
dtHoulyData.Rows[0]["UtilizationRate04"],
dtHoulyData.Rows[0]["UtilizationRate05"],
dtHoulyData.Rows[0]["UtilizationRate06"],
dtHoulyData.Rows[0]["UtilizationRate07"],
dtHoulyData.Rows[0]["UtilizationRate08"],
dtHoulyData.Rows[0]["UtilizationRate09"],
dtHoulyData.Rows[0]["UtilizationRate10"],
dtHoulyData.Rows[0]["UtilizationRate11"],
dtHoulyData.Rows[0]["UtilizationRate12"],
dtHoulyData.Rows[0]["UtilizationRate13"],
dtHoulyData.Rows[0]["UtilizationRate14"],
dtHoulyData.Rows[0]["UtilizationRate15"],
dtHoulyData.Rows[0]["UtilizationRate16"],
dtHoulyData.Rows[0]["UtilizationRate17"],
dtHoulyData.Rows[0]["UtilizationRate18"],
dtHoulyData.Rows[0]["UtilizationRate19"],
dtHoulyData.Rows[0]["UtilizationRate20"],
dtHoulyData.Rows[0]["UtilizationRate21"],
dtHoulyData.Rows[0]["UtilizationRate22"],
dtHoulyData.Rows[0]["UtilizationRate23"],
cityCode,
cityName,
ReportDate,
"In.UtilizationRate",
"工时利用率"
);
            ccm_db.ExecuteNonQuery(sql);
        }

        private void UpdateHalfHoulyData(DataTable dtHalfHoulyData, string cityCode, string cityName, string ReportDate, SQLHelper ccm_db)
        {
            string sql = string.Format(@"merge into ccm_half_hourly_stat a
using (
select newid() ID,
'{48}' CityCode,
'{49}' CityName,
'{50}' ReportDate,
'{51}' KPICode,
'{52}' KPIName,
{0} Data00,
{1} Data01,
{2} Data02,
{3} Data03,
{4} Data04,
{5} Data05,
{6} Data06,
{7} Data07,
{8} Data08,
{9} Data09,
{10} Data10,
{11} Data11,
{12} Data12,
{13} Data13,
{14} Data14,
{15} Data15,
{16} Data16,
{17} Data17,
{18} Data18,
{19} Data19,
{20} Data20,
{21} Data21,
{22} Data22,
{23} Data23,
{24} Data24,
{25} Data25,
{26} Data26,
{27} Data27,
{28} Data28,
{29} Data29,
{30} Data30,
{31} Data31,
{32} Data32,
{33} Data33,
{34} Data34,
{35} Data35,
{36} Data36,
{37} Data37,
{38} Data38,
{39} Data39,
{40} Data40,
{41} Data41,
{42} Data42,
{43} Data43,
{44} Data44,
{45} Data45,
{46} Data46,
{47} Data47,
getdate() TimeStamp
) b on a.CityCode=b.CityCode and a.ReportDate=b.ReportDate and a.KPICode=b.KPICode
when matched then 
update set a.Data00=b.Data00,
a.Data01=b.Data00,
a.Data02=b.Data02,
a.Data03=b.Data03,
a.Data04=b.Data04,
a.Data05=b.Data05,
a.Data06=b.Data06,
a.Data07=b.Data07,
a.Data08=b.Data08,
a.Data09=b.Data09,
a.Data10=b.Data10,
a.Data11=b.Data11,
a.Data12=b.Data12,
a.Data13=b.Data13,
a.Data14=b.Data14,
a.Data15=b.Data15,
a.Data16=b.Data16,
a.Data17=b.Data17,
a.Data18=b.Data18,
a.Data19=b.Data19,
a.Data20=b.Data20,
a.Data21=b.Data21,
a.Data22=b.Data22,
a.Data23=b.Data23,
a.Data24=b.Data24,
a.Data25=b.Data25,
a.Data26=b.Data26,
a.Data27=b.Data27,
a.Data28=b.Data28,
a.Data29=b.Data29,
a.Data30=b.Data30,
a.Data31=b.Data31,
a.Data32=b.Data32,
a.Data33=b.Data33,
a.Data34=b.Data34,
a.Data35=b.Data35,
a.Data36=b.Data36,
a.Data37=b.Data37,
a.Data38=b.Data38,
a.Data39=b.Data39,
a.Data40=b.Data40,
a.Data41=b.Data41,
a.Data42=b.Data42,
a.Data43=b.Data43,
a.Data44=b.Data44,
a.Data45=b.Data45,
a.Data46=b.Data46,
a.Data47=b.Data47,
a.TimeStamp=b.TimeStamp
when not matched then
insert (ID,
CityCode,
CityName,
ReportDate,
KPICode,
KPIName,
Data00,
Data01,
Data02,
Data03,
Data04,
Data05,
Data06,
Data07,
Data08,
Data09,
Data10,
Data11,
Data12,
Data13,
Data14,
Data15,
Data16,
Data17,
Data18,
Data19,
Data20,
Data21,
Data22,
Data23,
Data24,
Data25,
Data26,
Data27,
Data28,
Data29,
Data30,
Data31,
Data32,
Data33,
Data34,
Data35,
Data36,
Data37,
Data38,
Data39,
Data40,
Data41,
Data42,
Data43,
Data44,
Data45,
Data46,
Data47,
TimeStamp) values(newid(),
'{48}',--CityCode
'{49}',--CityName
'{50}',--ReportDate
'{51}',--KPICode
'{52}',--KPIName
b.Data00,
b.Data01,
b.Data02,
b.Data03,
b.Data04,
b.Data05,
b.Data06,
b.Data07,
b.Data08,
b.Data09,
b.Data10,
b.Data11,
b.Data12,
b.Data13,
b.Data14,
b.Data15,
b.Data16,
b.Data17,
b.Data18,
b.Data19,
b.Data20,
b.Data21,
b.Data22,
b.Data23,
b.Data24,
b.Data25,
b.Data26,
b.Data27,
b.Data28,
b.Data29,
b.Data30,
b.Data31,
b.Data32,
b.Data33,
b.Data34,
b.Data35,
b.Data36,
b.Data37,
b.Data38,
b.Data39,
b.Data40,
b.Data41,
b.Data42,
b.Data43,
b.Data44,
b.Data45,
b.Data46,
b.Data47,
getdate());",
dtHalfHoulyData.Rows[0]["UtilizationRate00"],
dtHalfHoulyData.Rows[0]["UtilizationRate01"],
dtHalfHoulyData.Rows[0]["UtilizationRate02"],
dtHalfHoulyData.Rows[0]["UtilizationRate03"],
dtHalfHoulyData.Rows[0]["UtilizationRate04"],
dtHalfHoulyData.Rows[0]["UtilizationRate05"],
dtHalfHoulyData.Rows[0]["UtilizationRate06"],
dtHalfHoulyData.Rows[0]["UtilizationRate07"],
dtHalfHoulyData.Rows[0]["UtilizationRate08"],
dtHalfHoulyData.Rows[0]["UtilizationRate09"],
dtHalfHoulyData.Rows[0]["UtilizationRate10"],
dtHalfHoulyData.Rows[0]["UtilizationRate11"],
dtHalfHoulyData.Rows[0]["UtilizationRate12"],
dtHalfHoulyData.Rows[0]["UtilizationRate13"],
dtHalfHoulyData.Rows[0]["UtilizationRate14"],
dtHalfHoulyData.Rows[0]["UtilizationRate15"],
dtHalfHoulyData.Rows[0]["UtilizationRate16"],
dtHalfHoulyData.Rows[0]["UtilizationRate17"],
dtHalfHoulyData.Rows[0]["UtilizationRate18"],
dtHalfHoulyData.Rows[0]["UtilizationRate19"],
dtHalfHoulyData.Rows[0]["UtilizationRate20"],
dtHalfHoulyData.Rows[0]["UtilizationRate21"],
dtHalfHoulyData.Rows[0]["UtilizationRate22"],
dtHalfHoulyData.Rows[0]["UtilizationRate23"],
dtHalfHoulyData.Rows[0]["UtilizationRate24"],
dtHalfHoulyData.Rows[0]["UtilizationRate25"],
dtHalfHoulyData.Rows[0]["UtilizationRate26"],
dtHalfHoulyData.Rows[0]["UtilizationRate27"],
dtHalfHoulyData.Rows[0]["UtilizationRate28"],
dtHalfHoulyData.Rows[0]["UtilizationRate29"],
dtHalfHoulyData.Rows[0]["UtilizationRate30"],
dtHalfHoulyData.Rows[0]["UtilizationRate31"],
dtHalfHoulyData.Rows[0]["UtilizationRate32"],
dtHalfHoulyData.Rows[0]["UtilizationRate33"],
dtHalfHoulyData.Rows[0]["UtilizationRate34"],
dtHalfHoulyData.Rows[0]["UtilizationRate35"],
dtHalfHoulyData.Rows[0]["UtilizationRate36"],
dtHalfHoulyData.Rows[0]["UtilizationRate37"],
dtHalfHoulyData.Rows[0]["UtilizationRate38"],
dtHalfHoulyData.Rows[0]["UtilizationRate39"],
dtHalfHoulyData.Rows[0]["UtilizationRate40"],
dtHalfHoulyData.Rows[0]["UtilizationRate41"],
dtHalfHoulyData.Rows[0]["UtilizationRate42"],
dtHalfHoulyData.Rows[0]["UtilizationRate43"],
dtHalfHoulyData.Rows[0]["UtilizationRate44"],
dtHalfHoulyData.Rows[0]["UtilizationRate45"],
dtHalfHoulyData.Rows[0]["UtilizationRate46"],
dtHalfHoulyData.Rows[0]["UtilizationRate47"],
cityCode,
cityName,
ReportDate,
"In.UtilizationRate",
"工时利用率"
);
            ccm_db.ExecuteNonQuery(sql);
        }

        #endregion

        #region 非工时率时段数据

        /// <summary>
        /// 非工时率时段数据（该方法内的sql未支持重算）
        /// </summary>
        private void PumpHourlySpanData()
        {
            SQLHelper ccm_db = null;
            SQLHelper aecc_db = null;
            try
            {
                string reportDate = DateTime.Now.ToString("yyyy-MM-dd");
                ccm_db = new SQLHelper(ccm_db_string);
                aecc_db = new SQLHelper(aecc_db_string);
                PumpHourlySpanData(ccm_db, aecc_db, reportDate);
            }
            catch (Exception exp)
            {
                Log.Debug(exp);
            }
            finally
            {
                bool flag = ccm_db != null;
                if (flag)
                {
                    ccm_db.CloseConnection();
                    ccm_db = null;
                }
                flag = aecc_db != null;
                if (flag)
                {
                    aecc_db.CloseConnection();
                    aecc_db = null;
                }
            }
        }

        private void PumpHourlySpanData(SQLHelper ccm_db, SQLHelper aecc_db, string reportDate)
        {
            string ReportDate = reportDate.Replace("-", "");

            #region 总的

            HourlyData CallsTotalStat = FunCallsTotalStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);

            HourlyData CompletionTotalStat = FunCompletionTotalStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);
            HourlyData CompletionRateStat = FunCompletionRateStat(CompletionTotalStat, CallsTotalStat);
            HourlyData GiveUpTotalStat = FunGiveUpTotalStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);
            HourlyData SLAIn20STotalStat = FunSLAIn20STotalStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);
            HourlyData SLAIn20S = FunSLAIn20S(SLAIn20STotalStat, CallsTotalStat);
            //人均通话时长
            HourlyData CallTimeAverageStat = FunCallTimeAverageStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);
            HourlyData BreakTinmeAverageStat = FunBreakTinmeAverageStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);
            //人均后处理时长
            HourlyData AfterCallTImeAverageStat = FunAfterCallTImeAverageStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);
            HourlyData LoginTimeDurStat = FunLoginTimeDurStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);
            HourlyData BreakTimeDurStat = FunBreakTimeDurStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);
            //工时利用率

            //人均分配时长
            HourlyData AllocatedTimeAverageStat = FunAllocatedTimeAverageStat(ReportDate, "Dashboard.Org.Inbound", aecc_db);
            //小休率
            HourlyData BreakRateStat = FunHourlyBreakRateStat(LoginTimeDurStat, BreakTimeDurStat);

            FunUpdateHoulyData(CallsTotalStat, ccm_db);
            FunUpdateHoulyData(CompletionTotalStat, ccm_db);
            FunUpdateHoulyData(CompletionRateStat, ccm_db);
            FunUpdateHoulyData(GiveUpTotalStat, ccm_db);
            FunUpdateHoulyData(SLAIn20S, ccm_db);
            FunUpdateHoulyData(CallTimeAverageStat, ccm_db);
            FunUpdateHoulyData(BreakTinmeAverageStat, ccm_db);
            FunUpdateHoulyData(AfterCallTImeAverageStat, ccm_db);
            FunUpdateHoulyData(LoginTimeDurStat, ccm_db);
            FunUpdateHoulyData(BreakTimeDurStat, ccm_db);
            FunUpdateHoulyData(BreakTimeDurStat, ccm_db);
            FunUpdateHoulyData(AllocatedTimeAverageStat, ccm_db);
            FunUpdateHoulyData(BreakRateStat, ccm_db);

            #endregion

            #region 深圳


            HourlyData szCallsTotalStat = FunCallsTotalStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);
            HourlyData szCompletionTotalStat = FunCompletionTotalStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);
            HourlyData szCompletionRateStat = FunCompletionRateStat(szCompletionTotalStat, szCallsTotalStat);
            HourlyData szGiveUpTotalStat = FunGiveUpTotalStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);
            HourlyData szSLAIn20STotalStat = FunSLAIn20STotalStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);
            HourlyData szSLAIn20S = FunSLAIn20S(szSLAIn20STotalStat, szCallsTotalStat);
            //人均通话时长
            HourlyData szCallTimeAverageStat = FunCallTimeAverageStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);
            HourlyData szBreakTinmeAverageStat = FunBreakTinmeAverageStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);
            //人均后处理时长
            HourlyData szAfterCallTImeAverageStat = FunAfterCallTImeAverageStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);
            HourlyData szLoginTimeDurStat = FunLoginTimeDurStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);
            HourlyData szBreakTimeDurStat = FunBreakTimeDurStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);

            //人均分配时长
            HourlyData szAllocatedTimeAverageStat = FunAllocatedTimeAverageStat(ReportDate, "Dashboard.Org.Inbound.SZ", aecc_db);
            //小休率
            HourlyData szBreakRateStat = FunHourlyBreakRateStat(szLoginTimeDurStat, szBreakTimeDurStat);

            FunUpdateHoulyData(szCallsTotalStat, ccm_db);
            FunUpdateHoulyData(szCompletionTotalStat, ccm_db);
            FunUpdateHoulyData(szCompletionRateStat, ccm_db);
            FunUpdateHoulyData(szGiveUpTotalStat, ccm_db);
            FunUpdateHoulyData(szSLAIn20S, ccm_db);
            FunUpdateHoulyData(szCallTimeAverageStat, ccm_db);
            FunUpdateHoulyData(szBreakTinmeAverageStat, ccm_db);
            FunUpdateHoulyData(szAfterCallTImeAverageStat, ccm_db);
            FunUpdateHoulyData(szLoginTimeDurStat, ccm_db);
            FunUpdateHoulyData(szBreakTimeDurStat, ccm_db);
            FunUpdateHoulyData(szBreakTimeDurStat, ccm_db);
            FunUpdateHoulyData(szAllocatedTimeAverageStat, ccm_db);
            FunUpdateHoulyData(szBreakRateStat, ccm_db);

            #endregion

            #region 济南

            HourlyData jnCallsTotalStat = FunCallsTotalStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);
            HourlyData jnCompletionTotalStat = FunCompletionTotalStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);
            HourlyData jnCompletionRateStat = FunCompletionRateStat(jnCompletionTotalStat, jnCallsTotalStat);
            HourlyData jnGiveUpTotalStat = FunGiveUpTotalStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);
            HourlyData jnSLAIn20STotalStat = FunSLAIn20STotalStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);
            HourlyData jnSLAIn20S = FunSLAIn20S(jnSLAIn20STotalStat, jnCallsTotalStat);
            HourlyData jnCallTimeAverageStat = FunCallTimeAverageStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);
            HourlyData jnBreakTinmeAverageStat = FunBreakTinmeAverageStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);
            //人均后处理时长
            HourlyData jnAfterCallTImeAverageStat = FunAfterCallTImeAverageStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);
            HourlyData jnLoginTimeDurStat = FunLoginTimeDurStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);
            HourlyData jnBreakTimeDurStat = FunBreakTimeDurStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);


            //人均分配时长
            HourlyData jnAllocatedTimeAverageStat = FunAllocatedTimeAverageStat(ReportDate, "Dashboard.Org.Inbound.JN", aecc_db);
            HourlyData jnBreakRateStat = FunHourlyBreakRateStat(jnLoginTimeDurStat, jnBreakTimeDurStat);

            FunUpdateHoulyData(jnCallsTotalStat, ccm_db);
            FunUpdateHoulyData(jnCompletionTotalStat, ccm_db);
            FunUpdateHoulyData(jnCompletionRateStat, ccm_db);
            FunUpdateHoulyData(jnGiveUpTotalStat, ccm_db);
            FunUpdateHoulyData(jnSLAIn20S, ccm_db);
            FunUpdateHoulyData(jnCallTimeAverageStat, ccm_db);
            FunUpdateHoulyData(jnBreakTinmeAverageStat, ccm_db);
            FunUpdateHoulyData(jnAfterCallTImeAverageStat, ccm_db);
            FunUpdateHoulyData(jnLoginTimeDurStat, ccm_db);
            FunUpdateHoulyData(jnBreakTimeDurStat, ccm_db);
            FunUpdateHoulyData(jnBreakTimeDurStat, ccm_db);
            FunUpdateHoulyData(jnAllocatedTimeAverageStat, ccm_db);
            FunUpdateHoulyData(jnBreakRateStat, ccm_db);

            #endregion
        }

        /// <summary>
        /// 呼叫总量
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public HourlyData FunCallsTotalStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string cityCode = "", cityName = "", whereOrg = "", hourlySql = "", halfHourlySql = "", whereVDN = "";
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = "'"+ VDNSZOrgID + "'";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_CallsTotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CallsTotal, rptDate, whereOrg, whereVDN);
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;
                whereOrg = "'" + VDNJNOrgID + "'";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_CallsTotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CallsTotal, rptDate, whereOrg, whereVDN);
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = "'" + VDNInboundOrgID + "'";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_CallsTotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CallsTotal, rptDate, whereOrg, whereVDN);
            }
            return FunHourlyStat(rptDate, cityCode, cityName, "In.CallsTotal", "呼叫总量", hourlySql, halfHourlySql, aecc_db);
        }

        /// <summary>
        /// 接通量
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public HourlyData FunCompletionTotalStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string cityCode = "", cityName = "", whereOrg = "", hourlySql = "", halfHourlySql = "", whereVDN = "";
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = SZVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_CompletionTotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CompletionTotal, rptDate, whereOrg, whereVDN);
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;
                whereOrg = JNVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_CompletionTotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CompletionTotal, rptDate, whereOrg, whereVDN);
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = ALLVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_CompletionTotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CompletionTotal, rptDate, whereOrg, whereVDN);
            }

            return FunHourlyStat(rptDate, cityCode, cityName, "In.Completion", "接通量", hourlySql, halfHourlySql, aecc_db);
        }

        /// <summary>
        /// 接通率
        /// </summary>
        /// <param name="CompletionTotalStat"></param>
        /// <param name="CallsTotalStat"></param>
        /// <returns></returns>
        public HourlyData FunCompletionRateStat(HourlyData CompletionTotalStat, HourlyData CallsTotalStat)
        {
            return FunRateStat(CompletionTotalStat.CityCode, CompletionTotalStat.CityName, "In.CompletionRate", "接通率", CallsTotalStat, CompletionTotalStat);
        }

        /// <summary>
        /// 放弃量
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public HourlyData FunGiveUpTotalStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string cityCode = "", cityName = "", whereOrg = "", hourlySql = "", halfHourlySql = "", whereVDN = "";
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = SZVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_GiveUpTotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_GiveUpTotal, rptDate, whereOrg, whereVDN);
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;

                whereOrg = JNVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_GiveUpTotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_GiveUpTotal, rptDate, whereOrg, whereVDN);
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = ALLVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_GiveUpTotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_GiveUpTotal, rptDate, whereOrg, whereVDN);
            }
            return FunHourlyStat(rptDate, cityCode, cityName, "In.GiveUp", "放弃量", hourlySql, halfHourlySql, aecc_db);
        }

        /// <summary>
        /// 20S服务水平
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public HourlyData FunSLAIn20STotalStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string cityCode = "", cityName = "", whereOrg = "", hourlySql = "", halfHourlySql = "", whereVDN = "";
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = SZVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_In20STotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_In20STotal, rptDate, whereOrg, whereVDN);
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;
                whereOrg = JNVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_In20STotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_In20STotal, rptDate, whereOrg, whereVDN);
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = ALLVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_In20STotal, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_In20STotal, rptDate, whereOrg, whereVDN);
            }
            return FunHourlyStat(rptDate, cityCode, cityName, "In.SLAIn20S.Total", "20S服务呼叫量", hourlySql, halfHourlySql, aecc_db);
        }

        /// <summary>
        /// 20S服务水平
        /// </summary>
        /// <param name="SLAIn20STotalStat"></param>
        /// <param name="CallsTotalStat"></param>
        /// <returns></returns>
        public HourlyData FunSLAIn20S(HourlyData SLAIn20STotalStat, HourlyData CallsTotalStat)
        {
            return FunRateStat(SLAIn20STotalStat.CityCode, SLAIn20STotalStat.CityName, "In.SLAIn20S", "20S服务水平", CallsTotalStat, SLAIn20STotalStat, false);
        }

        /// <summary>
        /// 人均通话时长
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public HourlyData FunCallTimeAverageStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string cityCode = "", cityName = "", whereOrg = "", hourlySql = "", halfHourlySql = "", whereVDN = "";
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = "'" + VDNSZOrgID + "'";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_CallTimeAverage, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CallTimeAverage, rptDate, whereOrg, whereVDN);
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;
                whereOrg = "'" + VDNJNOrgID + "'";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_CallTimeAverage, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CallTimeAverage, rptDate, whereOrg, whereVDN);
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = "'" + VDNInboundOrgID + "'";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_CallTimeAverage, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CallTimeAverage, rptDate, whereOrg, whereVDN);
            }
            return FunHourlyStat(rptDate, cityCode, cityName, "In.CallTimeAverage", "人均通话时长", hourlySql, halfHourlySql, aecc_db);
        }

        /// <summary>
        /// 人均小休时长
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public HourlyData FunBreakTinmeAverageStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string cityCode = "", cityName = "", whereOrg = "", hourlySql = "", halfHourlySql = "", whereVDN = "";
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + VDNSZOrgID + @"')";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_BreakTimeAverage, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CallTimeAverage, rptDate, whereOrg, whereVDN);
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + VDNJNOrgID + @"')";
                whereVDN = " and AgentID not in (select AgentID from v_Agent_Special) ";
                hourlySql = string.Format(SQLEntity.SQL_Hour_BreakTimeAverage, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CallTimeAverage, rptDate, whereOrg, whereVDN);
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + VDNInboundOrgID + @"')";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_BreakTimeAverage, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_CallTimeAverage, rptDate, whereOrg, whereVDN);
            }
            return FunHourlyStat(rptDate, cityCode, cityName, "In.BreakTinmeAverage", "人均小休时长", hourlySql, halfHourlySql, aecc_db);
        }

        /// <summary>
        /// 人均后处理时长
        /// </summary>
        /// <param name="rptDate"></param>
        /// <returns></returns>
        public HourlyData FunAfterCallTImeAverageStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string cityCode = "", cityName = "", whereOrg = "", sql = SQLEntity.SQL_Range_AfterCallTImeAverage;
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + SZOrgID + @"')";
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + JNOrgID + @"')";
                sql += " and AgentID not in (select AgentID from v_Agent_Special) ";
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + InboundOrgID + @"')";
            }
            return FunHourlyStatByRange(rptDate, cityCode, cityName, "In.AfterCallTImeAverage", "人均后处理时长", sql, aecc_db, whereOrg);
        }

        /// <summary>
        /// 登入时长
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public HourlyData FunLoginTimeDurStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string cityCode = "", cityName = "", whereOrg = "", sql = SQLEntity.SQL_Range_Login_DUR;
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + SZOrgID + @"')";
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + JNOrgID + @"')";
                sql += " and AgentID not in (select AgentID from v_Agent_Special) ";
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + InboundOrgID + @"')";
            }
            return FunHourlyStatByRange(rptDate, cityCode, cityName, "In.LoginTimeDur", "登入时长", sql, aecc_db, whereOrg);
        }

        /// <summary>
        /// 小休时长
        /// </summary>
        /// <param name="rptDate"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public HourlyData FunBreakTimeDurStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            string cityCode = "", cityName = "", whereOrg = "", hourlySql = "", halfHourlySql = "", whereVDN = "";
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + SZOrgID + @"')";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_BREAKTIME_DUR, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_BREAKTIME_DUR, rptDate, whereOrg, whereVDN);
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + JNOrgID + @"')";
                whereVDN = " and AgentID not in (select AgentID from v_Agent_Special) ";
                hourlySql = string.Format(SQLEntity.SQL_Hour_BREAKTIME_DUR, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_BREAKTIME_DUR, rptDate, whereOrg, whereVDN);
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = "select OrgID from  f_GetOrganizationByParentId('" + InboundOrgID + @"')";
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_BREAKTIME_DUR, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_BREAKTIME_DUR, rptDate, whereOrg, whereVDN);
            }
            return FunHourlyStat(rptDate, cityCode, cityName, "In.BreakTimeDur", "小休时长", hourlySql, halfHourlySql, aecc_db);
        }

        /// <summary>
        /// 人均分配时长 In.AllocatedTimeAverage
        /// </summary>
        /// <param name="rptDate"></param>
        /// <returns></returns>
        public HourlyData FunAllocatedTimeAverageStat(String rptDate, string OrgCode, SQLHelper aecc_db)
        {
            //OrgCode:Dashboard.Org.Inbound
            string cityCode = "", cityName = "", whereOrg = "", hourlySql = "", halfHourlySql = "", whereVDN = "";
            if (OrgCode == "Dashboard.Org.Inbound.SZ")
            {
                cityCode = CityCode.SZ.Code;
                cityName = CityCode.SZ.Name;
                whereOrg = SZVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_AllocatedTimeAverage, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_AllocatedTimeAverage, rptDate, whereOrg, whereVDN);
            }
            else if (OrgCode == "Dashboard.Org.Inbound.JN")
            {
                cityCode = CityCode.JN.Code;
                cityName = CityCode.JN.Name;
                whereOrg = JNVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_AllocatedTimeAverage, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_AllocatedTimeAverage, rptDate, whereOrg, whereVDN);
            }
            else
            {
                cityCode = CityCode.ALL.Code;
                cityName = CityCode.ALL.Name;
                whereOrg = ALLVDNIDS;
                whereVDN = "";
                hourlySql = string.Format(SQLEntity.SQL_Hour_AllocatedTimeAverage, rptDate, whereOrg, whereVDN);
                halfHourlySql = string.Format(SQLEntity.SQL_Half_Hour_AllocatedTimeAverage, rptDate, whereOrg, whereVDN);
            }

            return FunHourlyStat(rptDate, cityCode, cityName, "In.AllocatedTimeAverage", "人均分配时长", hourlySql, halfHourlySql, aecc_db);
        }

        public HourlyData FunHourlyBreakRateStat(HourlyData LoginTimeDurStat, HourlyData BreakTimeDurStat)
        {
            HourlyData HourlyBreakRateStat = new HourlyData();
            HourlyBreakRateStat.CityCode = LoginTimeDurStat.CityCode;
            HourlyBreakRateStat.CityName = LoginTimeDurStat.CityName;
            HourlyBreakRateStat.KPICode = "In.BreakRate";
            HourlyBreakRateStat.KPIName = "小休率";
            HourlyBreakRateStat.Title = "小休率";
            HourlyBreakRateStat.ReportDate = LoginTimeDurStat.ReportDate;

            HourlyBreakRateStat.DataItems = new decimal[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            HourlyBreakRateStat.HalfDataItems = new decimal[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            for (int i = 0; i < LoginTimeDurStat.DataItems.Count(); i++)
            {
                decimal LoginTimeDur = LoginTimeDurStat.DataItems[i];
                if (LoginTimeDur != 0)
                {
                    HourlyBreakRateStat.DataItems[i] = 100 * (BreakTimeDurStat.DataItems[i]) / LoginTimeDur;
                }
            }

            for (int i = 0; i < LoginTimeDurStat.HalfDataItems.Count(); i++)
            {
                decimal LoginTimeDur = LoginTimeDurStat.HalfDataItems[i];
                if (LoginTimeDur != 0)
                {
                    HourlyBreakRateStat.HalfDataItems[i] = 100 * (BreakTimeDurStat.HalfDataItems[i]) / LoginTimeDur;
                }
            }
            return HourlyBreakRateStat;
        }

        private void FunUpdateHoulyData(HourlyData houtlyData, SQLHelper ccm_db)
        {
            if (houtlyData == null)
                return;

            //一小时数据
            string sql = string.Format(@"merge into ccm_hourly_stat a
using (
select newid() ID,
'{24}' CityCode,
'{25}' CityName,
'{26}' ReportDate,
'{27}' KPICode,
'{28}' KPIName,
{0} Data00,
{1} Data01,
{2} Data02,
{3} Data03,
{4} Data04,
{5} Data05,
{6} Data06,
{7} Data07,
{8} Data08,
{9} Data09,
{10} Data10,
{11} Data11,
{12} Data12,
{13} Data13,
{14} Data14,
{15} Data15,
{16} Data16,
{17} Data17,
{18} Data18,
{19} Data19,
{20} Data20,
{21} Data21,
{22} Data22,
{23} Data23,
getdate() TimeStamp
) b on a.CityCode=b.CityCode and a.ReportDate=b.ReportDate and a.KPICode=b.KPICode
when matched then 
update set a.Data00=b.Data00,
a.Data01=b.Data00,
a.Data02=b.Data02,
a.Data03=b.Data03,
a.Data04=b.Data04,
a.Data05=b.Data05,
a.Data06=b.Data06,
a.Data07=b.Data07,
a.Data08=b.Data08,
a.Data09=b.Data09,
a.Data10=b.Data10,
a.Data11=b.Data11,
a.Data12=b.Data12,
a.Data13=b.Data13,
a.Data14=b.Data14,
a.Data15=b.Data15,
a.Data16=b.Data16,
a.Data17=b.Data17,
a.Data18=b.Data18,
a.Data19=b.Data19,
a.Data20=b.Data20,
a.Data21=b.Data21,
a.Data22=b.Data22,
a.Data23=b.Data23,
a.TimeStamp=b.TimeStamp
when not matched then
insert (ID,
CityCode,
CityName,
ReportDate,
KPICode,
KPIName,
Data00,
Data01,
Data02,
Data03,
Data04,
Data05,
Data06,
Data07,
Data08,
Data09,
Data10,
Data11,
Data12,
Data13,
Data14,
Data15,
Data16,
Data17,
Data18,
Data19,
Data20,
Data21,
Data22,
Data23,
TimeStamp) values(
newid(),
'{24}',--CityCode
'{25}',--CityName
'{26}',--ReportDate
'{27}',--KPICode
'{28}',--KPIName
b.Data00,
b.Data01,
b.Data02,
b.Data03,
b.Data04,
b.Data05,
b.Data06,
b.Data07,
b.Data08,
b.Data09,
b.Data10,
b.Data11,
b.Data12,
b.Data13,
b.Data14,
b.Data15,
b.Data16,
b.Data17,
b.Data18,
b.Data19,
b.Data20,
b.Data21,
b.Data22,
b.Data23,
getdate());",
houtlyData.DataItems[0],
houtlyData.DataItems[1],
houtlyData.DataItems[2],
houtlyData.DataItems[3],
houtlyData.DataItems[4],
houtlyData.DataItems[5],
houtlyData.DataItems[6],
houtlyData.DataItems[7],
houtlyData.DataItems[8],
houtlyData.DataItems[9],
houtlyData.DataItems[10],
houtlyData.DataItems[11],
houtlyData.DataItems[12],
houtlyData.DataItems[13],
houtlyData.DataItems[14],
houtlyData.DataItems[15],
houtlyData.DataItems[16],
houtlyData.DataItems[17],
houtlyData.DataItems[18],
houtlyData.DataItems[19],
houtlyData.DataItems[20],
houtlyData.DataItems[21],
houtlyData.DataItems[22],
houtlyData.DataItems[23],
houtlyData.CityCode,
houtlyData.CityName,
houtlyData.ReportDate,
houtlyData.KPICode,
houtlyData.KPIName
);
            ccm_db.ExecuteNonQuery(sql);

            //半小时数据
            sql = string.Format(@"merge into ccm_half_hourly_stat a
using (
select newid() ID,
'{48}' CityCode,
'{49}' CityName,
'{50}' ReportDate,
'{51}' KPICode,
'{52}' KPIName,
{0} Data00,
{1} Data01,
{2} Data02,
{3} Data03,
{4} Data04,
{5} Data05,
{6} Data06,
{7} Data07,
{8} Data08,
{9} Data09,
{10} Data10,
{11} Data11,
{12} Data12,
{13} Data13,
{14} Data14,
{15} Data15,
{16} Data16,
{17} Data17,
{18} Data18,
{19} Data19,
{20} Data20,
{21} Data21,
{22} Data22,
{23} Data23,
{24} Data24,
{25} Data25,
{26} Data26,
{27} Data27,
{28} Data28,
{29} Data29,
{30} Data30,
{31} Data31,
{32} Data32,
{33} Data33,
{34} Data34,
{35} Data35,
{36} Data36,
{37} Data37,
{38} Data38,
{39} Data39,
{40} Data40,
{41} Data41,
{42} Data42,
{43} Data43,
{44} Data44,
{45} Data45,
{46} Data46,
{47} Data47,
getdate() TimeStamp
) b on a.CityCode=b.CityCode and a.ReportDate=b.ReportDate and a.KPICode=b.KPICode
when matched then 
update set a.Data00=b.Data00,
a.Data01=b.Data00,
a.Data02=b.Data02,
a.Data03=b.Data03,
a.Data04=b.Data04,
a.Data05=b.Data05,
a.Data06=b.Data06,
a.Data07=b.Data07,
a.Data08=b.Data08,
a.Data09=b.Data09,
a.Data10=b.Data10,
a.Data11=b.Data11,
a.Data12=b.Data12,
a.Data13=b.Data13,
a.Data14=b.Data14,
a.Data15=b.Data15,
a.Data16=b.Data16,
a.Data17=b.Data17,
a.Data18=b.Data18,
a.Data19=b.Data19,
a.Data20=b.Data20,
a.Data21=b.Data21,
a.Data22=b.Data22,
a.Data23=b.Data23,
a.Data24=b.Data24,
a.Data25=b.Data25,
a.Data26=b.Data26,
a.Data27=b.Data27,
a.Data28=b.Data28,
a.Data29=b.Data29,
a.Data30=b.Data30,
a.Data31=b.Data31,
a.Data32=b.Data32,
a.Data33=b.Data33,
a.Data34=b.Data34,
a.Data35=b.Data35,
a.Data36=b.Data36,
a.Data37=b.Data37,
a.Data38=b.Data38,
a.Data39=b.Data39,
a.Data40=b.Data40,
a.Data41=b.Data41,
a.Data42=b.Data42,
a.Data43=b.Data43,
a.Data44=b.Data44,
a.Data45=b.Data45,
a.Data46=b.Data46,
a.Data47=b.Data47,
a.TimeStamp=b.TimeStamp
when not matched then
insert (ID,
CityCode,
CityName,
ReportDate,
KPICode,
KPIName,
Data00,
Data01,
Data02,
Data03,
Data04,
Data05,
Data06,
Data07,
Data08,
Data09,
Data10,
Data11,
Data12,
Data13,
Data14,
Data15,
Data16,
Data17,
Data18,
Data19,
Data20,
Data21,
Data22,
Data23,
Data24,
Data25,
Data26,
Data27,
Data28,
Data29,
Data30,
Data31,
Data32,
Data33,
Data34,
Data35,
Data36,
Data37,
Data38,
Data39,
Data40,
Data41,
Data42,
Data43,
Data44,
Data45,
Data46,
Data47,
TimeStamp) values(newid(),
'{48}',--CityCode
'{49}',--CityName
'{50}',--ReportDate
'{51}',--KPICode
'{52}',--KPIName
b.Data00,
b.Data01,
b.Data02,
b.Data03,
b.Data04,
b.Data05,
b.Data06,
b.Data07,
b.Data08,
b.Data09,
b.Data10,
b.Data11,
b.Data12,
b.Data13,
b.Data14,
b.Data15,
b.Data16,
b.Data17,
b.Data18,
b.Data19,
b.Data20,
b.Data21,
b.Data22,
b.Data23,
b.Data24,
b.Data25,
b.Data26,
b.Data27,
b.Data28,
b.Data29,
b.Data30,
b.Data31,
b.Data32,
b.Data33,
b.Data34,
b.Data35,
b.Data36,
b.Data37,
b.Data38,
b.Data39,
b.Data40,
b.Data41,
b.Data42,
b.Data43,
b.Data44,
b.Data45,
b.Data46,
b.Data47,
getdate());",
houtlyData.HalfDataItems[0],
houtlyData.HalfDataItems[1],
houtlyData.HalfDataItems[2],
houtlyData.HalfDataItems[3],
houtlyData.HalfDataItems[4],
houtlyData.HalfDataItems[5],
houtlyData.HalfDataItems[6],
houtlyData.HalfDataItems[7],
houtlyData.HalfDataItems[8],
houtlyData.HalfDataItems[9],
houtlyData.HalfDataItems[10],
houtlyData.HalfDataItems[11],
houtlyData.HalfDataItems[12],
houtlyData.HalfDataItems[13],
houtlyData.HalfDataItems[14],
houtlyData.HalfDataItems[15],
houtlyData.HalfDataItems[16],
houtlyData.HalfDataItems[17],
houtlyData.HalfDataItems[18],
houtlyData.HalfDataItems[19],
houtlyData.HalfDataItems[20],
houtlyData.HalfDataItems[21],
houtlyData.HalfDataItems[22],
houtlyData.HalfDataItems[23],
houtlyData.HalfDataItems[24],
houtlyData.HalfDataItems[25],
houtlyData.HalfDataItems[26],
houtlyData.HalfDataItems[27],
houtlyData.HalfDataItems[28],
houtlyData.HalfDataItems[29],
houtlyData.HalfDataItems[30],
houtlyData.HalfDataItems[31],
houtlyData.HalfDataItems[32],
houtlyData.HalfDataItems[33],
houtlyData.HalfDataItems[34],
houtlyData.HalfDataItems[35],
houtlyData.HalfDataItems[36],
houtlyData.HalfDataItems[37],
houtlyData.HalfDataItems[38],
houtlyData.HalfDataItems[39],
houtlyData.HalfDataItems[40],
houtlyData.HalfDataItems[41],
houtlyData.HalfDataItems[42],
houtlyData.HalfDataItems[43],
houtlyData.HalfDataItems[44],
houtlyData.HalfDataItems[45],
houtlyData.HalfDataItems[46],
houtlyData.HalfDataItems[47],
houtlyData.CityCode,
houtlyData.CityName,
houtlyData.ReportDate,
houtlyData.KPICode,
houtlyData.KPIName
);
            ccm_db.ExecuteNonQuery(sql);
        }

        private HourlyData FunHourlyStat(String rptDate, string cityCode, string cityName, string kpiCode, string kpiName, string hourlySql, string halfHourlySql, SQLHelper aecc_db)
        {
            HourlyData rt = new HourlyData();
            rt.Title = kpiName;
            rt.KPICode = kpiCode;
            rt.KPIName = kpiName;
            rt.CityCode = cityCode;
            rt.CityName = cityName;
            rt.ReportDate = rptDate;

            rt.DataItems = new decimal[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            rt.HalfDataItems = new decimal[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            //Log.Debug(hourlySql);
            DataTable dt = aecc_db.GetDataTable(hourlySql);
            int lastHour = 0;
            decimal lastValue = 0;
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    int tmphour = int.Parse(dr["hour"].ToString());
                    decimal tmpvalue = decimal.Parse(dr["value"].ToString());
                    if (tmphour >= 0 && tmphour <= 23)
                    {
                        rt.DataItems[tmphour] = tmpvalue;
                    }
                    if (tmphour > lastHour)
                    {
                        lastHour = tmphour;
                        lastValue = tmpvalue;
                    }
                }
                for (int i = lastHour; i <= 23; i++)
                {
                    rt.DataItems[i] = lastValue;
                }
            }

            //Log.Debug(halfHourlySql);
            dt = aecc_db.GetDataTable(halfHourlySql);
            lastHour = 0;
            lastValue = 0;
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    int tmphour = int.Parse(dr["hour"].ToString());
                    decimal tmpvalue = decimal.Parse(dr["value"].ToString());
                    if (tmphour >= 0 && tmphour <= 47)
                    {
                        rt.HalfDataItems[tmphour] = tmpvalue;
                    }
                    if (tmphour > lastHour)
                    {
                        lastHour = tmphour;
                        lastValue = tmpvalue;
                    }
                }
                for (int i = lastHour; i <= 47; i++)
                {
                    rt.HalfDataItems[i] = lastValue;
                }
            }

            return rt;
        }

        private HourlyData FunRateStat(string cityCode, string cityName, string kpiCode, string kpiName, HourlyData TotalStat, HourlyData ValueStat, bool zoreFull = true)
        {
            HourlyData RateStat = new HourlyData();
            RateStat.CityCode = cityCode;
            RateStat.CityName = cityName;
            RateStat.KPICode = kpiCode;
            RateStat.KPIName = kpiName;
            RateStat.Title = kpiName;
            RateStat.ReportDate = TotalStat.ReportDate;

            if (zoreFull)
            {
                RateStat.DataItems = new decimal[] { 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100 };
                RateStat.HalfDataItems = new decimal[] { 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100 };
            }
            else
            {
                RateStat.DataItems = new decimal[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                RateStat.HalfDataItems = new decimal[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            }

            for (int i = 0; i < TotalStat.DataItems.Count(); i++)
            {
                decimal total = TotalStat.DataItems[i];
                if (total != 0)
                {
                    RateStat.DataItems[i] = 100 * (ValueStat.DataItems[i]) / total;
                }
            }

            for (int i = 0; i < TotalStat.HalfDataItems.Count(); i++)
            {
                decimal totlal = TotalStat.HalfDataItems[i];
                if (totlal != 0)
                {
                    RateStat.HalfDataItems[i] = 100 * (ValueStat.HalfDataItems[i]) / totlal;
                }
            }

            return RateStat;
        }

        private HourlyData FunHourlyStatByRange(String rptDate, string cityCode, string cityName, string kpiCode, string kpiName, string hourlySql, SQLHelper aecc_db, string orgQueryString = "")
        {
            HourlyData rt = new HourlyData();
            rt.Title = kpiName;
            rt.KPICode = kpiCode;
            rt.KPIName = kpiName;
            rt.CityCode = cityCode;
            rt.CityName = cityName;
            rt.ReportDate = rptDate;

            rt.DataItems = new decimal[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            rt.HalfDataItems = new decimal[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            var startDate = DateTime.Parse(rptDate.Substring(0, 4) + "/" + rptDate.Substring(4, 2) + "/" + rptDate.Substring(6, 2));

            DateTime now = DateTime.Now;
            for (int i = 1; i < 25; i++)
            {
                DateTime st = startDate.AddHours(i - 1);
                DateTime ed = startDate.AddHours(i);


                if (ed > now)
                {
                    ed = now;
                }

                string sql = string.Format(hourlySql, st.ToString("yyyy/MM/dd HH:mm:ss"), ed.ToString("yyyy/MM/dd HH:mm:ss"), orgQueryString);
                //Log.Debug(sql);
                DataTable dt = aecc_db.GetDataTable(sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    rt.DataItems[i - 1] = decimal.Parse(dt.Rows[0][0].ToString());
                }
                //var rs = dbContext.Database.SqlQuery<decimal>(sql).FirstOrDefault();
                //rt.DataItems[i - 1] = rs;
            }

            startDate = DateTime.Parse(rptDate.Substring(0, 4) + "/" + rptDate.Substring(4, 2) + "/" + rptDate.Substring(6, 2));
            for (int i = 1; i < 49; i++)
            {
                DateTime st = startDate.AddMinutes((i - 1) * 30);
                DateTime ed = startDate.AddMinutes(i * 30);

                if (ed > now)
                {
                    ed = now;
                }

                string sql = string.Format(hourlySql, st.ToString("yyyy/MM/dd HH:mm:ss"), startDate.AddMinutes(i * 30).ToString("yyyy/MM/dd HH:mm:ss"), orgQueryString);
                //Log.Debug(sql);
                DataTable dt = aecc_db.GetDataTable(sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    rt.HalfDataItems[i - 1] = decimal.Parse(dt.Rows[0][0].ToString());
                }
                //var rs = dbContext.Database.SqlQuery<decimal>(sql).FirstOrDefault();
                //rt.HalfDataItems[i - 1] = rs;
            }
            return rt;
        }

        #endregion

        #region 每晚重算前一天的数据

        private void FixYesterdayData()
        {
            SQLHelper ccm_db = null;
            SQLHelper aecc_db = null;
            try
            {
                //前一天
                string reportDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                ccm_db = new SQLHelper(ccm_db_string);
                aecc_db = new SQLHelper(aecc_db_string);
                //单值指标
                PumpDashboard(ccm_db, aecc_db, reportDate);
                //单值工时率
                PumpUtilizationRate(ccm_db, aecc_db, reportDate);
                //时段工时率
                PumpHourlyUtilizationRate(ccm_db, aecc_db, reportDate);
            }
            catch (Exception exp)
            {
                Log.Debug(exp);
            }
            finally
            {
                bool flag = ccm_db != null;
                if (flag)
                {
                    ccm_db.CloseConnection();
                    ccm_db = null;
                }
                flag = aecc_db != null;
                if (flag)
                {
                    aecc_db.CloseConnection();
                    aecc_db = null;
                }
            }
        }
        #endregion

        #region  调用生命接口推送呼损数据
        private void pushCallLossData()
        {
            // 查询AECC定时任务时间内是否存在呼损数据
            SQLHelper aecc_db = null;
            try
            {
                Log.Debug("开始查询两个定时任务时间内是否存在呼损数据");
                // 获取定时任务间隔
                double jobInterval = double.Parse(ConfigurationManager.AppSettings["interval7"]);
                DateTime nowTime = DateTime.Now.AddMilliseconds(-jobInterval);
               // 上一次定时任务时间
                string filePath = ConfigurationManager.AppSettings["lastTimeFilePath"];
                string lastTime;
                if (File.Exists(filePath))
                {
                    lastTime = File.ReadAllText(filePath);
                    Console.WriteLine("上次执行任务时间为"+lastTime);
                } else
                {
                    DateTime lastDateTime = nowTime.AddMilliseconds(-2*jobInterval);
                    lastTime = lastDateTime.ToString();
                }
                // 获取测试时间
                //DateTime lastTime = nowTime.AddYears(-3);
                aecc_db = new SQLHelper(aecc_db_string);
                DataTable dt = null;
                string sql = "";
                sql = string.Format(SQLEntity.SQL_GetCallLoss, lastTime, nowTime);
                dt = aecc_db.GetDataTable(sql);
                Log.Debug("执行SQL"+sql);
                // 判断定时任务时间段是否有呼损数据
                Log.Debug("开始查询"+lastTime+"至"+nowTime+"是否存在呼损");
                if (dt!=null&&dt.Rows.Count > 0)
                {
                    Log.Debug(lastTime + "至" + nowTime + "存在呼损" + dt.Rows.Count);
                    String url= ConfigurationManager.AppSettings["pushCallLossDataUrl"];
                    // 循环输出每一行并转换为JSON格式
                    foreach (DataRow row in dt.Rows)
                    {
                        String CIRC_CALLID = row["CIRC_CALLID"].ToString();
                        String ANI = row["ANI"].ToString();
                        String RINGING_DURATION = row["RINGING_DURATION"].ToString();
                        String WAITING_DURATION = row["WAITING_DURATION"].ToString();
                        String getUrl = $"{url}?CIRC_CALLID={CIRC_CALLID}&ANI={ANI}&RINGING_DURATION={RINGING_DURATION}&WAITING_DURATION={WAITING_DURATION}";
                        HttpGet(getUrl);
                        Log.Debug("调用接口"+getUrl);
                    }
                }
                // 持久化上次执行时间到本地
                File.WriteAllText(filePath, nowTime.ToString());
            }
            catch (Exception exp)
            {
                Log.Debug(exp);
            }
            finally
            {
                Boolean flag = aecc_db != null;
                if (flag)
                {
                    aecc_db.CloseConnection();
                    aecc_db = null;
                }
            }

        }

        // post方法调用接口
        public string HttpGet(string url)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/json";
            request.Headers["Accept-Encoding"] = "gzip,deflase";
            request.AutomaticDecompression = DecompressionMethods.GZip;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        // post方法调用接口
        public string HttpPost2(string url, string body)
        {
            //把用户传过来的数据转成“UTF-8”的字节流
            Encoding encoding = Encoding.UTF8;
            //先根据用户请求的uri构造请求地址
            //创建Web访问对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json; charset=UTF-8";
            request.Headers["Accept-Encoding"] = "gzip, deflate";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            //通过Web访问对象获取响应内容
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            }
        }

        // 将table的row转化成json字符串
        public static string ConvertToJson(DataRow row)
        {
            var dictionary = new System.Collections.Generic.Dictionary<string, object>();
            foreach (DataColumn column in row.Table.Columns)
            {
                dictionary[column.ColumnName] = row[column];
            }
            return JsonConvert.SerializeObject(dictionary);
        }
        #endregion

        #endregion

    }

    public class CityCode
    {
        public class ALL
        {
            public const string Code = "ALL";
            public const string Name = "两地";
        }

        public class SZ
        {
            public const string Code = "SZ";
            public const string Name = "深圳";
        }

        public class JN
        {
            public const string Code = "JN";
            public const string Name = "济南";
        }
    }

}
