using System;
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 TotalCallController : BaseController
    {
        public IActionResult Index()
        {
            return View();
        }

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


        //获取图形数据
        [Authorize]
        [HttpGet("getchartdata")]
        public async Task<IActionResult> GetChartData(string years)
        {
            string[] arr = new string[12];

            //var dt = await _call_recordsRepository.Get(null);
            DateTime dtNow;

            if (string.IsNullOrEmpty(years))
            {
                dtNow = DateTime.Now;
            }
            else
            {
                dtNow = DateTime.Parse(years + "年");
            }
            for (int i = 1; i <= 12; i++)
            {
                DateTime beginTime = Convert.ToDateTime(dtNow.Year + "-" + i + "-01 00:00:00");
                int days = DateTime.DaysInMonth(dtNow.Year, beginTime.Month);
                //DataRow[] dtRow = dt.Select("begintime >='" + beginTime.ToString() + "' and  beginTime<'" + beginTime.AddDays(days).AddSeconds(-1) + "'");

                var listfilter = new List<FilterDefinition<mw_call_records>>();

                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(beginTime) >= 0 && s.begintime.CompareTo(beginTime.AddDays(days).AddSeconds(-1)) < 0));
                var filter = Builders<mw_call_records>.Filter.And(listfilter);

                var redCount = await _call_recordsRepository.CountAsync(filter);

                arr[i - 1] = redCount.ToString();

            }

            return Success("获取呼叫量图形数据成功", arr);
            
        }


        //获取数据
        [Authorize]
        [HttpGet("getdata")]
        public async Task<IActionResult> GetDataList(string years)
        {
            
                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("Count", Type.GetType("System.String"));

                dtNew.Columns.Add(dc1);
                dtNew.Columns.Add(dc2);
                dtNew.Columns.Add(dc3);
                dtNew.Columns.Add(dc4);
                #endregion
                //DataTable dt = new BLL.T_Call_CallRecords().GetList("1=1").Tables[0];
                DateTime dtNow;
                long Count = 0;
                long DayCount = 0;

                if (string.IsNullOrEmpty(years))
                {
                    dtNow = DateTime.Now;
                }
                else
                {
                    dtNow = DateTime.Parse(years + "年");
                }
                int monthcount = 0;
                for (int i = 1; i <= 12; i++)
                {
                    DataRow drNew = dtNew.NewRow();

                    DateTime beginTime = Convert.ToDateTime(dtNow.Year + "-" + i + "-01 00:00:00");
                    int days = DateTime.DaysInMonth(dtNow.Year, beginTime.Month);
                    //DataRow[] dtRow = dt.Select("begintime >='" + beginTime.ToString() + "' and  beginTime<'" + beginTime.AddDays(days).AddSeconds(-1) + "'");
                #region
                var listfilter = new List<FilterDefinition<mw_call_records>>();

                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(beginTime) >= 0 && s.begintime.CompareTo(beginTime.AddDays(days).AddSeconds(-1)) < 0));
                var filter = Builders<mw_call_records>.Filter.And(listfilter);

                var redCount = await _call_recordsRepository.CountAsync(filter);
                #endregion
                if (redCount > 0)
                    {
                        Count += redCount;
                        for (int j = 1; j <= days; j++)
                        {
                            DataRow dr1 = dtNew.NewRow();
                        #region
                        var listfilter1 = new List<FilterDefinition<mw_call_records>>();

                        listfilter1.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(beginTime.AddDays(j - 1)) >= 0 && s.begintime.CompareTo(beginTime.AddDays(j).AddSeconds(-1)) < 0));
                        var filter1 = Builders<mw_call_records>.Filter.And(listfilter1);

                        var redCount1 = await _call_recordsRepository.CountAsync(filter1);
                        #endregion
                        if (redCount1 > 0)
                            {
                                DayCount += 1;

                                dr1["月份"] = beginTime.Month + "月";
                                dr1["日期"] = beginTime.AddDays(j - 1).ToShortDateString();
                                dr1["总数"] = redCount1;
                                dr1["Count"] = "1";
                                dtNew.Rows.Add(dr1);
                            }
                        }

                        if (DayCount != 0)
                        {
                            drNew["月份"] = beginTime.Month + "月";
                            drNew["日期"] = "总计";
                            drNew["总数"] = redCount;
                            drNew["Count"] = DayCount.ToString();
                            dtNew.Rows.Add(drNew);
                        }
                        DayCount = 0;
                        monthcount += 1;
                    }
                }
                if (monthcount != 0)
                {
                    DataRow drzj = dtNew.NewRow();
                    drzj["月份"] = dtNow.Year + "年";
                    drzj["日期"] = "总计";
                    drzj["总数"] = Count;
                    drzj["Count"] = monthcount.ToString();
                    dtNew.Rows.Add(drzj);
                }

            return Success("获取呼叫量数据成功", dtNew);
            
            
        }

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

                DataTable dtNew = new DataTable();
                dtNew = GetData(years).Result;
                if (dtNew != null)
                {
                    //导出dtnew 
                    NPOIHelper npoi = new NPOIHelper();
                    string[] cols = { "月份", "日期", "总数" };
                    string[] colname = { "月份", "日期", "总数" };
                    byte[] sm = npoi.ExportToExcel1(dtNew, cols, colname);
                    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 async Task<DataTable> GetData(string years)
        {
            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("Count", Type.GetType("System.String"));

            dtNew.Columns.Add(dc1);
            dtNew.Columns.Add(dc2);
            dtNew.Columns.Add(dc3);
            dtNew.Columns.Add(dc4);
            #endregion
            //DataTable dt = new BLL.T_Call_CallRecords().GetList("1=1").Tables[0];
            DateTime dtNow;
            long Count = 0;
            long DayCount = 0;

            if (string.IsNullOrEmpty(years))
            {
                dtNow = DateTime.Now;
            }
            else
            {
                dtNow = DateTime.Parse(years + "年");
            }
            int monthcount = 0;
            for (int i = 1; i <= 12; i++)
            {
                DataRow drNew = dtNew.NewRow();

                DateTime beginTime = Convert.ToDateTime(dtNow.Year + "-" + i + "-01 00:00:00");
                int days = DateTime.DaysInMonth(dtNow.Year, beginTime.Month);
                //DataRow[] dtRow = dt.Select("begintime >='" + beginTime.ToString() + "' and  beginTime<'" + beginTime.AddDays(days).AddSeconds(-1) + "'");
                #region
                var listfilter = new List<FilterDefinition<mw_call_records>>();

                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(beginTime) >= 0 && s.begintime.CompareTo(beginTime.AddDays(days).AddSeconds(-1)) < 0));
                var filter = Builders<mw_call_records>.Filter.And(listfilter);

                var redCount = await _call_recordsRepository.CountAsync(filter);
                #endregion
                if (redCount > 0)
                {
                    Count += redCount;
                    for (int j = 1; j <= days; j++)
                    {
                        DataRow dr1 = dtNew.NewRow();
                        #region
                        var listfilter1 = new List<FilterDefinition<mw_call_records>>();

                        listfilter1.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(beginTime.AddDays(j - 1)) >= 0 && s.begintime.CompareTo(beginTime.AddDays(j).AddSeconds(-1)) < 0));
                        var filter1 = Builders<mw_call_records>.Filter.And(listfilter1);

                        var redCount1 = await _call_recordsRepository.CountAsync(filter1);
                        #endregion
                        if (redCount1 > 0)
                        {
                            DayCount += 1;

                            dr1["月份"] = beginTime.Month + "月";
                            dr1["日期"] = beginTime.AddDays(j - 1).ToShortDateString();
                            dr1["总数"] = redCount1;
                            dr1["Count"] = "1";
                            dtNew.Rows.Add(dr1);
                        }
                    }

                    if (DayCount != 0)
                    {
                        drNew["月份"] = beginTime.Month + "月";
                        drNew["日期"] = "总计";
                        drNew["总数"] = redCount;
                        drNew["Count"] = DayCount.ToString();
                        dtNew.Rows.Add(drNew);
                    }
                    DayCount = 0;
                    monthcount += 1;
                }
            }
            if (monthcount != 0)
            {
                DataRow drzj = dtNew.NewRow();
                drzj["月份"] = dtNow.Year + "年";
                drzj["日期"] = "总计";
                drzj["总数"] = Count;
                drzj["Count"] = monthcount.ToString();
                dtNew.Rows.Add(drzj);
            }

            
            return dtNew;
        }
    }
}