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

namespace CallCenterApi.Controllers.report
{
    /// <summary>
    /// 呼叫数据图形分析
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class YearContrastController : BaseController
    {
        public IActionResult Index()
        {
            return View();
        }

        private readonly ILogger<YearContrastController> _logger;
        private readonly ICall_RecordsRepository _call_recordsRepository;

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

        //呼叫数据对比
        [Authorize]
        [HttpGet("getdatalist")]
        public async Task<IActionResult> GetDataList(string beginyear, string endyear)
        {
            
            ArrayList arrlist = new ArrayList();

            if (beginyear != null && beginyear.Trim() != "")
            {
                var x = GetKhCall(beginyear);
                var data = new
                {
                    key = beginyear + "客户呼叫数",
                    value = x.Result.TrimEnd(',').Split(','),
                    type = 0
                };
                arrlist.Add(data);

                var y = GetZxJt(beginyear);
                var data1 = new
                {
                    key = beginyear + "坐席接听数",
                    value = y.Result .TrimEnd(',').Split(','),
                    type = 0
                };
                arrlist.Add(data1);
                var z = GetJTL(beginyear);
                var data2 = new
                {
                    key = beginyear + "接通率",
                    value = z.Result .TrimEnd(',').Split(','),
                    type = 0
                };
                arrlist.Add(data2);
            }
            if (endyear != null && endyear.Trim() != "")
            {
                var x = GetKhCall(endyear);
                var data = new
                {
                    key = endyear + "客户呼叫数",
                    value = x.Result .TrimEnd(',').Split(','),
                    type = 1
                };
                arrlist.Add(data);
                var y = GetZxJt(endyear);
                var data1 = new
                {
                    key = endyear + "坐席接听数",
                    value = y.Result .TrimEnd(',').Split(','),
                    type = 1
                };
                arrlist.Add(data1);
                var z = GetJTL(endyear);
                var data2 = new
                {
                    key = endyear + "接通率",
                    value = z.Result .TrimEnd(',').Split(','),
                    type = 1
                };
                arrlist.Add(data2);
            }
            if (arrlist != null && arrlist.Count > 0)
            {
                return Success("获取呼叫数据分析数据成功", arrlist);
            }
            else
            {
                return Error("获取呼叫数据分析数据失败");
            }
            
        }


        [Authorize]
        [HttpGet("exportexcel")]
        [AllowAnonymous]
        public async Task<IActionResult> ExportExcelAsync(string beginyear, string endyear)
        {
            try
            {

                DataTable dtNew = new DataTable();
                dtNew = GetData(beginyear, endyear);
                if (dtNew != null)
                {
                    //导出dtnew 
                    NPOIHelper npoi = new NPOIHelper();
                    //string[] cols = { "日期", "接通次数", "呼损次数", "接通率", "呼损率" };

                    byte[] sm = npoi.ExportToExcel1(dtNew, null );
                    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("导出成功");
        }

        private DataTable GetData(string beginyear, string endyear)
        {
            DataTable dtNew = new DataTable();
            if ((beginyear != null && beginyear.Trim() != "") && (endyear != null && endyear.Trim() != ""))
            {
                #region 编辑表头
                DataColumn dc1 = new DataColumn("月份", Type.GetType("System.String"));
                DataColumn dc2 = new DataColumn(beginyear + "年客户呼叫数", Type.GetType("System.String"));
                DataColumn dc3 = new DataColumn(beginyear + "年坐席接听数", Type.GetType("System.String"));
                DataColumn dc4 = new DataColumn(beginyear + "年坐席接听率", Type.GetType("System.String"));
                DataColumn dc5 = new DataColumn(endyear + "年客户呼叫数", Type.GetType("System.String"));
                DataColumn dc6 = new DataColumn(endyear + "年坐席接听数", Type.GetType("System.String"));
                DataColumn dc7 = new DataColumn(endyear + "年坐席接听率", 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);
                #endregion
                string[] bkhcall = GetKhCall(beginyear).Result .Split(',');
                string[] bzxjt = GetZxJt(beginyear).Result.Split(',');
                string[] bjtl = GetJTL(beginyear).Result.Split(',');

                string[] ekhcall = GetKhCall(endyear).Result.Split(',');
                string[] ezxjt = GetZxJt(endyear).Result.Split(',');
                string[] ejtl = GetJTL(endyear).Result.Split(',');

                for (int i = 0; i < 12; i++)
                {
                    DataRow drNew = dtNew.NewRow();
                    drNew["月份"] = (i + 1).ToString() + "月";
                    drNew[beginyear + "年客户呼叫数"] = bkhcall[i];
                    drNew[beginyear + "年坐席接听数"] = bzxjt[i];
                    drNew[beginyear + "年坐席接听率"] = bjtl[i];
                    drNew[endyear + "年客户呼叫数"] = ekhcall[i];
                    drNew[endyear + "年坐席接听数"] = ezxjt[i];
                    drNew[endyear + "年坐席接听率"] = ejtl[i];
                    dtNew.Rows.Add(drNew);
                }
            }

            return dtNew;
        }

        #region 通话记录表读取
        //客户呼叫数
        private async  Task<string > GetKhCall(string strtime)
        {
            string str = "";
            for (int i = 1; i <= 12; i++)
            {                
                string strmm = i.ToString();
                if (i <= 9)
                {
                    strmm = "0" + i;
                }               
                var listfilter = new List<FilterDefinition<mw_call_records>>();
                if (strtime != "")
                {
                    //listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(strtime + "-" + strmm + "-01 00:00:01")) >= 0 && s.begintime.CompareTo(DateTime.Parse(strtime + "-" + strmm + "-31 00:00:01")) < 0));
                    DateTime beginTime = Convert.ToDateTime(strtime + "-" + i + "-01 00:00:00");
                    int days = DateTime.DaysInMonth(beginTime.Year, beginTime.Month);
                    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(beginTime) >= 0 && s.begintime.CompareTo(beginTime.AddDays(days).AddSeconds(-1)) < 0));
                }
                listfilter.Add(Builders<mw_call_records>.Filter.Eq("calltype", 0));
                var filter = Builders<mw_call_records>.Filter.And(listfilter);

                var count = await _call_recordsRepository.CountAsync(filter);
               
                str += count.ToString() + ",";
            }
            if (str != "")
            {
                str.TrimEnd(',');
            }
            return str;
        }

        //坐席接听数
        private async Task<string> GetZxJt(string strtime)
        {
            string str = "";
            for (int i = 1; i <= 12; i++)
            {
                
                string strmm = i.ToString();
                if (i <= 9)
                {
                    strmm = "0" + i;
                }
                
                var listfilter = new List<FilterDefinition<mw_call_records>>();
                if (strtime != "")
                {
                    //listfilter.Add(Builders<mw_call_records>.Filter.Gt("begintime", DateTime.Parse(strtime + "-" + strmm + "-01 00:00:01")));
                    //listfilter.Add(Builders<mw_call_records>.Filter.Lt("begintime", DateTime.Parse(strtime + "-" + strmm + "-31 23:59:59")));
                    //listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(strtime + "-" + strmm + "-01 00:00:01")) >= 0 ));
                    //listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(strtime + "-" + strmm + "-31 23:59:59")) < 0));
                    DateTime beginTime = Convert.ToDateTime(strtime + "-" + i + "-01 00:00:00");
                    int days = DateTime.DaysInMonth(beginTime.Year, beginTime.Month);
                    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(beginTime) >= 0 && s.begintime.CompareTo(beginTime.AddDays(days).AddSeconds(-1)) < 0));
                }
                listfilter.Add(Builders<mw_call_records>.Filter.Eq("calltype", 0));
                listfilter.Add(Builders<mw_call_records>.Filter.Eq("callstate", 1));
                listfilter.Add(Builders<mw_call_records>.Filter.Eq("dealtype", 6));
                var filter = Builders<mw_call_records>.Filter.And(listfilter);

                var count = await _call_recordsRepository.CountAsync(filter);

                
                str += count.ToString() + ",";

            }
            if (str != "")
            {
                str.TrimEnd(',');
            }
            return str;
        }

        //坐席接听率
        private async Task<string> GetJTL(string strtime)
        {
            
            string str = "";
            for (int i = 1; i <= 12; i++)
            {
                string sqltimeCallRecords = "";
                string strmm = i.ToString();
                if (i <= 9)
                {
                    strmm = "0" + i;
                }
                //if (strtime != "")
                //{
                //    sqltimeCallRecords += " and CONVERT(varchar , begintime, 120)>=CONVERT(varchar , '" + strtime + "-" + strmm + "-01 00:00:01', 120) ";
                //    sqltimeCallRecords += " and CONVERT(varchar , begintime, 120)<=CONVERT(varchar , '" + strtime + "-" + strmm + "-31 23:59:59', 120) ";
                //}

                var listfilter0 = new List<FilterDefinition<mw_call_records>>();
                if (strtime != "")
                {
                    //listfilter0.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(strtime + "-" + strmm + "-01 00:00:01")) >= 0 && s.begintime.CompareTo(DateTime.Parse(strtime + "-" + strmm + "-31 23:59:59")) < 0));
                    DateTime beginTime = Convert.ToDateTime(strtime + "-" + i + "-01 00:00:00");
                    int days = DateTime.DaysInMonth(beginTime.Year, beginTime.Month);
                    listfilter0.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(beginTime) >= 0 && s.begintime.CompareTo(beginTime.AddDays(days).AddSeconds(-1)) < 0));
                }
                listfilter0.Add(Builders<mw_call_records>.Filter.Eq("calltype", 0));
                var filter0 = Builders<mw_call_records>.Filter.And(listfilter0);

                var count = await _call_recordsRepository.CountAsync(filter0);


                var listfilter = new List<FilterDefinition<mw_call_records>>();
                if (strtime != "")
                {
                    //listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(strtime + "-" + strmm + "-01 00:00:01")) >= 0 && s.begintime.CompareTo(DateTime.Parse(strtime + "-" + strmm + "-31 23:59:59")) < 0));
                    DateTime beginTime = Convert.ToDateTime(strtime + "-" + i + "-01 00:00:00");
                    int days = DateTime.DaysInMonth(beginTime.Year, beginTime.Month);
                    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(beginTime) >= 0 && s.begintime.CompareTo(beginTime.AddDays(days).AddSeconds(-1)) < 0));
                }
                listfilter.Add(Builders<mw_call_records>.Filter.Eq("calltype", 0));
                listfilter.Add(Builders<mw_call_records>.Filter.Eq("callstate", 1));
                listfilter.Add(Builders<mw_call_records>.Filter.Eq("dealtype", 6));
                var filter = Builders<mw_call_records>.Filter.And(listfilter);

                var jtcount = await _call_recordsRepository.CountAsync(filter);


                double ibgnjtl = 0.00;
                if (count > 0)
                {
                    ibgnjtl = jtcount / double.Parse(count.ToString());
                    str += (ibgnjtl * 100).ToString("0.00") + ",";
                }
                else
                {
                    str += "0.00,";
                }

            }
            if (str != "")
            {
                str.TrimEnd(',');
            }
            return str;
        }
        #endregion
    }
}