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

namespace CallCenterApi.Interface.Controllers.report
{
    [Authority]
    public class TotalTelController : BaseController
    {
        //话务量统计

        //获取表头
        public ActionResult GetColumnList()
        {
            String[] str = getcols();
            //String[] str = { "时间", "电话呼入次数", "电话呼出次数", "正常接听次数","未接通次数", "语音留言次数", "主动放弃次数", "黑名单拒接", "平均呼入时间（秒）" };
            //String[] str = { "时间", "电话呼入次数", "电话呼出次数", "正常接听次数", "语音留言次数", "主动放弃次数", "平均呼入时间（秒）" };
            return Success("获取话务量统计表头成功", str);
        }
        private string[] getcols()
        {
            String[] str = { "时间", "电话呼入次数", "电话呼出次数", "正常呼入接听次数", "呼入未接通次数", "呼入主动放弃次数", "黑名单拒接", "平均呼入时间", "峰值排队人数", "正常呼出接听次数" };
            return str;
        }

        //获取数据
        public ActionResult GetDataList(string stime, string etime)
        {
            DataTable dtNew = new DataTable();
            dtNew = getData(stime, etime);

            var obj = new
            {
                state = "success",
                message = "获取话务量数据成功",
                rows = dtNew,
                total = dtNew.Rows.Count
            };

            return Content(obj.ToJson());
        }

        //导出数据
        public ActionResult ExptList(string stime, string etime)
        {
            NPOIHelper npoi = new NPOIHelper();
            DataTable dt = getData(stime, etime);
            if (npoi.ExportToExcel("话务量数据", dt, getcols()) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }
        }

