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

namespace CallCenterApi.Controllers
{
    /// <summary>
    /// 外呼任务控制器 存储获取外呼任务号码及相关信息
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/AutoCall")]
    public class AutoCallController : BaseController
    {
        private readonly ILogger<AutoCallController> _logger;
        private readonly ICall_AutoCallNumRepository _call_autocallnumRepository;
        private readonly ISys_SystemConfigRepository _sys_systemconfigRepository;
        private readonly ICall_OutTaskFPRepository _call_outtaskfpRepository;
        private readonly ICall_OutTaskRepository _call_outtaskRepository;
        private readonly ICall_OutTaskTelNumRepository _call_outtasktelnumRepository;
        private readonly ICall_MobileDataRepository _call_mobiledataRepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISys_SeatGroupRepository _sys_seatgroupRepository;
        private readonly IMW_Autocall_Call_RecordRepository _mw_autocall_call_recordRepository;
        private readonly ICall_OutTaskTelNumRecordRepository _call_outtasktelnumrecordRepository;
        

        public AutoCallController(ILogger<AutoCallController> logger, ICall_AutoCallNumRepository call_autocallnumRepository, ISys_SystemConfigRepository sys_systemconfigRepository, ICall_OutTaskFPRepository call_outtaskfpRepository,ICall_OutTaskRepository call_outtaskRepository, ICall_OutTaskTelNumRepository call_outtasktelnumRepository, ICall_MobileDataRepository call_mobiledataRepository, ISys_User_AccountRepository sys_user_accountRepository, ISys_SeatGroupRepository sys_seatgroupRepository, IMW_Autocall_Call_RecordRepository mw_autocall_call_recordRepository,ICall_OutTaskTelNumRecordRepository call_outtasktelnumrecordRepository)
        {
            _logger = logger;
            _call_autocallnumRepository =call_autocallnumRepository;
            _sys_systemconfigRepository = sys_systemconfigRepository;
            _call_outtaskfpRepository = call_outtaskfpRepository;
            _call_outtaskRepository = call_outtaskRepository;
            _call_outtasktelnumRepository = call_outtasktelnumRepository;
            _call_mobiledataRepository = call_mobiledataRepository;
            _sys_user_accountRepository = sys_user_accountRepository;
            _sys_seatgroupRepository = sys_seatgroupRepository;
            _mw_autocall_call_recordRepository = mw_autocall_call_recordRepository;
            _call_outtasktelnumrecordRepository = call_outtasktelnumrecordRepository;
        }

        [HttpGet]
        public string Get()
        {
            _call_autocallnumRepository.RemoveAll();

            _call_autocallnumRepository.Add(new Call_AutoCallNum() { task_icon  = "364", call_number = "018937115568", voice_file_name = "", record_file_name = "" });
            _call_autocallnumRepository.Add(new Call_AutoCallNum() { task_icon = "364", call_number = "012345678945", voice_file_name = "", record_file_name = "" });
            _call_autocallnumRepository.Add(new Call_AutoCallNum() { task_icon = "364", call_number = "015378755972", voice_file_name = "", record_file_name = "" });
            _call_autocallnumRepository.Add(new Call_AutoCallNum() { task_icon = "364", call_number = "017739071022", voice_file_name = "", record_file_name = "" });

            return "初始化数据成功";
        }

