using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using CallCenterApi.IRepositories;
using MadRunFabric.Common;
using MadRunFabric.Model.CallCenterApi;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;

namespace CallCenterApi.Controllers.report
{
    /// <summary>
    /// 通话时长统计
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SwitchedlossCallController : BaseController
    {
        public IActionResult Index()
        {
            return View();
        }

        private readonly ILogger<SwitchedlossCallController> _logger;
        private readonly ICall_RecordsRepository _call_recordsRepository;
        
        public SwitchedlossCallController(ILogger<SwitchedlossCallController> logger, ICall_RecordsRepository call_recordsRepository)
        {
            _call_recordsRepository = call_recordsRepository;
            _logger = logger;
            
        }

        //获取表头
        [Authorize]
        [HttpGet("getcolumnlist")]
        public async Task<IActionResult> GetColumnList()
        {

            String[] str = { "日期", "接通次数", "呼损次数", "接通率", "呼损率" };
            return Success("获取接通呼损统计表头成功", str);
        }

        //获取数据
        [Authorize]
        [HttpGet("getdatalist")]
        public async Task<IActionResult> GetDataList(string stime, string endtime)
        {


            DataTable dtNew = new DataTable();
            dtNew = GetData(stime, endtime);
            if (dtNew != null)
            {
                return Success("获取接通呼损统计数据成功", dtNew);
            }
            else
            {
                return Error("获取接通呼损统计数据失败");
            }
        }

        //获取数据源
        private DataTable GetData(string stime, string endtime)
        {
            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"));

            dtNew.Columns.Add(dc1);
            dtNew.Columns.Add(dc2);
            dtNew.Columns.Add(dc3);
            dtNew.Columns.Add(dc4);
            dtNew.Columns.Add(dc5);
            #endregion
            string[] DataArr = GetStatisticalTime(stime, endtime).TrimStart('[').TrimEnd(']').Split(',');
            string[] CallConnectData = GetStatisticalCallConnectData(stime, endtime).TrimStart('[').TrimEnd(']').Split(',');
            string[] CallLossData = GetStatisticalCallLossData(stime, endtime).TrimStart('[').TrimEnd(']').Split(',');
            string[] CallConnectDataRate = GetStatisticalCallConnectDataRate(stime, endtime).TrimStart('[').TrimEnd(']').Split(',');
            string[] CallLossDataRate = GetStatisticalCallLossDataRate(stime, endtime).TrimStart('[').TrimEnd(']').Split(',');

            for (int i = 0; i < DataArr.Length; i++)
            {
                DataRow drNew = dtNew.NewRow();

                drNew["日期"] = DataArr[i];
                drNew["接通次数"] = CallConnectData[i];
                drNew["呼损次数"] = CallLossData[i];
                drNew["接通率"] = CallConnectDataRate[i];
                drNew["呼损率"] = CallLossDataRate[i];

                dtNew.Rows.Add(drNew);
            }
            dtNew.DefaultView.Sort = "日期 ASC";

            dtNew = dtNew.DefaultView.ToTable();
            return dtNew;
        }

        //导出
        [Authorize]
        [HttpGet("exportexcel")]
        [AllowAnonymous]
        public async Task<IActionResult> ExportExcelAsync(string stime, string endtime)
        {
            try
            {

                DataTable dtNew = new DataTable();
                dtNew = GetData(stime, endtime);
                if (dtNew != null)
                {
                    //导出dtnew 
                    NPOIHelper npoi = new NPOIHelper();
                    string[] cols = { "日期", "接通次数", "呼损次数", "接通率", "呼损率" };
                    
                    byte[] sm = npoi.ExportToExcel1(dtNew, cols);
                    if (sm != null)
                    {
                        return File(sm, "application/vnd.ms-excel", "接通呼损统计.xlsx");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                return Error("导出失败");

                //return Success("根据条件获取数据成功", tasklist);

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出异常");
                return Error("导出失败");
            }
            //return Success("导出成功");
        }

        #region
        /// <summary>
        /// 获取highcharts统计中的时间轴坐标
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public string GetStatisticalTime(string BeginTime, string EndTime)
        {
            string result = "[";

            foreach (DictionaryEntry item in GetStatistical(BeginTime, EndTime))
            {
                //result = (JTHS)item.Value.ToString();
                result += item.Key.ToString().TrimStart('{').TrimEnd('}') + ",";
            }

            result = result.TrimEnd(',');
            return result + "]";
        }
        /// <summary>
        /// 获取highcharts统计中的接通次数的数据
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public string GetStatisticalCallConnectData(string BeginTime, string EndTime)
        {
            string result = "[";

            foreach (DictionaryEntry item in GetStatistical(BeginTime, EndTime))
            {
                result += ((JTHS)item.Value).CallConnectCount + ",";
            }

            result = result.TrimEnd(',');
            return result + "]";
        }
        /// <summary>
        /// 获取highcharts统计中呼损次数的数据
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public string GetStatisticalCallLossData(string BeginTime, string EndTime)
        {
            string result = "[";

            foreach (DictionaryEntry item in GetStatistical(BeginTime, EndTime))
            {
                result += ((JTHS)item.Value).CallLossCount + ",";
            }

            result = result.TrimEnd(',');
            return result + "]";
        }
        /// <summary>
        /// 获取highcharts统计中接通率数据
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public string GetStatisticalCallConnectDataRate(string BeginTime, string EndTime)
        {
            string result = "[";

            foreach (DictionaryEntry item in GetStatistical(BeginTime, EndTime))
            {
                result += ((JTHS)item.Value).CallConnectRate.ToString("F2") + ",";
            }

            result = result.TrimEnd(',');
            return result + "]";
        }

        /// <summary>
        /// 获取highcharts统计中呼损率数据
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public string GetStatisticalCallLossDataRate(string BeginTime, string EndTime)
        {
            string result = "[";

            foreach (DictionaryEntry item in GetStatistical(BeginTime, EndTime))
            {
                result += ((JTHS)item.Value).CallLossRate.ToString("F2") + ",";
            }

            result = result.TrimEnd(',');
            return result + "]";
        }
        /// <summary>
        /// 获取需要统计的数据
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public Hashtable GetStatistical(string stime, string endtime)
        {
            Hashtable tab = new Hashtable();


            DateTime beginTime;
            DateTime endTime;
            string sql = "";
            Dictionary<string, JTHS> myDic = new Dictionary<string, JTHS>();
            JTHS model = null;
            double callConnectRate = 0, callLossRate = 0;

            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 (endtime != null && endtime != "")
                endTime = DateTime.Parse(endtime + " 23:59:59");
            else
                endTime = DateTime.Parse(DateTime.Now.ToShortDateString() + " 23:59:59");

            #region
            //排序字段
            var sort = Builders<mw_call_records>.Sort.Descending("begintime");

            
            //listcc.Add(Builders<mw_call_records>.Filter.Eq("deleteflag", 0));
            //listcl.Add(Builders<mw_call_records>.Filter.Eq("deleteflag", 0));
            //if (!string.IsNullOrWhiteSpace(stime))
            //{
            //    DateTime dt2 = new DateTime();
            //    if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
            //    {
            //        listcc.Add(Builders<mw_call_records>.Filter.Gt("begintime", dt2));
            //        listcl.Add(Builders<mw_call_records>.Filter.Gt("begintime", dt2));
            //    }
            //}

            //if (!string.IsNullOrWhiteSpace(endtime))
            //{
            //    DateTime dt2 = new DateTime();
            //    if (DateTime.TryParse(endtime.Trim(), out dt2))
            //    {
            //        listcc.Add(Builders<mw_call_records>.Filter.Lt("begintime", dt2));
            //        listcl.Add(Builders<mw_call_records>.Filter.Lt("begintime", dt2));
            //    }
            //}
            #endregion

            //DataTable dt = new BLL.T_Call_CallRecords().GetList("1=1 and calltype=0" + sql).Tables[0]; //BusinessType=0代表ivr中选择了转人工,calltype=1代表呼入



            for (DateTime t = beginTime; t <= endTime; t = t.AddDays(1))
            {
                string key = t.ToString("{yyyyMMdd}");
                //根据条件查询集合
                var listcc = new List<FilterDefinition<mw_call_records>>();
                var listcl = new List<FilterDefinition<mw_call_records>>();
                #region

                listcc.Add(Builders<mw_call_records>.Filter.Eq("callstate", 1));
                listcc.Add(Builders<mw_call_records>.Filter.Gt("begintime", t.ToString ("yyyy-MM-dd") +" 00:00:00"));
                listcc.Add(Builders<mw_call_records>.Filter.Lt("begintime", t.ToString("yyyy-MM-dd") + " 23:59:59"));

                listcc.Add(Builders<mw_call_records>.Filter.Where(s => !s.dealtype.Equals(1)));// || s.dealtype.Equals(2) || s.dealtype.Equals(3) || s.dealtype.Equals(4) || s.dealtype.Equals(5) || s.dealtype.Equals(6)
                var filtercc = Builders<mw_call_records>.Filter.And(listcc);
                //var tasklist = await _call_recordsRepository.Get(filter);//, pageindex, pagesize, sort);
                var count =  _call_recordsRepository.CountAsync(filtercc);
                long  callConnectCount = count.Result;
                #endregion

                #region

                listcl.Add(Builders<mw_call_records>.Filter.Eq("callstate", 0));
                listcl.Add(Builders<mw_call_records>.Filter.Gt("begintime", t.ToString("yyyy-MM-dd") + " 00:00:00"));
                listcl.Add(Builders<mw_call_records>.Filter.Lt("begintime", t.ToString("yyyy-MM-dd") + " 23:59:59"));

                listcl.Add(Builders<mw_call_records>.Filter.Where(s => s.dealtype.Equals(5) ));
                var filtercl = Builders<mw_call_records>.Filter.And(listcl);
                //var tasklist = await _call_recordsRepository.Get(filter);//, pageindex, pagesize, sort);
                var countl = _call_recordsRepository.CountAsync(filtercl);
                long callLossCount = countl.Result;
                #endregion
                //int callConnectCount = dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and CallState=1 and dealtype<>1").Length;
                //int callLossCount = dt.Select("begintime >='" + t.ToString() + "' and begintime<'" + t.AddDays(1).ToString() + "' and CallState=0 and dealtype=5").Length;

                if ((callConnectCount + callLossCount) != 0)
                {
                    callConnectRate = (callConnectCount + callLossCount) == 0 ? 0 : double.Parse((callConnectCount * 100).ToString()) / (callConnectCount + callLossCount);
                    callLossRate = 100 - callConnectRate;
                }
                else
                {
                    callConnectRate = 0;
                    callLossRate = 0;
                }

                if (!myDic.ContainsKey(key))
                {
                    model = new JTHS();
                    model.CallConnectCount = callConnectCount;
                    model.CallLossCount = callLossCount;
                    model.CallConnectRate = callConnectRate;
                    model.CallLossRate = callLossRate;

                    tab.Add(key, model);
                }
            }
            return tab;
        }
        #endregion
    }

    /// <summary>
    /// 接通呼损率统计辅助类
    /// </summary>
    [Serializable]
    public class JTHS
    {
        public long CallConnectCount
        {
            get;
            set;
        }
        public long CallLossCount
        {
            get;
            set;
        }
        public double CallConnectRate
        {
            get;
            set;
        }
        public double CallLossRate
        {
            get;
            set;
        }
    }
}