        private DataTable getData(string stime, string etime)
        {
            DataTable dtNew = new DataTable();
            #region 编辑表头
            DataColumn dc1 = new DataColumn("时间", Type.GetType("System.String"));
            DataColumn dc2 = new DataColumn("电话呼入次数", Type.GetType("System.String"));
            DataColumn dc3 = new DataColumn("电话呼出次数", Type.GetType("System.String"));
            DataColumn dc4 = new DataColumn("正常接听次数", Type.GetType("System.String"));
            DataColumn dc5 = new DataColumn("未接通次数", Type.GetType("System.String"));
            //DataColumn dc6 = new DataColumn("语音留言次数", Type.GetType("System.String"));
            DataColumn dc7 = new DataColumn("主动放弃次数", Type.GetType("System.String"));
            DataColumn dc8 = new DataColumn("电话骚扰次数", Type.GetType("System.String"));
            DataColumn dc9 = new DataColumn("平均呼入时间", Type.GetType("System.String"));
            DataColumn dc10 = new DataColumn("峰值排队人数", Type.GetType("System.String"));
            DataColumn dc11 = new DataColumn("正常呼出接听次数", Type.GetType("System.String"));
          
            dtNew.Columns.Add(dc1);
            dtNew.Columns.Add(dc2);
            dtNew.Columns.Add(dc3);
            dtNew.Columns.Add(dc4);
            dtNew.Columns.Add(dc5);
            //dtNew.Columns.Add(dc6);
            dtNew.Columns.Add(dc7);
            dtNew.Columns.Add(dc8);
            dtNew.Columns.Add(dc9);
            dtNew.Columns.Add(dc10);
            dtNew.Columns.Add(dc11);
            #endregion

            DateTime beginTime;
            DateTime endTime;
            string sql = "";

            int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
            if (stime != null && stime != "")
                beginTime = DateTime.Parse(stime);
            else
                beginTime = DateTime.Parse(DateTime.Now.AddDays(-days).ToShortDateString());

            if (etime != null && etime != "")
                endTime = DateTime.Parse(etime );
            else
                endTime = DateTime.Parse(DateTime.Now.ToShortDateString() + " 23:59:59");


            sql += " and DATEDIFF(d,BeginTime,'" + beginTime.ToString("yyyy-MM-dd HH:mm:ss") + "')<=0";
            sql += " and DATEDIFF(d,BeginTime,'" + endTime.ToString("yyyy-MM-dd HH:mm:ss") + "')>=0";
            //  sqll += " and DATEDIFF(d,F_LeaveTime,'" + beginTime.ToString("yyyy-MM-dd HH:mm:ss") + "')<=0";
            //   sqll += " and DATEDIFF(d,F_LeaveTime,'" + endTime.ToString("yyyy-MM-dd HH:mm:ss") + "')>=0";

            var  dt = new BLL.T_Call_CallRecords().GetModelList("1=1  " + sql);


            
            int tcallincount = 0;
            int tcalloutcount = 0;
            int tcallinjtcount = 0;
            //int tlycount = 0;
            int tsrcount = 0;
            int tfqcount = 0;
            int twjtcount = 0;
            double tthsc = 0;
            for (DateTime t = beginTime; t <= endTime; t = t.AddDays(1))
            {
                string key = t.ToString("yyyy.MM.dd");
                int callincount = dt.Where(x => x.BeginTime.Value.ToString("yyyy.MM.dd") ==key  && x.CallType == 0).Count();

                //int callincount = dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and CallType=0").Length;
                int calloutcount = dt.Where(x => x.BeginTime.Value.ToString("yyyy.MM.dd") == key && x.CallType == 1).Count();
                //int calloutcount = dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and CallType=1").Length;
                int callinjtcount = dt.Where(x => x.BeginTime.Value.ToString("yyyy.MM.dd") == key && x.CallType == 0&&
              x. CallState == 1).Count();
                // int callinjtcount = dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and CallType=0 and CallState=1 ").Length;
                int callinhcjtcount = dt.Where(x => x.BeginTime.Value.ToString("yyyy.MM.dd") == key && x.CallType == 1 &&
              x.CallState == 1).Count();
                //int callinhcjtcount = dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and CallType=1 and CallState=1 ").Length;

                int srcount = dt.Where(x => x.BeginTime.Value.ToString("yyyy.MM.dd") == key && x.DealType == 1).Count();
                // int srcount = dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and DealType=1 ").Length;
                int wjtcount = dt.Where(x => x.BeginTime.Value.ToString("yyyy.MM.dd") == key && x.DealType == 1
                && (x.UserCode == "" || x.UserCode == null)).Count();
                //  int wjtcount = dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and CallState=0 and CallType=0 and isnull(usercode,'')<>'' ").Length;

                int fqcount = dt.Where(x => x.BeginTime.Value.ToString("yyyy.MM.dd") == key && x.CallState == 0
              && (x.UserCode == "" || x.UserCode == null)).Count();
                // int fqcount = dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and CallState=0 and isnull(usercode,'')='' ").Length;

                int thsc =dt.Where(x => x.BeginTime.Value.ToString("yyyy.MM.dd") == key && x.CallType == 0
              && x.CallState==1&&x.TalkLongTime !=null ).Sum (x=>x.TalkLongTime.Value  );
              //  string thsc = gettimes(dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and CallType=0 and CallState=1 "));
                

                tcallincount = tcallincount + callincount;
                tcalloutcount = tcalloutcount + calloutcount;
                tcallinjtcount = tcallinjtcount + callinjtcount;
                twjtcount = twjtcount + wjtcount;
                //tlycount = tlycount + lycount;
                tsrcount = tsrcount + srcount;
                tfqcount = tfqcount + fqcount;
                tthsc = tthsc + thsc;

                DataRow drNew = dtNew.NewRow();

                drNew["时间"] = key;
                drNew["电话呼入次数"] = callincount;
                drNew["电话呼出次数"] = calloutcount;
                drNew["正常接听次数"] = callinjtcount;
                drNew["未接通次数"] = wjtcount;
                //drNew["语音留言次数"] = lycount;
                drNew["主动放弃次数"] = fqcount;
                drNew["电话骚扰次数"] = srcount;
                drNew["正常呼出接听次数"] = callinhcjtcount;
                if ((callincount + calloutcount) > 0 && thsc > 0)
                    drNew["平均呼入时间"] = DateTimeConvert.parseTimeSeconds((int)(thsc / callinjtcount), 0);
                else
                    drNew["平均呼入时间"] = "0";

                dtNew.Rows.Add(drNew);
            }
            DataView dv = dtNew.DefaultView;
            dv.Sort = "时间 desc";
            dtNew = dv.ToTable();


            DataRow drtNew = dtNew.NewRow();

            drtNew["时间"] = "合计";
            drtNew["电话呼入次数"] = tcallincount;
            drtNew["电话呼出次数"] = tcalloutcount;
            drtNew["正常接听次数"] = tcallinjtcount;
            drtNew["未接通次数"] = twjtcount;
            //drtNew["语音留言次数"] = tlycount;
            drtNew["主动放弃次数"] = tfqcount;
            drtNew["电话骚扰次数"] = tsrcount;
            
            
            if ((tcallincount + tcalloutcount) > 0 && tthsc > 0)
                drtNew["平均呼入时间"] = DateTimeConvert.parseTimeSeconds((int)(tthsc / tcallinjtcount), 0);
            else
                drtNew["平均呼入时间"] = "0";

            dtNew.Rows.Add(drtNew);
            var dtdc = DbHelperSQL.Query("select convert(varchar(10),updatetime,120) updatetime,max(Count) sal from rep_wait_count group by convert(varchar(10),updatetime,120); ").Tables[0];
            for (int i = 0; i < dtdc.Rows.Count; i++)
            {
                var time = dtdc.Rows[i]["updatetime"];
                var sal = dtdc.Rows[i]["sal"];
                for (int j = 0; j < dtNew.Rows.Count; j++)
                {
                    var timeto = dtNew.Rows[j]["时间"].ToString().Replace(".", "-");

                    if (time.ToString() == timeto)
                    {
                        dtNew.Rows[j]["峰值排队人数"] = sal;
                    }


                }
            }
            for (int i = 0; i < dtNew.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dtNew.Rows[i]["峰值排队人数"].ToString()))
                {
                    dtNew.Rows[i]["峰值排队人数"] = "0";

                }
            }
            return dtNew;
        }

        private string gettimes(DataRow[] drs)
        {
            int thsc = 0;
            for (int i = 0; i < drs.Length; i++)
            {
                if (drs[i]["TalkLongTime"].ToString() != "")
                    thsc += int.Parse(drs[i]["TalkLongTime"].ToString());
            }
            return thsc.ToString();
        }
    }
}