        //2018-7-20导入预测外呼号码
        /// <summary>
        /// 导入预测外呼号码
        /// </summary>
        /// <returns></returns>
        [HttpPost("importautocall")]
        public async Task<IActionResult> ImportAutoCall()
        {
            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_AutoCallNum> ICalls = ModelConvertHelper<Call_AutoCallNum>.ConvertToModel(dtExcel);
                List<Call_AutoCallNum> calls = ModelConvertHelper<Call_AutoCallNum>.ConvertIListToList(ICalls);
                int num = calls.Count;
                int isuccess = 0;
                foreach (var eq in calls)
                {
                    #region 保存数据库
                    var model = new Call_AutoCallNum();
                    model.call_number = eq.call_number;
                    model.task_icon   = eq.task_icon  ;
                    model.record_file_name = eq.record_file_name;
                    model.voice_file_name  = eq.voice_file_name;
                    bool b = await _call_autocallnumRepository.Add(model);
                    if (b)
                        isuccess++;

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

        //POST开启预测外呼
        [HttpPost("startprecall")]
        public async Task<IActionResult> StartPreCall(string taskid)
        {
            //taskid = "5b63c7e3672619914f9d9338";
            #region 获取路径

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

            #endregion
            //测试用
            /*string strURL = "http://192.168.5.41:10003/v1/pcp/qy";
            var m = new
            {
                task = "364",
                type = 100
            };*/

            string strURL = "http://" + acdip + "/v1/acd/precall";
            var m = new
            {
                task = taskid,
                type = 1
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["state"].ToString() == "success")
            {
                return Success("开启预测外呼成功");  
            }
            return Error("开启预测外呼失败"); 
        }

        //DELETE结束预测外呼
        [HttpPost("stopprecall")]
        public async Task<IActionResult> StopPreCall(string taskid)
        {
            #region 获取路径

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

            #endregion
            //groupid = "364";
            string strURL = "http://"+ acdip + "/v1/acd/precall";
            var m = new
            {
                task = taskid,
                type = 11
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["state"].ToString() == "success")
            {
                return Success("结束预测外呼成功");
            }
            return Error("结束预测外呼失败");
        }

        //坐席参与预测外呼
        [HttpPost("joinprecall")]
        public async Task<IActionResult> JoinPreCall(string taskid,string agentid,int joinflag = 0)
        {
            //taskid = "5b63c98a672619914f9d933b";
            //agentid = "8000";
            //joinflag = 1;
            var ml = await _call_outtaskfpRepository.GetSingle(p => p.taskid == taskid && p.usercode == agentid && p.deleteflag ==0);
            ml.joinflag = joinflag;
            if (await _call_outtaskfpRepository.Update(ml))
            //return Success("参与标志更新成功");

            //else
            //return Error("参与标志更新失败");
            {
                #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/precall";
                if (joinflag == 1)
                {
                    var m = new
                    {
                        task = taskid,
                        agent = agentid,
                        type = 2
                    };
                    //实体序列化和反序列化
                    string json1 = JsonConvert.SerializeObject(m);
                    string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
                    JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
                    if (jo1 != null && jo1["state"].ToString() == "success")
                    {
                        return Success("坐席参与外呼成功");
                    }
                    return Error("坐席参与外呼失败");
                }
                else
                {
                    var m = new
                    {
                        task = taskid,
                        agent = agentid,
                        type = 12
                    };
                    //实体序列化和反序列化
                    string json1 = JsonConvert.SerializeObject(m);
                    string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
                    JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
                    if (jo1 != null && jo1["state"].ToString() == "success")
                    {
                        return Success("坐席退出外呼成功");
                    }
                    return Error("坐席退出外呼失败");
                }
            }
            else
               return Error("参与标志更新失败");
        }

        //设定并发数
        [HttpPost("setbfnum")]
        public async Task<IActionResult> SetBFNum(string taskid,int bfnum,string bftype)
        {
            #region 获取路径

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

            #endregion
            //groupid = "364";
            string strURL = "http://" + acdip + "/v1/acd/precall";
            var m = new
            {
                task = taskid,
                type = 20,
                num=bfnum 
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["state"].ToString() == "success")
            {
                #region
                var ml = await _call_outtaskRepository.GetSingle(x => x.id == taskid);
                ml.bfnum  = bfnum;
                if (bftype != null)
                {
                    ml.bftype = bftype;
                }

                if (await _call_outtaskRepository.Update(ml))
                { return Success("并发数修改成功"); }
                else
                { return Error("任务并发数修改失败"); }
                
                #endregion
                //return Success("并发数设定成功");
            }
            return Error("并发数设定失败");
        }

        //POST请求
        [HttpPost("postsend")]
        public async Task<IActionResult> PostSend(string paramcode,  string  postobj)//, JObject postcontent = null)//[FromBody]JObject postcontent,
        {

            var dModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals(paramcode) & s.isdelete == false, null);
            string posturl = dModel.paramvalue;
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(posturl, postobj);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);

            if (jo1 != null)
            {
                return Success("post请求成功", jo1);
            }
            return Error("post请求失败");
        }

