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

namespace CallCenterApi.Controllers
{
    /// <summary>
    /// 外呼号码
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class CallOutTelNumController : BaseController
    {
        private readonly ILogger<CallOutTelNumController> _logger;
        private readonly ICall_OutTaskRepository _call_outtaskRepository;
        private readonly ICall_ClickOutTaskTelNumRepository _call_clickouttasktelnumRepository;
        private readonly IConfiguration _configuration;
        

        public CallOutTelNumController(ILogger<CallOutTelNumController> logger,
            ICall_OutTaskRepository call_outtaskRepository,
            ICall_ClickOutTaskTelNumRepository call_clickouttasktelnumRepository,
            IConfiguration configuration)
        {
            _logger = logger;
            _call_outtaskRepository = call_outtaskRepository;
            _call_clickouttasktelnumRepository = call_clickouttasktelnumRepository;
            _configuration = configuration;
            
        }


        //点击外呼任务号码分配
        [Authorize]
        [HttpPost("fpdata")]
        public async Task<IActionResult> fpdata(string fpvalue, string[] arruser, string key)
        {
            try
            {
                if (Convert.ToInt32(fpvalue.Trim()) < 1)
                {
                    return Error("请输入分配数量！");
                }
                if (arruser == null || arruser.Length == 0)
                {
                    return Error("请选择分配坐席！");
                }
                Call_OutTask comodel = new Call_OutTask();
                var list = new List<FilterDefinition<Call_OutTask>>();
                var filterBuilder = Builders<Call_OutTask>.Filter;
                list.Add(filterBuilder.Eq("isautocall", 0));
                list.Add(filterBuilder.Eq("isstart", 1));
                list.Add(filterBuilder.Eq("deleteflag", 0));
                var filter = Builders<Call_OutTask>.Filter.And(list);
                var tt = await _call_outtaskRepository.Get(filter, null, null);
                if (tt != null)
                {
                    var listTelNum = new List<CallOutTelNumDto>();
                    foreach (var item in tt.ToList())
                    {
                        //var modelTask = new CallOutTaskDto();
                        //根据任务id查询待分配的号码
                        #region
                        Call_ClickOutTaskTelNum model = new Call_ClickOutTaskTelNum();
                        var listc = new List<FilterDefinition<Call_ClickOutTaskTelNum>>();
                        var filterBuilderc = Builders<Call_ClickOutTaskTelNum>.Filter;
                        listc.Add(filterBuilderc.Eq("taskid", item.id));
                        listc.Add(filterBuilderc.Eq("fpstate", 0));
                        listc.Add(filterBuilderc.Eq("deleteflag", 0));
                        var filterc = Builders<Call_ClickOutTaskTelNum>.Filter.And(listc);
                        var tc = await _call_clickouttasktelnumRepository.Get(filterc, null, null);
                        #endregion

                        foreach (var it in tc.ToList())
                        {
                            var modelTask = new CallOutTelNumDto();
                           
                            modelTask.id = it.id;
                            modelTask.taskid = it.taskid;
                            modelTask.cusid = it.cusid;
                            modelTask.cusname = it.cusname;
                            modelTask.cusaddr = it.cusaddr;
                            modelTask.phone = it.phone;
                            modelTask.phoneby = it.phoneby;
                            modelTask.fpstate = it.fpstate;
                            modelTask.yjstate = it.yjstate;
                            modelTask.hcstate = it.hcstate;
                            modelTask.userid = it.userid;
                            modelTask.username = it.username;
                            modelTask.createtime = it.createtime;
                            modelTask.askinfo = it.askinfo;
                            modelTask.askres = it.askres;
                            modelTask.hjjgid = it.hjjgid;
                            modelTask.hjjgname = it.hjjgname;
                            modelTask.yhfkid = it.yhfkid;
                            modelTask.yhfkname = it.yhfkname;
                            modelTask.deleteflag = item.deleteflag;

                            listTelNum.Add(modelTask);
                        }

                    }
                    if (listTelNum.Count > 0)
                    {
                        #region
                        int count = listTelNum.Count;
                        int cqcount = Convert.ToInt32(fpvalue.Trim()); //按数量平均分配
                       
                        int successcount = 0;
                        if (cqcount > 0)
                        {
                            int m = 0;
                            //int n = 0;
                            for (int i = 0; i < cqcount; i++)
                            {
                                #region 更新分配数据
                                //更新
                                if (m < cqcount)
                                {
                                    for (int n=0; n < arruser.Length; n++)
                                    {
                                        var ml = await _call_clickouttasktelnumRepository.GetSingle(listTelNum[m].id);
                                        ml.fpstate = 1;
                                        ml.userid = arruser[n];
                                        if (await _call_clickouttasktelnumRepository.Update(ml))
                                        {
                                            successcount++;
                                            m++;
                                        }
                                    }
                                   
                                }
                                else
                                {
                                    //n++;
                                    m = 0;
                                    i--;
                                }
                                #endregion
                            }
                            //cqcount--;
                        }
                        return Success("成功分配外呼计划任务" + successcount.ToString() + "条数据" + ",操作人：" + User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value);
                        #endregion
                    }
                }
               
                    return Error("外呼计划任务分配失败");
               

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "外呼计划任务分配异常");
                return Error("外呼计划任务分配失败");

            }
        }


