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;
using SignTokenApi.IRepositories;

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

        private readonly ILogger<DaysTalkTimeController> _logger;
        private readonly ICall_RecordsRepository _call_recordsRepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        public DaysTalkTimeController(ILogger<DaysTalkTimeController> logger, ICall_RecordsRepository call_recordsRepository, ISys_User_AccountRepository sys_user_accountRepository)
        {
            _call_recordsRepository = call_recordsRepository;
            _logger = logger;
            _sys_user_accountRepository = sys_user_accountRepository;
        }


        //获取表头
        [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("获取日通话时长数据失败");
            }
        }

        //获取数据源
        [HttpGet("getdata")]
        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 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 dc9 = new DataColumn("接通总次数", Type.GetType("System.String"));
            DataColumn dc8 = new DataColumn("通话总时长", Type.GetType("System.String"));
            DataColumn dc9 = 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;
            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");

           
            
            for (DateTime t = beginTime; t <= endTime; t = t.AddDays(1))
            {
                string key = t.ToString("yyyyMMdd");
               
                string starttime = t.ToString("yyyy-MM-dd") + " 00:00:00";
                string etime= t.ToString("yyyy-MM-dd") + " 23:59:59";
                DataRow drNew = dtNew.NewRow();
                string agentcode = "";
                drNew["日期"] = key;
                string citime = GetCallRecordIn(starttime, etime, "0", "", agentcode);
                drNew["呼入次数"] = citime;// GetCallRecordIn(stime, endtime, "0", "", agentcode);
                drNew["呼入时长"] = GetCallRecordTotalTime(agentcode, starttime, etime, "0");
                //drNew["呼入未接通次数"] = GetCallRecordIn(stime, endtime, "0", "0", agentcode);
                string cotime = GetCallRecordOut(starttime, etime, "1", "", agentcode);
                drNew["呼出次数"] = cotime;//GetCallRecordOut(stime, endtime, "1", "", agentcode);
                drNew["呼出时长"] = GetCallRecordTotalTime(agentcode, starttime, etime, "1");
                drNew["呼出未接通次数"] = GetCallRecordOut(starttime, etime, "1", "0", agentcode);
                drNew["振铃时长"] = GetCallRecordRingTime(agentcode, starttime, etime);
                //drNew["接通总次数"] = GetCallRecord(stime, endtime, "", "1", agentcode);
                string ttime = GetCallRecordTotalTime(agentcode, starttime, etime, "");
                drNew["通话总时长"] = ttime;// GetCallRecordTotalTime(agentcode,stime, endtime, "");
                drNew["平均通话时长"] = GetCallAverageTime(citime, cotime, ttime);

                dtNew.Rows.Add(drNew);
            }
                

               
            return dtNew;
        }

        /// <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>
        /// 获取需要统计的数据
        /// </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");

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


           
            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 countl = _call_recordsRepository.CountAsync(filtercl);
                long callLossCount = countl.Result;
                #endregion
               

                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;
        }

        //导出
        [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>
        /// 获取坐席的呼出次数
        /// </summary>
        /// <param name="BeginTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <param name="Tag">1表示呼出，0表示呼入</param>
        /// <returns></returns>
        public string GetCallRecordOut(string BeginTime, string EndTime, string Tag, string state, string agentcode)
        {
            return GetHighChartData(BeginTime, EndTime, Tag, state, agentcode);
        }
        
       
       

        /// <summary>
        /// 获取通话平均时长
        /// </summary>
        /// <param name="BeginTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <returns></returns>
        public string GetCallAverageTime(string callintime, string callouttime, string calltotaltime)
        {
            string result = "[";

           
            double subt = 0.0;
            if (double.Parse(callintime) != 0)
            {
                subt += double.Parse(callintime);
            }
            if (double.Parse(callouttime) != 0)
            {
                subt += double.Parse(callouttime);
            }
            if (subt != 0)
                result = (double.Parse(calltotaltime) / subt).ToString("F2");
            else
                result = "0";

            return result;
        }
        /// <summary>
        /// 获取坐席的呼入次数
        /// </summary>
        /// <param name="BeginTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <returns></returns>
        public string GetCallRecordIn(string BeginTime, string EndTime, string Tag, string state, string agentcode)
        {
            return GetHighChartData(BeginTime, EndTime, Tag, state, agentcode);
        }
        /// <summary>
        /// 获取坐席的接通次数
        /// </summary>
        /// <param name="BeginTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <returns></returns>
        public string GetCallRecord(string BeginTime, string EndTime, string Tag, string state, string agentcode)
        {
            return GetHighChartData(BeginTime, EndTime, Tag, state, agentcode);
        }
       
        
        #endregion


        #region 新修改
        /// <summary>
        /// 获取通话时长
        /// </summary>
        /// <param name="agentcode"></param>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        //[HttpGet("getdata")]
        public string GetCallRecordTotalTime(string agentcode, string BeginTime, string EndTime, string tag)
        {
            var x = _call_recordsRepository.GetCallRecordTotalTime(agentcode, tag, BeginTime, EndTime).ToString();
            int i = x.IndexOf(",") + 1;
            return x.Substring(i, x.Length - i);
        }


        public string GetCallRecordRingTime(string agentcode, string BeginTime, string EndTime)
        {
            var x = _call_recordsRepository.GetCallRecordRingTime(agentcode, BeginTime, EndTime).ToString();
            int i = x.IndexOf(",") + 1;
            return x.Substring(i, x.Length - i);
        }

        private string GetHighChartData(string BeginTime, string EndTime, string tag, string state, string agentcode)
        {
            var x = _call_recordsRepository.GetHighChartData(agentcode, BeginTime, EndTime, tag, state).ToString();

            return x;
        }
        #endregion
    }
}