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;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;

namespace CallCenterApi.Controllers.report
{
    /// <summary>
    /// 坐席满意度报表
    /// </summary>
    //[Area("hy")]
    [Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class ZuoXiManYiDuController : BaseController
    {
        public IActionResult Index()
        {
            return View();
        }

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

        //坐席满意度报表
        //获取数据
        [Authorize]
        [HttpGet("getdatalist")]
        public async Task<IActionResult> GetDataList(string stime, string endtime,string agentcode)
        {


            DataTable dtNew = new DataTable();
            dtNew = GetData(stime, endtime, agentcode).Result ;
            if (dtNew != null)
            {
                return Success("获取坐席满意度数据成功", dtNew);
            }
            else
            {
                return Error("获取坐席满意度数据失败");
            }
        }

        //获取数据源
        [HttpGet("getdata")]
        private async Task<DataTable>  GetData(string stime, string endtime,string code)
        {
            #region
            if (string.IsNullOrWhiteSpace(stime))
            {
                stime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";

            }
            if (string.IsNullOrWhiteSpace(endtime))
            {
                endtime = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";

            }
            else if (!string.IsNullOrWhiteSpace(endtime))
            {
                endtime = endtime + " 23:59:59";

            }
            #endregion

            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"));
            
            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);

            #endregion
            if (string.IsNullOrEmpty(code))
            {
                string[] AgentArr = GetAgent().Result.TrimStart('[').TrimEnd(']').Split(',');
                string[] AgentCode = GetAgentCode().Result.TrimStart('[').TrimEnd(']').Split(',');

                for (int i = 0; i < AgentArr.Length; i++)
                {
                    DataRow drNew = dtNew.NewRow();
                    string agentcode = AgentCode[i].Replace('\'', ' ').Trim();
                    drNew["坐席姓名"] = AgentArr[i].Replace('\'', ' ');
                    long tn = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    long fcmy = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.evaluation == 1 && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    drNew["非常满意"] = fcmy;
                    if (tn > 0)
                    {
                        drNew["非常满意占比"] = Math.Round(decimal.Parse(fcmy.ToString()) / decimal.Parse(tn.ToString()), 4) * 100 + "%";
                    }
                    else
                    {
                        drNew["非常满意占比"] = "0";
                    }
                    long jbmy = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.evaluation == 2 && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    drNew["基本满意"] = jbmy;
                    if (tn > 0)
                    {
                        drNew["基本满意占比"] = Math.Round(decimal.Parse(jbmy.ToString()) / decimal.Parse(tn.ToString()), 4) * 100 + "%";
                    }
                    else
                    {
                        drNew["基本满意占比"] = "0";
                    }
                    long bmy = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.evaluation == 3 && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    drNew["不满意"] = bmy;
                    if (tn > 0)
                    {
                        drNew["不满意占比"] = Math.Round(decimal.Parse(bmy.ToString()) / decimal.Parse(tn.ToString()), 4) * 100 + "%";
                    }
                    else
                    {
                        drNew["不满意占比"] = "0";
                    }
                    long wpj = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.evaluation == 0 && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    drNew["未评价"] = wpj;
                    if (tn > 0)
                    {
                        drNew["未评价占比"] = Math.Round(decimal.Parse(wpj.ToString()) / decimal.Parse(tn.ToString()), 4) * 100 + "%";
                    }
                    else
                    {
                        drNew["未评价占比"] = "0";
                    }



                    dtNew.Rows.Add(drNew);
                }
            }
            else
            {
                string agentname = "";
                string agentcode = code ;
                var list = new List<FilterDefinition<Sys_User_Account>>();
                list.Add(Builders<Sys_User_Account>.Filter.Eq("usercode", agentcode));
                list.Add(Builders<Sys_User_Account>.Filter.Eq("delete_flag", false));
                var filter = Builders<Sys_User_Account>.Filter.And(list);
                var agentlist = await _sys_user_accountRepository.GetSingle(x => x.usercode  == agentcode);
                if (agentlist != null)
                {
                    agentname = agentlist.username;
                }

                    DataRow drNew = dtNew.NewRow();
                    
                    drNew["坐席姓名"] = agentname;
                    long tn = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    long fcmy = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.evaluation == 1 && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    drNew["非常满意"] = fcmy;
                    if (tn > 0)
                    {
                        drNew["非常满意占比"] = Math.Round(decimal.Parse(fcmy.ToString()) / decimal.Parse(tn.ToString()), 4) * 100 + "%";
                    }
                    else
                    {
                        drNew["非常满意占比"] = "0";
                    }
                    long jbmy = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.evaluation == 2 && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    drNew["基本满意"] = jbmy;
                    if (tn > 0)
                    {
                        drNew["基本满意占比"] = Math.Round(decimal.Parse(jbmy.ToString()) / decimal.Parse(tn.ToString()), 4) * 100 + "%";
                    }
                    else
                    {
                        drNew["基本满意占比"] = "0";
                    }
                    long bmy = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.evaluation == 3 && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    drNew["不满意"] = bmy;
                    if (tn > 0)
                    {
                        drNew["不满意占比"] = Math.Round(decimal.Parse(bmy.ToString()) / decimal.Parse(tn.ToString()), 4) * 100 + "%";
                    }
                    else
                    {
                        drNew["不满意占比"] = "0";
                    }
                    long wpj = await _call_recordsRepository.Count(x => x.agent_code == agentcode && x.evaluation == 0 && x.begintime >= Convert.ToDateTime(stime) && x.begintime <= Convert.ToDateTime(endtime));
                    drNew["未评价"] = wpj;
                    if (tn > 0)
                    {
                        drNew["未评价占比"] = Math.Round(decimal.Parse(wpj.ToString()) / decimal.Parse(tn.ToString()), 4) * 100 + "%";
                    }
                    else
                    {
                        drNew["未评价占比"] = "0";
                    }



                    dtNew.Rows.Add(drNew);
                
            }

            return dtNew;
        }

        /// <summary>
        /// 获取坐席名称（x轴数据）
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetAgent()
        {
            string result = "[";
            #region
            var list = new List<FilterDefinition<Sys_User_Account>>();
            list.Add(Builders<Sys_User_Account>.Filter.Eq("seat_flag", true));
            list.Add(Builders<Sys_User_Account>.Filter.Eq("delete_flag", false));
            var filter = Builders<Sys_User_Account>.Filter.And(list);
            var agentlist = await _sys_user_accountRepository.Get(filter, null, null);
            if (agentlist != null)
            {
                foreach (var items in agentlist)
                {
                    result += "'" + items.username + "',";
                }
            }
            #endregion

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

        /// <summary>
        /// 获取坐席名称（x轴数据）
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetAgentCode()
        {
            string result = "[";
            #region
            var list = new List<FilterDefinition<Sys_User_Account>>();
            list.Add(Builders<Sys_User_Account>.Filter.Eq("seat_flag", true));
            list.Add(Builders<Sys_User_Account>.Filter.Eq("delete_flag", false));
            var filter = Builders<Sys_User_Account>.Filter.And(list);
            var agentlist = await _sys_user_accountRepository.Get(filter, null, null);
            if (agentlist != null)
            {
                foreach (var items in agentlist)
                {
                    result += "'" + items.usercode + "',";
                }
            }
            #endregion

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


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

                DataTable dtNew = new DataTable();
                dtNew = GetData(stime, endtime, agentcode).Result;
                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("导出成功");
        }
    }
}