        //点击外呼号码导入
        /// <summary>
        /// 上传文件并导入数据库
        /// </summary>
        /// <returns></returns>
        [HttpPost("importexcel")]
        public async Task<IActionResult> ImportExcel(string taskid, int headrow = 0)
        {
            if (string.IsNullOrEmpty(taskid))
                return Error("任务id不能为空");

            //string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            Microsoft.AspNetCore.Http.IFormFile _upfile = Request.Form.Files[0];
            if (!_upfile.ContentType.Equals("application/vnd.ms-excel") && !_upfile.ContentType.Equals("application/x-xls") && !_upfile.ContentType.Equals("application/x-xlsx") && !_upfile.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !_upfile.ContentType.Equals("application/octet-stream"))
                return Error($"请正确上传Excel文件：file.ContentType={_upfile.ContentType}");

            NPOIHelper npoi = new NPOIHelper();
            var dtExcel = npoi.ExcelToTable1(_upfile, headrow);
            int num = dtExcel.Rows.Count;
            var cols = dtExcel.Columns;
            int colnum = cols.Count;

            string dbkeys = _configuration["upload:acotdbkeys"].ToString();
            string[] dbcols = dbkeys.Split(",");
            string errmsg = string.Empty;

            if (num > 0)
            {
                int index = 1;
                foreach (System.Data.DataRow dr in dtExcel.Rows)
                {
                    var model = new Call_ClickOutTaskTelNum();

                    model.taskid = taskid;
                    //model.cusname = dr.cusname;
                    //model.phone = dr.phone;
                    //model.cusaddr = dr.cusaddr;
                    model.createtime = DateTime.Now.ToLocalTime();
                    model.deleteflag = 0;

                    var dbcolslist = dbcols.ToList();

                    Type t = model.GetType();
                    PropertyInfo[] PropertyList = t.GetProperties();

                    foreach (PropertyInfo item in PropertyList)
                    {
                        if (dbcolslist.Contains(item.Name))
                        {
                            object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
                            item.SetValue(model, v, null);
                        }
                    }

                    bool b = await _call_clickouttasktelnumRepository.Add(model);
                    if (!b)
                    {
                        if (!string.IsNullOrEmpty(errmsg))
                        {
                            errmsg = errmsg + "\r\n第" + index + "行导入失败！";
                        }
                        else
                        {
                            errmsg = "第" + index + "行导入失败！";
                        }
                    }
                    index++;
                }
            }
            else
            {
                return Error("文件中无数据");
            }

            if (!string.IsNullOrEmpty(errmsg))
            {
                //删除已导入的部分
                return Error(errmsg);
            }

            return Success("导入成功");
        }


        /// <summary>
        /// 清空号码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost("removeall")]
        public async Task<IActionResult> RemoveAll(string id)
        {
            Call_ClickOutTaskTelNum imodel = new Call_ClickOutTaskTelNum();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("deleteflag", "1");

            var list = new List<FilterDefinition<Call_ClickOutTaskTelNum>>();
            var filterBuilder = Builders<Call_ClickOutTaskTelNum>.Filter;
            list.Add(filterBuilder.Eq("taskid", id));
            long n = await _call_clickouttasktelnumRepository.Count(x => x.taskid == id);
            if (n > 0)
            {
                var filter = Builders<Call_ClickOutTaskTelNum>.Filter.And(list);
                var tt = await _call_clickouttasktelnumRepository.UpdateManay(imodel, dic, filter);
                if (tt)
                { return Success("点击外呼任务电话列表删除成功"); }
                else
                { return Error("点击外呼任务电话列表删除失败"); }
            }
            else
            {
                { return Error("点击外呼任务下没有可清空的电话号码"); }
            }
        }

        [Authorize]
        [HttpPost("deletetel")]
        public async Task<IActionResult> RemoveTelAsync(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _call_clickouttasktelnumRepository.GetSingle(item);
                        ml.deleteflag = 1;
                        if (await _call_clickouttasktelnumRepository.Update(ml))
                            res += 1;
                    }

