using CallCenter.Utility;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Dto;
using CallCenterApi.Interface.Models.Filter;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.callout
{
    public class CallPlanController : BaseController
    {
        private BLL.T_CTI_Task taskBLL = new BLL.T_CTI_Task();
        private BLL.T_Call_TaskTelNum taskTellNumBLL = new BLL.T_Call_TaskTelNum();
        private BLL.T_Sys_DictionaryValue dictValueBLL = new BLL.T_Sys_DictionaryValue();
        private BLL.T_CTI_TaskAgent taskAgentBLL = new BLL.T_CTI_TaskAgent();
        private BLL.T_Sys_UserAccount userAccount = new BLL.T_Sys_UserAccount();
        private BLL.T_CTI_TaskRecord taskRecordBLL = new BLL.T_CTI_TaskRecord();
        private BLL.CallResult callResultBLL = new BLL.CallResult();
        private BLL.T_CTI_TaskDaily taskDailyBLL = new BLL.T_CTI_TaskDaily();
        private BLL.T_CTI_TaskPhonePart taskPhonePartBLL = new BLL.T_CTI_TaskPhonePart();

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public ActionResult GetList(FilterCallPlan filter)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var sql = " and State>=0  and TaskType=" + filter.TaskType;
            if (!string.IsNullOrWhiteSpace(filter.Name))
            {
                sql += "  and (TaskName like '%" + filter.Name.Trim() + "%' ) ";
            }

            Model.PageData<Model.T_CTI_Task> pageModel = new Model.PageData<Model.T_CTI_Task>();
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                             "T_CTI_Task",
                             "TaskID",
                             "*",
                             sql,
                             "ORDER BY AddTime desc",
                             filter.PageSize,
                             filter.PageIndex,
                             true,
                             out recordCount);
            List<Model.T_CTI_Task> modelList = new BLL.T_CTI_Task().DataTableToList(dt);
            var list = new List<CallPlanDto>();

            //查询坐席组
            var agentGroupList = dictValueBLL.DataTableToList(dictValueBLL.GetList(" F_DictionaryFlag='ZXZ'").Tables[0]);
            //查询坐席
            var agentList = userAccount.DataTableToList(userAccount.GetList(" F_DeleteFlag=0 ").Tables[0]);

            foreach (var model in modelList)
            {
                string calledRate = "0";
                var allcount = model.y_HMCount ?? 0;
                float calledcount = model.y_HCCount ?? 0;
                calledRate = allcount == 0 ? "" : calledcount / allcount * 100 + "%";

                string connectedRate = "0";
                float connected = model.y_YJCount ?? 0;
                connectedRate = calledcount == 0 ? "0" : connected / calledcount * 100 + "%";

                var taskTellNumDt = taskTellNumBLL.GetList(" F_HCState=1 and F_YJState=1 and F_UserId>0 ").Tables[0];
                float connectedAgentCount = taskTellNumDt?.Rows.Count ?? 0;
                var connectedAgentRate = "0";
                connectedAgentRate = connected == 0 ? "0" : connectedAgentCount / connected * 100 + "%";

                var agentGroup = agentGroupList.SingleOrDefault(x => x.F_DictionaryValueId == model.AgentGroupId);
                var agentCount = agentList.Where(x => x.F_GroupId == (agentGroup?.F_DictionaryValueId ?? 0)).Count();
                list.Add(new CallPlanDto
                {
                    id = model.TaskID,
                    name = model.TaskName,
                    tasktype = model.TaskType == 1 ? "点击外呼" : "自动外呼",
                    state = Enum.GetName(typeof(EnumTaskState), (model.State ?? -1)),
                    addtime = Convert.ToDateTime(model.AddTime).ToString("yyyy-MM-dd HH:mm:ss"),
                    talkid = model.y_TkModelId ?? 0,
                    pre = model.Pre, //线路前缀
                    concurrencytype = model.ConcurrencyType,
                    concurrency = model.Concurrency,
                    planstartdate = model.PlanStartDate.ToString("yyyy-MM-dd"),
                    planenddate = model.PlanEndDate.ToString("yyyy-MM-dd"),
                    starttime1 = model.StartTime1.ToString("HH:mm:ss"),
                    endtime1 = model.EndTime1.ToString("HH:mm:ss"),
                    starttime2 = model.StartTime2.ToString("HH:mm:ss"),
                    endtime2 = model.EndTime2.ToString("HH:mm:ss"),
                    agentgroup = agentGroup?.F_Name ?? "",//坐席组
                    agentcount = agentCount,//坐席组人数
                    allcount = model.y_HMCount ?? 0,     //号码总数
                    calledcount = model.y_HCCount ?? 0,  //已呼个数
                    calledrate = calledRate,             //已完成百分比
                    callleftcount = (int)(allcount - calledcount), //剩余个数
                    connected = model.y_YJCount ?? 0,    //总应答数
                    connectedrate = connectedRate,       //应答率
                    connectedagentcount = (int)connectedAgentCount,             //转坐席数
                    connectedagentrate = connectedAgentRate,             //转坐席率   
                });


            }
            var obj = new
            {
                rows = list,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetModel(int id)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = taskBLL.GetModel(id);

            //计算数据
            string calledRate = "0";
            var allcount = model.y_HMCount ?? 0;
            float calledcount = model.y_HCCount ?? 0;
            calledRate = allcount == 0 ? "" : calledcount / allcount * 100 + "%";

            string connectedRate = "0";
            float connected = model.y_YJCount ?? 0;
            connectedRate = calledcount == 0 ? "0" : connected / calledcount * 100 + "%";

            var taskTellNumDt = taskTellNumBLL.GetList(" F_HCState=1 and F_YJState=1 and F_UserId>0 ").Tables[0];
            float connectedAgentCount = taskTellNumDt?.Rows.Count ?? 0;
            var connectedAgentRate = "0";
            connectedAgentRate = connected == 0 ? "0" : connectedAgentCount / connected * 100 + "%";

            //查询坐席组
            var agentGroupList = dictValueBLL.DataTableToList(dictValueBLL.GetList(" F_DictionaryFlag='ZXZ'").Tables[0]);
            //查询坐席
            var agentList = userAccount.DataTableToList(userAccount.GetList(" F_DeleteFlag=0 ").Tables[0]);


            var agentGroup = agentGroupList.SingleOrDefault(x => x.F_DictionaryValueId == model.AgentGroupId);
            var agentCount = agentList.Where(x => x.F_GroupId == (agentGroup?.F_DictionaryValueId ?? 0)).Count();

            return Success("获取成功", new CallPlanDto
            {
                id = model.TaskID,
                name = model.TaskName,
                tasktype = model.TaskType == 1 ? "点击外呼" : "自动外呼",
                state = "暂停",
                addtime = Convert.ToDateTime(model.AddTime).ToString("yyyy-MM-dd HH:mm:ss"),
                talkid = model.y_TkModelId ?? 0,
                pre = model.Pre, //线路前缀
                concurrencytype = model.ConcurrencyType,
                concurrency = model.Concurrency,
                planstartdate = model.PlanStartDate.ToString("yyyy-MM-dd"),
                planenddate = model.PlanEndDate.ToString("yyyy-MM-dd"),
                starttime1 = model.StartTime1.ToString("HH:mm"),
                endtime1 = model.EndTime1.ToString("HH:mm"),
                starttime2 = model.StartTime2.ToString("HH:mm"),
                endtime2 = model.EndTime2.ToString("HH:mm"),
                agentgroupid = agentGroup?.F_DictionaryValueId ?? 0,
                agentgroup = agentGroup?.F_Name ?? "",//坐席组
                agentcount = agentCount,//坐席组人数
                allcount = model.y_HMCount ?? 0,     //号码总数
                calledcount = model.y_HCCount ?? 0,  //已呼个数
                calledrate = calledRate,             //已完成百分比
                callleftcount = (int)(allcount - calledcount), //剩余个数
                connected = model.y_YJCount ?? 0,    //总应答数
                connectedrate = connectedRate,       //应答率
                connectedagentcount = (int)connectedAgentCount,             //转坐席数
                connectedagentrate = connectedAgentRate,             //转坐席率    
            });
        }

        /// <summary>
        /// 添加/修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult CreateOrUpdate(CallPlanInput input)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = new Model.T_CTI_Task();

            if (input.Id <= 0)
            {
                model.TaskID = input.Id;
                model.TaskName = input.Name;
                model.TaskType = input.Type;
                model.AgentGroupId = input.AgentGroupId;
                model.y_TkModelId = input.PagerId;
                model.Pre = input.Pre;
                if (input.ConcurrencyType == 0)
                {
                    var num = 0;
                    if (!int.TryParse(input.Concurrency.ToString(), out num))
                        return Error("并发数必须为不小于1的整数");
                    input.Concurrency = (int)input.Concurrency;
                }
                if (input.Concurrency < 1)
                    return Error("输入的并发数和进号速率必须不小于1");
                model.ConcurrencyType = input.ConcurrencyType;
                model.Concurrency = input.ConcurrencyType == 0 ? (int)input.Concurrency : input.Concurrency;
                model.y_HMCount = 0;
                model.y_HCCount = 0;
                model.y_YJCount = 0;
                model.y_HTCount = 0;
                model.TrunkGroupID = 0;
                model.CallType = 1;
                model.State = 2;
                model.AddTime = DateTime.Now;
                model.y_PSort = 2;
                model.y_SXH = 0;
                model.y_FPCount = 0;
                model.y_HSCount = 0;
                model.y_OkCount = 0;
                model.y_RFCount = 0;
                model.y_ConsCount = 0;
                model.y_InvlCount = 0;
                model.y_NoAnswerCount = 0;
                model.y_ShutDownCount = 0;
                model.PlanStartDate = input.PlanStartDate;
                model.PlanEndDate = input.PlanEndDate;
                model.StartTime1 = input.StartTime1;
                model.EndTime1 = input.EndTime1;
                model.StartTime2 = input.StartTime2;
                model.EndTime2 = input.EndTime2;
                var taskId = taskBLL.Add(model);
                if (taskId > 0)
                {
                    // return Success("添加成功", i);
                        model.TaskID = taskId;
                        DataTable dt = taskTellNumBLL.GetTableDesign();
                        switch (input.ImportType)
                        {
                            case 1: //从文本文件导入
                                var file = Request.Files[0];
                                using (StreamReader sr = new StreamReader(file.InputStream))
                                {
                                    String line;
                                    while ((line = sr.ReadLine()) != null)
                                    {
                                        var row = dt.NewRow();
                                        row["F_TaskId"] = model.TaskID;
                                        row["F_Phone"] = line.ToString();
                                        dt.Rows.Add(row);
                                    }
                                }
                                break;
                            case 2: //从文本框中导入
                                if (string.IsNullOrWhiteSpace(input.PhoneList))
                                    return Error("号码不可以为空");
                                var arr = input.PhoneList.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var p in arr)
                                {
                                    var row = dt.NewRow();
                                    row["F_TaskId"] = model.TaskID;
                                    row["F_Phone"] = p;
                                    dt.Rows.Add(row);
                                }
                                break;
                            case 3: //从号码段导入
                                if (string.IsNullOrWhiteSpace(input.PhoneStr))
                                    return Error("号码不可以为空");
                                double phoneInt = 0;
                                if (!double.TryParse(input.PhoneStr, out phoneInt))
                                    return Error("请输入正确的手机号码段");
                                phoneInt = phoneInt * 10000;
                                for (int i = 1; i < 10000; i++)
                                {
                                    var row = dt.NewRow();
                                    row["F_TaskId"] = model.TaskID;
                                    row["F_Phone"] = phoneInt + i;
                                    dt.Rows.Add(row);
                                }
                                break;
                            case 4: //从Excel中导入
                                NPOIHelper npoi = new NPOIHelper();
                                var dtExcel = npoi.ExcelToTable(input.PhoneStr, 1);
                                break;
                        }
                        if (input.CheckFilter1)
                        {
                            PhoneNumFilter(dt);
                        }
                        if (input.CheckFilter2)
                        {
                            PhoneNumFilterMonth(dt);
                        }
                        taskTellNumBLL.SqlBulkCopy(dt);

                        model.y_HMCount = dt.Rows.Count;
                        if (taskBLL.Update(model))
                            return Success("添加成功");
                        return Error("添加失败");
                }
                return Error("添加失败");
            }

            model = taskBLL.GetModel(input.Id);
            if (model == null)
                return Error("当前外呼任务不存在");
            model.TaskName = input.Name;
            model.TaskType = input.Type;
            model.AgentGroupId = input.AgentGroupId;
            model.y_TkModelId = input.PagerId;
            model.Pre = input.Pre;
            if (input.ConcurrencyType == 0)
            {
                var num = 0;
                if (!int.TryParse(input.Concurrency.ToString(), out num))
                    return Error("并发数必须为不小于1的整数");
                input.Concurrency = (int)input.Concurrency;
            }
            if (input.Concurrency < 1)
                return Error("输入的并发数和进号速率必须不小于1");
            model.ConcurrencyType = input.ConcurrencyType;
            model.Concurrency = input.ConcurrencyType == 0 ? (int)input.Concurrency : input.Concurrency;
            model.PlanStartDate = input.PlanStartDate;
            model.PlanEndDate = input.PlanEndDate;
            model.StartTime1 = input.StartTime1;
            model.EndTime1 = input.EndTime1;
            model.StartTime2 = input.StartTime2;
            model.EndTime2 = input.EndTime2;
            if (taskBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult UpdateState(int[] ids, int state)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var sql = "";
            if (ids.Length > 0)
            {
                sql += " TaskID in (" + string.Join(",", ids) + ") ";
            }
            var model = taskBLL.GetList(sql).Tables[0];
            foreach (DataRow item in model.Rows)
            {
                if (Convert.ToInt32(item["State"]) == -1)
                    return Error("选择的任务存在已删除状态，执行失败");
            }

            if (taskBLL.UpdateStateBatch(sql, state))
                return Success("修改成功");
            return Error("修改失败");

        }

        /// <summary>
        /// 导入号码信息
        /// </summary>
        /// <param name="type">导入方式：1=Excel; 2=txt .......</param>
        /// <returns></returns>
        public ActionResult ImportData(ImportDataInput input)
        {
                DataTable dt = taskTellNumBLL.GetTableDesign();
                switch (input.Type)
                {
                    case 1: //从文本文件导入
                        var file = Request.Files[0];
                        using (StreamReader sr = new StreamReader(file.InputStream))
                        {
                            String line;
                            while ((line = sr.ReadLine()) != null)
                            {
                                var row = dt.NewRow();
                                row["F_TaskId"] = input.TaskId;
                                row["F_Phone"] = line.ToString();
                                dt.Rows.Add(row);
                            }
                        }
                        break;
                    case 2: //从文本框中导入
                        if (string.IsNullOrWhiteSpace(input.PhoneStr))
                            return Error("号码不可以为空");
                        var arr = input.PhoneStr.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var p in arr)
                        {
                            var row = dt.NewRow();
                            row["F_TaskId"] = input.TaskId;
                            row["F_Phone"] = p;
                            dt.Rows.Add(row);
                        }
                        break;
                    case 3: //从号码段导入
                        if (string.IsNullOrWhiteSpace(input.PhoneStr))
                            return Error("号码不可以为空");
                        double phoneInt = 0;
                        if (!double.TryParse(input.PhoneStr, out phoneInt))
                            return Error("请输入正确的手机号码段");
                        phoneInt = phoneInt * 10000;
                        for (int i = 1; i < 10000; i++)
                        {
                            var row = dt.NewRow();
                            row["F_TaskId"] = input.TaskId;
                            row["F_Phone"] = phoneInt + i;
                            dt.Rows.Add(row);
                        }
                        break;
                    case 4: //从Excel中导入
                        NPOIHelper npoi = new NPOIHelper();
                        var dtExcel = npoi.ExcelToTable(input.PhoneStr, 1);
                        break;
                }
                if (input.CheckFilter1)
                {
                    PhoneNumFilter(dt);
                }
                if (input.CheckFilter2)
                {
                    PhoneNumFilterMonth(dt);
                }
                taskTellNumBLL.SqlBulkCopy(dt);
                return Content("<script type='javascript/text'>alert('啊啊啊');</script>");

        }

        /// <summary>
        /// 导出号码信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportData(long taskId, int type = 0)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            NPOIHelper npoi = new NPOIHelper();
            var task = taskBLL.GetModel(taskId);
            if (task == null)
                return Error("该外呼任务不存在");
            switch (type)
            {
                case 1:
                    var dt1 = taskTellNumBLL.GetList(" F_TaskId=" + task.TaskID + "  and F_HCState=1 and  F_YJState=0 ").Tables[0];
                    var msg1 = npoi.ExportToExcel(DateTime.Now.ToString("yyyyMMdd") + task.TaskName + "导出未接通号码", dt1);
                    return !string.IsNullOrWhiteSpace(msg1) ? Error(msg1) : Success("导出成功");
                case 2:
                    var dt2 = taskTellNumBLL.GetList(" F_TaskId=" + task.TaskID + " and F_HCState=1 and  F_YJState=1 ").Tables[0];
                    var msg2 = npoi.ExportToExcel(DateTime.Now.ToString("yyyyMMdd") + task.TaskName + "导出已接通号码", dt2);
                    return !string.IsNullOrWhiteSpace(msg2) ? Error(msg2) : Success("导出成功");
            }
            return Error("参数错误");
        }

        /// <summary>
        /// 更新并发数
        /// </summary>
        /// <param name="id"></param>
        /// <param name="concurrency"></param>
        /// <returns></returns>
        public ActionResult UpdateConcurrency(long id, float concurrency)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = taskBLL.GetModel(id);
            if (model == null)
                return Error("该外呼任务不存在");
            var num = 0;
            if (!int.TryParse(concurrency.ToString(), out num))
                return Error("并发数必须为不小于1的整数");
            model.Concurrency = (int)concurrency;
            if (taskBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }

        /// <summary>
        /// 获取自动放音文件
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRecordDropList()
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var list = taskRecordBLL.DataTableToList(taskRecordBLL.GetList("").Tables[0]).Select(x => new
            {
                id = x.Id,
                name = x.Name,
            });
            return Success("成功", list.ToList());
        }
        /// <summary>
        /// 获取自动放音文件
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRecordList()
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var list = taskRecordBLL.DataTableToList(taskRecordBLL.GetList("").Tables[0]).Select(x => new
            {
                id = x.Id,
                name = x.Name,
                recordpath = x.RecordPath,
                recordtime = x.RecordTime,
            });
            return Success("成功", list.ToList());
        }
        /// <summary>
        /// 获取录音
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetRecord(int id)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var x = taskRecordBLL.GetModel(id);
            return Success("成功", new
            {
                id = x.Id,
                name = x.Name,
                recordpath = x.RecordPath,
                recordtime = x.RecordTime,
                remark = x.Remark
            });
        }
        /// <summary>
        /// 添加/更新自动放音
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult CreateOrUpdateRecord(Model.T_CTI_TaskRecord input)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            Model.T_CTI_TaskRecord model = new Model.T_CTI_TaskRecord();
            if (input.Id <= 0)
            {
                var file = Request.Files[0];




                model.Name = input.Name;
                model.RecordPath = input.RecordPath;
                model.RecordTime = input.RecordTime;
                model.Remark = input.Remark;

                if (taskRecordBLL.Add(model) > 0)
                    return Success("添加成功");
                return Error("添加失败");
            }
            return Success("");
        }

        /// <summary>
        /// 清空号码
        /// </summary>
        /// <returns></returns>
        public ActionResult ClearPhone(long id)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var num = taskBLL.DeletePhoneByTaskId(id);
            if (num > 0)
            {
                var task = taskBLL.GetModel(id);


                return Success("删除成功");
            }
            return Error("删除失败");
        }


        /// <summary>
        /// 话务分析
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTalkAnalysis(DateTime? start, DateTime? end)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");

            //var where = "";
            //if (start != null && end != null)
            //{
            //    where += " PlanStartDate<'" + start.ToString() + "' and  PlanEndDate>";

            //}

            var fir = taskDailyBLL.DataTableToList(taskDailyBLL.GetList("").Tables[0]);
            var sec = taskPhonePartBLL.DataTableToList(taskPhonePartBLL.GetList("").Tables[0]);
            var thi = taskDailyBLL.DataTableToList(taskDailyBLL.GetList().Tables[0]);


            var obj = new
            {
                fir = fir,
                sec = sec,
                thi = thi
            };


            return Success("", obj);
        }

        /// <summary>
        /// 获取通话记录列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTalkRecords(FilterTalkRecord filter)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");

            var sql = "";

            // 未接通   F_YJState=0
            // 接通未转入坐席 F_YJState=0 
            // 接通未分配坐席 
            // 接通且分配坐席  F_YJState=1 and agentid>0
            int recordCount = 0;
            Model.PageData<Model.CallResult> pageModel = new Model.PageData<Model.CallResult>();
            StringBuilder fields = new StringBuilder();
            fields.Append(" cr.id,cr.itemid,cr.callee,cr.agentid,ua.f_username as username ,cr.recordpath  ");
            fields.Append(", (case when datediff(y,'1970-01-01 00:00:00.000',cr.StartDate)>0 then cr.StartDate else null end) as startdate ");
            fields.Append(", (case when datediff(y,'1970-01-01 00:00:00.000',cr.GetInAgentDate)>0 then cr.GetInAgentDate else null end) as getinagentdate ");
            fields.Append(", (case when datediff(y,'1970-01-01 00:00:00.000',cr.EndDate)>0 then cr.EndDate else null end) as enddate ");
            fields.Append(", (case when t.F_YJState=0 then '未接通'  when (t.F_YJState=1 and cr.AgentId>0) then '接通且转坐席' end ) as state ");
            fields.Append(", (case when datediff(s,cr.GetInAgentDate,cr.endDate)<0 then 0 else datediff(s,cr.GetInAgentDate,cr.endDate) end) as talktime");
            var dt = BLL.PagerBLL.GetListPager(
                    " CallResult cr left join T_Sys_UserAccount ua on cr.agentId=ua.f_usercode left join T_Call_TaskTelNum t ON t.F_Id=cr.Id ",
                    "cr.Id",
                    fields.ToString(),
                    sql,
                    "ORDER BY cr.Id desc",
                    filter.PageSize,
                    filter.PageIndex,
                    true,
                    out recordCount);
            var list = callResultBLL.DataTableToList(dt).Select(x => new
            {
                id = x.Id,
                taskid = x.TaskId,
                callnumber = x.CallNumber,
                usercode = x.Usercode == "0" ? "" : x.Usercode,
                startdate = x.StartDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                getinagentdate = x.GetInAgentDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                enddate = x.EndDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                recordpath = x.RecordPath,
                username = x.Username,
                state = x.State,
                talktime = x.TalkTime > 0 ? x.TalkTime.ToString() : ""
            });
            var obj = new
            {
                rows = list,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        public ActionResult Test()
        {
            BLL.T_Sys_MobileData mBLL = new BLL.T_Sys_MobileData();
            var list = mBLL.DataTableToList(mBLL.GetAllList().Tables[0]);
            StringBuilder sb = new StringBuilder();
            var s = "";
            foreach (var item in list)
            {
                try
                {
                    var str = item.F_CityDes;
                    var arr = str.Split(new char[] { ',', '-', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    //item.Province = arr[0];
                    //item.City = arr[1];
                    s = arr[0];
                    if (mBLL.Update(item))
                    {
                        sb.Append("【");
                        sb.Append(item.F_MobileNum);
                        sb.Append("】");
                    }
                }
                catch (Exception ex)
                {
                    //item.Province = s;
                    //item.City = s;
                    if (mBLL.Update(item))
                    {
                        sb.Append("【");
                        sb.Append(item.F_MobileNum);
                        sb.Append("】");
                    }
                    continue;
                }
            }
            return Success("", sb.ToString());
        }

        #region 过滤号码-数据源
        /// <summary>
        /// 过滤号码
        /// </summary>
        /// <param name="dt"></param>
        private DataTable PhoneNumFilter(DataTable dt)
        {
            var dtClone = dt.Copy();
            foreach (DataRow row in dtClone.Rows)
            {
                var rows = dt.Select("[F_Phone]='" + row["F_Phone"] + "'");
                if (rows.Length > 1)
                {
                    for (int num = 0; num < rows.Count() - 1; num++)
                    {
                        dt.Rows.Remove(rows[num]);
                    }
                }

            }
            return dt;
        }
        #endregion

        #region 过滤号码-前三个月
        private DataTable PhoneNumFilterMonth(DataTable dt, string phone = "F_Phone")
        {
            var taskTelNumDt = taskTellNumBLL.GetList(" datediff(mm,F_CreateTime,getdate())<=3 ").Tables[0];
            foreach (DataRow row in taskTelNumDt.Rows)
            {
                var rows = dt.Select("[" + phone + "]='" + row["F_Phone"] + "'");
                if (rows.Length > 1)
                {
                    for (int num = 0; num < rows.Count() - 1; num++)
                    {
                        dt.Rows.Remove(rows[num]);
                    }
                }
            }
            return dt;
        }

        #endregion


    }
}