        //将外呼号码转存至外呼表
        [HttpPost("transferold")]
        public async Task<IActionResult> TransferAsyncOLD(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);
                var taskinfo = await _call_outtaskRepository.GetSingle(x => x.id == taskid );
                string voicepath = "";
                int calltype = 0;
                if (taskinfo != null)
                {
                    calltype = taskinfo.calltype;
                    if (calltype > 0)
                    {
                        List<FileBaseModel> voice = taskinfo.voicepath;
                        if (calltype != 3)
                        {
                            if (voice.Count > 0)
                            {
                                voicepath = voice[0].fileurl;
                            }
                        }
                        else 
                        if (calltype == 3)
                        {
                            if (taskinfo.voicestring != null)
                            {
                                voicepath = taskinfo.voicestring;
                            }
                        }
                    }
                }
                int tnum = tlist.Count();
                if (tlist != null)
                {
                    foreach (var titem in tlist)
                    {
                        #region 
                        Call_AutoCallNum model = new Call_AutoCallNum();
                        model.task_icon  = taskid;
                        model.flag = calltype;
                        model.invalid_flag  = 1;
                        model.timestamp = DateTimeConvert.ToTimespan(DateTime.Now);//保存导入时间时间戳
                        //model.cusaddr = titem.cusaddr;
                        model.call_number  = titem.phone;
                        Task<string> y = GetCallOutprefix(titem.phone);
                        if (y.Result != "")
                        {
                            model.call_number = y.Result;
                        }
                        //获取放音文件路径
                        if (voicepath != "")
                        {
                            model.voice_file_name = voicepath;
                        }
                       
                        var aclist = await _call_autocallnumRepository.GetSingle(x => x.task_icon  == taskid && x.call_number  == model.call_number&&x.invalid_flag ==1);
                        if (aclist == null)
                        {
                            if (await _call_autocallnumRepository.Add(model))
                                res++;
                        }

                        #endregion
                        
                    }
                    if (res == tnum)
                    {
                        //await _call_outtasktelnumRepository.Remove(x => x.taskid == taskid);//转存成功删除数据
                        
                        return Success("任务号码转存成功");
                    }

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

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

        //将外呼号码转存至外呼表
        [HttpPost("transfer")]
        public async Task<IActionResult> TransferAsync(string taskid)
        {
            try
            {
                var list = new List<FilterDefinition<Call_AutoCallNum>>();
                //list.Add(Builders<Call_AutoCallNum>.Filter.Eq("deleteflag", 0));
                list.Add(Builders<Call_AutoCallNum>.Filter.Where(s => s.task_icon .Equals(taskid)));
                int res = 0;
                var filter = Builders<Call_AutoCallNum>.Filter.And(list);
                var tlist = await _call_autocallnumRepository.Get(filter);
                var taskinfo = await _call_outtaskRepository.GetSingle(x => x.id == taskid);
                string voicepath = "";
                int calltype = 0;
                if (taskinfo != null)
                {
                    calltype = taskinfo.calltype;
                    if (calltype > 0)
                    {
                        List<FileBaseModel> voice = taskinfo.voicepath;
                        if (calltype != 3)
                        {
                            if (voice.Count > 0)
                            {
                                voicepath = voice[0].fileurl;
                            }
                        }
                        else
                        if (calltype == 3)
                        {
                            if (taskinfo.voicestring != null)
                            {
                                voicepath = taskinfo.voicestring;
                            }
                        }
                    }
                }
                int tnum = tlist.Count();
                if (tlist != null)
                {
                    int ii = 0;
                    #region
                    foreach (var titem in tlist)
                    {
                        titem.timestamp = DateTimeConvert.ToTimespan(DateTime.Now);

                        titem.flag = calltype;
                        titem.voice_file_name = voicepath;
                        titem.invalid_flag = 1;

                        var t = await _call_autocallnumRepository.Update(titem);
                        if (t)
                            ii += 1;
                    }
                    if (ii > 0)
                    {
                        return Success("自动外呼号码表更新成功");
                    }
                    else
                    {
                        return Error("自动外呼号码表更新失败");
                    }
                    #endregion

                    #region 更新标志
                    //Call_AutoCallNum imodel = new Call_AutoCallNum();
                    //    Dictionary<string, string> dic = new Dictionary<string, string>();
                    //    dic.Add("flag", calltype.ToString ());
                    //    //dic.Add("timestamp", DateTimeConvert.ToTimespan(DateTime.Now).ToString ());
                    //    if (voicepath != "")
                    //    {
                    //        dic.Add("voice_file_name", voicepath);
                    //    }
                        
                    //    dic.Add("invalid_flag", "1");
                    //    var listc = new List<FilterDefinition<Call_AutoCallNum>>();
                    //    var filterBuilder = Builders<Call_AutoCallNum>.Filter;
                    //    listc.Add(filterBuilder.Eq("task_icon", taskid));
                    //    var filterc = Builders<Call_AutoCallNum>.Filter.And(listc);
                    //    var tt = await _call_autocallnumRepository.UpdateManay(imodel, dic, filterc);
                    //    if (tt)
                    //    {
                    //        return Success("自动外呼号码表更新成功");
                    //    }
                    //    else
                    //    { return Error("自动外呼号码表更新失败"); }
                    #endregion

                    


                    }
                else
                {
                    return Error("任务没有数据");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "自动外呼号码表更新异常");
                return Error("自动外呼号码表更新失败");
            }
        }

        //获取自动外呼前缀
        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 "";


        }