                    if (res == ids.Length)
                        return Success("自动外呼号码删除成功");
                    else if (res > 0 && res < ids.Length)
                        return Error("部分外呼号码删除失败");
                    else
                        return Error("自动外呼号码删除失败");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "自动外呼号码删除异常");
                    return Error("自动外呼号码删除失败");
                }
            }
            else
                return Error("请选择要删除的记录");
        }

        //我的任务
        [Authorize]
        [HttpGet("getmytasklist")]
        public async Task<IActionResult> GetTaskListsByPageAsync(string taskid, string stime, string etime,string telnum,  int pageindex = 1, int pagesize = 10)
        {
            try
            {

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

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_ClickOutTaskTelNum>>();
                list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Eq("deleteflag", 0));
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                        list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Gt("createtime", stime));
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                        list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Lt("createtime", etime));
                }

                if (!string.IsNullOrEmpty(telnum))
                {
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.phone .Equals(telnum)));
                }

                //hjjgname
                list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.hjjgname.Contains("无人接听") || s.hjjgname.Contains("关机") || s.hjjgname.Contains("不是本人")||s.hjjgname.Equals ("")||s.hjjgname.Equals( null)));

                string agentcode =  User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; 
                list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.userid .Equals (agentcode)));

                if (!string.IsNullOrWhiteSpace(taskid))
                        list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Eq("taskid", taskid));

                    var filter = Builders<Call_ClickOutTaskTelNum>.Filter.And(list);
                    var blacklist = await _call_clickouttasktelnumRepository.GetByPage(filter, pageindex, pagesize, sort);
                    var count = await _call_clickouttasktelnumRepository.CountAsync(filter);
                    var obj = new
                    {
                        state = "success",
                        message = "根据条件获取分页数据成功",
                        rows = blacklist,
                        total = count,
                    };
                    return Content(obj.ToJson());
               
                

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取自动外呼任务号码分页数据异常");
                return Error("根据条件获取自动外呼任务号码分页数据失败");
            }
        }


        //我的任务结果
        [Authorize]
        [HttpGet("getmyresultlist")]
        public async Task<IActionResult> GetMyResultListsByPageAsync(string taskid,string hjjgid,string telnum, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            try
            {

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

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_ClickOutTaskTelNum>>();
                list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Eq("deleteflag", 0));
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                        list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Gt("createtime", stime));
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                        list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Lt("createtime", etime));
                }
                if (!string.IsNullOrEmpty(telnum))
                {
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.phone.Equals(telnum)));
                }
                if (!string.IsNullOrEmpty(hjjgid))
                {
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.hjjgid .Equals (hjjgid )));
                }
                else
                {
                    //hjjgname
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.hjjgname != null && s.hjjgname != ""));
                }
                string agentcode =  User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; 
                list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.userid.Equals(agentcode)));

                if (!string.IsNullOrWhiteSpace(taskid))
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Eq("taskid", taskid));

                var filter = Builders<Call_ClickOutTaskTelNum>.Filter.And(list);
                var blacklist = await _call_clickouttasktelnumRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _call_clickouttasktelnumRepository.CountAsync(filter);
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = blacklist,
                    total = count,
                };
                return Content(obj.ToJson());



            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取自动外呼任务号码分页数据异常");
                return Error("根据条件获取自动外呼任务号码分页数据失败");
            }
        }


        //任务结果
        //我的任务结果
        [Authorize]
        [HttpGet("getresultlist")]
        public async Task<IActionResult> GetResultListsByPageAsync(string taskid, string hjjgid,string usercode, string telnum,string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            try
            {

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

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_ClickOutTaskTelNum>>();
                list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Eq("deleteflag", 0));
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                        list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Gt("createtime", stime));
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                        list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Lt("createtime", etime));
                }
                if (!string.IsNullOrEmpty(telnum))
                {
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.phone.Equals(telnum)));
                }
                if (!string.IsNullOrEmpty(hjjgid))
                {
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.hjjgid.Equals(hjjgid)));
                }
                else
                {
                    //hjjgname
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.hjjgname != null && s.hjjgname != ""));
                }
                //string agentcode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                if (!string.IsNullOrEmpty(usercode))
                {
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.userid.Equals(usercode)));
                }

                if (!string.IsNullOrWhiteSpace(taskid))
                    list.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Eq("taskid", taskid));

                var filter = Builders<Call_ClickOutTaskTelNum>.Filter.And(list);
                var blacklist = await _call_clickouttasktelnumRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _call_clickouttasktelnumRepository.CountAsync(filter);
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = blacklist,
                    total = count,
                };
                return Content(obj.ToJson());



            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取自动外呼任务号码分页数据异常");
                return Error("根据条件获取自动外呼任务号码分页数据失败");
            }
        }


        /// <summary>
        /// 点击外呼任务电话详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getteldetails")]
        public async Task<IActionResult> GetTelDetailsAsync(string telnum, string taskid, int isautocall = -1)
        {

            var model = await _call_clickouttasktelnumRepository.GetSingle(p => p.phone == telnum && p.taskid == taskid);
            if (model == null)
                return Error("参数错误");
            var modelTask = await _call_clickouttasktelnumRepository.GetSingle(model.taskid);
            var obj = new
            {
                tasktel = model,
                task = modelTask
            };
            return Success("获取成功", obj);
        }


        //获取待分配的电话号码
        [Authorize]
        [HttpGet("getwfplistbypage")]
        public async Task<IActionResult> GetWFPListsByPageAsync(string key, int pageindex = 1, int pagesize = 10)
        {
            try
            {

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

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_OutTask>>();
                list.Add(Builders<Call_OutTask>.Filter.Eq("deleteflag", 0));               
                list.Add(Builders<Call_OutTask>.Filter.Eq("isstart", 1));               
                list.Add(Builders<Call_OutTask>.Filter.Eq("isautocall", 0));               
                list.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype.Equals (0)|| s.calltype.Equals(1)|| s.calltype.Equals(2)));

                var filter = Builders<Call_OutTask>.Filter.And(list);
                var blacklist = await _call_outtaskRepository.Get(filter,null, sort);
                int  count = 0;
                
                //新添加问卷名称page_name
                var listTask = new List<Call_ClickOutTaskTelNum>();
                foreach (var item in blacklist.ToList())
                {
                    var modelTask = new CallOutTelNumDto();
                    //根据条件查询集合
                    var list0 = new List<FilterDefinition<Call_ClickOutTaskTelNum>>();
                    list0.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Eq("deleteflag", 0));
                    list0.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Eq("fpstate", 0));
                    list0.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Eq("taskid", item.id ));
                    if(!string.IsNullOrEmpty (key))
                    {
                        list0.Add(Builders<Call_ClickOutTaskTelNum>.Filter.Where(s => s.phone .Contains (key)));
                    }
                    
                    var filter0 = Builders<Call_ClickOutTaskTelNum>.Filter.And(list0);
                    var blacklist0 = await _call_clickouttasktelnumRepository.GetByPage(filter0, pageindex, pagesize, null);
                                        
                    foreach (var item0 in blacklist0.ToList())
                    {
                        listTask.Add(item0);
                        count++;
                    }
                }

                var obj = new
                {
                    state = "success",
                    message = "根据条件获取未分配号码分页数据成功",
                    rows = listTask,
                    total = count
                };
                return Content(obj.ToJson());

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取未分配号码分页数据异常");
                return Error("根据条件获取未分配号码分页数据失败");
            }
        }

        //根据号码获取任务详情
        /// <summary>
        /// 点击外呼任务电话详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getteltaskdetails")]
        public async Task<IActionResult> GetTelTaskDetailsAsync(string id)
        {

            var model = await _call_clickouttasktelnumRepository.GetSingle(p => p.id == id );
            if (model == null)
                return Error("参数错误");
            var modelTask = await _call_outtaskRepository.GetSingle(model.taskid);
            var obj = new
            {
                pagerid=modelTask .pagerid ,
                tasktel = model,
                task = modelTask
            };
            return Success("获取成功", obj);
        }

        //点击外呼报表
        [HttpGet("gettaskreport")]
        public async Task<IActionResult> GetTaskReportByPageAsync(string taskid, string taskname, string agentid, string stime, string etime, int pageindex = 1, int pagesize = 10, int infokind = 0, int isstart = -1, int calltype = -1, int isautocall = 0)//infokind为0时默认全部数据，为1时获取当前任务，为2时历史任务
        {
            try
            {
                #region 编辑表头
                DataTable dtNew = new DataTable();
                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"));
                //DataColumn dc12 = new DataColumn("任务结束日期", Type.GetType("System.String"));
                DataColumn dc13 = 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);
                //dtNew.Columns.Add(dc12);
                dtNew.Columns.Add(dc13);
                #endregion
                #region 已结束的
                #region 查询条件
                //排序字段
                var sort = Builders<Call_OutTask>.Sort.Descending("createtime");

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_OutTask>>();
                list.Add(Builders<Call_OutTask>.Filter.Eq("deleteflag", 0));
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                        list.Add(Builders<Call_OutTask>.Filter.Gt("createtime", dt2));
                }
                else if (string.IsNullOrWhiteSpace(taskname))
                {
                    DateTime dt2 = DateTime.Now.AddDays(1 - DateTime.Now.Day);
                    //if (DateTime.TryParse(dt2 .Date  + " 00:00:00", out dt2))
                    list.Add(Builders<Call_OutTask>.Filter.Gt("createtime", dt2.ToString("yyyy-MM-dd") + " 00:00:00"));
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                        list.Add(Builders<Call_OutTask>.Filter.Lt("createtime", dt2));
                }
                else if (string.IsNullOrWhiteSpace(taskname))
                {
                    DateTime dt2 = DateTime.Now;
                    //if (DateTime.TryParse(dt2.Date + " 23:59:59", out dt2))
                    list.Add(Builders<Call_OutTask>.Filter.Lt("createtime", dt2.ToString("yyyy-MM-dd") + " 23:59:59"));
                }
                if (isstart > 0)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.isstart.Equals(isstart)));
                }
                else if (infokind == 2)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.isstart.Equals(3) || s.isstart.Equals(5)));
                }
                else if (infokind == 1)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.isstart.Equals(0) || s.isstart.Equals(1) || s.isstart.Equals(2)));
                }
                if (calltype > -1)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype.Equals(calltype)));
                }
                if (isautocall > -1)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.isautocall.Equals(isautocall)));
                }
                //模糊查询
                if (!string.IsNullOrWhiteSpace(taskid))
                    list.Add(Builders<Call_OutTask>.Filter.Eq("id", taskid));
                //list.Add(Builders<Call_OutTask>.Filter.Where(s => s.id .Contains(taskid)));
                if (!string.IsNullOrWhiteSpace(taskname))
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.taskname.Contains(taskname)));
                #endregion
                var filter = Builders<Call_OutTask>.Filter.And(list);
                var tasklist = await _call_outtaskRepository.Get(filter, null, sort);//GetByPage(filter, pageindex, pagesize, sort);
                var count = await _call_outtaskRepository.CountAsync(filter);
                List<Call_OutTask> asList = tasklist.ToList();
                if (asList != null && asList.Count > 0)
                {
                    int l = asList.Count();
                    for (int m = l; m > 0; m--)
                    {
                        DataRow dr = dtNew.NewRow();
                        #region 任务状态
                        switch (asList[m - 1].isstart)
                        {
                            case 0:
                                dr["状态"] = "未启动";
                                break;
                            case 1:
                                dr["状态"] = "已启动";
                                break;
                            case 3:
                                dr["状态"] = "处理完成";
                                break;
                            case 4:
                                dr["状态"] = "撤销";
                                break;
                            case 5:
                                dr["状态"] = "完结";
                                break;
                            default:
                                break;
                        }
                        dr["计划名称"] = asList[m - 1].taskname;
                        dr["创建时间"] = asList[m - 1].createtime.ToString() ;
                        #endregion

                        asList[m - 1].totalnum = await _call_clickouttasktelnumRepository.Count(x => x.taskid == asList[m - 1].id && x.deleteflag == 0);//任务量
                        dr["号码数量"] = asList[m - 1].totalnum;
                            asList[m - 1].successnum = await _call_clickouttasktelnumRepository.Count(x => x.taskid  == asList[m - 1].id && x.hjjgname.Equals ("正常接通"));//呼通量
                        dr["接通数量"] = asList[m - 1].successnum;
                        long an = await _call_clickouttasktelnumRepository.Count(x => x.taskid == asList[m - 1].id&&x.hjjgname!="");//已呼叫量，包括接通未接通
                        dr["已呼叫数量"] = an.ToString ();
                        asList[m - 1].surplusnum = asList[m - 1].totalnum - an;
                        dr["剩余数量"] = asList[m - 1].surplusnum;
                        asList[m - 1].callnum = asList[m - 1].totalnum - asList[m - 1].surplusnum;
                        if (an > 0)
                        {
                            decimal p = Math.Round(Convert.ToDecimal(asList[m - 1].successnum) / Convert.ToDecimal(asList[m - 1].callnum) * 100, 2);
                            asList[m - 1].successpercent = (p).ToString() + "%";
                            dr["接通率"] = asList[m - 1].successpercent;
                        }
                        else
                        {
                            asList[m - 1].successpercent = "0";
                            dr["接通率"] = "0";
                        }
                        dtNew.Rows.Add(dr);                            
                    }
                }
                
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取数据成功",
                    rows = dtNew 
                    
                };
                return Content(obj.ToJson());
                #endregion


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取数据异常");
                return Error("根据条件获取数据失败");
            }
        }

    }
}