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
{
    [Authority]
    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_Sys_SystemConfig systemConfigBLL = new BLL.T_Sys_SystemConfig();
        private readonly BLL.T_Sys_UserAccount userAccount = new BLL.T_Sys_UserAccount();
        private readonly BLL.T_Sys_SeatGroup seatGroupBLL = new BLL.T_Sys_SeatGroup();
        private readonly BLL.T_CTI_TaskCategory taskCategoryBLL = new BLL.T_CTI_TaskCategory();
        private readonly BLL.T_CTI_TaskVoiceTemp taskVoiceTempBLL = new BLL.T_CTI_TaskVoiceTemp();

        #region 外呼任务
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetList(FilterCallPlan filter)
        {
            var sql = " and State>=0  ";
            if (!string.IsNullOrWhiteSpace(filter.Name))
            {
                sql += "  and (TaskName like '%" + filter.Name.Trim() + "%' ) ";
            }
            if (filter.CategoryId > 0)
            {
                sql += "  and TaskCategoryId=" + filter.CategoryId;
            }

            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 categoryList = taskCategoryBLL.DataTableToList(taskCategoryBLL.GetList("").Tables[0]);
            var list = new List<CallPlanDto>();

            var obj = new
            {
                rows = modelList.Select(x => new
                {
                    id = x.TaskID,
                    name = x.TaskName,
                    categoryname = categoryList.SingleOrDefault(y => y.F_Id == x.TaskCategoryId)?.F_Name ?? "",
                    allcount = x.y_HMCount,     //号码总数
                    connected = x.y_YJCount,    //已接总数
                    connectfailed = (x.y_HMCount - x.y_YJCount) < 0 ? 0 : (x.y_HMCount - x.y_YJCount),  //未呼叫总数
                    state = Enum.GetName(typeof(EnumTaskState), (x.State ?? -1)),
                }),
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetModel(int id)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            if (id == -10001)
                return Error("该任务为固定试听队列，不可查询");
            var model = taskBLL.GetModel(id);
            var categoryList = taskCategoryBLL.DataTableToList(taskCategoryBLL.GetList("").Tables[0]);
            if (model == null)
                return Error("语音通知不存在");
            return Success("获取成功", new CallPlanDto
            {
                id = model.TaskID,
                name = model.TaskName,
                categoryid = model.TaskCategoryId,
                categoryname = categoryList.SingleOrDefault(x => x.F_Id == model.TaskCategoryId)?.F_Name ?? "",
                content = model.TaskContent,
                isexcutenow = model.IsExcuteNow ?? false,
                looptime = model.LoopTime,
                //state = "暂停",
                addtime = Convert.ToDateTime(model.AddTime).ToString("yyyy-MM-dd HH:mm:ss"),
                //pre = model.Pre, //线路前缀
                //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:ss") ?? "",
                endtime1 = model.EndTime1.ToString("HH:mm:ss") ?? "",
                starttime2 = model.StartTime2.ToString("HH:mm:ss") ?? "",
                endtime2 = model.EndTime2.ToString("HH:mm:ss") ?? "",
            });
        }
        /// <summary>
        /// 添加/修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult CreateOrUpdate(CallPlanInput input)
        {
          //  if (!Request.IsAuthenticated)
              //  return NoToken("未知错误，请重新登录");
            var model = new Model.T_CTI_Task();
            if (string.IsNullOrWhiteSpace(input.TaskContent))
                return Error("请输入通知内容");

            var category = taskCategoryBLL.GetModel(input.TaskCategoryId);
            if (category == null)
                return Error("分类不存在");

            if (!(input.IsExcuteNow ?? false))
            {
                if (input.StartTime1 == null || input.StartTime2 == null || input.EndTime1 == null || input.EndTime2 == null)
                    return Error("定时执行必须设置开始、结束时间段");
            }

            #region 该任务为固定试听队列，不可编辑
            if (input.Id == -10001)
                return Error("该任务为固定试听队列，不可编辑");
            #endregion


            if (input.Id == 0)
            {
                model.TaskName = input.Name;
                model.TaskCategoryId = input.TaskCategoryId;
                model.TaskContent = input.TaskContent;
                model.IsExcuteNow = input.IsExcuteNow ?? false;
                model.LoopTime = input.LoopTime;
                //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_YJCount = 0;
                model.State = Convert.ToBoolean(model.IsExcuteNow) ? 1 : 2;
                model.AddTime = DateTime.Now;
                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)
                {
                    // return Success("添加成功", i);
                    try
                    {
                        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();
                                if (Request.Files.Count <= 0)
                                    throw new Exception("请选中导入的Excel文件！");
                                var a = Request.Files[0];
                                var dtExcel = npoi.ExcelToTable(Request.Files[0], 0);
                                foreach (DataRow item in dtExcel.Rows)
                                {
                                    var row = dt.NewRow();
                                    row["F_TaskId"] = model.TaskID;
                                    row["F_Phone"] = item[0].ToString();
                                    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("当前外呼任务不存在");

            //taskid=-10002 是语音自动回访任务，固定，仅可以修改内容
            if (model.TaskID == -10002)
            {
                model.TaskContent = input.TaskContent;
            }
            else
            {
                model.TaskName = input.Name;
                model.TaskCategoryId = input.TaskCategoryId;
                model.TaskContent = input.TaskContent;
                model.IsExcuteNow = input.IsExcuteNow ?? false;
                if (model.IsExcuteNow ?? false)
                {
                    model.State = 1;
                }
                model.LoopTime = input.LoopTime;
                //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;
            }
            if (taskBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult Delete(int id)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            if (id == -10001)
                return Error("该任务为固定试听队列，不可删除");
            if (taskBLL.UpdateStateBatch($" where TaskID={id}", -1))
                return Success("删除成功");
            return Error("删除失败");
        }
        /// <summary>
        /// 获取号码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetPhoneList(FilterCallPhone filter)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = taskBLL.GetModel(filter.Id);
            if (model == null)
                return Error("语音通知不存在");
            var sql = "";
            if (!string.IsNullOrWhiteSpace(filter.Phone))
            {
                sql = $" and F_Phone like '%{filter.Phone}%'";
            }

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                             "T_Call_TaskTelNum",
                             "F_Id",
                             "*",
                             " 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().DataTableToList(dt);
            var obj = new
            {
                rows = modelList.Select(x => new
                {
                    phone = x.F_Phone,
                    isconnected = x.F_YJState > 0 ? "正常接通" : "",
                    looptime = model.LoopTime,
                    calltime = x.F_HCCount,
                    dtmf = x.DTMF > 0 ? x.DTMF.ToString() : ""
                }),
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        #endregion

        #region 语音试听 //taskid=-10001 是语音试听任务，固定不可修改
        public ActionResult TryListen(string phone = "", string text = "", string fix = "")
        {
            string phone1 = RequestString.ToDBC(RequestString.RemoveNotNumber(WebHelper.NoHtml(phone)));
            if (string.IsNullOrWhiteSpace(text))
                return Error("请正确填写试听内容");

            var model = taskBLL.GetModel(-10001);
            if (model == null)
                return Error("试听队列阻塞，请联系管理员");

            model.y_HMCount = model.y_HMCount + 1;
            model.State = 1;
            model.TaskContent = text;
            var flag = taskBLL.Update(model);

            if (flag)
            {
                var i = taskTellNumBLL.Add(new T_Call_TaskTelNum
                {
                    F_TaskId = -10001,
                    // F_Phone = fix + phone1
                    F_Phone = phone1
                });
                if (i > 0)
                    return Success("号码已加入试听队列，请注意接听");
                return Error("");
            }
            return Error("试听队列阻塞，请联系管理员");
        }

        #endregion

        #region 语音自动回访  //taskid=-10002 是语音自动回访任务，固定，仅可以修改内容
        public ActionResult AddToVoiceNotice(AutoVoiceNoticeInput input)
        {
            string phone = RequestString.ToDBC(RequestString.RemoveNotNumber(WebHelper.NoHtml(input.Phone)));
            var msg = "";
            var flag = taskBLL.AddToAutoVoiceNotice(phone, input.WorkOrderId, input.AssignId, out msg);
            if (flag)
                return Success(msg);
            return Error(msg);
        }
        #endregion


        #region 语音通知类别 
        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetCategoryList(FilterVoiceCategory filter)
        {
            var sql = " ";
            if (!string.IsNullOrWhiteSpace(filter.Name))
            {
                sql += "  and (T1.F_Name like '%" + filter.Name.Trim() + "%' ) ";
            }
            if (filter.CategoryId >= 0)
            {
                sql += $"  and T1.F_ParentId={filter.CategoryId}";
            }
            Model.PageData<Model.T_CTI_TaskCategory> pageModel = new Model.PageData<Model.T_CTI_TaskCategory>();
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                             "T_CTI_TaskCategory T1 left join T_CTI_TaskCategory AS T2 on T1.F_ParentId =T2.F_Id ",
                             "T1.F_Id",
                             " T1.F_Id,T1.F_ParentId,T1.F_Name,T2.F_Name AS F_ParentName",
                             sql,
                             "ORDER BY T1.F_Id desc",
                             filter.PageSize,
                             filter.PageIndex,
                             true,
                             out recordCount);
            List<Model.T_CTI_TaskCategory> modelList = taskCategoryBLL.DataTableToList(dt);
            var obj = new
            {
                rows = modelList.Select(x => new
                {
                    id = x.F_Id,
                    pid = x.F_ParentId,
                    name = x.F_Name,
                    pname = x.F_ParentId == 0 ? "顶级分类" : x.F_ParentName
                }),
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 获取所有类别（包含顶级分类）
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetCategoryAllList()
        {
            List<Model.T_CTI_TaskCategory> modelList = taskCategoryBLL.DataTableToList(taskCategoryBLL.GetList("").Tables[0]);
            modelList.Add(new T_CTI_TaskCategory
            {
                F_Id = 0,
                F_Name = "顶级分类"
            });
            return Success("success", modelList.Select(x => new
            {
                id = x.F_Id,
                name = x.F_Name
            }));
        }
        /// <summary>
        /// 获取所有类别（不包含顶级分类）
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetCategoryALLList2()
        {
            List<Model.T_CTI_TaskCategory> modelList = taskCategoryBLL.DataTableToList(taskCategoryBLL.GetList("").Tables[0]);
            return Success("success", modelList.Select(x => new
            {
                id = x.F_Id,
                name = x.F_Name
            }));
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetCategory(int id)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = taskCategoryBLL.GetModel(id);
            if (model == null)
                return Error("预测外呼任务不存在");
            return Success("获取成功", new
            {
                id = model.F_Id,
                pid = model.F_ParentId,
                name = model.F_Name,
                pname = model.F_ParentId == 0 ? "顶级分类" : model.F_ParentName
            });
        }
        /// <summary>
        /// 添加/修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult CreateOrUpdateCategory(VoiceCategoryInput input)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            if(string.IsNullOrEmpty(input.Name))
                return Error("类别名称不允许为空");
            var model = new Model.T_CTI_TaskCategory();
            if (input.ParentId > 0)
            {
                var pModel = taskCategoryBLL.GetModel(input.ParentId);
                if (pModel == null)
                    return Error("父分类不存在");
            }
            if (input.Id <= 0)
            {
                model.F_ParentId = input.ParentId;
                model.F_Name = input.Name;
                var categoryId = taskCategoryBLL.Add(model);
                if (categoryId > 0)
                    return Success("添加成功");
                return Error("添加失败");
            }

            model = taskCategoryBLL.GetModel(input.Id);
            if (model == null)
                return Error("当前分类不存在");
            model.F_Name = input.Name;
            model.F_ParentId = input.ParentId;
            if (taskCategoryBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult DeleteCategory(int id)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            if (taskCategoryBLL.Delete(id))
                return Success("删除成功");
            return Error("删除失败");
        }
        #endregion

        #region 语音通知模板
        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetVoiceTempList(FilterVoiceTemp filter)
        {
            var sql = " ";
            if (!string.IsNullOrWhiteSpace(filter.Title))
            {
                sql += $"  and (T1.F_Title like '%{filter.Title.Trim()}%' ) ";
            }
            if (filter.CategoryId >= 0)
            {
                sql += $"  and T1.F_CategoryId={filter.CategoryId}";
            }
            Model.PageData<Model.T_CTI_TaskVoiceTemp> pageModel = new Model.PageData<Model.T_CTI_TaskVoiceTemp>();
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                             "T_CTI_TaskVoiceTemp T1 left join T_CTI_TaskCategory AS T2 on  T1.F_CategoryId =T2.F_Id ",
                             "T1.F_Id",
                             " T1.F_Id,T1.F_CategoryId,T1.F_Title,T1.F_Content,T1.F_UpdateTime,T2.F_Name  AS F_CategoryName",
                             sql,
                             "ORDER BY T1.F_Id desc",
                             filter.PageSize,
                             filter.PageIndex,
                             true,
                             out recordCount);
            List<Model.T_CTI_TaskVoiceTemp> modelList = taskVoiceTempBLL.DataTableToList(dt);
            var obj = new
            {
                rows = modelList.Select(x => new
                {
                    id = x.F_Id,
                    categoryid = x.F_CategoryId,
                    categoryname = x.F_CategoryId == 0 ? "顶级分类" : x.F_CategoryName,
                    title = x.F_Title,
                    content = x.F_Content,
                    updatetime = x.F_UpdateTime.ToString("yyyy-MM-dd HH:mm:ss")
                }),
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        //[Authority]
        public ActionResult GetVoiceTempTitleList(FilterVoiceTemp filter)
        {
            var list = taskVoiceTempBLL.DataTableToList2(taskVoiceTempBLL.GetList("").Tables[0]);
            return Success("获取成功", list.Select(x => new
            {
                id = x.F_Id,
                title = x.F_Title,
            }));
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetVoiceTemp(int id)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = taskVoiceTempBLL.GetModel(id);
            if (model == null)
                return Error("预测外呼任务不存在");
            return Success("获取成功", new
            {
                id = model.F_Id,
                categoryid = model.F_CategoryId,
                categoryname = model.F_CategoryId == 0 ? "顶级分类" : model.F_CategoryName,
                title = model.F_Title,
                content = model.F_Content,
                updatetime = model.F_UpdateTime.ToString("yyyy-MM-dd HH:mm:ss")
            });
        }
        /// <summary>
        /// 添加/修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult CreateOrUpdateVoiceTemp(VoiceTempleteInput input)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = new Model.T_CTI_TaskVoiceTemp();
            var category = taskCategoryBLL.GetModel(input.CategoryId);
            if (category == null)
                return Error("分类不存在");
            if (input.Id <= 0)
            {
                model.F_CategoryId = input.CategoryId;
                model.F_Title = input.Title;
                model.F_Content = input.Content;
                model.F_UpdateTime = DateTime.Now;

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

            model = taskVoiceTempBLL.GetModel(input.Id);
            if (model == null)
                return Error("当前语音模板不存在");
            model.F_CategoryId = input.CategoryId;
            model.F_Title = input.Title;
            model.F_Content = input.Content;
            model.F_UpdateTime = DateTime.Now;
            if (taskVoiceTempBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult DeleteVoiceTemp(int[] ids)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            if (ids == null || ids.Length <= 0)
                return Error("获取参数失败");
            var idStr = string.Join(",", ids);
            if (taskVoiceTempBLL.DeleteBatch(idStr))
                return Success("修改成功");
            return Error("修改失败");
        }
        #endregion

        #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

    }
}