using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CallCenterApi.IRepositories;
using MadRunFabric.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MadRunFabric.Common;
using MongoDB.Driver;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using MadRunFabric.Model.CallCenterApi;
using AutoMapper;
using Microsoft.Extensions.Configuration;
using System.Data;
using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using OfficeOpenXml;
using MadRunFabric.Common.Helpers;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CallCenterApi.Dto;

namespace CallCenterApi.Controllers.autocallout
{
    /// <summary>
    /// 自动外呼任务
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class AutoCallOutTaskController : BaseController
    {
        private readonly ILogger<AutoCallOutTaskController> _logger;
        private readonly ICall_OutTaskRepository _call_outtaskRepository;
        private readonly ICall_OutTaskTelNumRepository _call_outtasktelnumRepository;
        private readonly IConfiguration _configuration;
        private readonly ICall_OutTaskFPRepository _call_outtaskfpRepository;
        private readonly IMW_Autocall_Call_RecordRepository _mw_autocall_call_recordRepository;
        private readonly ICall_OutTaskTelNumRecordRepository _call_outtasktelnumrecordRepository;
        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly ISys_SystemConfigRepository _sys_systemconfigRepository;
        private readonly IAsk_QuestionPagerRepository _ask_questionpagerRepository;
        private readonly ICall_ClickOutTaskTelNumRepository _call_clickouttasktelnumRepository;
        private readonly ICall_AutoCallNumRepository _call_autocallnumRepository;
        private readonly ICall_MobileDataRepository _call_mobiledataRepository;

        public AutoCallOutTaskController(ILogger<AutoCallOutTaskController> logger, 
            ICall_OutTaskRepository call_outtaskRepository, 
            ICall_OutTaskTelNumRepository call_outtasktelnumRepository, 
            IConfiguration configuration, 
            ICall_OutTaskFPRepository call_outtaskfpRepository, 
            IMW_Autocall_Call_RecordRepository mw_autocall_call_recordRepository,
            ICall_OutTaskTelNumRecordRepository call_outtasktelnumrecordRepository, 
            IHostingEnvironment hostingEnvironment, 
            ISys_SystemConfigRepository sys_systemconfigRepository,
            IAsk_QuestionPagerRepository ask_questionpagerRepository,
            ICall_AutoCallNumRepository call_autocallnumRepository,
            ICall_MobileDataRepository call_mobiledataRepository,
            ICall_ClickOutTaskTelNumRepository call_clickouttasktelnumRepository)
        {
            _logger = logger;
            _call_outtaskRepository = call_outtaskRepository;
            _call_outtasktelnumRepository = call_outtasktelnumRepository;
            _configuration = configuration;
            _call_outtaskfpRepository = call_outtaskfpRepository;
            _mw_autocall_call_recordRepository = mw_autocall_call_recordRepository;
            _call_outtasktelnumrecordRepository = call_outtasktelnumrecordRepository;
            _hostingEnvironment = hostingEnvironment;
            _sys_systemconfigRepository = sys_systemconfigRepository;
            _ask_questionpagerRepository = ask_questionpagerRepository;
            _call_clickouttasktelnumRepository = call_clickouttasktelnumRepository;
            _call_mobiledataRepository = call_mobiledataRepository;
            _call_autocallnumRepository = call_autocallnumRepository;
        }

        public IActionResult Index()
        {
            return View();
        }

        #region 外呼 - 外呼任务（计划）
        [Authorize]
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListsAsync(string key, string stime, string etime,int calltype=-1,int isautocall=1)
        {
            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));
                if (stime != null)
                    list.Add(Builders<Call_OutTask>.Filter.Gt("createtime", stime));
                if (etime != null)
                    list.Add(Builders<Call_OutTask>.Filter.Lt("createtime", etime));
                if (key != null)
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.taskname.Contains(key)));
                //2019-6-10
                if (isautocall > -1)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Eq("isautocall", isautocall));
                }

                if (calltype > 0)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Eq("calltype", calltype));
                }
                else
                {
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype!=3));
                }

                var filter = Builders<Call_OutTask>.Filter.And(list);
                var tasklist = await _call_outtaskRepository.Get(filter, null, sort);

                return Success("根据条件获取数据成功", tasklist);

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

        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string key, string stime, string etime, int taskstate = -1, int isallot = -1, int isautocall = 1,int calltype=-1, 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));
                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", stime));
                }
                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", etime));
                }

                //模糊查询
                if (!string.IsNullOrWhiteSpace(key))
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.taskname.Contains(key.Trim ())));


                if (taskstate > -1)
                    list.Add(Builders<Call_OutTask>.Filter.Eq("isstart", taskstate));
                if (isallot > -1)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Eq("isallot", isallot));

                }
                //2019-6-10
                if (isautocall > -1)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Eq("isautocall", isautocall));
                }
                
                if (calltype  > -1)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Eq("calltype", calltype));
                }
                else
                {
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype != 3));
                }

                #region 获取分配未分配数量
                //根据条件查询集合
                var list0 = new List<FilterDefinition<Call_OutTask>>();
                var list1 = new List<FilterDefinition<Call_OutTask>>();
                list0.Add(Builders<Call_OutTask>.Filter.Eq("deleteflag", 0));
                list1.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))
                    {
                        list0.Add(Builders<Call_OutTask>.Filter.Gt("createtime", stime));
                        list1.Add(Builders<Call_OutTask>.Filter.Gt("createtime", stime));
                    }
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                    {
                        list0.Add(Builders<Call_OutTask>.Filter.Lt("createtime", etime));
                        list1.Add(Builders<Call_OutTask>.Filter.Lt("createtime", etime));
                    }
                }

                //模糊查询
                if (!string.IsNullOrWhiteSpace(key))
                {
                    list0.Add(Builders<Call_OutTask>.Filter.Where(s => s.taskname.Contains(key)));
                    list1.Add(Builders<Call_OutTask>.Filter.Where(s => s.taskname.Contains(key)));
                }
                //2020-6-4 修改
                if (calltype > -1)
                {
                    list0.Add(Builders<Call_OutTask>.Filter.Eq("calltype", calltype));
                    list1.Add(Builders<Call_OutTask>.Filter.Eq("calltype", calltype));
                }
                else
                {
                    list0.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype != 3));
                    list1.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype != 3));
                }

                if (taskstate > -1)
                {
                    list0.Add(Builders<Call_OutTask>.Filter.Eq("isstart", taskstate));
                    list1.Add(Builders<Call_OutTask>.Filter.Eq("isstart", taskstate));
                }

                list0.Add(Builders<Call_OutTask>.Filter.Eq("isallot", 0));
                list1.Add(Builders<Call_OutTask>.Filter.Eq("isallot", 1));

                var filter0 = Builders<Call_OutTask>.Filter.And(list0);
                long wfpcount = await _call_outtaskRepository.CountAsync(filter0);

                var filter1 = Builders<Call_OutTask>.Filter.And(list1);
                long fpcount = await _call_outtaskRepository.CountAsync(filter1);

                long totalcount = fpcount + wfpcount;
                #endregion

                var filter = Builders<Call_OutTask>.Filter.And(list);
                var blacklist = await _call_outtaskRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _call_outtaskRepository.CountAsync(filter);
                var pageList = await _ask_questionpagerRepository.GetAll(); //所有问卷

                //新添加问卷名称page_name
                var listTask = new List<CallOutTaskDto>();
                foreach (var item in blacklist.ToList())
                {
                    var modelTask = new CallOutTaskDto();
                    string pager_name = "";
                    if (!string.IsNullOrEmpty(item.pagerid))
                    {
                        var modelPage = pageList.Where(x => x.id == item.pagerid).FirstOrDefault();
                        if (modelPage != null)
                            pager_name = modelPage.title;
                    }

                    modelTask.id = item.id;
                    modelTask.taskid = item.taskid;
                    modelTask.taskname = item.taskname;
                    modelTask.taskremark = item.taskremark;
                    modelTask.pagerid = item.pagerid;
                    modelTask.pager_name = pager_name;
                    modelTask.isstart = item.isstart;
                    modelTask.starttime = item.starttime;
                    modelTask.endtime = item.endtime;
                    modelTask.isallot = item.isallot;
                    modelTask.allotusercode = item.allotusercode;
                    modelTask.allottime = item.allottime;
                    modelTask.createusercode = item.createusercode;
                    modelTask.createtime = item.createtime;
                    modelTask.deleteflag = item.deleteflag;
                    modelTask.isonline = item.isonline;
                    modelTask.workstarttimes1 = item.workstarttimes1;
                    modelTask.workendtimes1 = item.workendtimes1;
                    modelTask.workstarttimes2 = item.workstarttimes2;
                    modelTask.workendtimes2 = item.workendtimes2;
                    modelTask.calltype = item.calltype;
                    modelTask.voicepath = item.voicepath;
                    modelTask.voicestring = item.voicestring;
                    modelTask.pressnum = item.pressnum;
                    modelTask.bftype = item.bftype;
                    modelTask.bfnum = item.bfnum;
                    modelTask.joinflag = item.joinflag;
                    modelTask.totalnum = item.totalnum;
                    modelTask.surplusnum = item.surplusnum;
                    modelTask.successnum = item.successnum;
                    modelTask.callnum = item.callnum;
                    modelTask.agentnum = item.agentnum;
                    modelTask.successpercent = item.successpercent;
                    modelTask.agentsuccessnum = item.agentsuccessnum;
                    modelTask.agentsuccesspercent = item.agentsuccesspercent;
                    modelTask.secondflag = item.secondflag;
                    modelTask.ishand = item.ishand;
                    listTask.Add(modelTask);
                }

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

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

        [Authorize]
        [HttpGet("getcount")]
        public async Task<IActionResult> GetFPCount(string key, string stime, string etime, int taskstate = -1, int isautocall = 1)
        {
            try
            {

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

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

                //模糊查询
                if (!string.IsNullOrWhiteSpace(key))
                {
                    list0.Add(Builders<Call_OutTask>.Filter.Where(s => s.taskname.Contains(key)));
                    list1.Add(Builders<Call_OutTask>.Filter.Where(s => s.taskname.Contains(key)));
                }
                //2019-6-10
                if (isautocall > -1)
                {
                    list0.Add(Builders<Call_OutTask>.Filter.Eq("isautocall", isautocall));
                    list1.Add(Builders<Call_OutTask>.Filter.Eq("isautocall", isautocall));
                }

                if (taskstate > -1)
                {
                    list0.Add(Builders<Call_OutTask>.Filter.Eq("isstart", taskstate));
                    list1.Add(Builders<Call_OutTask>.Filter.Eq("isstart", taskstate));
                }

                list0.Add(Builders<Call_OutTask>.Filter.Eq("isallot", 0));
                list1.Add(Builders<Call_OutTask>.Filter.Eq("isallot", 1));

                list0.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype!=3));//2019-6-14 除去语音群呼
                list1.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype != 3));

                var filter = Builders<Call_OutTask>.Filter.And(list0);
                long wfpcount = await _call_outtaskRepository.CountAsync(filter);

                var filter1 = Builders<Call_OutTask>.Filter.And(list1);
                long fpcount = await _call_outtaskRepository.CountAsync(filter1);

                long totalcount = fpcount + wfpcount;
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取数量成功",
                    wfpcount = wfpcount,
                    fpcount = fpcount,
                    totalcount = totalcount,
                };
                return Content(obj.ToJson());

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

        /// <summary>
        /// 添加 - 外呼计划
        /// 20181126 新添加问卷id
        /// </summary>
        /// <param name="taskname"></param>
        /// <param name="taskremark"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="swtime1"></param>
        /// <param name="ewtime1"></param>
        /// <param name="swtime2"></param>
        /// <param name="ewtime2"></param>
        /// <param name="voicepath"></param>
        /// <param name="pressnum"></param>
        /// <param name="bftype"></param>
        /// <param name="pageid">问卷id</param>
        /// <param name="bfnum"></param>
        /// <param name="calltype"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string taskname, string taskremark, string stime, string etime, string swtime1, string ewtime1, string swtime2, string ewtime2, List<FileBaseModel> voicepath, string pressnum, string bftype,string pagerid,string voicestring, int bfnum = 0, int calltype = 0,int isautocall=1)
        {
            try
            {

                Call_OutTask comodel = new Call_OutTask();
                var res = false;
                if (!string.IsNullOrWhiteSpace(taskname))
                    comodel.taskname = taskname;

                if (!string.IsNullOrWhiteSpace(taskremark))
                    comodel.taskremark = taskremark.Trim();
                if (!string.IsNullOrWhiteSpace(stime))
                {

                    comodel.starttime = stime;
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {

                    comodel.endtime = etime;
                }

                comodel.isallot = 0;
                comodel.isstart = 0;
                comodel.isonline = 0;
                comodel.isautocall = isautocall;
                comodel.createusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                comodel.deleteflag = 0;
                comodel.createtime = DateTime.Now.ToLocalTime();
                if (!string.IsNullOrWhiteSpace(swtime1))
                    comodel.workstarttimes1 = swtime1.Trim();
                if (!string.IsNullOrWhiteSpace(ewtime1))
                    comodel.workendtimes1 = ewtime1.Trim();
                if (!string.IsNullOrWhiteSpace(swtime2))
                    comodel.workstarttimes2 = swtime2.Trim();
                if (!string.IsNullOrWhiteSpace(ewtime2))
                    comodel.workendtimes2 = ewtime2.Trim();
                if (voicepath != null)
                    comodel.voicepath = voicepath;
                if (voicestring != null&& voicestring!="")
                    comodel.voicestring = voicestring;
                if (!string.IsNullOrWhiteSpace(pressnum))
                    comodel.pressnum = pressnum.Trim();
                if (!string.IsNullOrWhiteSpace(bftype))
                    comodel.bftype = bftype.Trim();
                comodel.bfnum = bfnum;
                comodel.calltype = calltype;
                if (!string.IsNullOrWhiteSpace(pagerid))
                    comodel.pagerid = pagerid;
                else
                    comodel.pagerid = "000000000000000000000000";

                //calltype,string voicepath,string pressnum,string bftype,int bfnum
                res = await _call_outtaskRepository.Add(comodel);


                if (res)
                    return Success("任务保存成功");
                else
                    return Error("任务保存失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "自动外呼任务保存异常");
                return Error("自动外呼任务保存失败");
            }
        }

        /// <summary>
        /// 修改 - 外呼计划
        /// 20181126 新添加问卷id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="taskname"></param>
        /// <param name="taskremark"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="swtime1"></param>
        /// <param name="ewtime1"></param>
        /// <param name="swtime2"></param>
        /// <param name="ewtime2"></param>
        /// <param name="voicepath"></param>
        /// <param name="pressnum"></param>
        /// <param name="bftype"></param>
        /// <param name="pageid">问卷id</param>
        /// <param name="bfnum"></param>
        /// <param name="calltype"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, string taskname, string taskremark, string stime, string etime, string swtime1, string ewtime1, string swtime2, string ewtime2, List<FileBaseModel> voicepath, string pressnum, string bftype,string pagerid,string voicestring, int bfnum = 0, int calltype = 0, int isautocall = 1)
        {
            var res = false;
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var clmodel = await _call_outtaskRepository.GetSingle(id);
                    if (clmodel != null)
                    {
                        if (!string.IsNullOrWhiteSpace(taskname))
                            clmodel.taskname = taskname;

                        if (!string.IsNullOrWhiteSpace(taskremark))
                            clmodel.taskremark = taskremark.Trim();
                        //clmodel.interceptnum += 1;//2018-7-26clmodel.interceptnum += 1;
                        if (!string.IsNullOrWhiteSpace(stime))
                        {

                            clmodel.starttime = stime;
                        }
                        if (!string.IsNullOrWhiteSpace(etime))
                        {

                            clmodel.endtime = etime;
                        }
                        if (!string.IsNullOrWhiteSpace(swtime1))
                            clmodel.workstarttimes1 = swtime1.Trim();
                        if (!string.IsNullOrWhiteSpace(ewtime1))
                            clmodel.workendtimes1 = ewtime1.Trim();
                        if (!string.IsNullOrWhiteSpace(swtime2))
                            clmodel.workstarttimes2 = swtime2.Trim();
                        if (!string.IsNullOrWhiteSpace(ewtime2))
                            clmodel.workendtimes2 = ewtime2.Trim();
                        if (voicepath != null)
                            clmodel.voicepath = voicepath;
                        if (voicestring != null && voicestring != "")
                            clmodel.voicestring = voicestring;
                        if (!string.IsNullOrWhiteSpace(pressnum))
                            clmodel.pressnum = pressnum.Trim();
                        if (!string.IsNullOrWhiteSpace(bftype))
                            clmodel.bftype = bftype.Trim();
                        if (!string.IsNullOrWhiteSpace(pagerid))
                            clmodel.pagerid = pagerid;
                        else
                            clmodel.pagerid = "000000000000000000000000";
                        clmodel.bfnum = bfnum;
                        clmodel.calltype = calltype;
                        clmodel.isautocall = isautocall;

                        res = await _call_outtaskRepository.Update(clmodel);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "自动外呼任务保存异常");
                    return Error("自动外呼任务保存失败");
                }
            }
            if (res)
                return Success("自动外呼任务保存成功");
            else
                return Error("自动外呼任务保存失败");
        }

        [Authorize]
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        #region
                        //根据条件查询集合
                        var flist = new List<FilterDefinition<Call_OutTaskTelNum>>();
                        flist.Add(Builders<Call_OutTaskTelNum>.Filter.Eq("deleteflag", 0));

                        if (!string.IsNullOrWhiteSpace(item))
                            flist.Add(Builders<Call_OutTaskTelNum>.Filter.Where(s => s.taskid.Contains(item)));
                        var filter = Builders<Call_OutTaskTelNum>.Filter.And(flist);

                        var count = await _call_outtasktelnumRepository.CountAsync(filter);
                        if (count > 0)
                        {
                            return Error("请先清理任务下的号码，再做删除！");
                        }
                        #endregion


                        var ml = await _call_outtaskRepository.GetSingle(item);
                        ml.deleteflag = 1;
                        if (await _call_outtaskRepository.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("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id)
        {
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var dModel = await _call_outtaskRepository.GetSingle(id.Trim());

                    if (dModel != null)
                    {
                        return Success("获取自动外呼任务成功", dModel);
                    }
                    else
                    {
                        return Error("获取自动外呼任务失败");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取自动外呼任务实体异常");
                    return Error("获取自动外呼任务失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        [Authorize]
        [HttpGet("gettaskwfp")]
        public async Task<IActionResult> GetWFP(string key,int isautocall=1, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                int count = 0;
                DataTable dt = new DataTable();
                dt.Columns.Add("号码");
                dt.Columns.Add("名字");
                //排序字段
                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("isonline", 1));
                if (!string.IsNullOrWhiteSpace(key))
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.taskname.Contains(key)));
                //区分是否为自动外呼任务
                if (isautocall > -1)
                {
                    list.Add(Builders<Call_OutTask>.Filter.Eq("isautocall", isautocall));
                }
                list.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype !=3));
                var listc = new List<FilterDefinition<Call_OutTaskTelNum>>();
                listc.Add(Builders<Call_OutTaskTelNum>.Filter.Eq("deleteflag", 0));
                listc.Add(Builders<Call_OutTaskTelNum>.Filter.Eq("fpstate", 0));


                var filter = Builders<Call_OutTask>.Filter.And(list);
                var blacklist = await _call_outtaskRepository.Get(filter);
                foreach (var items in blacklist)
                {
                    string id = items.taskid;
                    var dModel = await _call_outtasktelnumRepository.GetSingle(id);
                    if (dModel != null)
                    {
                        DataRow dr = dt.NewRow();
                        dr["号码"] = dModel.phone;
                        dr["名字"] = dModel.cusname;
                        dt.Rows.Add(dr);
                        count++;
                    }
                }
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = blacklist,
                    total = count,
                };
                return Content(obj.ToJson());

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

        [Authorize]
        [HttpPost("fpdata")]
        public async Task<IActionResult> fpdata(string taskid, string[] arruser)
        {
            try
            {
                //arruser = new string[3];
                //taskid = "5b62b32316c146d74644fa51";
                //arruser[0] = "8001";
                //arruser[1] = "8002";
                //arruser[2] = "8003";
                Call_OutTaskFP comodel = new Call_OutTaskFP();
                #region 先删除旧数据
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("deleteflag", "1");

                var list = new List<FilterDefinition<Call_OutTaskFP>>();
                var filterBuilder = Builders<Call_OutTaskFP>.Filter;
                list.Add(filterBuilder.Eq("taskid", taskid));
                var filter = Builders<Call_OutTaskFP>.Filter.And(list);
                var tt = await _call_outtaskfpRepository.UpdateManay(comodel, dic, filter);
                #endregion
                int t = arruser.Length;
                int res = 0;
                for (int i = 0; i < arruser.Length; i++)
                {
                    var cmodel = new Call_OutTaskFP();

                    if (!string.IsNullOrWhiteSpace(taskid))
                        cmodel.taskid = taskid;

                    cmodel.usercode = arruser[i];


                    cmodel.createusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                    cmodel.deleteflag = 0;
                    cmodel.createtime = DateTime.Now.ToLocalTime();

                    if (await _call_outtaskfpRepository.Add(cmodel))
                        res++;
                }
                if (res == t)
                {
                    #region 更新分配标志
                    Call_OutTask model = new Call_OutTask();
                    Dictionary<string, string> dic0 = new Dictionary<string, string>();
                    dic0.Add("isallot", "1");

                    var list0 = new List<FilterDefinition<Call_OutTask>>();
                    var filterBuilder0 = Builders<Call_OutTask>.Filter;
                    list0.Add(filterBuilder0.Eq("id", taskid));
                    var filter0 = Builders<Call_OutTask>.Filter.And(list0);
                    var tt0 = await _call_outtaskRepository.UpdateManay(model, dic0, filter0);
                    #endregion
                    return Success("添加坐席分配数据成功");
                }
                else
                {
                    return Error("添加坐席分配数据失败");
                }

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加坐席分配数据异常");
                return Error("添加坐席分配数据失败");
            }
        }

        [Authorize]
        [HttpGet("getfplist")]
        public async Task<IActionResult> GetFPListsAsync(string taskid,int joinflag=-1,int deleteflag=0)
        {
            try
            {

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

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_OutTaskFP>>();
                
                list.Add(Builders<Call_OutTaskFP>.Filter.Eq("deleteflag", deleteflag));
                list.Add(Builders<Call_OutTaskFP>.Filter.Eq("taskid", taskid));
                if (joinflag > 0)
                {
                    list.Add(Builders<Call_OutTaskFP>.Filter.Eq("joinflag", joinflag));
                }
                var filter = Builders<Call_OutTaskFP>.Filter.And(list);
                var tasklist = await _call_outtaskfpRepository.Get(filter, null, sort);

                return Success("根据条件获取数据成功", tasklist);

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

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

            var list = new List<FilterDefinition<Call_OutTaskTelNum>>();
            var filterBuilder = Builders<Call_OutTaskTelNum>.Filter;
            list.Add(filterBuilder.Eq("taskid", id));
            long n = await _call_outtasktelnumRepository.Count(x => x.taskid == id);
            if (n > 0)
            {
                var filter = Builders<Call_OutTaskTelNum>.Filter.And(list);
                var tt = await _call_outtasktelnumRepository.UpdateManay(imodel, dic, filter);
                if (tt)
                {
                    //删除自动外呼表数据
                    await _call_autocallnumRepository.Remove(x => x.task_icon  == id);

                    return Success("外呼任务电话列表删除成功");
                }
                else
                { return Error("外呼任务电话列表删除失败"); }
            }
            else
            {
                { return Error("外呼任务下没有可清空的电话号码"); }
            }
        }

        //2018-7-20导入预测外呼号码
        /// <summary>
        /// 导入预测外呼号码（无用）
        /// </summary>
        /// <returns></returns>
        [HttpPost("importexcelold")]
        public async Task<IActionResult> TelInput(string taskid)
        {
            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}");

            //将数据导入数据库
            int headrow = 0;
            NPOIHelper npoi = new NPOIHelper();
            var dtExcel = npoi.ExcelToTable1(_upfile, headrow);
            if (dtExcel.Rows.Count > 0)
            {
                IList<Call_OutTaskTelNum> ICalls = ModelConvertHelper<Call_OutTaskTelNum>.ConvertToModel(dtExcel);
                List<Call_OutTaskTelNum> calls = ModelConvertHelper<Call_OutTaskTelNum>.ConvertIListToList(ICalls);
                int num = calls.Count;
                int isuccess = 0;
                foreach (var eq in calls)
                {
                    #region 保存数据库
                    var model = new Call_OutTaskTelNum();
                    model.taskid = taskid;
                    model.cusname = eq.cusname;
                    model.phone = eq.phone;
                    model.cusaddr = eq.cusaddr;
                    model.createtime = DateTime.Now.ToLocalTime();
                    bool b = await _call_outtasktelnumRepository.Add(model);
                    if (b)
                        isuccess++;

                    #endregion
                }
                if (num == isuccess)
                {
                    return Success("已导入数据");
                }
                else
                {
                    return Error("导入失败");
                }
            }
            return Success("请选择要导入的文件");
        }
        #endregion

        #region 外呼 - 任务电话
        //外呼任务电话相关接口
        [Authorize]
        [HttpGet("gettellistbypage")]
        public async Task<IActionResult> GetTelListsByPageAsync(string taskid, string stime, string etime, int isautocall = 1, int pageindex = 1, int pagesize = 10)
        {
            try
            {

                if (isautocall == 0)
                {
                    //排序字段
                    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.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());
                }
                else
                {
                    //排序字段
                    var sort = Builders<Call_OutTaskTelNum>.Sort.Descending("cusname");

                    //根据条件查询集合
                    var list = new List<FilterDefinition<Call_OutTaskTelNum>>();
                    list.Add(Builders<Call_OutTaskTelNum>.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_OutTaskTelNum>.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_OutTaskTelNum>.Filter.Lt("createtime", etime));
                    }


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

                    var filter = Builders<Call_OutTaskTelNum>.Filter.And(list);
                    var blacklist = await _call_outtasktelnumRepository.GetByPage(filter, pageindex, pagesize, sort);
                    var count = await _call_outtasktelnumRepository.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_outtasktelnumRepository.GetSingle(p => p.phone == telnum && p.taskid == taskid);
            if (model == null)
                return Error("参数错误");
            var modelTask = await _call_outtaskRepository.GetSingle(model.taskid);
            var obj = new
            {
                tasktel = model,
                task = modelTask
            };
            return Success("获取成功", obj);
        }

        [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_outtasktelnumRepository.GetSingle(item);
                        string taskid = ml.taskid;
                        ml.deleteflag = 1;
                        if (await _call_outtasktelnumRepository.Update(ml))
                        {
                            //删除自动外呼表数据
                            await _call_autocallnumRepository.Remove(x => x.task_icon == taskid&&x.call_number .Contains (ml.phone ));
                            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]
        [HttpPost("updateonline")]
        public async Task<IActionResult> UpdateOnlineAsync(string taskid, int state = 0)
        {
            var res = false;
            var result = string.Empty;
            if (state == 1)
            {
                if (taskid != null && taskid.Trim() != "")
                {
                    try
                    {
                        // 判断电话是否已上传（有电话时可上架）
                        var list_Num = await _call_outtasktelnumRepository.Count(x => x.taskid == taskid && x.deleteflag == 0);
                        if (list_Num > 0)
                        {
                            var clmodel = await _call_outtaskRepository.GetSingle(taskid);
                            if (clmodel != null)
                            {
                                clmodel.isonline = 1;
                                res = await _call_outtaskRepository.Update(clmodel);
                            }
                        }
                        else
                        {
                            res = false;
                            result = "请先导入外呼号码";
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "任务上线执行失败");
                        return Error("任务上线执行失败");
                    }
                }
            }
            else
            {
                if (taskid != null && taskid.Trim() != "")
                {
                    try
                    {
                        var clmodel = await _call_outtaskRepository.GetSingle(taskid);
                        if (clmodel != null)
                        {
                            if (clmodel.isonline == 0)
                            {
                                return Error("计划未上线，无法执行下线操作");
                            }
                            else
                            {
                                clmodel.isonline = 0;
                                res = await _call_outtaskRepository.Update(clmodel);
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "任务下线执行失败");
                        return Error("任务下线执行失败");
                    }
                }
            }
            if (res)
            {
                return Success("执行成功");
            }
            else
            {
                if (string.IsNullOrEmpty(result))
                    return Error("执行失败");
                else
                    return Error("执行失败" + result);
            }
        }

        /// <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_OutTaskTelNum();

                    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();
                    string cphone = "";
                    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);
                            if (item.Name == "phone")
                            {
                                cphone = v.ToString();
                            }
                        }
                    }

                    bool b = await _call_outtasktelnumRepository.Add(model);

                    #region 将号码保存至中间件号码表
                    Call_AutoCallNum modelc = new Call_AutoCallNum();
                    modelc.task_icon = taskid;
                    modelc.flag = 1;
                    modelc.invalid_flag = 0;
                    modelc.timestamp = DateTimeConvert.ToTimespan(DateTime.Now);//保存导入时间时间戳
                                                                               //model.cusaddr = titem.cusaddr;
                    modelc.call_number = cphone;
                    Task<string> y = GetCallOutprefix(cphone);
                    if (y.Result != "")
                    {
                        modelc.call_number = y.Result;
                    }
                    //获取放音文件路径//启动时更新flag、invalid_flag和voice_file_name
                    //if (voicepath != "")
                    //{
                    //    modelc.voice_file_name = voicepath;
                    //}

                    var aclist = await _call_autocallnumRepository.GetSingle(x => x.task_icon == taskid && x.call_number == modelc.call_number );
                    if (aclist == null)
                    {
                        bool bbb = await _call_autocallnumRepository.Add(modelc);
                        if (index == 1)
                        {
                            _logger.LogInformation("任务号码转存AAAA" + bbb);
                        }
                    }
                    #endregion

                    if (!b)
                    {
                        if (!string.IsNullOrEmpty(errmsg))
                        {
                            errmsg = errmsg + "\r\n第" + index + "行导入失败！";
                        }
                        else
                        {
                            errmsg = "第" + index + "行导入失败！";
                        }
                    }
                    index++;
                    _logger.LogInformation("任务号码转存AAAA" + index);
                }
            }
            else
            {
                return Error("文件中无数据");
            }

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

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

        //根据坐席id获取分配任务
        //[Authorize]
        [HttpGet("getjoinlist")]
        public async Task<IActionResult> GetJoinListsAsync(string agentid, int joinflag = -1)//string agengid
        {
            try
            {
                
                //排序字段
                var sort = Builders<Call_OutTask>.Sort.Descending("createtime");
                string agentcode = "";
                if (!string.IsNullOrEmpty(agentid))
                {
                    agentcode = agentid;
                }
                else
                {
                    agentcode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                }

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_OutTask>>();
                list.Add(Builders<Call_OutTask>.Filter.Eq("deleteflag", 0));
                list.Add(Builders<Call_OutTask>.Filter.Eq("isallot", 1));
                list.Add(Builders<Call_OutTask>.Filter.Where(s => s.isstart.Equals(0) || s.isstart.Equals(1) || s.isstart.Equals(2)));
                var filter = Builders<Call_OutTask>.Filter.And(list);
                var tasklist = await _call_outtaskRepository.Get(filter, null, sort);
                List<Call_OutTask> asList = tasklist.ToList();

                if (asList != null)
                {
                    int l = asList.Count();
                    for (int m = l; m > 0; m--)
                    {
                        if (joinflag > 0)
                        {
                            string taskid = asList[m - 1].id;
                            #region 先更新参与标志
                            /*if (!string.IsNullOrWhiteSpace(agentcode))
                            {
                                var jo = CheckJoinState(taskid, agentcode);
                                if (jo != null)
                                {
                                    int x = jo.Result;
                                    if (x > 0)
                                    {
                                        var ml = await _call_outtaskfpRepository.GetSingle(p => p.taskid == taskid && p.usercode == agentcode && p.deleteflag == 0);
                                        if (ml != null)
                                        {
                                            ml.joinflag = x;
                                            await _call_outtaskfpRepository.Update(ml);
                                        }
                                    }
                                }
                            }*/
                            #endregion

                            long n = await _call_outtaskfpRepository.Count(x => x.taskid == taskid && x.usercode == agentcode && x.deleteflag == 0 && x.joinflag == joinflag);
                            if (n <= 0)
                            {
                                asList.RemoveAt(m - 1);
                                continue;
                            }
                            else
                            {
                                asList[m - 1].joinflag = joinflag;
                                #region 获取数量
                                long tn = await _call_outtasktelnumRepository.Count(x => x.taskid == taskid && x.deleteflag == 0);//任务量
                                long sn = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid && x.is_call_out_ok == 1);//呼通量
                                long an = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid);//已呼叫量，包括接通未接通
                                asList[m - 1].totalnum = tn;
                                asList[m - 1].surplusnum = tn - an;
                                asList[m - 1].successnum = sn;
                                #endregion
                            }

                        }
                        else
                        {
                            string taskid = asList[m - 1].id;
                            #region 先更新参与标志
                            /*if (!string.IsNullOrWhiteSpace(agentcode))
                            {
                                var jo = CheckJoinState(taskid, agentcode);
                                if (jo != null)
                                {
                                    int x = jo.Result;
                                    if (x >= 0)
                                    {
                                        var ml = await _call_outtaskfpRepository.GetSingle(p => p.taskid == taskid && p.usercode == agentcode && p.deleteflag == 0);
                                        if (ml != null)
                                        {
                                            ml.joinflag = x;
                                            await _call_outtaskfpRepository.Update(ml);
                                        }
                                    }
                                }
                            }*/
                            #endregion
                            long n = await _call_outtaskfpRepository.Count(x => x.taskid == taskid && x.usercode == agentcode && x.deleteflag == 0 && x.joinflag == 0);
                            if (n <= 0)
                            {
                                long n1 = await _call_outtaskfpRepository.Count(x => x.taskid == taskid && x.usercode == agentcode && x.deleteflag == 0 && x.joinflag == 1);
                                if (n1 <= 0)
                                {
                                    asList.RemoveAt(m - 1);
                                }
                                else
                                {
                                    asList[m - 1].joinflag = 1;
                                    #region 获取数量
                                    long tn = await _call_outtasktelnumRepository.Count(x => x.taskid == taskid && x.deleteflag == 0);//任务量
                                    long sn = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid && x.is_call_out_ok == 1);//呼通量
                                    long an = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid);//已呼叫量，包括接通未接通
                                    asList[m - 1].totalnum = tn;
                                    asList[m - 1].surplusnum = tn - an;
                                    asList[m - 1].successnum = sn;
                                    #endregion
                                }

                            }
                            else
                            {
                                asList[m - 1].joinflag = 0;
                                #region 获取数量
                                long tn = await _call_outtasktelnumRepository.Count(x => x.taskid == taskid && x.deleteflag == 0);//任务量
                                long sn = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid && x.is_call_out_ok == 1);//呼通量
                                long an = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid);//已呼叫量，包括接通未接通
                                asList[m - 1].totalnum = tn;
                                asList[m - 1].surplusnum = tn - an;
                                asList[m - 1].successnum = sn;
                                #endregion
                            }

                        }

                    }

                }

                return Success("获取坐席分配任务成功", asList);

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取坐席分配任务异常");
                return Error("获取坐席分配任务失败");
            }
        }

        //根据坐席id获取分配任务
        //[Authorize]
        [HttpGet("getqrjoinlist")]
        public async Task<IActionResult> GetQRJoinListsAsync(string agentid, int joinflag = -1)//string agengid
        {
            try
            {

                //排序字段
                var sort = Builders<Call_OutTask>.Sort.Descending("createtime");
                string agentcode = "";
                if (!string.IsNullOrEmpty(agentid))
                {
                    agentcode = agentid;
                }
                else
                {
                    agentcode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                }

                #region 更新参与标志
                Call_OutTaskFP imodel = new Call_OutTaskFP();
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("joinflag", "0");

                var list0 = new List<FilterDefinition<Call_OutTaskFP>>();
                var filterBuilder = Builders<Call_OutTaskFP>.Filter;
                list0.Add(filterBuilder.Eq("usercode", agentcode ));
                long mn = await _call_outtaskfpRepository.Count(x => x.usercode  == agentcode &&x.joinflag ==1&&x.deleteflag ==0);
                if (mn > 0)
                {
                    var filter0 = Builders<Call_OutTaskFP>.Filter.And(list0);
                    var tt = await _call_outtaskfpRepository.UpdateManay(imodel, dic, filter0);
                    
                }
                #endregion

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_OutTask>>();
                list.Add(Builders<Call_OutTask>.Filter.Eq("deleteflag", 0));
                list.Add(Builders<Call_OutTask>.Filter.Eq("isallot", 1));
                list.Add(Builders<Call_OutTask>.Filter.Where(s => s.isstart.Equals(0) || s.isstart.Equals(1) || s.isstart.Equals(2)));
                var filter = Builders<Call_OutTask>.Filter.And(list);
                var tasklist = await _call_outtaskRepository.Get(filter, null, sort);
                List<Call_OutTask> asList = tasklist.ToList();

                if (asList != null)
                {
                    int l = asList.Count();
                    for (int m = l; m > 0; m--)
                    {
                        if (joinflag > 0)
                        {
                            string taskid = asList[m - 1].id;
                            #region 先更新参与标志，签入的时候坐席为未参与状态
                            //var ml = await _call_outtaskfpRepository.GetSingle(p => p.taskid == taskid && p.usercode == agentcode && p.deleteflag == 0 && p.joinflag == 1);
                            //if (ml != null)
                            //{
                            //    ml.joinflag = 0;
                            //    await _call_outtaskfpRepository.Update(ml);
                            //}
                            #endregion

                            long n = await _call_outtaskfpRepository.Count(x => x.taskid == taskid && x.usercode == agentcode && x.deleteflag == 0 && x.joinflag == joinflag);
                            if (n <= 0)
                            {
                                asList.RemoveAt(m - 1);
                                continue;
                            }
                            else
                            {
                                asList[m - 1].joinflag = joinflag;
                                #region 获取数量
                                long tn = await _call_outtasktelnumRepository.Count(x => x.taskid == taskid && x.deleteflag == 0);//任务量
                                long sn = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid && x.is_call_out_ok == 1);//呼通量
                                long an = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid);//已呼叫量，包括接通未接通
                                asList[m - 1].totalnum = tn;
                                asList[m - 1].surplusnum = tn - an;
                                asList[m - 1].successnum = sn;
                                #endregion
                            }

                        }
                        else
                        {
                            string taskid = asList[m - 1].id;
                            #region 先更新参与标志
                            //var ml = await _call_outtaskfpRepository.GetSingle(p => p.taskid == taskid && p.usercode == agentcode && p.deleteflag == 0 && p.joinflag == 1);
                            //if (ml != null)
                            //{
                            //    ml.joinflag = 0;
                            //    await _call_outtaskfpRepository.Update(ml);
                            //}
                            #endregion
                            long n = await _call_outtaskfpRepository.Count(x => x.taskid == taskid && x.usercode == agentcode && x.deleteflag == 0 && x.joinflag == 0);
                            if (n <= 0)
                            {
                                long n1 = await _call_outtaskfpRepository.Count(x => x.taskid == taskid && x.usercode == agentcode && x.deleteflag == 0 && x.joinflag == 1);
                                if (n1 <= 0)
                                {
                                    asList.RemoveAt(m - 1);
                                }
                                else
                                {
                                    asList[m - 1].joinflag = 1;
                                    #region 获取数量
                                    long tn = await _call_outtasktelnumRepository.Count(x => x.taskid == taskid && x.deleteflag == 0);//任务量
                                    long sn = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid && x.is_call_out_ok == 1);//呼通量
                                    long an = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid);//已呼叫量，包括接通未接通
                                    asList[m - 1].totalnum = tn;
                                    asList[m - 1].surplusnum = tn - an;
                                    asList[m - 1].successnum = sn;
                                    #endregion
                                }

                            }
                            else
                            {
                                asList[m - 1].joinflag = 0;
                                #region 获取数量
                                long tn = await _call_outtasktelnumRepository.Count(x => x.taskid == taskid && x.deleteflag == 0);//任务量
                                long sn = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid && x.is_call_out_ok == 1);//呼通量
                                long an = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid);//已呼叫量，包括接通未接通
                                asList[m - 1].totalnum = tn;
                                asList[m - 1].surplusnum = tn - an;
                                asList[m - 1].successnum = sn;
                                #endregion
                            }

                        }

                    }

                }

                return Success("获取坐席分配任务成功", asList);

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取坐席分配任务异常");
                return Error("获取坐席分配任务失败");
            }
        }
        #endregion

        //更新参与标志
        [Authorize]
        [HttpPost("updatejoin")]
        public async Task<IActionResult> UpdateJoinFlag(string taskid, string agentid, int joinflag)
        {

            var ml = await _call_outtaskfpRepository.GetSingle(p => p.taskid == taskid && p.usercode == agentid);
            ml.joinflag = joinflag;
            if (await _call_outtaskfpRepository.Update(ml))
                return Success("参与标志更新成功");

            else
                return Error("参与标志更新失败");

        }

        //任务结束时转存任务数据        
        [HttpPost("transfer")]
        public async Task<IActionResult> TransferAsync(string taskid)
        {
            try
            {
                var list = new List<FilterDefinition<Call_OutTaskTelNum>>();
                list.Add(Builders<Call_OutTaskTelNum>.Filter.Eq("deleteflag", 0));
                list.Add(Builders<Call_OutTaskTelNum>.Filter.Where(s => s.taskid.Equals(taskid)));
                int res = 0;
                var filter = Builders<Call_OutTaskTelNum>.Filter.And(list);
                var tlist = await _call_outtasktelnumRepository.Get(filter);
                int tnum = tlist.Count();
                if (tlist != null)
                {
                    foreach (var titem in tlist)
                    {
                        #region 
                        Call_OutTaskTelNumRecord model = new Call_OutTaskTelNumRecord();
                        model.taskid = titem.id;
                        model.cusid = titem.cusid;
                        model.cusname = titem.cusname;
                        model.cusaddr = titem.cusaddr;
                        model.phone = titem.phone;
                        model.phoneby = titem.phoneby;
                        model.fpstate = titem.fpstate;
                        model.yjstate = titem.yjstate;
                        model.hcstate = titem.hcstate;
                        //model.userid = titem.userid;
                        //model.username = titem.username;
                        model.createtime = titem.createtime;
                        model.askinfo = titem.askinfo;
                        model.askres = titem.askres;
                        model.hjjgid = titem.hjjgid;
                        model.hjjgname = titem.hjjgname;

                        model.hjjgtime = titem.hjjgtime;
                        model.yhfkid = titem.yhfkid;
                        model.yhfkname = titem.yhfkname;
                        var aclist = await _mw_autocall_call_recordRepository.GetSingle(x => x.task_icon == taskid && x.callee == model.phone);
                        if (aclist != null)
                        {
                            model.iscallout = 1;
                            model.iscalloutsuccess = aclist.is_call_out_ok;
                            model.userid = aclist.agent_id;
                        }

                        #endregion
                        if (await _call_outtasktelnumrecordRepository.Add(model))
                            res++;
                    }
                    if (res == tnum)
                    {
                        
                        #region 更新任务数据
                        long tn = await _call_outtasktelnumRepository.Count(x => x.taskid == taskid && x.deleteflag == 0);//任务量
                        long sn = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid && x.is_call_out_ok == 1);//呼通量
                        long an = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid);//已呼叫量，包括接通未接通

                        var clmodel = await _call_outtaskRepository.GetSingle(taskid);
                        if (clmodel != null)
                        {

                            clmodel.totalnum = tn;
                            clmodel.surplusnum = tn - an;
                            clmodel.successnum = sn;

                            await _call_outtaskRepository.Update(clmodel);
                        }
                        #endregion
                        //await _call_outtasktelnumRepository.Remove(x => x.taskid == taskid);//转存成功删除数据//2019-7-10注释掉，删除查不到数据
                        return Success("任务转存成功");
                    }

                    else
                    { return Error("任务转存失败"); }

                }
                else
                {
                    return Error("任务没有数据");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "任务转存异常");
                return Error("任务转存失败");
            }
        }

        //我的任务相关接口
        //[Authorize]
        [HttpGet("getmytask")]
        public async Task<IActionResult> GetMyTaskByPageAsync(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=1)//infokind为0时默认全部数据，为1时获取当前任务，为2时历史任务
        {
            try
            {
               

                #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", stime));
                }
                else if (string.IsNullOrWhiteSpace(stime ))
                {
                    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(etime ))
                {
                    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 > -1)
                {
                    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) ));
                }
                else
                {
                    list.Add(Builders<Call_OutTask>.Filter.Where(s => s.calltype != 3));
                }
                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.Trim ())));
                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--)
                    {
                        #region 先更新参与标志
                        //string ja = agentid;
                        //if (string.IsNullOrWhiteSpace(agentid))
                        //{
                        //    ja = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                        //}
                        //if (!string.IsNullOrWhiteSpace(ja))
                        //{
                        //    var jo = CheckJoinState(asList[m - 1].id, ja);
                        //    if (jo != null)
                        //    {
                        //        int x = jo.Result;
                        //        if (x >= 0)
                        //        {
                        //            var ml = await _call_outtaskfpRepository.GetSingle(p => p.taskid == asList[m - 1].id && p.usercode == ja && p.deleteflag == 0);
                        //            if (ml != null)
                        //            {
                        //                ml.joinflag = x;
                        //                await _call_outtaskfpRepository.Update(ml);
                        //            }
                        //        }
                        //    }
                        //}
                        #endregion


                        if (!string.IsNullOrWhiteSpace(agentid))
                        {
                            if (await _call_outtaskfpRepository.Count(x => x.taskid == asList[m - 1].id && x.usercode == agentid&&x.deleteflag ==0) <= 0)
                            {
                                asList.RemoveAt(m - 1);
                                count--;
                                continue;
                            }
                            else
                            {
                                var aclist = await _call_outtaskfpRepository.GetSingle(x => x.taskid == asList[m - 1].id && x.usercode == agentid);
                                if (aclist != null)
                                {
                                    asList[m - 1].joinflag = aclist.joinflag;
                                }
                            }
                        }
                        if (asList[m - 1].isstart == 3 || asList[m - 1].isstart == 5)
                        {
                            asList[m - 1].callnum = asList[m - 1].totalnum - asList[m - 1].surplusnum;
                            if (asList[m - 1].callnum > 0)
                            {
                                //asList[m - 1].successpercent = asList[m - 1].successnum / asList[m - 1].callnum;
                                decimal p = Math.Round(Convert.ToDecimal(asList[m - 1].successnum) / Convert.ToDecimal(asList[m - 1].callnum) * 100, 2);
                                asList[m - 1].successpercent = (p).ToString() + "%";
                            }
                            else
                            { asList[m - 1].successpercent = "0"; }
                            asList[m - 1].agentnum = await _call_outtaskfpRepository.Count(x => x.taskid  == asList[m - 1].id && x.deleteflag  == 0 && x.joinflag  == 1);//0;//坐席数量
                            long wantagent = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id && x.is_want_agent_ok == 1);
                            asList[m - 1].agentsuccessnum = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id && x.is_turn_agent_ok == 1);
                            if (wantagent > 0)
                            {
                                //asList[m - 1].agentsuccesspercent = asList[m - 1].agentsuccessnum / wantagent;
                                decimal p = Math.Round(Convert.ToDecimal(asList[m - 1].agentsuccessnum) / Convert.ToDecimal(wantagent) * 100,2);
                                asList[m - 1].agentsuccesspercent = (p ).ToString() + "%";
                            }
                            else
                            { asList[m - 1].agentsuccesspercent = "0"; }
                        }
                        else
                        {
                            asList[m - 1].totalnum = await _call_outtasktelnumRepository.Count(x => x.taskid == asList[m - 1].id && x.deleteflag == 0);//任务量
                            asList[m - 1].successnum = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id && x.is_call_out_ok == 1);//呼通量
                            long an = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id);//已呼叫量，包括接通未接通
                            asList[m - 1].surplusnum = asList[m - 1].totalnum - an;
                            asList[m - 1].callnum = asList[m - 1].totalnum - asList[m - 1].surplusnum;
                            if (asList[m - 1].callnum > 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 ()+"%";
                            }
                            else
                            { asList[m - 1].successpercent = "0"; }
                            asList[m - 1].agentnum = await _call_outtaskfpRepository.Count(x => x.taskid == asList[m - 1].id && x.deleteflag == 0 && x.joinflag == 1);//0;//坐席数量
                            long wantagent = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id && x.is_want_agent_ok == 1);
                            asList[m - 1].agentsuccessnum = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id && x.is_turn_agent_ok == 1);
                            if (wantagent > 0)
                            {
                                //asList[m - 1].agentsuccesspercent = asList[m - 1].agentsuccessnum / wantagent;
                                decimal p = Math.Round(Convert.ToDecimal(asList[m - 1].agentsuccessnum) * 100 / Convert.ToDecimal(wantagent), 2);
                                asList[m - 1].agentsuccesspercent = (p ).ToString() + "%";
                            }
                            else
                            { asList[m - 1].agentsuccesspercent = "0"; }
                        }
                    }
                }
                long total = 0;
                long dqnum = 0;
                long lsnum = 0;
                if (infokind == 0)
                {
                    total = count;// asList.Count;
                    Task<int> x = GetMyTaskCountAsync(taskid, taskname, agentid, stime, etime, 1, 10, 1, -1,calltype ,isautocall );                   
                    dqnum  = x.Result;

                    Task<int> y = GetMyTaskCountAsync(taskid, taskname, agentid, stime, etime, 1, 10, 2, -1, calltype, isautocall);
                    lsnum = y.Result;
                }
                else if (infokind == 1)
                {
                    dqnum = count;//asList.Count;
                    Task<int> x = GetMyTaskCountAsync(taskid, taskname, agentid, stime, etime, 1, 10, 0, -1, calltype, isautocall);
                    total  = x.Result;

                    Task<int> y = GetMyTaskCountAsync(taskid, taskname, agentid, stime, etime, 1, 10, 2, -1, calltype, isautocall);
                    lsnum = y.Result;
                }
                else if (infokind == 2)
                {
                    lsnum = count;//asList.Count;
                    Task<int> x = GetMyTaskCountAsync(taskid, taskname, agentid, stime, etime, 1, 10, 0, -1, calltype, isautocall);
                    total = x.Result;

                    Task<int> y = GetMyTaskCountAsync(taskid, taskname, agentid, stime, etime, 1, 10, 1, -1, calltype, isautocall);
                    dqnum = y.Result;
                }

                var obj = new
                {
                    state = "success",
                    message = "根据条件获取数据成功",
                    rows = asList,
                    total ,
                    dqnum ,//当前
                    lsnum ,//历史
                };
                return Content(obj.ToJson());
                #endregion


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

        #region
        public async Task<int> GetMyTaskCountAsync(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 = 1)//infokind为0时默认全部数据，为1时获取当前任务，为2时历史任务
        {
            try
            {
                #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)));
                var filter = Builders<Call_OutTask>.Filter.And(list);
                var tasklist = await _call_outtaskRepository.Get(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--)
                    {
                        if (!string.IsNullOrWhiteSpace(agentid))
                        {
                            if (await _call_outtaskfpRepository.Count(x => x.taskid == asList[m - 1].id && x.usercode == agentid && x.deleteflag == 0) <= 0)
                            {
                                asList.RemoveAt(m - 1);
                                continue;
                            }
                        }
                        if (asList[m - 1].isstart == 3 || asList[m - 1].isstart == 5)
                        {
                            asList[m - 1].callnum = asList[m - 1].totalnum - asList[m - 1].surplusnum;
                            if (asList[m - 1].callnum > 0)
                            {
                                //asList[m - 1].successpercent = asList[m - 1].successnum / asList[m - 1].callnum;
                                decimal p = Math.Round(Convert.ToDecimal(asList[m - 1].successnum) / Convert.ToDecimal(asList[m - 1].callnum) * 100, 2);
                                asList[m - 1].successpercent = (p ).ToString() + "%";
                            }
                            else
                            { asList[m - 1].successpercent = "0"; }
                            asList[m - 1].agentnum = await _call_outtaskfpRepository.Count(x => x.taskid == asList[m - 1].id && x.deleteflag == 0 && x.joinflag == 1);//0;//坐席数量
                            long wantagent = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id && x.is_want_agent_ok == 1);
                            asList[m - 1].agentsuccessnum = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id && x.is_turn_agent_ok == 1);
                            if (wantagent > 0)
                            {
                                //asList[m - 1].agentsuccesspercent = asList[m - 1].agentsuccessnum / wantagent;
                                decimal p = Math.Round(Convert.ToDecimal(asList[m - 1].agentsuccessnum) / Convert.ToDecimal(wantagent) * 100, 2);
                                asList[m - 1].agentsuccesspercent = (p ).ToString() + "%";
                            }
                            else
                            { asList[m - 1].agentsuccesspercent = "0"; }
                        }
                        else
                        {
                            asList[m - 1].totalnum = await _call_outtasktelnumRepository.Count(x => x.taskid == taskid && x.deleteflag == 0);//任务量
                            asList[m - 1].successnum = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid && x.is_call_out_ok == 1);//呼通量
                            long an = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == taskid);//已呼叫量，包括接通未接通
                            asList[m - 1].surplusnum = asList[m - 1].totalnum - an;
                            asList[m - 1].callnum = asList[m - 1].totalnum - asList[m - 1].surplusnum;
                            if (asList[m - 1].callnum > 0)
                            {
                                //asList[m - 1].successpercent = asList[m - 1].successnum / asList[m - 1].callnum;
                                decimal p = Math.Round(Convert.ToDecimal(asList[m - 1].successnum) / Convert.ToDecimal(asList[m - 1].callnum) * 100, 2);
                                asList[m - 1].successpercent = (p ).ToString() + "%";
                            }
                            else
                            { asList[m - 1].successpercent = "0"; }
                            asList[m - 1].agentnum = await _call_outtaskfpRepository.Count(x => x.taskid == asList[m - 1].id && x.deleteflag == 0 && x.joinflag == 1);//0;//坐席数量
                            long wantagent = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id && x.is_want_agent_ok == 1);
                            asList[m - 1].agentsuccessnum = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == asList[m - 1].id && x.is_turn_agent_ok == 1);
                            if (wantagent > 0)
                            {
                                //asList[m - 1].agentsuccesspercent = asList[m - 1].agentsuccessnum / wantagent;
                                decimal p = Math.Round(Convert.ToDecimal(asList[m - 1].agentsuccessnum) / Convert.ToDecimal(wantagent) * 100, 2);
                                asList[m - 1].agentsuccesspercent = (p ).ToString() + "%";
                            }
                            else
                            { asList[m - 1].agentsuccesspercent = "0"; }
                        }
                    }
                }


                //var obj = new
                //{
                //    state = "success",
                //    message = "根据条件获取分页数据成功",
                //    total = asList.Count ,
                    
                //};
                //return Content(obj.ToJson());
                return asList.Count;
                #endregion


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取数据异常");
                return -1;
            }
        }
        #endregion

        //导出未接通和已接通
        [Authorize]
        [HttpGet("exportexcel")]
        [AllowAnonymous]
        public async Task<IActionResult> ExportExcelAsync(string taskid,int  calloutok=0)
        {
            try
            {
                //排序字段
                //var sort = Builders<MW_Autocall_Call_Record>.Sort.Descending("createtime");

                //根据条件查询集合
                var list = new List<FilterDefinition<MW_Autocall_Call_Record>>();
                if (taskid != null)
                    list.Add(Builders<MW_Autocall_Call_Record>.Filter.Where(s => s.task_icon.Equals(taskid)));
                list.Add(Builders<MW_Autocall_Call_Record>.Filter.Where(s => s.is_call_out_ok .Equals(calloutok)));
                var filter = Builders<MW_Autocall_Call_Record>.Filter.And(list);
                var tasklist = await _mw_autocall_call_recordRepository.Get(filter, null);
                //导出dtnew 
                NPOIHelper npoi = new NPOIHelper();
                List<MW_Autocall_Call_Record> tlist = tasklist.ToList();
                var tb = ModelConvertHelper<MW_Autocall_Call_Record>.ConvertListToDataTable(tlist);
                string strname = "未接通";
                if (calloutok == 1)
                {
                    strname = "已接通";
                }
                string[] cols = { "电话"};
                string[] colname = { "callee"};
                byte[] sm = npoi.ExportToExcel1(tb, cols, colname);
                if (sm != null)
                {
                    return File(sm, "application/vnd.ms-excel", strname +"号码信息.xlsx");
                }
                else
                {
                    return Error("导出失败");
                }
                //return Success("根据条件获取数据成功", tasklist);

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出异常");
                return Error("导出失败");
            }
            //return Success("导出成功");
        } 

        public string Export(DataTable dt,string filename, string[] cols = null)
        {
            if (string.IsNullOrWhiteSpace(_hostingEnvironment.WebRootPath))
            {
                _hostingEnvironment.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            }
            string sWebRootFolder = _hostingEnvironment.WebRootPath;
            //sWebRootFolder = @"C:\Epan\";


            string sFileName = @filename;
            string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
            FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
            if (file.Exists)
            {
                file.Delete();
                file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
            }
            using (ExcelPackage package = new ExcelPackage(file))
            {
                // add a new worksheet
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1");
                if (cols != null)
                {
                    for (int i = 0; i < cols.Length; i++)
                    {
                        worksheet.Cells[1, i + 1].Value = cols[i];
                    }
                }
                else
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        worksheet.Cells[1, i + 1].Value = dt.Columns[i].ColumnName;
                    }
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        worksheet.Cells[i+2, j + 1].Value = dt.Rows[i][j];
                    }
                }
                //sheet header
                /*worksheet.Cells[1, 1].Value = "ID";
                worksheet.Cells[1, 2].Value = "Name";
                worksheet.Cells[1, 3].Value = "Age";

                //Add values
                worksheet.Cells["A2"].Value = 1000;
                worksheet.Cells["B2"].Value = "Jeffcky1";
                worksheet.Cells["C2"].Value = 18;

                worksheet.Cells["A3"].Value = 1001;
                worksheet.Cells["B3"].Value = "Jeffcky2";
                worksheet.Cells["C3"].Value = 19;*/


                package.Save(); //Save the workbook.
            }
            return URL;

        }

        //获取任务监控信息
        [Authorize]
        [HttpGet("getmonitor")]
        public async Task<IActionResult> GetMonitorAsync(string id)
        {
            if (id != null && id.Trim() != "")
            {
                try
                {
                    #region 变量定义
                    string createtime = "";
                    string starttime = "";
                    string endtime = "";
                    string workstarttimes1 = "";
                    string workendtimes1 = "";
                    string workstarttimes2 = "";
                    string workendtimes2 = "";
                    string bftype = "";
                    string bfnum = "";
                    int zxrs = 0;
                    int thrs = 0;
                    int kxrs = 0;
                    long  totalnum = 0;
                    long  yhnum = 0;
                    long zyds = 0;
                    long zzzxs = 0;
                    long dqhhs = 0;
                    long hjzsc = 0;
                    string ywc = "0%";
                    string ydl = "0%";
                    string zzxl = "0%";
                    int fys = 0;
                    #endregion
                    var dModel = await _call_outtaskRepository.GetSingle(id.Trim());

                    if (dModel != null)
                    {
                        createtime = dModel.createtime.ToString();
                        starttime = dModel.starttime;
                        endtime = dModel.endtime;
                        workstarttimes1 = dModel.workstarttimes1;
                        workendtimes1 = dModel.workendtimes1;
                        workstarttimes2 = dModel.workstarttimes2;
                        workendtimes2 = dModel.workendtimes2;
                        bftype = dModel.bftype;
                        bfnum = dModel.bfnum.ToString();
                        #region post请求中间件获取数据
                        #region 获取路径
                        try
                        {
                            var aModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("ACDAutoCall") & s.isdelete == false, null);
                            string acdip = aModel.paramvalue;


                            //groupid = "364";
                            string strURL = "http://" + acdip + "/v1/acd/group/resource/info?group=" + id;
                            string strHTML0 = MadRunFabric.Common.HttpMethods.HttpGet(strURL);
                            JObject jo0 = (JObject)JsonConvert.DeserializeObject(strHTML0);
                            if (jo0 != null && jo0["total_nums"] != null)
                            {
                                thrs = Convert.ToInt32(jo0["talk_nums"]);//talk_nums
                                kxrs = Convert.ToInt32(jo0["free_nums"]);
                                zxrs = thrs + kxrs;

                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "获取中间件坐席人数异常");
                            return Error("获获取中间件信息失败");
                        }
                        #endregion

                        #region pcp地址获取放音数
                        #region 获取路径
                        try
                        {
                            var pModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("PCPIP") & s.isdelete == false, null);
                            string pcpip = pModel.paramvalue;

                            #endregion
                            //groupid = "364";
                            string strPURL = "http://" + pcpip + "/v1/pcp/qy";
                            var m = new
                            {
                                task = id,
                                type = 100,

                            };
                            //实体序列化和反序列化
                            string json1 = JsonConvert.SerializeObject(m);
                            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strPURL, json1);
                            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
                            if (jo1 != null && jo1["play_nums"] != null)
                            {
                                fys = Convert.ToInt32(jo1["play_nums"]);

                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "获取中间件放音数异常");
                            return Error("获获取中间件放音数失败");
                        }
                        #endregion
                        #endregion

                        totalnum = await _call_outtasktelnumRepository.Count(x => x.taskid == id&&x.deleteflag ==0);

                        yhnum = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == id);
                        zyds = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == id&&x.is_call_out_ok==1);
                        zzzxs = await _mw_autocall_call_recordRepository.Count(x => x.task_icon == id && x.is_turn_agent_ok == 1);
                        
                        //hjzsc = 0;
                        #region 统计呼叫时长
                        var list = new List<FilterDefinition<MW_Autocall_Call_Record>>();
                        list.Add(Builders<MW_Autocall_Call_Record>.Filter.Eq("task_icon", id));
                        var filter = Builders<MW_Autocall_Call_Record>.Filter.And(list);
                        var tasklist = await _mw_autocall_call_recordRepository.Get(filter, null, null );
                        List<MW_Autocall_Call_Record> asList = tasklist.ToList();
                        if (asList != null)
                        {
                            foreach (var item in asList)
                            {
                                hjzsc += item.talk_time_len;
                            }
                        }
                        #endregion

                        dqhhs = thrs + fys;
                        if (totalnum > 0)
                        {
                            ywc = Math.Round ((decimal.Parse(yhnum.ToString()) / decimal.Parse(totalnum.ToString())*100),2).ToString() + "%";
                        }
                        if (zyds > 0)
                        {
                            zzxl = Math.Round((decimal.Parse(zzzxs.ToString()) / decimal.Parse(zyds.ToString()) * 100),2).ToString() + "%";
                        }
                        if (yhnum > 0)
                        {
                            ydl = Math.Round((decimal.Parse(zyds.ToString()) / decimal.Parse(yhnum.ToString()) * 100),2).ToString() + "%";
                        }

                        var obj = new
                        {
                            state = "success",
                            message = "获取任务监控信息成功",
                             createtime ,
                         starttime ,
                         endtime ,
                         workstarttimes1 ,
                         workendtimes1 ,
                         workstarttimes2 ,
                         workendtimes2,
                         zxrs ,
                         thrs ,
                         kxrs ,
                         totalnum ,
                         yhnum ,
                         zyds ,
                         zzzxs ,
                         dqhhs,
                         hjzsc ,
                         ywc ,
                         ydl ,
                         zzxl ,
                         fys ,
                        bftype ,
                        bfnum
                    };
                        return Content(obj.ToJson());
                        
                    }
                    else
                    {
                        return Error("此任务信息不存在");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取任务监控信息异常");
                    return Error("获取任务监控信息失败");
                }
            }
            else
            {
                return Error("获取任务监控信息失败");
            }

        }

        //获取任务参与坐席
        [HttpGet("checkjoin")]
        public async Task<int > CheckJoinState(string taskid,string agentid)
        {
            int ret = -1;
            #region 获取路径

            var dModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("ACDAutoCall") & s.isdelete == false, null);
            string acdip = dModel.paramvalue;

            #endregion
            
           
            //实体序列化和反序列化
            string strURL = "http://" + acdip + "/v1/acd/group/resource/infoagent?group=" + taskid;
            string strHTML0 = MadRunFabric.Common.HttpMethods.HttpGet(strURL);
            JObject jo0 = (JObject)JsonConvert.DeserializeObject(strHTML0);
            if (jo0 != null )
            {
                //jo0["agents"] = "[8000,8001,8002]";
                if (jo0["agents"] != null&& jo0["agents"].ToString()!="[]")
                {
                    int l = jo0["agents"].ToString().Length;
                    string s = jo0["agents"].ToString().Substring(1,l-2);
                    string[] strs = s.Split(',');
                    //JArray jsonArray = JArray.FromObject(jo0["agents"].ToString()); //把list的值转为json数组对象。
                    //Object[] strs = jsonArray.ToArray();
                    if (strs != null && strs.Length > 0)
                    {
                        foreach (var item in strs)
                        {
                            if (item.ToString() .Contains ( "\r\n  "+ agentid ))
                            {
                                ret = 1;
                                return ret;
                            }
                        }
                        ret = 0;
                    }
                    ret = 0;
                }
                 

            }
            return ret;
        }

        //获取自动外呼前缀
        public async Task<string> GetCallOutprefix(string phone)
        {
            int i;
            bool isnum = int.TryParse(phone.Substring(0, 1), out i);//判断是否为数字
            if (!isnum)
            {
                return "";
            }
            string phone1 = phone;
            string tophone = phone1;
            string zipcode = ""; string bfix = "0"; string wfix = ""; string fix = "";

            var dModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("ZDWHQZ") & s.isdelete == false, null);
            string whqz = dModel.paramvalue;
            if (whqz != "")
            {
                var typearr = whqz.Split('#');
                if (typearr.Length > 2)
                {
                    zipcode = typearr[2];
                    bfix = typearr[1];
                    wfix = typearr[0];
                    int zip = 0;
                    #region
                    if (phone.Trim().Length >= 7)
                    {
                        //7位及7位以上是固定电话或手机
                        //判断是否手机
                        if (phone.Trim().Length == 11 && phone[0] == '1')
                        {//号码为11位，首位是1，为手机号
                         //BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                         //Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModelList("F_MobileNum='" + phone.Substring(0, 7) + "'").FirstOrDefault();
                         //_call_mobiledataRepository
                            var mobileModel = await _call_mobiledataRepository.Get(x => x.mobilenum == phone.Substring(0, 7));
                            if (mobileModel != null)
                            {
                                foreach (var items in mobileModel)
                                {
                                    if (items.zipcode.Equals(zipcode))
                                    {
                                        zip = 1;
                                    }
                                    else
                                    {
                                        zip = 2;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (phone.Trim().Length == 11 && phone.Substring(0, 3).Equals(zipcode))
                            {//号码为11位
                             //截取前三位区号判断是否本地
                                bool resbd3 = phone.Substring(0, 3).Equals(zipcode);
                                //截取前四位区号判断是否本地
                                bool resbd4 = phone.Substring(0, 4).Equals(zipcode);
                                if (resbd3 || resbd4)
                                {
                                    zip = 3;
                                }
                                else
                                {
                                    zip = 4;
                                }
                            }
                            else if (phone.Trim().Length < 11)
                            {//号码小于11位，为本地
                                zip = 3;
                            }
                            else if (phone.Trim().Length > 11 && phone.Substring(0, 4).Equals(zipcode))
                            {//号码大于11位，截取前四位区号判断是否本地
                                zip = 3;
                            }
                            else
                            {
                                zip = 4;
                            }
                        }
                    }
                    #endregion
                    #region 
                    if (zip == 1)
                    {//手机本地号码
                        fix = bfix;
                    }
                    else if (zip == 2)
                    {//手机外地号码
                        fix = wfix;
                    }
                    else
                    {
                        tophone = phone1.TrimStart('0');
                        if (zip == 3)
                        {//本地固话去0加9 比如：988888517，937188888517
                            fix = bfix;
                        }
                        else if (zip == 4)
                        {//外地固话前加9 比如：9037188888517
                            fix = wfix;
                        }
                    }
                    #endregion
                    //var obj = new
                    //{
                    //    phone = fix + tophone,
                    //    fix = fix
                    //};
                    string y = fix + tophone;
                    return y;
                }
            }
            else//默认本地
            {
                fix = bfix;
                string y = fix + tophone;
                return y;
            }


            return "";


        }

    }

}
