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

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

        private readonly ILogger<TalkTimeController> _logger;
        private readonly ICall_RecordsRepository _call_recordsRepository;
        private readonly SignTokenApi.IRepositories.ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISys_ProvincesRepository _sys_provincesrepository;
        private readonly ISys_CityRepository _sys_cityrepository;
        public TalkTimeController(ILogger<TalkTimeController> logger, ICall_RecordsRepository call_recordsRepository, SignTokenApi.IRepositories.ISys_User_AccountRepository sys_user_accountRepository,
            ISys_ProvincesRepository sys_provincesrepository,
            ISys_CityRepository sys_cityrepository)
        {
            _call_recordsRepository = call_recordsRepository;
            _logger = logger;
            _sys_user_accountRepository = sys_user_accountRepository;
            _sys_provincesrepository = sys_provincesrepository;
            _sys_cityrepository = sys_cityrepository;
        }


        //获取表头
        [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)
        {
            #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"));
            DataColumn dc10 = new DataColumn("通话总时长", Type.GetType("System.String"));
            DataColumn dc11 = 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


            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('\'', ' ');
                string citime = GetCallRecordIn(stime, endtime, "0", "", agentcode);
                drNew["呼入次数"] = citime;// GetCallRecordIn(stime, endtime, "0", "", agentcode);
                drNew["呼入时长"] = GetCallRecordTotalTime(agentcode, stime, endtime, "0");
                drNew["呼入未接通次数"] = GetCallRecordIn(stime, endtime, "0", "0", agentcode);
                string cotime = GetCallRecordOut(stime, endtime, "1", "", agentcode);
                drNew["呼出次数"] = cotime;//GetCallRecordOut(stime, endtime, "1", "", agentcode);
                drNew["呼出时长"] = GetCallRecordTotalTime(agentcode, stime, endtime, "1");
                drNew["呼出未接通次数"] = GetCallRecordOut(stime, endtime, "1", "0", agentcode);
                drNew["振铃时长"] = GetCallRecordRingTime(agentcode, stime, endtime);
                drNew["接通总次数"] = GetCallRecord(stime, endtime, "", "1", agentcode);
                string ttime = GetCallRecordTotalTime(agentcode, stime, endtime, "");
                drNew["通话总时长"] = ttime;// GetCallRecordTotalTime(agentcode,stime, endtime, "");
                drNew["平均通话时长"] = GetCallAverageTime(citime, cotime, ttime);

                dtNew.Rows.Add(drNew);
            }

            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>
        /// 获取坐席的呼出次数
        /// </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>
        [HttpGet("getdataold")]
        public async Task<IActionResult> GetCallRecordTotalTimeold(string agentcode, string BeginTime, string EndTime, string tag)
        {
            string result = "[";
            /*string sql = "";

            if (BeginTime != null && BeginTime != "")
            {
                sql += " and DATEDIFF(d,BeginTime,'" + BeginTime + "')<=0";
            }
            if (EndTime != null && EndTime != "")
            {
                sql += " and DATEDIFF(d,BeginTime,'" + EndTime + "')>=0";
            }
            if (tag != "")
            {
                sql += " and CallType=" + tag;
            }

            var userAccountList = new BLL.T_Sys_UserAccount().GetModelList(" F_SeatFlag=1");
            DataTable dt = DbHelperSQL.Query("SELECT UserId,UserCode,UserName,COUNT(*) AS calloutCount,SUM(TalkLongTime) AS TalkSummaryTime FROM T_Call_CallRecords where 1=1 " + sql + "  GROUP BY UserId,UserCode,UserName").Tables[0];*/
            var x = _call_recordsRepository.GetCallRecordTotalTime("", tag, BeginTime, EndTime).ToJson();
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(x);
            #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);
            #endregion
            if (agentlist != null)
            {
                //return Success("",x);
                foreach (var item in agentlist)
                {
                    //DataRow drUser = dt.AsEnumerable().FirstOrDefault(dr => dr.Field<string>("UserName") == item.F_UserName);
                    foreach (var sitem in jo1)
                    {


                    }
                    /*if (drUser != null && drUser[4].ToString() != "")
                        result += drUser[4].ToString() + ",";
                    else
                        result += "0,";*/
                }

                result = result.TrimEnd(',');
            }
            return Success("", result + "]");
        }
        /// <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 + "]";
        }

        /// <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


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

            String[] str = { "省市", "呼入次数", "呼入时长", "呼入未接通次数", "呼出次数", "呼出时长", "呼出未接通次数", "振铃时长", "接通总次数", "通话总时长", "平均通话时长" };
            return Success("获取省市通话时长统计表头成功", str);
        }

        //根据省市统计
        //获取数据
        [Authorize]
        [HttpGet("getpcdatalist")]
        public async Task<IActionResult> GetPCDataList(string stime, string endtime, string province, string city)
        {


            DataTable dtNew = new DataTable();
            dtNew = GetPCData(stime, endtime, province,  city).Result ;
            if (dtNew != null)
            {
                return Success("获取省市通话时长数据成功", dtNew);
            }
            else
            {
                return Error("获取省市通话时长数据失败");
            }
        }

        //获取省市查询数据
        [HttpGet("getpcdata")]
        private async Task<DataTable>  GetPCData(string stime, string endtime,string province,string city)
        {
            #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"));
            DataColumn dc10 = new DataColumn("通话总时长", Type.GetType("System.String"));
            DataColumn dc11 = 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

            if (!string.IsNullOrEmpty(city))
            {
                DataRow drNew = dtNew.NewRow();
                string agentcode = "";
                drNew["省市"] = city;
                string citime = GetPCCallRecordIn(stime, endtime, "0", "", agentcode, province, city);
                drNew["呼入次数"] = citime;// GetCallRecordIn(stime, endtime, "0", "", agentcode);
                drNew["呼入时长"] = GetPCCallRecordTotalTime(agentcode, stime, endtime, "0", province, city);
                drNew["呼入未接通次数"] = GetPCCallRecordIn(stime, endtime, "0", "0", agentcode, province, city);
                string cotime = GetPCCallRecordOut(stime, endtime, "1", "", agentcode, province, city);
                drNew["呼出次数"] = cotime;//GetCallRecordOut(stime, endtime, "1", "", agentcode);
                drNew["呼出时长"] = GetPCCallRecordTotalTime(agentcode, stime, endtime, "1", province, city);
                drNew["呼出未接通次数"] = GetPCCallRecordOut(stime, endtime, "1", "0", agentcode, province, city);
                drNew["振铃时长"] = GetPCCallRecordRingTime(agentcode, stime, endtime, province, city);
                drNew["接通总次数"] = GetPCCallRecord(stime, endtime, "", "1", agentcode, province, city);
                string ttime = GetPCCallRecordTotalTime(agentcode, stime, endtime, "", province, city);
                drNew["通话总时长"] = ttime;// GetCallRecordTotalTime(agentcode,stime, endtime, "");
                drNew["平均通话时长"] = GetCallAverageTime(citime, cotime, ttime);

                dtNew.Rows.Add(drNew);
            }
            else if (!string.IsNullOrEmpty(province ))
            {
                
                var prolist =await  _sys_provincesrepository.GetSingle(x => x.provincename  == province );
                if (prolist != null)
                {
                    province = prolist.provincecode ;
                }
                string[] AgentArr = GetCity(province).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 = "";
                    string citys = AgentArr[i].Replace('\'', ' ');
                    drNew["省市"] = AgentArr[i].Replace('\'', ' ');
                    string citime = GetPCCallRecordIn(stime, endtime, "0", "", agentcode, province, citys);
                    drNew["呼入次数"] = citime;// GetCallRecordIn(stime, endtime, "0", "", agentcode);
                    drNew["呼入时长"] = GetPCCallRecordTotalTime(agentcode, stime, endtime, "0", province, citys);
                    drNew["呼入未接通次数"] = GetPCCallRecordIn(stime, endtime, "0", "0", agentcode, province, citys);
                    string cotime = GetPCCallRecordOut(stime, endtime, "1", "", agentcode, province, citys);
                    drNew["呼出次数"] = cotime;//GetCallRecordOut(stime, endtime, "1", "", agentcode);
                    drNew["呼出时长"] = GetPCCallRecordTotalTime(agentcode, stime, endtime, "1", province, citys);
                    drNew["呼出未接通次数"] = GetPCCallRecordOut(stime, endtime, "1", "0", agentcode, province, citys);
                    drNew["振铃时长"] = GetPCCallRecordRingTime(agentcode, stime, endtime, province, citys);
                    drNew["接通总次数"] = GetPCCallRecord(stime, endtime, "", "1", agentcode, province, citys);
                    string ttime = GetPCCallRecordTotalTime(agentcode, stime, endtime, "", province, citys);
                    drNew["通话总时长"] = ttime;// GetCallRecordTotalTime(agentcode,stime, endtime, "");
                    drNew["平均通话时长"] = GetCallAverageTime(citime, cotime, ttime);

                    dtNew.Rows.Add(drNew);
                }
            }
            else
            {
                //string[] AgentArr = GetAgent().Result.TrimStart('[').TrimEnd(']').Split(',');
                //string[] AgentCode = GetAgentCode().Result.TrimStart('[').TrimEnd(']').Split(',');
                string[] AgentArr = GetProvince().Result.TrimStart('[').TrimEnd(']').Split(',');
                for (int i = 0; i < AgentArr.Length; i++)
                {
                    DataRow drNew = dtNew.NewRow();
                    string agentcode = "";
                    string provinces= AgentArr[i].Replace('\'', ' ');
                    drNew["省市"] = AgentArr[i].Replace('\'', ' ');
                    string citime = GetPCCallRecordIn(stime, endtime, "0", "", agentcode, provinces, city);
                    drNew["呼入次数"] = citime;// GetCallRecordIn(stime, endtime, "0", "", agentcode);
                    drNew["呼入时长"] = GetPCCallRecordTotalTime(agentcode, stime, endtime, "0", provinces, city);
                    drNew["呼入未接通次数"] = GetPCCallRecordIn(stime, endtime, "0", "0", agentcode, provinces, city);
                    string cotime = GetPCCallRecordOut(stime, endtime, "1", "", agentcode, provinces, city);
                    drNew["呼出次数"] = cotime;//GetCallRecordOut(stime, endtime, "1", "", agentcode);
                    drNew["呼出时长"] = GetPCCallRecordTotalTime(agentcode, stime, endtime, "1", provinces, city);
                    drNew["呼出未接通次数"] = GetPCCallRecordOut(stime, endtime, "1", "0", agentcode, provinces, city);
                    drNew["振铃时长"] = GetPCCallRecordRingTime(agentcode, stime, endtime, provinces, city);
                    drNew["接通总次数"] = GetPCCallRecord(stime, endtime, "", "1", agentcode, provinces, city);
                    string ttime = GetPCCallRecordTotalTime(agentcode, stime, endtime, "", provinces, city);
                    drNew["通话总时长"] = ttime;// GetCallRecordTotalTime(agentcode,stime, endtime, "");
                    drNew["平均通话时长"] = GetCallAverageTime(citime, cotime, ttime);

                    dtNew.Rows.Add(drNew);
                }
            }

            return dtNew;
        }

        #region
        /// <summary>
        /// 获取坐席的呼出次数
        /// </summary>
        /// <param name="BeginTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <param name="Tag">1表示呼出，0表示呼入</param>
        /// <returns></returns>
        public string GetPCCallRecordOut(string BeginTime, string EndTime, string Tag, string state, string agentcode, string province, string city)
        {
            return GetPCHighChartData(BeginTime, EndTime, Tag, state, agentcode, province, city);
        }

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


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

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

            return x;
        }

        /// <summary>
        /// 获取坐席的呼入次数
        /// </summary>
        /// <param name="BeginTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <returns></returns>
        public string GetPCCallRecordIn(string BeginTime, string EndTime, string Tag, string state, string agentcode, string province, string city)
        {
            return GetPCHighChartData(BeginTime, EndTime, Tag, state, agentcode, province, city);
        }
        /// <summary>
        /// 获取坐席的接通次数
        /// </summary>
        /// <param name="BeginTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <returns></returns>
        public string GetPCCallRecord(string BeginTime, string EndTime, string Tag, string state, string agentcode, string province, string city)
        {
            return GetPCHighChartData(BeginTime, EndTime, Tag, state, agentcode, province, city);
        }

        /// <summary>
        /// 获取省
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetProvince()
        {
            string result = "[";
            #region
            var agentlist = await _sys_provincesrepository.GetAll();
            if (agentlist != null)
            {
                foreach (var items in agentlist)
                {
                    result += "'" + items.provincename + "',";
                }
            }
            #endregion

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

        /// <summary>
        /// 获取市
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetCity(string provincecode)
        {
            string result = "[";
            #region

            if (!string.IsNullOrEmpty(provincecode))
            {
                var list = new List<FilterDefinition<Sys_City>>();

                list.Add(Builders<Sys_City>.Filter.Eq("provincecode", provincecode));

                var filter = Builders<Sys_City>.Filter.And(list);

                var agentlist = await _sys_cityrepository.Get(filter);
                if (agentlist != null)
                {
                    foreach (var items in agentlist)
                    {
                        result += "'" + items.cityname + "',";
                    }
                }
            }
            else
            {
                var agentlist = await _sys_cityrepository.GetAll();
                if (agentlist != null)
                {
                    foreach (var items in agentlist)
                    {
                        result += "'" + items.cityname + "',";
                    }
                }
            }
            #endregion

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

        //导出
        [Authorize]
        [HttpGet("exportpcexcel")]
        [AllowAnonymous]
        public async Task<IActionResult> ExportPCExcelAsync(string stime, string endtime, string province, string city)
        {
            try
            {

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