        //任务重新执行
        //将外呼号码转存至外呼表
        [HttpPost("restart")]
        public async Task<IActionResult> TransfersAsync(string taskid)
        {
            try
            {
                //先创建一个新任务
                #region 创建新任务
                long n = await _call_outtaskRepository.Count(x => x.taskid == taskid ||x.id ==taskid );
                var aclist = await _call_outtaskRepository.GetSingle(x => x.id  == taskid);
                if (aclist != null)
                {
                    string oid = aclist.taskid;
                    if (oid!=null&&oid != "")
                    {
                        n = await _call_outtaskRepository.Count(x => x.taskid == oid  || x.id == oid);
                    }
                    string oldtaskid = taskid;
                    string oldtaskname= aclist.taskname + "##" + (n+1).ToString();
                    string newtaskname = oldtaskname;
                    string newremark = aclist.taskremark + "(" + (n + 1).ToString() + "次执行)"; 
                    if (n > 1)
                    {
                        var ac = await _call_outtaskRepository.GetSingle(x => x.id == oid);
                        oldtaskid = aclist.taskid;
                        //int index = oldtaskname.IndexOf("##");
                        //oldtaskname = oldtaskname.Substring(0, index + 2);
                        //newtaskname = oldtaskname + (n+1).ToString();
                        if (ac != null)
                        {
                            newtaskname =ac .taskname + "##" + (n + 1).ToString();
                            newremark = ac.taskremark + "(" + (n + 1).ToString() + "次执行)";
                        }
                    }

                    Call_OutTask comodel = new Call_OutTask();
                    //var re = false;
                    comodel.taskid = oldtaskid;//用于关联任务
                    comodel.taskname = newtaskname;//名字包含##的任务为非首次执行，在重新执行创建任务时转存数据
                    comodel.taskremark = newremark ;
                    comodel.starttime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");                                        
                    comodel.endtime = DateTime.Now.AddDays(2).ToString("yyyy-MM-dd");                     
                    comodel.isallot = aclist .isallot;
                    comodel.isstart = 0;
                    comodel.isonline = aclist .isonline;
                    comodel.createusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //aclist.createusercode;//
                    comodel.deleteflag = 0;
                    comodel.createtime = DateTime.Now.ToLocalTime();
                    comodel.workstarttimes1 = aclist.workstarttimes1;
                    comodel.workendtimes1 = aclist.workendtimes1;
                    comodel.workstarttimes2 = aclist.workstarttimes2;
                    comodel.workendtimes2 = aclist.workendtimes2;
                    comodel.voicepath = aclist.voicepath;
                    comodel.voicestring = aclist.voicestring;
                    comodel.pressnum = aclist.pressnum;
                    comodel.bftype = aclist.bftype;
                    comodel.bfnum = aclist.bfnum;
                    comodel.calltype = aclist.calltype;

                    //calltype,string voicepath,string pressnum,string bftype,int bfnum
                    string tid = await _call_outtaskRepository.AddRetID(comodel);
                    if (tid!=null )
                    {
                        //将号码转存至外呼表
                        #region 
                        var list = new List<FilterDefinition<MW_Autocall_Call_Record>>();

                        list.Add(Builders<MW_Autocall_Call_Record>.Filter.Where(s => s.task_icon.Equals(taskid)&&s.is_call_out_ok ==0));
                        int res = 0;
                        var filter = Builders<MW_Autocall_Call_Record>.Filter.And(list);
                        var tlist = await _mw_autocall_call_recordRepository.Get(filter);
                        int tnum = tlist.Count();
                        if (tlist != null)
                        {
                            foreach (var titem in tlist)
                            {
                                #region 
                                Call_AutoCallNum model = new Call_AutoCallNum();
                                model.task_icon = titem.task_icon;
                                model.flag = 0;
                                model.invalid_flag = 1;
                                model.timestamp = DateTimeConvert.ToTimespan(DateTime.Now);//保存导入时间时间戳
                                                                                           //model.cusaddr = titem.cusaddr;
                                model.call_number = titem.callee;


                                var acslist = await _call_autocallnumRepository.GetSingle(x => x.task_icon == taskid && x.call_number == model.call_number && x.invalid_flag == 1);
                                if (acslist == null)
                                {
                                    if (await _call_autocallnumRepository.Add(model))
                                        res++;
                                }

                                #endregion

                            }
                            if (res == tnum)
                            {
                                //await _call_outtasktelnumRepository.Remove(x => x.taskid == taskid);//转存成功删除数据
                                #region 坐席分配
                                var ml = await _call_outtaskfpRepository.Get(p => p.taskid == taskid && p.deleteflag == 0);
                                if (ml != null)
                                {
                                    int rt = 0;
                                    foreach (var items in ml)
                                    {
                                        Call_OutTaskFP fmodel = new Call_OutTaskFP();
                                        fmodel.taskid = tid;
                                        fmodel.usercode = items .usercode ;
                                        fmodel.createusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                                        fmodel.deleteflag = 0;
                                        fmodel.createtime = DateTime.Now.ToLocalTime();

                                        if (await _call_outtaskfpRepository.Add(fmodel))
                                            rt++;
                                    }
                                }
                                #endregion

                                aclist.secondflag = 1;
                                await _call_outtaskRepository.Update(aclist);
                                return Success("任务重新执行操作成功");
                            }

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

                        }
                        else
                        {
                            return Error("任务没有数据");
                        }
                        #endregion
                    }
                    else
                        return Error("任务保存失败");
                }
                #endregion
                return Error("任务数据获取失败");

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "任务号码转存异常");
                return Error("任务号码转存失败");
            }
        }

