using CallCenter.Utility;
using CallCenter.Utility.Time;
using CallCenterApi.DB;
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 readonly BLL.T_CTI_Task taskBLL = new BLL.T_CTI_Task();
        private readonly BLL.T_Call_TaskTelNum taskTellNumBLL = new BLL.T_Call_TaskTelNum();
        private readonly BLL.T_Sys_DictionaryValue dictValueBLL = new BLL.T_Sys_DictionaryValue();
        private readonly BLL.T_CTI_TaskAgent taskAgentBLL = new BLL.T_CTI_TaskAgent();
        private readonly BLL.T_Sys_UserAccount userAccount = new BLL.T_Sys_UserAccount();
        private readonly BLL.T_CTI_TaskRecord taskRecordBLL = new BLL.T_CTI_TaskRecord();
        private readonly BLL.CallResult callResultBLL = new BLL.CallResult();
        private readonly BLL.T_CTI_TaskDaily taskDailyBLL = new BLL.T_CTI_TaskDaily();
        private readonly BLL.T_CTI_TaskPhonePart taskPhonePartBLL = new BLL.T_CTI_TaskPhonePart();
        private readonly BLL.T_Sys_SeatGroup seatGroupBLL = new BLL.T_Sys_SeatGroup();
        private readonly BLL.T_Sys_SystemConfig systemConfigBLL = new BLL.T_Sys_SystemConfig();
        private readonly BLL.T_Call_PageField pageFieldBLL = new BLL.T_Call_PageField();
        private readonly BLL.T_Ask_PagerInfo pagerInfoBLL = new BLL.T_Ask_PagerInfo();
        private readonly BLL.T_Call_Answers ansBLL = new BLL.T_Call_Answers();
        private readonly BLL.T_Sys_Department departmentBLL = new BLL.T_Sys_Department();
        private readonly BLL.T_Ask_Question questionBLL = new BLL.T_Ask_Question();
        private readonly BLL.T_Ask_QuestionItems questionItemBLL = new BLL.T_Ask_QuestionItems();
        #region 外呼任务
        /// <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() + "%' ) ";
            }

            var roleid = CurrentUser.UserData.F_RoleId;
            var deptid = CurrentUser.UserData.F_DeptId;
            var deptCode = CurrentUser.UserData.F_DeptCode;
            var usercode = CurrentUser.UserData.F_UserCode;
            if (roleid != 0)
            {
                if (roleid != 17)
                {
                    if (deptCode.Replace("|0|1|", "").Length > 0)
                    {
                        sql += " and DeptId in (select F_DeptId from T_Sys_Department where F_DeptCode like '" + deptCode + "%') ";
                    }
                }
            }


            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 = seatGroupBLL.DataTableToList(seatGroupBLL.GetList("").Tables[0]);
            //查询坐席
            var agentList = userAccount.DataTableToList(userAccount.GetList(" F_DeleteFlag=0 ").Tables[0]);
            //查询部门
            var deptList = departmentBLL.DataTableToList(departmentBLL.GetList(" F_State=1 ").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).ToString("f2") + "%";

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

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

                var agentGroupStr = model.AgentGroupId == -999 ? "不转坐席" : "";
                var agentGroup = agentGroupList.SingleOrDefault(x => x.F_ZXZID == model.AgentGroupId);
                var agentCount = agentList.Where(x => x.F_SeartGroupID == (agentGroup?.F_ZXZID ?? 0)).Count();

                var dept = deptList.SingleOrDefault(y => y.F_DeptId == model.DeptId);
                list.Add(new CallPlanDto
                {
                    id = model.TaskID,
                    name = model.TaskName,
                    tasktype = model.TaskType == 1 ? "点击外呼" : "自动外呼",
                    deptname = dept?.F_DeptName ?? "",
                    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_ZXZName ?? agentGroupStr,//坐席组
                    agentgroupid = model.AgentGroupId,
                    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);
            if (model == null)
                return Error("预测外呼任务不存在");
            //计算数据
            string calledRate = "0";
            var allcount = model.y_HMCount ?? 0;
            float calledcount = model.y_HCCount ?? 0;
            calledRate = allcount == 0 ? "" : (calledcount / allcount * 100).ToString("f2") + "%";

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

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

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


            var agentGroupStr = model.AgentGroupId == -999 ? "不转坐席" : "";
            var agentGroup = agentGroupList.SingleOrDefault(x => x.F_ZXZID == model.AgentGroupId);
            var agentCount = agentList.Where(x => x.F_SeartGroupID == (agentGroup?.F_ZXZID ?? 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, //线路前缀
                recordpathid = model.RecordFileId,
                concurrencytypestr = model.ConcurrencyType == 0 ? "并发数" : "并发速率",
                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"),
                agentgroup = agentGroup?.F_ZXZName ?? agentGroupStr,//坐席组
                agentgroupid = model.AgentGroupId,
                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.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.RecordFileId = input.RecordPathId;
                model.DeptId = input.DeptId <= 0 ? CurrentUser.UserData.F_DeptId : input.DeptId;
                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 ?? DateTime.Now;
                model.PlanEndDate = input.PlanEndDate?.AddDays(1).AddSeconds(-1) ?? DateTime.Now;
                model.StartTime1 = input.StartTime1 ?? DateTime.Now;
                model.EndTime1 = input.EndTime1 ?? DateTime.Now;
                model.StartTime2 = input.StartTime2 ?? DateTime.Now;
                model.EndTime2 = input.EndTime2 ?? DateTime.Now;
                var taskId = taskBLL.Add(model);
                if (taskId > 0)
                {
                    try
                    {
                        if (input.TempId > 0)
                        {
                            var fields = pageFieldBLL.DataTableToList(pageFieldBLL.GetList($" F_TaskId=0 and  F_TempId={input.TempId}").Tables[0]);
                            foreach (var item in fields)
                            {
                                pageFieldBLL.Add(new T_Call_PageField()
                                {
                                    F_Name = item.F_Name,
                                    F_FeildId = item.F_FeildId,
                                    F_TaskId = (int)taskId,
                                    F_Sort = item.F_Sort,
                                    F_DBFieldlName = item.F_DBFieldlName
                                });
                            }
                        }
                        else
                        {
                            pageFieldBLL.UpdateByTaskId(taskId);
                        }




                        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中导入
                                if (!string.IsNullOrWhiteSpace(input.SelectIds))
                                {
                                    string[] strArr = input.SelectIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    var idArr = strArr.Select(x => Convert.ToInt32(x)).ToArray();
                                    var fieldList = pageFieldBLL.DataTableToList(pageFieldBLL.GetList($"F_ID in ({string.Join(",", idArr)})").Tables[0]);
                                    NPOIHelper npoi = new NPOIHelper();
                                    var dtExcel = npoi.ExcelToTable(input.FilePath, 0);
                                    for (int i = 0; i < dtExcel.Rows.Count; i++)
                                    {
                                        var row = dt.NewRow();
                                        for (int j = 0; j < dtExcel.Columns.Count; j++)
                                        {
                                            if (fieldList.Count < (j + 1))
                                                break;
                                            row["F_TaskId"] = model.TaskID;
                                            var field = fieldList.SingleOrDefault(x => x.F_Id == idArr[j]);
                                            row[field.F_DBFieldlName] = dtExcel.Rows[i][j];
                                        }
                                        dt.Rows.Add(row);
                                    }
                                }
                                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("添加失败");
                    }
                    catch (Exception e)
                    {
                        return Error(e.Message);
                    }
                }
                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.DeptId = input.DeptId;
            //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 ?? DateTime.Now;
            model.PlanEndDate = input.PlanEndDate?.AddDays(1).AddSeconds(-1) ?? DateTime.Now;
            model.StartTime1 = input.StartTime1 ?? DateTime.Now;
            model.EndTime1 = input.EndTime1 ?? DateTime.Now;
            model.StartTime2 = input.StartTime2 ?? DateTime.Now;
            model.EndTime2 = input.EndTime2 ?? DateTime.Now;
            model.RecordFileId = input.RecordPathId;
            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="id"></param>
        /// <param name="concurrency"></param>
        /// <returns></returns>
        public ActionResult UpdateConcurrency(long id, float concurrency, int concurrencyType = 0)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = taskBLL.GetModel(id);
            if (model == null)
                return Error("该外呼任务不存在");
            if (concurrencyType == 0)
            {
                var num = 0;
                if (!int.TryParse(concurrency.ToString(), out num))
                    return Error("并发数必须为不小于1的整数");
                concurrency = num;
            }
            if (concurrency < 1)
                return Error("输入的并发数和进号速率必须不小于1");
            model.ConcurrencyType = concurrencyType;
            model.Concurrency = concurrency;
            if (taskBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }
        /// <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>
        /// <param name="callId"></param>
        /// <param name="tel"></param>
        /// <returns></returns>
        public ActionResult RemovePre(string callId, string tel)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var callResult = callResultBLL.GetModel(callId);
            if (callResult == null)
                return Error("通话记录未正常添加");
            var task = taskBLL.GetModel(callResult.TaskId);
            if (task == null)
                return Error("任务不存在");
            var len = task.Pre.Length;
            return Success("去除成功", tel.Substring(len));
        }
        /// <summary>
        /// 更新外呼任务状态
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateCallPlanState()
        {
            StringBuilder sb = new StringBuilder();
            var log = LogFactory.GetLogger(this.GetType().ToString());
            var list = taskBLL.DataTableToList(taskBLL.GetList(" state>=0 ").Tables[0]);
            foreach (var task in list)
            {
                if (task.PlanStartDate <= DateTime.Now && task.PlanEndDate > DateTime.Now)
                {
                    if (task.State == 2)
                    {
                        if (task.PlanStartDate < DateTime.Now && DateTime.Now < task.StartTime1)
                        {
                            task.State = 0;
                            if (!taskBLL.Update(task))
                                return Error($"更新自动外呼任务状态为0=待处理失败,ID={task.TaskID},Name={task.TaskName}");
                            log.Info($"更新自动外呼任务状态为0=待处理成功,ID={task.TaskID},Name={task.TaskName}");
                        }
                    }
                    if (task.State == 0)
                    {
                        if ((DateTime.Now >= task.StartTime1 && DateTime.Now < task.EndTime1) || (DateTime.Now > task.StartTime2 && DateTime.Now < task.EndTime2))
                        {
                            task.State = 1;
                            if (!taskBLL.Update(task))
                                return Error($"更新自动外呼任务状态为1=处理中失败,ID={task.TaskID},Name={task.TaskName}");
                            log.Info($"更新自动外呼任务状态为1=处理中成功,ID={task.TaskID},Name={task.TaskName}");

                        }
                    }
                    if (task.State == 1)
                    {
                        if (task.PlanEndDate < DateTime.Now)
                        {
                            task.State = 0;
                            if (!taskBLL.Update(task))
                                return Error($"更新自动外呼任务状态为2=暂停失败,ID={task.TaskID},Name={task.TaskName}");
                            log.Info($"更新自动外呼任务状态为2=暂停成功,ID={task.TaskID},Name={task.TaskName}");
                        }
                    }
                }
            }
            return Success("处理完成");
        }
        /// <summary>
        /// 获取号码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ActionResult GetPhoneList(FilterCallPhone filter)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = taskBLL.GetModel(filter.Id);
            if (model == null)
                return Error("外呼任务不存在");
            var sql = "";
            if (filter.UserId > 0)
            {
                sql += $" and F_UserId={filter.UserId} ";
            }
            if (!string.IsNullOrWhiteSpace(filter.Phone))
            {
                sql += $" and F_Phone like '%{filter.Phone}%'";
            }
            if (filter.FPState > -1)
            {
                sql += $" and F_FPState={filter.FPState} ";
            }
            if (filter.HCState > -1)
            {
                sql += $" and F_HCState={filter.HCState} ";
            }
            if (filter.YJState > -1)
            {
                sql += $" and F_YJState={filter.YJState} ";
            }

            var field = "F_Id,t.TaskName,F_Phone,F_FPState,F_HCState,F_YJState,F_Username,tn.F_CreateTime,tn.F_LastCallTime";
            if (model.TaskType == 2)
            {
                field = " F_Phone,F_HCState,F_YJState,F_Username,tn.F_CreateTime,tn.F_LastCallTime";
            }

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                             " T_Call_TaskTelNum tn left join T_CTI_Task t on t.TaskID=tn.F_TaskId left join T_Call_CallRecords c on c.TaskType=9 and c.TaskPhoneID=tn.F_Id and c.TaskID=tn.F_TaskId ",
                             " F_Id ",
                             field,
                             " and F_TaskId=" + filter.Id + sql,
                             "ORDER BY F_Id desc",
                             filter.PageSize,
                             filter.PageIndex,
                             true,
                             out recordCount);
            List<Model.T_Call_TaskTelNum> modelList = new BLL.T_Call_TaskTelNum().DataTableToListForShow(dt);
            var obj = new
            {
                rows = modelList.Select(x => new
                {
                    taskname = x.TaskName,
                    phone = x.F_Phone,
                    agent = string.IsNullOrWhiteSpace(x.F_UserName) ? "" : x.F_UserName,
                    isallot = x.F_FPState == null ? "" : (x.F_FPState > 0 ? "已分配" : "未分配"),
                    iscalled = x.F_HCState > 0 ? "已呼叫" : "未呼叫",
                    isconnected = x.F_YJState > 0 ? "已接通" : "未接通",
                    createtime = x.F_CreateTime == null ? "" : Convert.ToDateTime(x.F_CreateTime).ToString("yyyy-MM-dd HH:mm:ss"),
                    lastcalltime = x.F_LastCallTime == null ? "" : Convert.ToDateTime(x.F_LastCallTime).ToString("yyyy-MM-dd HH:mm:ss")
                }),
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 获取分配给当前登录坐席的号码
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public ActionResult GetMyPhoneList(FilterCallPhone filter)
        {
            if (!Request.IsAuthenticated)
                return NoToken("未知错误，请重新登录");

            var sql = $" and t.State=1 and F_UserId={CurrentUser.UserData.F_UserId} ";
            if (filter.Id > 0)
            {
                var model = taskBLL.GetModel(filter.Id);
                sql += " and F_TaskId=" + filter.Id;
                if (model == null)
                    return Error("外呼任务不存在");
            }
            if (!string.IsNullOrWhiteSpace(filter.Phone))
            {
                sql += $" and F_Phone like '%{filter.Phone}%'";
            }

            switch (filter.RequestType)
            {
                case 1://我的任务
                    sql += $" and F_HCState=0 ";
                    break;
                case 2://我的任务结果
                    sql += $" and F_HCState=1 ";
                    break;
                case 3://任务结果数据

                    break;
                default:
                    break;
            }



            if (filter.FPState > -1)
            {
                sql += $" and F_FPState={filter.FPState} ";
            }
            if (filter.HCState > -1)
            {
                sql += $" and F_HCState={filter.HCState} ";
            }
            if (filter.YJState > -1)
            {
                sql += $" and F_YJState={filter.YJState} ";
            }
            if (filter.YHFKID > -1)
            {
                sql += $" and F_YHFKID={filter.YHFKID} ";
            }
            if (filter.HJJGID > -1)
            {
                sql += $" and F_HJJGID={filter.HJJGID} ";
            }

            var field = "F_Id,t.TaskName,F_Phone,F_FPState,F_HCState,F_YJState,F_Username,tn.F_CreateTime,F_HJJGName,F_YHFKName,F_LastCallTime";


            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                             " T_Call_TaskTelNum tn left join T_CTI_Task t on t.TaskID=tn.F_TaskId",
                             " F_Id ",
                             field,
                              sql,
                             "ORDER BY F_LastCallTime desc,F_ID DESC ",
                             filter.PageSize,
                             filter.PageIndex,
                             true,
                             out recordCount);
            List<Model.T_Call_TaskTelNum> modelList = new BLL.T_Call_TaskTelNum().DataTableToListForShow(dt);
            var obj = new
            {
                rows = modelList.Select(x => new
                {
                    id = x.F_Id,
                    taskname = x.TaskName,
                    phone = x.F_Phone,
                    agent = string.IsNullOrWhiteSpace(x.F_UserName) ? "" : x.F_UserName,
                    isallot = x.F_FPState == null ? "" : (x.F_FPState > 0 ? "已分配" : "未分配"),
                    iscalled = x.F_HCState > 0 ? "已呼叫" : "未呼叫",
                    isconnected = x.F_YJState > 0 ? "已接通" : "未接通",
                    hjjg = x.F_HJJGName,
                    yhfk = x.F_YHFKName,
                    createtime = Convert.ToDateTime(x.F_CreateTime).ToString("yyyy-MM-dd HH:mm:ss"),
                    lastcalltime = x.F_LastCallTime == null ? "" : Convert.ToDateTime(x.F_LastCallTime).ToString("yyyy-MM-dd HH:mm:ss")
                }),
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        public ActionResult GetPhoneResult(FilterCallPhone filter)
        {
            var headList1 = new List<string>() { "序号", "外呼计划", "号码Id", "号码", "分配坐席", "呼叫状态", "接通状态", "呼叫结果", "结果反馈", "导入时间", "呼出时间" };
            //根据任务id查问卷
            var task = taskBLL.GetModel(filter.Id);
            if (task == null)
                return Error("该任务不存在");
            var headDt = DbHelperSQL.Query($"select Q.F_TITLE from T_Ask_Question Q  LEFT JOIN T_Ask_PagerItems PIT ON PIT.F_QuestionId = Q.F_QuestionId LEFT JOIN T_Ask_PagerInfo PIN ON PIN.F_PagerId = PIT.F_PagerId LEFT JOIN T_CTI_Task T ON T.y_TkModelId = PIN.F_PagerId where T.TaskID ={task.TaskID} ORDER BY Q.F_SortModel").Tables[0];
            var headList2 = new List<string>();
            foreach (DataRow row in headDt.Rows)
            {
                headList2.Add(row["F_TITLE"]?.ToString() ?? "");
            }

            var headList = new List<string>();
            headList.AddRange(headList1);
            headList.AddRange(headList2);


            //查询数据
            var sql = "";
            if (filter.Id > 0)
            {
                var model = taskBLL.GetModel(filter.Id);
                sql += " and F_TaskId=" + filter.Id;
                if (model == null)
                    return Error("外呼任务不存在");
            }
            if (!string.IsNullOrWhiteSpace(filter.Phone))
            {
                sql += $" and F_Phone like '%{filter.Phone}%'";
            }
            if (filter.FPState > -1)
            {
                sql += $" and F_FPState={filter.FPState} ";
            }
            if (filter.HCState > -1)
            {
                sql += $" and F_HCState={filter.HCState} ";
            }
            if (filter.YJState > -1)
            {
                sql += $" and F_YJState={filter.YJState} ";
            }
            if (filter.YHFKID > -1)
            {
                sql += $" and F_YHFKID={filter.YHFKID} ";
            }
            if (filter.HJJGID > -1)
            {
                sql += $" and F_HJJGID={filter.HJJGID} ";
            }
            var field = "F_Id,t.TaskName,F_Phone,F_FPState,F_HCState,F_YJState,F_Username,tn.F_CreateTime,F_HJJGName,F_YHFKName,tn.F_LastCallTime";
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                             " T_Call_TaskTelNum tn left join T_CTI_Task t on t.TaskID=tn.F_TaskId",
                             " F_Id ",
                             field,
                              sql,
                             "ORDER BY F_LastCallTime desc,F_ID DESC ",
                             filter.PageSize,
                             filter.PageIndex,
                             true,
                             out recordCount);
            List<Model.T_Call_TaskTelNum> modelList = new BLL.T_Call_TaskTelNum().DataTableToListForShow(dt);

            List<Model.T_Call_Answers> answerList = new List<T_Call_Answers>();
            if (modelList.Count > 0)
            {
                answerList = ansBLL.DataTableToListDTO(DbHelperSQL.Query($" select A.F_QID, A.F_CusTelID, A.F_Answer from T_Call_Answers A LEFT JOIN T_Ask_Question Q ON Q.F_QuestionId=A.F_QID where F_TaskID={ task.TaskID} AND F_CusTelID in ({ string.Join(", ", string.Join(", ", modelList.Select(x => x.F_Id).ToArray()))}) ORDER BY Q.F_SortModel  ").Tables[0]);
            }

            var numList = modelList.Select(x => new
            {
                id = x.F_Id.ToString(),
                taskname = x.TaskName,
                phone = x.F_Phone,
                agent = string.IsNullOrWhiteSpace(x.F_UserName) ? "" : x.F_UserName,
                isallot = x.F_FPState == null ? "" : (x.F_FPState > 0 ? "已分配" : "未分配"),
                iscalled = x.F_HCState > 0 ? "已呼叫" : "未呼叫",
                isconnected = x.F_YJState > 0 ? "已接通" : "未接通",
                hjjg = x.F_HJJGName,
                yhfk = x.F_YHFKName,
                createtime = Convert.ToDateTime(x.F_CreateTime).ToString("yyyy-MM-dd HH:mm:ss"),
                lastcalltime = x.F_LastCallTime == null ? "" : Convert.ToDateTime(x.F_LastCallTime).ToString("yyyy-MM-dd HH:mm:ss")
            });


            var dataList = new List<List<string>>();

            foreach (var item in numList)
            {
                var answer = answerList.Where(x => (x.F_CusTelID?.ToString() ?? "") == item.id).GroupBy(x => x.F_QID).ToList();
                var itemList = new List<string>();
                itemList.AddRange(new string[] { item.id, item.taskname, item.phone, item.agent, item.isallot, item.iscalled, item.isconnected, item.hjjg, item.yhfk, item.createtime, item.lastcalltime });
                foreach (var i in answer)
                {
                    itemList.Add(string.Join(", ", i.Where(x => !string.IsNullOrWhiteSpace(x.F_Answer)).Select(x => x.F_Answer).Distinct()));
                }
                dataList.Add(itemList);
            }







            return Success("获取成功", new
            {
                headlist = headList,
                datalist = dataList
            });
        }


        /// <summary>
        /// 坐席自主获取号码(点击外呼分配号码）
        /// </summary>
        /// <param name="id">外呼任务ID</param>
        /// <param name="userId">坐席ID</param>
        /// <returns></returns>
        public ActionResult AllotPhoneList(int id, int count)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            if (count <= 0)
                return Error("参数错误");
            if (id <= 0)
                return Error("请选择外呼任务");
            var model = taskBLL.GetModel(id);
            if (model == null)
                return Error("外呼任务不存在");
            var obj = DbHelperSQL.GetSingle($"SELECT Count(F_ID) FROM T_Call_TaskTelNum WHERE F_UserId={CurrentUser.UserData.F_UserId} and F_TaskId={id} and F_HCState=0 ");
            var sum = obj == null ? 0 : Convert.ToInt32(obj);
            var num = 50 - sum;
            if (num <= 0)
                return Error("请先完成已分配任务");
            num = Math.Abs(num);
            var res = DbHelperSQL.ExecuteSql($"UPDATE T_Call_TaskTelNum SET F_FPState=1,F_UserId={CurrentUser.UserData.F_UserId},F_Username='{CurrentUser.UserData.F_UserName}' WHERE F_Id in(SELECT TOP({(count > num ? num : count)}) F_Id FROM T_Call_TaskTelNum WHERE F_TaskId={id} and F_FPState=0)");
            if (res > 0)
                return Success($"获取到{res}条可用号码");
            return Error("未获取到可用号码");
        }
        /// <summary>
        /// 取消分配
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult CancelPhone(int[] ids)
        {
            if (ids == null || ids.Length <= 0)
                return Error("请选择");
            var arr = string.Join(",", ids);
            if (taskTellNumBLL.CancelFP(arr))
                return Success("取消成功");
            return Error("取消失败");
        }
        /// <summary>
        /// 获取坐席可进行呼叫的点击外呼任务
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMyCallPlan()
        {
            var roleid = CurrentUser.UserData.F_RoleId;
            var deptid = CurrentUser.UserData.F_DeptId;
            var deptCode = CurrentUser.UserData.F_DeptCode;
            var usercode = CurrentUser.UserData.F_UserCode;
            var sql = "";
            if (roleid != 0)
            {
                if (roleid != 17)
                {
                    if (deptCode.Replace("|0|1|", "").Length > 0)
                    {
                        sql += " and DeptId in (select F_DeptId from T_Sys_Department where F_DeptCode like '" + deptCode + "%') ";
                    }
                }
            }
            var taskList = taskBLL.DataTableToList(taskBLL.GetList("state=1 and tasktype=1 " + sql).Tables[0]);
            return Success("获取成功", taskList.Select(x => new
            {
                id = x.TaskID,
                name = x.TaskName
            }));
        }
        /// <summary>
        /// 获取拨出号码的详细信息+自定义导入信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetCallNumDetail(int id)
        {
            var taskId = DbHelperSQL.GetSingle($"SELECT F_TaskId FROM T_Call_TaskTelNum WHERE F_ID={id}");
            if (taskId == null || (int)taskId <= 0)
                return Error("外呼任务不存在");
            var task = taskBLL.GetModel((int)taskId);
            if (task == null)
                return Error("外呼任务不存在");

            var fieldList = pageFieldBLL.DataTableToList(pageFieldBLL.GetList($"F_TaskId={task.TaskID}").Tables[0]);
            StringBuilder sb = new StringBuilder();
            Dictionary<string, string> dicTitle = new Dictionary<string, string>();
            foreach (var item in fieldList)
            {
                sb.Append(item.F_DBFieldlName + ",");
                dicTitle.Add(item.F_DBFieldlName, item.F_Name);
            }
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (!string.IsNullOrWhiteSpace(sb.ToString()))
            {
                var callNum = DbHelperSQL.Query($"SELECT {sb.ToString().Trim(',')} FROM T_Call_TaskTelNum WHERE F_ID={id}").Tables[0];
                for (int j = 0; j < callNum.Columns.Count; j++)
                {
                    dic.Add(callNum.Columns[j].ColumnName, callNum.Rows[0][j].ToString());
                }
                return Success("获取成功", new
                {
                    detail = dic.Select(x => new
                    {
                        field = x.Key,
                        text = dicTitle[x.Key],
                        value = x.Value,
                    }),
                    pagerid = task.y_TkModelId ?? 0,
                    taskid = task.TaskID,
                    id = id

                });
            }
            else
            {
                var callNum = DbHelperSQL.Query($"SELECT F_Phone FROM T_Call_TaskTelNum WHERE F_ID={id}").Tables[0];
                for (int j = 0; j < callNum.Columns.Count; j++)
                {
                    dic.Add(callNum.Columns[j].ColumnName, callNum.Rows[0][j].ToString());
                }
                return Success("获取成功", new
                {
                    detail = dic.Select(x => new
                    {
                        field = x.Key,
                        text = "电话号码",
                        value = x.Value,
                    }),
                    pagerid = task.y_TkModelId ?? 0,
                    taskid = task.TaskID,
                    id = id

                });
            }

        }
        /// <summary>
        /// 更新拨出号码的 呼叫状态
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateCallState(int id)
        {
            var model = taskTellNumBLL.GetModel(id);
            if (model == null)
                return Error("该号码信息不存在");
            if (taskTellNumBLL.UpdateHC(model.F_Id, 1))
                return Success("更新成功");
            return Error("更新失败");

        }
        #region 问卷回答
        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskid">任务ID</param>
        /// <param name="custelid">客户电话ID</param>
        /// <param name="cusid">客户档案ID</param>
        /// <param name="ans">答案，数组形式["15_20_单选选项内容","17_25|36|58_复选选项内容1|选项内容2|选项内容3","30_0_问答题"]</param>
        /// <param name="hjjgid">呼叫结果</param>
        /// <param name="yhfkid">用户反馈</param>
        /// <returns></returns>
        public ActionResult Answers(CallNumberInput input)
        {
            if (input.Id <= 0)
                return Error("提交失败，当前号码不存在");
            var otnModel = taskTellNumBLL.GetModel(input.Id);
            if (otnModel.F_HCState <= 0)
                return Error("提交失败，号码未进行呼叫");
            int cc = 0;
            var ansModel = new Model.T_Call_Answers();
            string askqids = "";
            string ansids = "";
            if (input.Ans != null)
            {

                //先删除 后添加
                ansBLL.DeleteByTelid(input.Id, input.TaskId);

                ansModel.F_TaskID = input.TaskId;
                ansModel.F_CusTelID = input.Id;
                //ansModel.F_CusID = cusid;
                ansModel.F_OptBy = CurrentUser.UserData.F_UserId;
                ansModel.F_OptByName = CurrentUser.UserData.F_UserName;
                ansModel.F_OptOn = DateTime.Now;
                foreach (var item in input.Ans)
                {
                    var nn = 0;
                    var ii = item.Split('_');
                    ansModel.F_QID = int.Parse(ii[0]);

                    askqids += ii[0] + ",";
                    ansids += ii[1] + ",";

                    if (ii[1].IndexOf('|') > 0)
                    {
                        var iii = ii[1].Trim('|').Split('|');
                        var iia = ii[2].Trim('|').Split('|');
                        for (int i = 0; i < iii.Length; i++)
                        {
                            ansModel.F_QIID = int.Parse(iii[i]);
                            ansModel.F_Answer = iia[i];
                            if (ansBLL.Add(ansModel) > 0)
                                nn++;
                        }
                        if (nn == iii.Length)
                            cc++;
                    }
                    else
                    {
                        ansModel.F_QIID = int.Parse(ii[1]);
                        ansModel.F_Answer = ii[2];
                        if (ansBLL.Add(ansModel) > 0)
                            cc++;
                    }
                }
            }


            if (otnModel != null)
            {
                otnModel.F_HJJGId = input.HJJG;
                var hjconfig = new BLL.T_Sys_DictionaryValue().GetModel(input.HJJG);
                if (hjconfig != null)
                {
                    otnModel.F_HJJGName = hjconfig.F_Name;
                    if (hjconfig.F_Name == "正常接通")
                    {
                        otnModel.F_YJState = 1;
                    }
                }
                otnModel.F_YHFKID = input.YHFK;
                var fkconfig = new BLL.T_Sys_DictionaryValue().GetModel(input.YHFK);
                if (fkconfig != null)
                    otnModel.F_YHFKName = fkconfig.F_Name;
                otnModel.F_AskRes = askqids;
                otnModel.F_AskInfo = ansids;

                otnModel.F_Remark = input.Remark ?? "";
                taskTellNumBLL.Update(otnModel);

                //记录日志
                //planrecord(otnModel);
            }


            if (cc == (input.Ans?.Length ?? 0))
            {
                return Success("提交成功！taskid=" + input.TaskId + ",custelid=" + input.Id + ",操作人：" + CurrentUser.UserData.F_UserCode);
            }
            else
            {
                ansBLL.DeleteByTelid(input.Id, input.TaskId);
                return Error("问卷答案提交失败！taskid=" + input.TaskId + ",custelid=" + input.Id + ",操作人：" + CurrentUser.UserData.F_UserCode);
            }

        }
        #endregion
        public ActionResult GetTaskTelInfo(int id = 0)
        {
            if (id <= 0)
                return Error("参数不正确");
            var model = taskTellNumBLL.GetModel(id);

            var paperid = 0;
            if (model != null)
            {
                var anslist = ansBLL.GetModelList(" F_TaskID=" + model.F_TaskId.Value + " and F_CusTelID=" + id + " ");
                var tmodel = taskBLL.GetModel(model.F_TaskId.Value);
                if (tmodel != null)
                {
                    paperid = (int)tmodel.y_TkModelId.Value;
                    #region 获取问卷试题信息以及答案
                    var pmodel = pagerInfoBLL.GetModel(paperid);
                    if (pmodel != null)
                    {
                        var qlist = questionBLL.GetModelList(" F_DeleteFlag=0 and F_QuestionId in (select F_QuestionId from T_Ask_PagerItems where F_PagerId=" + paperid + ")  order by F_QuestionId ");
                        var qilist = questionItemBLL.GetModelList(" F_QuestionId in (select F_QuestionId from T_Ask_PagerItems where F_PagerId=" + paperid + ")  order by F_ItemId ");
                        var newmodel = new
                        {
                            F_Title = pmodel.F_Title,
                            F_Remark = pmodel.F_Remark,
                            F_Questions = qlist.Select(q =>
                            {
                                var answers = "";
                                var qalist = anslist.Where(al => al.F_QID.Value == q.F_QuestionId).ToList<Model.T_Call_Answers>();
                                if (qalist.Count > 0)
                                {
                                    if (q.F_Type > 1)
                                    {
                                        foreach (var item in qalist)
                                        {
                                            answers += item.F_QIID + "|";
                                        }
                                    }
                                    else
                                    {
                                        answers = qalist[0].F_Answer;
                                    }
                                }
                                return new
                                {
                                    quesid = q.F_QuestionId,
                                    questitle = q.F_Title,
                                    questype = q.F_Type,
                                    quescontent = q.F_Content,
                                    quesremark = q.F_Remark,
                                    quesanswers = answers.Trim('|'),
                                    quesitems = qilist.Where(qq => qq.F_QuestionId == q.F_QuestionId).Select(qi =>
                                    {
                                        return new
                                        {
                                            itemid = qi.F_ItemId,
                                            itemname = qi.F_ItemName,
                                            itemremark = qi.F_Remark,
                                        };
                                    })
                                };
                            })
                        };
                        return Success("获取详情成功", new
                        {
                            taskModel = model,
                            paperModel = newmodel
                        });
                    }
                    #endregion
                    return Success("获取详情成功", new
                    {
                        taskModel = model
                    });
                }
            }
            return Error("获取详情失败");
        }


        #endregion

        #region 导入导出号码
        /// <summary>
        /// 导入号码信息
        /// </summary>
        /// <param name="type">导入方式：1=Excel; 2=txt .......</param>
        /// <returns></returns>
        public ActionResult ImportData(ImportDataInput input)
        {
            if (Request.Files.Count <= 0)
                return Error("请正确上传Excel文件");
            var file = Request.Files[0];
            if (!file.ContentType.Equals("application/vnd.ms-excel") && !file.ContentType.Equals("application/x-xls") && !file.ContentType.Equals("application/x-xlsx") && !file.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !file.ContentType.Equals("application/octet-stream"))
                return Error($"请正确上传Excel文件：file.ContentType={file.ContentType}");
            var filePath = "";
            NPOIHelper npoi = new NPOIHelper();
            var dt = npoi.ExcelToTable(file, 0, out filePath);
            var obj = dt.AsEnumerable().Take(10).CopyToDataTable();
            var colCount = obj.Columns.Count;
            var rowCount = obj.Rows.Count;

            string[] headArr = new string[colCount];
            for (int i = 0; i < colCount; i++)
            {
                headArr[i] = obj.Columns[i].ToString();
            }

            string[][] itemArr = new string[rowCount][];
            itemArr[0] = new string[rowCount];
            for (int i = 0; i < rowCount; i++)
            {
                var row = obj.Rows[i];
                var itemArray = row.ItemArray;
                itemArr[i] = new string[itemArray.Count()];
                for (int j = 0; j < itemArray.Count(); j++)
                {
                    itemArr[i][j] = itemArray[j].ToString();
                }
            }

            return Success("上传成功", new
            {
                filepath = filePath,
                heads = headArr,
                items = itemArr
            });
        }
        /// <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.GetPhoneList(" F_TaskId=" + task.TaskID + "  and F_HCState=1 and  (F_YJState=0 or F_YJState is null) ").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.GetPhoneList(" 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("参数错误");
        }
        #endregion

        #region 自动放音
        /// <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(FilterTalkRecord filter)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                 "T_CTI_TaskRecord ",
                 "id",
                 "*",
                 "",
                 "ORDER BY id desc",
                 filter.PageSize,
                 filter.PageIndex,
                 true,
                 out recordCount);


            var list = taskRecordBLL.DataTableToList(dt).Select(x => new
            {
                id = x.Id,
                name = x.Name,
                recordpath = x.RecordPath,
                recordtime = x.RecordTime,
            });
            var obj = new
            {
                rows = list,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <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 dir = Server.MapPath("~/UploadRecord/");

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                var file = Request.Files[0];
                if (file.ContentType != "audio/x-wav" && file.ContentType != "audio/wav")
                    return Error("上传录音格式必须为.wav");

                var name = DateTime.Now.ToString("yyyyMMddHHmmss") + Guid.NewGuid().ToString("N").Substring(0, 10) + ".wav";
                var path = dir + name;
                Request.Files[0].SaveAs(path);

                FileInfo fileInfo = new FileInfo(path);
                var fileName = FileUp.UploadFile(fileInfo, "/", "120.194.141.197", "Administrator", "hykj@800100");

                var sysConfig = systemConfigBLL.GetModel(40);
                if (sysConfig == null)
                    return Error("自动放音录音路径查询失败");
                model.Name = input.Name;
                model.RecordPath = sysConfig.F_ParamValue + fileName;
                //model.RecordTime = input.RecordTime;
                model.Remark = input.Remark;

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

        #region 话单查询
        /// <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 = taskPhonePartBLL.DataTableToList(taskPhonePartBLL.GetList("").Tables[0]);
            var sec = taskDailyBLL.DataTableToList(taskDailyBLL.GetList("").Tables[0]);
            var thi = taskDailyBLL.DataTableToList(taskDailyBLL.GetList().Tables[0]);

            var obj = new
            {
                fir = fir.Select(x => new
                {
                    date = x.Date.ToString("yyyy-MM-dd"),
                    phonepart = x.PhonePart,
                    province = x.Province,
                    city = x.City,
                    connectedcount = x.CalledCount == 0 ? "" : (x.ConnectedCount / x.CalledCount * 100).ToString("f2") + "%",
                    connectedagentcount = x.ConnectedCount == 0 ? "" : (x.ConnectedAgentCount / x.ConnectedCount * 100).ToString("f2") + "%",
                }),
                sec = sec.Select(x => new
                {
                    date = x.Date.ToString("yyyy-MM-dd"),
                    allcount = x.AllCount,
                    calledcount = x.CalledCount,
                    connectedcount = x.ConnectedCount,
                    connectedagentcount = x.ConnectedAgentCount,
                    connectedrate = x.CalledCount == 0 ? "" : (x.ConnectedCount / x.CalledCount * 100).ToString("f2") + "%",
                    connectedagentrate = x.ConnectedCount == 0 ? "" : (x.ConnectedAgentCount / x.ConnectedCount * 100).ToString("f2") + "%",
                    taskid = x.TaskId,
                    taskname = x.TaskName

                }),
                thi = thi.Select(x => new
                {
                    date = x.Date.ToString("yyyy-MM-dd"),
                    allcount = x.AllCount,
                    calledcount = x.CalledCount,
                    connectedcount = x.ConnectedCount,
                    connectedagentcount = x.ConnectedAgentCount,
                    connectedrate = x.CalledCount == 0 ? "" : (x.ConnectedCount / x.CalledCount * 100).ToString("f2") + "%",
                    connectedagentrate = x.ConnectedCount == 0 ? "" : (x.ConnectedAgentCount / x.ConnectedCount * 100).ToString("f2") + "%",
                    taskid = x.TaskId,
                    taskname = x.TaskName
                })
            };


            return Success("", obj);
        }
        /// <summary>
        /// 获取通话记录列表
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetTalkRecords(FilterTalkRecord filter)
        {
            var sort = "ORDER BY startdate desc";
            if (!string.IsNullOrWhiteSpace(filter.SortField))
            {
                var arr = filter.SortField.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                EnumTalkRecordsSortField e;
                if (!Enum.TryParse(arr[0], out e))
                    return Error("排序字段参数错误");
                sort = "ORDER BY " + e.ToString() + " " + arr[1];
            }

            StringBuilder where = new StringBuilder();


            if (!string.IsNullOrWhiteSpace(filter.UserCode))
            {
                where.Append(" and agentid=" + filter.UserCode);
            }
            if (!string.IsNullOrWhiteSpace(filter.Phone))
            {
                where.Append(" and callee like '%" + filter.Phone + "%'");
            }

            //全部=0
            //未转坐席 = 1,
            //被叫接通转坐席未接 = 2,
            //转坐席且接通 = 3,
            if (filter.CallType != 0)
            {
                EnumTalkRecordsCallType calltype;
                if (!Enum.TryParse(filter.CallType.ToString(), out calltype))
                    return Error("通话类型字段参数错误");
                where.Append(" and calltype=" + (int)calltype);
            }

            if (!string.IsNullOrWhiteSpace(filter.TalkTime))
            {
                var arr = filter.TalkTime.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (arr.Length == 2)
                {
                    if (arr[0] == "1")
                    {
                        where.Append(" and talktime>" + arr[1]);
                    }
                    else if (arr[0] == "2")
                    {
                        where.Append(" and talktime=" + arr[1]);
                    }
                    else if (arr[0] == "3")
                    {
                        where.Append(" and talktime<" + arr[1]);
                    }
                    else { }
                }
            }

            if (filter.StartTime == null || filter.EndTime == null)
            {
                filter.StartTime = DateTools.FirstSecondOfOneDay(DateTime.Now);
                filter.EndTime = DateTools.LastSecondOfOneDay(DateTime.Now);
            }
            where.Append(" and datediff(s,'" + filter.StartTime + "',StartDate)>=0 and datediff(s,EndDate,'" + filter.EndTime + "')>=0 ");




            int recordCount = 0;
            Model.PageData<Model.CallResult> pageModel = new Model.PageData<Model.CallResult>();
            StringBuilder fields = new StringBuilder();
            var dt = BLL.PagerBLL.GetListPager(
                       "V_AutoCallResult",
                       " ID ",
                       " ID,itemid,taskname, callee, agentid, username,startdate,enddate,getinagentdate,calltype,talktime,RecordPath",
                       where.ToString(),
                       sort,
                       filter.PageSize,
                       filter.PageIndex,
                       true,
                       out recordCount);
            var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var callResultList = callResultBLL.DataTableToList(dt);
            var list = new List<AutoCallRecordDto>();
            callResultList.ForEach(x =>
            {
                var recordPath = "";
                if (!string.IsNullOrWhiteSpace(x.RecordPath) && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                {
                    var ym = config.F_ParamValue;
                    if (ym.Substring(ym.Length - 1) == "/")
                    {
                        ym = ym.Substring(0, ym.Length - 1);
                    }
                    recordPath = ym + x.RecordPath.Substring(x.RecordPath.IndexOf(':') + 1).Replace('\\', '/');
                }

                list.Add(new AutoCallRecordDto
                {
                    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 = recordPath,
                    username = x.Username,
                    calltype = Enum.Parse(typeof(EnumTalkRecordsCallType), x.CallType.ToString()).ToString(),
                    talktime = x.TalkTime > 0 ? x.TalkTime.ToString() : "0"
                });
            });

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

        public ActionResult GetCallType()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (int item in Enum.GetValues(typeof(EnumTalkRecordsCallType)))
            {
                dic.Add(((EnumTalkRecordsCallType)item).ToString(), item.ToString());
            }
            return Success("", dic.Select(x => new
            {
                text = x.Key,
                value = x.Value
            }));
        }

        #endregion

        #region 过滤号码
        #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
        #endregion

    }
}