        #region 开启、暂停、停止外呼
        //private bool issuccess = false;
        [HttpPost("precallope")]
        public async Task<IActionResult> precallope(string taskid, int type,int isautocall=1)//type为1时启动任务，为10时暂停任务，为11时停止任务
        {
            try
            {
                if (isautocall == 1)
                {
                    #region 获取路径

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

                    #endregion
                    //var ml = await _collection.Find(p => p.id == taskid && p.deleteflag == 0).FirstOrDefaultAsync();

                    string strURL = "http://" + acdip + "/v1/acd/precall";
                    var m = new
                    {
                        task = taskid,
                        type = type
                    };
                    //实体序列化和反序列化
                    string json1 = JsonConvert.SerializeObject(m);
                    string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
                    JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
                    if (jo1 != null && jo1["state"].ToString() == "success")
                    {
                        var tModel = await _call_outtaskRepository.GetSingle(s => s.id == taskid);
                        if (tModel != null)
                        {
                            if (type == 1)
                            {
                                if (tModel.isstart == 0)
                                { var c = TransferAsync(taskid); }
                                tModel.isstart = 1;
                                tModel.ishand = 1;
                            }
                            else if (type == 10)
                            {
                                tModel.isstart = 2;
                                tModel.ishand = 1;
                            }
                            else if (type == 11)
                            {
                                tModel.isstart = 3;
                                var x = TransferData(taskid);
                            }
                            if (await _call_outtaskRepository.Update(tModel))
                            {
                                string ope = "启动";
                                if (type == 10)
                                {
                                    ope = "暂停";
                                }
                                else if (type == 11)
                                {
                                    ope = "停止";
                                }
                                return Success("任务" + ope + "成功");
                            }
                            else
                            {
                                return Error("任务操作失败");
                            }
                        }
                        return Error("任务标志更新失败");
                    }

                    return Error("任务操作失败");
                }
                else
                {
                    var tModel = await _call_outtaskRepository.GetSingle(s => s.id == taskid);
                    tModel.isstart = 1;
                    if (type == 1)
                    {
                       
                        tModel.isstart = 1;
                       
                    }
                    else if (type == 10)
                    {
                        tModel.isstart = 2;
                        
                    }
                    else if (type == 11)
                    {
                        tModel.isstart = 3;
                        
                    }
                    tModel.ishand = 1;
                    if (await _call_outtaskRepository.Update(tModel))
                    {
                        return Success("任务操作成功");
                    }
                    else
                    { return Error("任务操作失败"); }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "任务操作异常");
                return Error("任务操作失败");
            }
        }
        #endregion

        //任务结束时转存任务数据

        [HttpPost("transferdata")]
        public async Task<IActionResult> TransferData(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);//转存成功，删除数据
                        return Success("任务转存成功");
                    }

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

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