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

namespace CallCenterApi.Interface.Controllers.callout
{
   
    public class CallOutPlanController : BaseController
    {
        private readonly BLL.T_Call_OutTask otBLL = new BLL.T_Call_OutTask();
        private readonly BLL.T_Call_OutTaskTelNum otnBLL = new BLL.T_Call_OutTaskTelNum();
        private readonly BLL.T_Call_OutTaskRecords otrBLL = new BLL.T_Call_OutTaskRecords();
        private readonly BLL.T_Cus_CustomerBase cusBLL = new BLL.T_Cus_CustomerBase();
        private readonly BLL.T_Call_OutAnswers ansBLL = new BLL.T_Call_OutAnswers();
        private readonly BLL.T_Ask_Question questionBLL = new BLL.T_Ask_Question();
        private readonly BLL.T_Ask_QuestionItems questionItemBLL = new BLL.T_Ask_QuestionItems();
        private readonly BLL.T_Ask_PagerInfo pagerInfoBLL = new BLL.T_Ask_PagerInfo();

        private readonly BLL.T_Ask_QuestionCategory  qcBLL = new BLL.T_Ask_QuestionCategory();
    

        #region 计划信息
        public ActionResult GetTaskList(string key, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and (F_TaskName like '%" + key + "%' or F_TaskRemark like '%" + key + "%') ");
            }

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Call_OutTask",
                    "F_TaskID",
                    "*",
                    " and F_DeleteFlag=0 " + sb.ToString(),
                    "ORDER BY F_TaskID desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        public ActionResult GetAllTaskList()
        {
            var alllist = otBLL.GetModelList(" F_DeleteFlag=0 order by F_TaskID desc");
            return Success("获取试题分类成功", alllist);
        }
        public ActionResult GetTaskModel(int id = 0)
        {
            if (id <= 0)
                return Error("参数不正确");
            var model = otBLL.GetModel(id);
            if (model == null)
                return Error("当前数据不存在");

            var papermodel = pagerInfoBLL.GetModel(model.F_PagerID.Value);
            var newmodel = new
            {
                taskmodel = model,
                pagermodel = papermodel
            };
            return Success("获取成功", newmodel);
        }
        public ActionResult CreateOrUpdateTask(int id = 0, int pagerid = 0, string name = "", string remark = "")
        {
            var model = new Model.T_Call_OutTask();
            if (string.IsNullOrWhiteSpace(name))
                return Error("请填写名称" + ",操作人：" + CurrentUser.UserData.F_UserCode);
            if (id <= 0)
            {
                model.F_TaskName = name;
                model.F_TaskRemark = remark;
                model.F_PagerID = pagerid;
                model.F_IsAllot = 0;
                model.F_IsStart = 0;
                model.F_CreateTime = DateTime.Now;
                model.F_CreateUserCode = CurrentUser.UserData.F_UserCode;
                model.F_DeleteFlag = 0;
                if (otBLL.Add(model) > 0)
                    return Success("添加成功" + ",操作人：" + CurrentUser.UserData.F_UserCode);
                return Error("添加失败" + ",操作人：" + CurrentUser.UserData.F_UserCode);
            }
            model = otBLL.GetModel(id);
            model.F_TaskName = name;
            model.F_TaskRemark = remark;
            model.F_PagerID = pagerid;
            if (otBLL.Update(model))
                return Success("修改成功" + ",操作人：" + CurrentUser.UserData.F_UserCode);
            return Error("修改失败" + ",操作人：" + CurrentUser.UserData.F_UserCode);
        }
        //删除任务
        public ActionResult DeleteTask(int id = 0)
        {
            if (id > 0)
            {
                var tellist = otnBLL.GetRecordCount(" F_DeleteFlag=0 and  F_TaskId=" + id);
                if (tellist > 0)
                {
                    return Error("请先清理任务下的号码，再做删除！");
                }
                if (otBLL.Delete(id))
                {
                    return Success("删除成功" + ",操作人：" + CurrentUser.UserData.F_UserCode);
                }
                else
                {
                    return Error("删除失败!" + ",操作人：" + CurrentUser.UserData.F_UserCode);
                }
            }
            return Error("参数传入失败");
        }
        //清理号码
        public ActionResult DeletesTaskTel(int id = 0)
        {
            if (otnBLL.DeleteByTask(id))
            {
                return Success("清理任务下号码成功" + ",操作人：" + CurrentUser.UserData.F_UserCode);
            }
            else
            {
                return Error("清理任务下号码失败!" + ",操作人：" + CurrentUser.UserData.F_UserCode);
            }
        }

        //计划启动并关联客户档案、生成任务
        public ActionResult EditTaskNum(int taskid = 0, int state = 0)
        {
            if (state == 1)
            {
                if (taskid > 0)
                {
                    //var cuslist = cusBLL.GetModelList(" F_AutoFlag=1 ");//标记为有效的客户
                    //int cc = 0;
                    //foreach (var cusitem in cuslist)
                    //{
                    //    var otnModel = new Model.T_Call_OutTaskTelNum();
                    //    otnModel.F_TaskId = taskid;
                    //    otnModel.F_CusID = cusitem.F_CustomerId;
                    //    otnModel.F_CusName = cusitem.F_CustomerName;
                    //    otnModel.F_CreateTime = DateTime.Now;
                    //    otnModel.F_Phone = cusitem.F_Mobile;
                    //    otnModel.F_FPState = 0;
                    //    otnModel.F_HCState = 0;
                    //    otnModel.F_YJState = 0;
                    //    otnModel.F_DeleteFlag = 0;
                    //    if (otnBLL.Add(otnModel) > 0)
                    //    {
                    //        cc++;
                    //    }
                    //}

                    //if (cc == cuslist.Count)
                    //{
                    if (otBLL.UpdateStart(taskid, 1, DateTime.Now, DateTime.MaxValue))
                    {
                        return Success("计划启动成功！taskid=" + taskid + ",操作人：" + CurrentUser.UserData.F_UserCode);
                    }
                    else
                    {
                        //otnBLL.DeleteByTask(taskid);
                        return Error("计划启动失败！taskid=" + taskid + ",操作人：" + CurrentUser.UserData.F_UserCode);
                    }
                    // }
                }
            }
            else
            {
                var taskmodel = otBLL.GetModel(taskid);
                if (taskmodel.F_IsStart == state)
                {
                    return Error("计划未启动，无法停止！taskid=" + taskid + ",操作人：" + CurrentUser.UserData.F_UserCode);
                }
                else
                {
                    if (otBLL.UpdateStart(taskid, 0, taskmodel.F_StartTime.Value, DateTime.Now))
                    {
                        //otnBLL.DeleteByTask(taskid);
                        return Success("计划已停止！taskid=" + taskid + ",操作人：" + CurrentUser.UserData.F_UserCode);
                    }
                }
            }
            return Error("计划操作失败！taskid=" + taskid + ",操作人：" + CurrentUser.UserData.F_UserCode);
        }
        #endregion
        #region 号码导入
        int vfileid = 0;
        // 导入号码读取填入数据库
        public ActionResult TelInput(int taskid)
        {
            DataTable dtres = new DataTable();
            string errres = "";
            int i = 0;
            int count = 0;//导入成功的条数
            string Excelsource = "";
            int rcount = 0;
            int ccount = 0;
            System.Text.StringBuilder strBuilder = null;
            //Excelsource = Server.MapPath(this.Request.ApplicationPath + "\\ExcelData\\") + filename.ToString();
            Excelsource = uploadexcel();
            #region 将文件中的数据导入数据库

            try
            {

                //************************将文件中的数据导入数据库*************************//
                DataSet dt = ReadEcxel(Excelsource, 0);
                try
                {
                    if (dt != null && dt.Tables[0].Rows.Count != 0)
                    {
                        rcount = dt.Tables[0].Rows.Count;
                        ccount = dt.Tables[0].Columns.Count;
                        strBuilder = new System.Text.StringBuilder();//用于如果导入失败，删除已经导入过的

                        DataTable dtInputData = dt.Tables[0];//要导入的电话号码
                        List<string> sqlList = new List<string>();
                        List<string> lstsql = new List<string>();
                        int ilns = dt.Tables[0].Columns.Count;
                        DataSet dsnew = new DataSet();


                        #region MyRegion
                        using (SqlConnection coon = new SqlConnection(DbHelperSQL.connectionString))
                        {
                            try
                            {
                                coon.Open();
                                int colscount = dtInputData.Columns.Count;//列数
                                int rowscount = dtInputData.Rows.Count;//行数
                                BLL.T_Call_OutTaskTelNum bll = new BLL.T_Call_OutTaskTelNum();
                                Model.T_Call_OutTaskTelNum modelPhoneImport = new Model.T_Call_OutTaskTelNum();
                                #region
                                modelPhoneImport.F_FPState = 0;
                                modelPhoneImport.F_YJState = 0;
                                modelPhoneImport.F_DeleteFlag = 0;
                                modelPhoneImport.F_HCState = 0;
                                modelPhoneImport.ExpandVchField15 = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");//导入时间
                                modelPhoneImport.ExpandVchField14 = CurrentUser.UserData.F_UserId.ToString();//导入坐席ID
                                modelPhoneImport.ExpandVchField13 = CurrentUser.UserData.F_UserName;

                                


                                modelPhoneImport.F_TaskId = taskid;
                                modelPhoneImport.ExpandIntField6 = vfileid;//导入文件id
                                #endregion
                                if (rowscount > 0)
                                {
                                    foreach (DataRow dr in dtInputData.Rows)
                                    {
                                        sqlList.Clear();
                                        lstsql.Clear();
                                        if (dr[1].ToString() != "")
                                        {
                                            string dddddd = dr[1].ToString();
                                            #region 导入表内容
                                            //目标分类、营业部、电话号码、宽带账号、地址、入网时间、入网渠道、营服、套餐、是否融合、状态
                                            modelPhoneImport.ExpandVchField1 = dr[0].ToString();//目标分类
                                               //modelPhoneImport.ExpandVchField2 = dr[1].ToString();//营业部
                                               //modelPhoneImport.ExpandVchField3 = dr[3].ToString();//宽带账号
                                                //modelPhoneImport.ExpandVchField4 = dr[5].ToString();//入网时间

                                            modelPhoneImport.Expandfield2 = dr[1].ToString();//营业部                                       
                                         
                                            modelPhoneImport.F_Phone = dr[2].ToString();//号码
                                            modelPhoneImport.Expandfield3 = dr[3].ToString();//宽带账号
                                            modelPhoneImport.ExpandVchField12 = dr[4].ToString();//地址
                                            modelPhoneImport.Expandfield4 = dr[5].ToString();//入网时间


                                            //  modelPhoneImport.ExpandVchField3 = dr[3].ToString();//dizhi



                                            // modelPhoneImport.ExpandVchField4 = dr[5].ToString();//入网时间

                                            modelPhoneImport.ExpandVchField5= dr[6].ToString(); //入网渠道
                                            modelPhoneImport.ExpandVchField6 = dr[7].ToString();   //营服
                                            modelPhoneImport.ExpandVchField7 = dr[8].ToString(); //套餐
                                            modelPhoneImport.ExpandVchField8 = dr[9].ToString();  //是否融合
                                            modelPhoneImport.ExpandVchField9 = dr[10].ToString();  //状态
                                           // modelPhoneImport.F_CusName = dr[0].ToString();//客户名称

                                         

                                         


                                            #endregion

                                            //#region 查重
                                            //string strwhere = " F_TaskId='" + taskid + "' and F_Phone='" + modelPhoneImport.F_Phone + "' and F_DeleteFlag=0";
                                            //DataSet ds = bll.GetList(strwhere);
                                            //if (ds != null && ds.Tables.Count > 0)
                                            //{
                                            //    if (ds.Tables[0].Rows.Count > 0)
                                            //    {
                                            //        continue;
                                            //    }
                                            //}
                                            //#endregion

                                            int rmw = otnBLL.Add(modelPhoneImport);
                                            if (rmw > 0)
                                            {
                                                count += 1;//导入成功，+1
                                            }
                                        }

                                    }
                                    dtres = dtInputData;

                                }
                                else
                                {
                                    errres += "该文档的内容为空";
                                }
                            }
                            catch (Exception ex)
                            {
                                if (coon.State == ConnectionState.Open)
                                {
                                    coon.Close();
                                }
                                i++;
                                errres += i.ToString() + ".导入出现异常，共导入" + count + "条数据，请从第" + (count + 2).ToString() + "行开始导入;\n";
                                if (strBuilder.Length > 0)
                                {
                                    errres += "重复的号码为：" + strBuilder.ToString() + "\n";
                                }
                            }
                            finally
                            {
                                if (coon.State == ConnectionState.Open)
                                {
                                    coon.Close();
                                }
                            }


                        }//****************using*********

                        #endregion

                    }
                    else
                    {
                        i++;
                        errres += i.ToString() + ".Excel中无数据;\n";
                    }

                }
                catch
                {
                    i++;
                    errres += i.ToString() + ".导入出现异常，导入失败;\n";
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }

            }
            catch
            {
                errres += i.ToString() + ".Excel格式不正确，系统错误，导入失败;\n";
            }

            #endregion
            if (errres != "")
            {
                return Error("导入失败！错误信息：" + errres);
            }
            else
            {
                string info = "本文件有" + rcount.ToString() + "行" + ccount.ToString() + "列数据";
                return Success("导入成功！" + info, vfileid);
            }
        }
        #region 上传文件
        private string uploadexcel()
        {
            string Excelsource = "";
            try
            {
                //HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                HttpPostedFile _upfile = RequestString.GetFile("upFile");
                if (_upfile != null)
                {
                    string imgPath = "";

                    string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
                    newFileName = newFileName + "_" + _upfile.FileName;
                    if (!Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData")))
                    {
                        Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData"));
                    }

                    imgPath = this.Request.ApplicationPath + "/ExcelData/" + newFileName.ToString();
                    string PhysicalPath = Server.MapPath(imgPath);
                    _upfile.SaveAs(PhysicalPath);

                    Excelsource = Server.MapPath(this.Request.ApplicationPath + "\\ExcelData\\") + newFileName.ToString();

                    Model.T_Vis_Files filesmodel = new Model.T_Vis_Files();
                    filesmodel.F_FileNewName = newFileName;
                    filesmodel.F_FileOldName = _upfile.FileName;
                    filesmodel.F_FilePath = Excelsource;
                    filesmodel.F_FileType = 0;
                    filesmodel.F_TypeGroup = 0;
                    filesmodel.F_FileFix = _upfile.FileName.Substring(_upfile.FileName.LastIndexOf('.') + 1);
                    filesmodel.F_InputDate = DateTime.Now;
                    filesmodel.F_InputUserCode = CurrentUser.UserData.F_UserCode;
                    filesmodel.F_InputUserID = CurrentUser.UserData.F_UserId;

                    vfileid = new BLL.T_Vis_Files().Add(filesmodel);
                }
            }
            catch (Exception ex) { }
            return Excelsource;
        }


        public ActionResult DeleteNoCall(int taskid=0)
        {
            if (taskid == 0)
            {
                return Error("taskid不能等于0");
            }

            string sql = " delete from T_Call_OutTaskTelNum where F_HJJGName is null and F_TaskId='"+taskid+"'";
            int n = DbHelperSQL.ExecuteSql(sql);
            LogFactory.GetLogger("DeleteNoCall").Warn("人工外呼 ，taskid=" + taskid + ",删除没有呼叫的电话,操作人：" + CurrentUser.UserData.F_UserCode);
            return Success("删除没有呼叫的电话");

        }

        //导入后获取
        public ActionResult GetList(int? fileid, int? taskid)
        {
                string sql = " and F_DeleteFlag=0 and F_FPState=0  ";
                DataTable dt = new DataTable();
                string userid = CurrentUser.UserData.F_UserId.ToString();
                if (userid.Trim() != "")
                {
                    sql += " and cast(ExpandVchField14 as varchar(max))='" + userid.Trim() + "' ";
                }
                if (fileid != null)
                {
                    sql += " and ExpandIntField6='" + fileid + "' ";
                }
                if (taskid != null)
                {
                    sql += " and F_TaskId=" + taskid;
                }
                //sql += " and F_InputDate=(select MAX(F_InputDate)from T_Vis_Telphone)";
                string strpageindex = RequestString.GetQueryString("page");
                int pageindex = 1;
                string strpagesize = RequestString.GetQueryString("pagesize");
                int pagesize = 10;
                if (strpageindex.Trim() != "")
                {
                    pageindex = Convert.ToInt32(strpageindex);
                }

                if (strpagesize.Trim() != "")
                {
                    pagesize = Convert.ToInt32(strpagesize);
                }
                int recordCount = 0;

                dt = BLL.PagerBLL.GetListPager(
                    "T_Call_OutTaskTelNum",
                    "F_Id",
                    "*",
                    " " + sql,
                    "ORDER BY F_Id desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

                var obj = new
                {
                    rows = dt,
                    total = recordCount
                };

            return Content(obj.ToJson());
        }

        //删除号码
        public ActionResult DeleteTels(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                if (otnBLL.DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                    return Error("删除失败");
            }
            else
            {
                return Error("请选择要删除的记录");
            }
            return Error("删除号码失败,操作人：" + CurrentUser.UserData.F_UserCode);
        }

        #endregion

        #region 读取Excel文件,返一个DataTable
        private DataSet ReadEcxel(string FileName, int Rows)
        {
            return ToDataTable(FileName);
        }

        /// <summary>
        /// 读取Excel文件到DataSet中
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        private DataSet ToDataTable(string filePath)
        {
            DataSet ds = new DataSet();
            DataTable dt = null;

            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                NPOI.SS.UserModel.IWorkbook book = null;
                if (filePath.IndexOf(".xlsx") > 0) // 2007版本
                    book = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
                else if (filePath.IndexOf(".xls") > 0) // 2003版本
                    book = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
                //NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);

                NPOI.SS.UserModel.ISheet sheet = book.GetSheetAt(0);


                NPOI.SS.UserModel.IRow row = sheet.GetRow(0);


                int firstCellNum = row.FirstCellNum;
                int lastCellNum = row.LastCellNum;
                //if (firstCellNum == lastCellNum) continue;

                dt = new DataTable(sheet.SheetName);
                //for (int i = firstCellNum; i < lastCellNum; i++)
                for (int i = firstCellNum; i < 12; i++)
                {
                    if (row.GetCell(i) != null)
                    {
                        dt.Columns.Add(row.GetCell(i).ToString() + i.ToString(), typeof(string));
                    }
                    else
                    {
                        dt.Columns.Add(i.ToString(), typeof(string));
                    }
                }

                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    if (sheet.GetRow(i).GetCell(1) != null && sheet.GetRow(i).GetCell(1).ToString() != "")
                    {
                        DataRow newRow = dt.Rows.Add();
                        for (int j = firstCellNum; j < 12; j++)
                        {
                            if (sheet.GetRow(i).GetCell(j) != null)
                            {
                                newRow[j] = sheet.GetRow(i).GetCell(j).ToString();
                            }
                            else
                            {
                                newRow[j] = "";
                            }
                        }
                    }
                }

                ds.Tables.Add(dt);
            }
            catch (Exception ex)
            {
                //SysLog.WriteLog(ex);
            }
            return ds;
        }
        #endregion
        #endregion

        #region 分配
        public ActionResult fpdata(string fpvalue, string[] arruser, string key,string yingyebu)
        {
            if (arruser.Length <= 0)
                return Error("请选择分配坐席");
            string fptype = "0";
            StringBuilder sb = new StringBuilder();

            sb.Append(" and F_FPState=0 and F_DeleteFlag=0 ");
            var sql = "";
            //if (!string.IsNullOrWhiteSpace(key))
            //{
            //    sql += " and F_Phone='" + key + "' or  F_TaskName like '%" + key + "%' or F_TaskRemark like '%" + key + "%'";
            //}

            if (!string.IsNullOrWhiteSpace(key))
            {
                sql += " and F_Phone='" + key + "'";
            }
            if (!string.IsNullOrWhiteSpace(yingyebu))
            {
                sql += " and Expandfield2='" + yingyebu + "'";
            }

            sb.Append(" and F_Taskid in (select F_TaskID from T_Call_OutTask where  F_IsStart=1 and F_DeleteFlag=0 " + sql + " ) ");
            #region 20180612 zhengbingbing 需要调整部分语句必须执行
            //if (!string.IsNullOrWhiteSpace(key))
            //{
            //    sb.Append(" and F_Taskid in (select F_TaskID from T_Call_OutTask where F_TaskName like '%" + key + "%' or F_TaskRemark like '%" + key + "%' and F_IsStart=1 and F_DeleteFlag=0 ) ");
            //}
            #endregion
            int userid = CurrentUser.UserData.F_UserId;
            string username = CurrentUser.UserData.F_UserName;
            #region 按数量平均分配
            DataTable dt = DbHelperSQL.Query("select *,NEWID() from T_Call_OutTaskTelNum where 1=1 " + sb.ToString() + "  order by NEWID()").Tables[0];
            //otnBLL.GetList(" F_FPState=0 ").Tables[0];
            List<Model.T_Sys_UserAccount> userlist = new BLL.T_Sys_UserAccount().GetModelList(" F_SeatFlag=1 ");
            if (dt != null)
            {
                int count = dt.Rows.Count;
                int cqcount = 0;
                if (fptype.Trim() == "0")
                {
                    //按数量平均分配
                    cqcount = Convert.ToInt32(fpvalue.Trim());
                }
                int successcount = 0;
                if (cqcount > 0)
                {
                    int m = 0;
                    int n = 0;
                    for (int i = 0; i < count; i++)
                    {
                        #region 更新分配数据
                        //更新
                        if (m < cqcount)
                        {
                            if (n < arruser.Length)
                            {
                                Model.T_Sys_UserAccount usermodel = userlist.Where(u => u.F_UserCode == arruser[n].ToString()).FirstOrDefault();
                                bool b = otnBLL.UpdateFP(dt.Rows[i]["F_Id"].ToString(), 1, usermodel.F_UserId.ToString(), usermodel.F_UserName);
                                if (b)
                                {
                                    successcount++;
                                }
                            }
                            m++;
                        }
                        else
                        {
                            n++;
                            m = 0;
                            i--;
                        }
                        #endregion
                    }
                }
                return Success("成功分配外呼计划任务" + successcount.ToString() + "条数据" + ",操作人：" + CurrentUser.UserData.F_UserCode);
            }
            #endregion
            return Error("分配外呼计划任务失败" + ",操作人：" + CurrentUser.UserData.F_UserCode);
        }
        //未分配列表 
        public ActionResult GetTaskWPF(string key,string yingyebu, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(" and F_FPState=0 and F_DeleteFlag=0 ");

            var sql = "";
            //if (!string.IsNullOrWhiteSpace(key))
            //{
            //    sql += " and F_Phone like '%" + key + "%' or  F_TaskName like '%" + key + "%' or F_TaskRemark like '%" + key + "%'";
            //}

            if (!string.IsNullOrWhiteSpace(key))
            {
                sql += " and F_Phone= '" + key + "' ";
            }

            if (!string.IsNullOrWhiteSpace(yingyebu))
            {
                sql += " and Expandfield2 ='"+ yingyebu + "'";
            }

            sb.Append(" and F_Taskid in (select F_TaskID from T_Call_OutTask where  F_IsStart=1 and F_DeleteFlag=0 "+sql+" ) ");

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Call_OutTaskTelNum",
                    "F_Id",
                    "*",
                     sb.ToString(),
                    "ORDER BY F_Id desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        //获取坐席列表
        public ActionResult GetSeatList(int pagesize = 10, int pageindex = 1)
        {
            DataTable dt = new DataTable();
            string sql = " ";
            sql = " and f_seatflag=1 ";
            int roleid = CurrentUser.UserData.F_RoleId;
            int deptid = CurrentUser.UserData.F_DeptId;
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                                    "T_Sys_UserAccount",
                                    "F_UserId",
                                    "*",
                                    sql,
                                    "ORDER BY F_UserId desc",
                                    pagesize,
                                    pageindex,
                                    true,
                                    out recordCount);
            #region 条件调整
            string sqlc = "";
            // sqlc += "  and isnull(F_HJJGName,'') not in ('正常接通','停机','空号','正常接通-不满意','不在本地居住') ";
            sqlc += "  and F_HJJGName is null ";
            sqlc += "and F_TaskID in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0) ";
            DataTable dtCount = otnBLL.GetList(" F_DeleteFlag=0 " + sqlc).Tables[0];
            //20180607 zhengbingbing
            //DataTable dtCount = otnBLL.GetList(" F_DeleteFlag=0 and isnull(F_HJJGName,'')!='正常接通' and isnull(F_YHFKName,'')!='已同意' and F_TaskID in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0) ").Tables[0];//new BLL.T_Vis_TelAllot().GetList(" F_state=1 and F_HFTelID in (select F_TelID from T_Vis_Telphone where  F_ISAllot=1 and F_ISCallRes=0 ) ").Tables[0];
            #endregion
            List<Model.UserAccount> modelList = new BLL.UserAccount().DataTableToList(dt);

            var obj = new
            {
                rows = modelList.Select(x => new
                {
                    UserCode = x.F_UserCode,
                    UserName = x.F_UserName,
                    Deparment = x.F_DeptName,
                    WWCCount = dtCount.Select(" F_UserId=" + x.F_UserId).Count()
                }),
                total = recordCount
            };

            return Content(obj.ToJson());
        }
        #endregion

        #region
        //获取任务
        public ActionResult GetTaskTelModel(int id = 0)
        {
            if (id <= 0)
                return Error("参数不正确");
            var model = otnBLL.GetModel(id);
            var paperid = 0;
            var taskmodel = new CallPlanNewDto();
            if (model != null)
            {
                
                #region 绑定任务和客户信息
                if (model.F_CusID != null)
                {
                    var cusmodel = cusBLL.GetModel(model.F_CusID.Value);
                    if (cusmodel != null)
                    {
                        taskmodel.F_CusID = model.F_CusID.Value;//客户id                
                        taskmodel.F_CityID = cusmodel.F_CityID.Value;//乡镇id 
                        taskmodel.F_Address = cusmodel.F_Address;//住址
                        taskmodel.F_CusName = cusmodel.F_CustomerName;//客户姓名                
                        taskmodel.F_Phone = cusmodel.F_Telephone;//号码                
                        taskmodel.F_Telephone = cusmodel.F_Mobile;//手机号码        
                        taskmodel.F_City = cusmodel.F_City;//乡镇   

                        taskmodel.F_ordernature = model.ExpandVchField1;
                        taskmodel.F_broadbandaccount = model.Expandfield3;

                        taskmodel.F_accesstime = model.Expandfield4;
                        taskmodel.F_channel = model.ExpandVchField5;


                        taskmodel.F_service = model.ExpandVchField6;
                        taskmodel.F_packaget = model.ExpandVchField7;

                        taskmodel.F_fusion = model.ExpandVchField8;                     

                        taskmodel.F_status = model.ExpandVchField9;
                        

                        //用户分类、电话号码、宽带账号、地址、入网时间、入网渠道、营服、套餐、是否融合、状态

 



                    }
                }
                taskmodel.F_Id = model.F_Id;//号码id
                taskmodel.F_TaskId = model.F_TaskId.Value;//任务id
                taskmodel.F_HJJGId = model.F_HJJGId != null ? model.F_HJJGId.Value : 0;//呼叫结果id

                taskmodel.F_ordernature = model.ExpandVchField1;
                taskmodel.F_broadbandaccount = model.Expandfield3;

                taskmodel.F_accesstime = model.Expandfield4;
                taskmodel.F_channel = model.ExpandVchField5;

             
                taskmodel.F_service = model.ExpandVchField6;
                taskmodel.F_packaget = model.ExpandVchField7;

                taskmodel.F_fusion = model.ExpandVchField8;

                taskmodel.F_status = model.ExpandVchField9;



                if (!string.IsNullOrWhiteSpace(model.F_CusName))
                    taskmodel.F_CusName = model.F_CusName;//客户姓名
                if (!string.IsNullOrWhiteSpace(model.F_Phone))
                    taskmodel.F_Phone = model.F_Phone;//号码
                if (!string.IsNullOrWhiteSpace(model.ExpandVchField12))
                    taskmodel.F_Address = model.ExpandVchField12;//住址
                #endregion
                var tmodel = otBLL.GetModel(model.F_TaskId.Value);
                if (tmodel != null)
                {
                    paperid = tmodel.F_PagerID.Value;

                    taskmodel.F_TaskName = tmodel.F_TaskName;//任务名称                
                    taskmodel.F_TaskRemark = tmodel.F_TaskRemark;//任务备注 
                }
            }

            if (model == null)
                return Error("当前数据不存在");

            var obj = new
            {
                taskModel = taskmodel,
                paperid = paperid
            };
            return Success("获取成功", obj);
        }

        //获取未接通 拒回访的任务列表
        public ActionResult GetRedialMyTaskList(string key, string sdate, string edate, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();
            int userid = CurrentUser.UserData.F_UserId;

            sb.Append(" and ExpandDatField1>'2024-05-29 00:00:00'");
            #region 条件查询
            if (!string.IsNullOrWhiteSpace(sdate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0");
            sb.Append(" and F_UserId=" + userid);
            sb.Append(" and F_DeleteFlag=0 ");
            #region 息县特殊要求
            //20180522 zhengbingbing
            //正常接通，停机，空号，正常接通-不满意，不在本地居住  均不显示在我的任务
            //sb.Append(" and isnull(F_HJJGName,'')!='正常接通' and isnull(F_YHFKName,'')!='已同意'");
            //sb.Append(" and isnull(F_HJJGName,'')=''");
            //   sb.Append(" and isnull(F_HJJGName,'') not in ('正常接通','停机','空号','正常接通-不满意','不在本地居住')");

            sb.Append(" and isnull(F_HJJGName,'')   in ('未接通','拒回访')");
            #endregion
            sb.Append(" and F_Taskid in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0)");
            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and F_Phone like '%" + key.Trim() + "%'");
            }
            //string sqlwhere = "";
            //if (!string.IsNullOrWhiteSpace(key))
            //{
            //    sqlwhere = " and F_TaskName like '%" + key + "%' or F_TaskRemark like '%" + key + "%' ";
            //}
            //sb.Append(" and F_TaskID in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0 " + sqlwhere + ") ");
            #endregion
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Call_OutTaskTelNum",
                    "F_Id",
                    "*",
                    sb.ToString(),
                    "ORDER BY ExpandDatField1 asc",//ExpandDatField1 asc 调查时间正序  
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

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




        //获取我的任务列表
        public ActionResult GetMyTaskList(string key, string sdate, string edate, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();
            int userid = CurrentUser.UserData.F_UserId;
            #region 条件查询
            if (!string.IsNullOrWhiteSpace(sdate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0");
            sb.Append(" and F_UserId=" + userid);
            sb.Append(" and F_DeleteFlag=0 ");
            #region 息县特殊要求
            //20180522 zhengbingbing
            //正常接通，停机，空号，正常接通-不满意，不在本地居住  均不显示在我的任务
            //sb.Append(" and isnull(F_HJJGName,'')!='正常接通' and isnull(F_YHFKName,'')!='已同意'");
            //sb.Append(" and isnull(F_HJJGName,'')=''");
            //   sb.Append(" and isnull(F_HJJGName,'') not in ('正常接通','停机','空号','正常接通-不满意','不在本地居住')");

            sb.Append(" and F_HJJGName is null");
            #endregion
            sb.Append(" and F_Taskid in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0)");
            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and F_Phone like '%" + key.Trim() + "%'");
            }
            //string sqlwhere = "";
            //if (!string.IsNullOrWhiteSpace(key))
            //{
            //    sqlwhere = " and F_TaskName like '%" + key + "%' or F_TaskRemark like '%" + key + "%' ";
            //}
            //sb.Append(" and F_TaskID in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0 " + sqlwhere + ") ");
            #endregion
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Call_OutTaskTelNum",
                    "F_Id",
                    "*",
                    sb.ToString(),
                    "ORDER BY ExpandDatField1 asc,F_Id desc",//ExpandDatField1 asc 调查时间正序 id倒序
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

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

        //导出我的任务
        public ActionResult ExportGetMyTaskList(string key, string sdate, string edate )
        {
            StringBuilder sb = new StringBuilder();
            int userid = CurrentUser.UserData.F_UserId;
            sb.Append(" 1=1");
            #region 条件查询
            if (!string.IsNullOrWhiteSpace(sdate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0");
            sb.Append(" and F_UserId=" + userid);
            sb.Append(" and F_DeleteFlag=0 ");     
            sb.Append(" and F_HJJGName is null");
    
            sb.Append(" and F_Taskid in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0)");
            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and F_Phone like '%" + key.Trim() + "%'");
            }       
            #endregion
          

            DataTable dt = new DataTable();
        dt=  DbHelperSQL.Query(" select Expandfield2,F_Phone,F_UserName,isnull(F_HJJGName,''), ExpandDatField1  from T_Call_OutTaskTelNum where " + sb.ToString()+ "  ORDER BY ExpandDatField1 asc,F_Id desc").Tables[0];

            NPOIHelper npoi = new NPOIHelper();
            if (npoi.ExportToExcel("我的任务", dt, col3()) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
            }

          
        }

        //导出我的wejieting任务
        public ActionResult ExportGetRedialMyTaskList(string key, string sdate, string edate)
        {
            StringBuilder sb = new StringBuilder();
            int userid = CurrentUser.UserData.F_UserId;
            sb.Append(" 1=1");
            sb.Append(" and ExpandDatField1>'2024-05-29 00:00:00'");
            #region 条件查询
            if (!string.IsNullOrWhiteSpace(sdate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0");
            sb.Append(" and F_UserId=" + userid);
            sb.Append(" and F_DeleteFlag=0 ");
            sb.Append(" and isnull(F_HJJGName,'')   in ('未接通','拒回访')");

            sb.Append(" and F_Taskid in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0)");
            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and F_Phone like '%" + key.Trim() + "%'");
            }
            #endregion


            DataTable dt = new DataTable();
            dt = DbHelperSQL.Query(" select Expandfield2,F_Phone,F_UserName,isnull(F_HJJGName,''), ExpandDatField1  from T_Call_OutTaskTelNum where " + sb.ToString() + "  ORDER BY ExpandDatField1 asc ").Tables[0];

            NPOIHelper npoi = new NPOIHelper();
            if (npoi.ExportToExcel("我的未接通任务", dt, col3()) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }


        }





        //获取我的任务结果
        public ActionResult GetMyResultList(string key, string sdate, string edate, int hjjgid = 0, int yhfkid = 0, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();
            int userid = CurrentUser.UserData.F_UserId;
            #region 条件查询
            sb.Append(" and F_UserId=" + userid);
            sb.Append(" and F_DeleteFlag=0 ");            
            if (!string.IsNullOrWhiteSpace(sdate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0");
            if (hjjgid != 0)
            {
                sb.Append(" and F_HJJGId=" + hjjgid);
            }
            else
            {
                sb.Append(" and isnull(F_HJJGId,'')!=''");
            }
            //if (yhfkid != 0)
            //{
            //    sb.Append(" and F_YHFKId=" + yhfkid);
            //}
            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and F_Phone like '%" + key.Trim() + "%'");
            }
            //string sqlwhere = "";
            //if (!string.IsNullOrWhiteSpace(key))
            //{
            //    sqlwhere = " and F_TaskName like '%" + key + "%' or F_TaskRemark like '%" + key + "%' ";
            //}
            //sb.Append(" and F_TaskID in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0 " + sqlwhere + ") ");
            #endregion
            var recordCount = 0;
            string tablenew = "( select a.*, b.F_typeValue1,b.F_typeValue2,b.F_typeValue3,b.F_typeValue4,b.F_typeValue5,b.F_typeValue6 from T_Call_OutTaskTelNum a left join T_TypeResult b on a.F_id=b.F_phoneid) as t";

            var dt = BLL.PagerBLL.GetListPager(
                    //"T_Call_OutTaskTelNum",
                    tablenew,
                    "F_Id",
                    "*",
                    sb.ToString(),
                    "ORDER BY ExpandDatField1 desc,F_Id desc",//ExpandDatField1 调查时间倒序，id倒序
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

            //dt.Columns.Add("type1");
            //dt.Columns.Add("type2");
            //dt.Columns.Add("type3");
            //dt.Columns.Add("type4");
            //dt.Columns.Add("type5");
            //dt.Columns.Add("type6");
            #region 判断是否已存在工单 ；再判断 如果问题里包括那六大类的问题，给分数赋值
            foreach (DataRow item in dt.Rows)
            {
                string wjid = item["F_Id"].ToString();
                int c=new BLL.T_Wo_WorkOrder().GetRecordCount(" isnull(WjID,'')='"+wjid+"'");
                if (c > 0)
                {
                    item["ExpandSintField1"] = 1;
                }
                else
                    item["ExpandSintField1"] = 0;

                ////如果问题里包括那六大类的问题，给分数赋值
                ////移网上网质量;移网通话质量；光网网络质量;装维服务;营业厅服务；套餐资费
             

                //int F_TaskId = Convert.ToInt32(item["F_TaskId"].ToString());
                
                //var model = otnBLL.GetModel(Convert.ToInt32(wjid));

                //if(model!=null)
                //{
                //  int cusid=  model.F_CusID.Value;

                //string sql1 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId+" and F_CusID = "+ cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '移网上网质量')   and F_SortModel = 0)";

                //item["type1"] = DbHelperSQL.GetSingle(sql1);
                //string sql2 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '移网通话质量')   and F_SortModel = 0)";

                //item["type2"] = DbHelperSQL.GetSingle(sql2);

                //string sql3 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '光网网络质量')   and F_SortModel = 0)";

                //item["type3"] = DbHelperSQL.GetSingle(sql3);
                //string sql4 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '装维服务')   and F_SortModel = 0)";

                //item["type4"] = DbHelperSQL.GetSingle(sql4);

                //string sql5 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '营业厅服务')   and F_SortModel = 0)";

                //item["type5"] = DbHelperSQL.GetSingle(sql5);
                //string sql6 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '套餐资费')   and F_SortModel = 0)";

                //item["type6"] = DbHelperSQL.GetSingle(sql6);

                //}




            }
            #endregion





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

        [Authorize]
        public ActionResult ExportGetMyResultList(string key, string sdate, string edate, int hjjgid = 0)
        {
            StringBuilder sb = new StringBuilder();
            int userid = CurrentUser.UserData.F_UserId;
            #region 条件查询
            sb.Append("  a. F_UserId=" + userid);
            sb.Append(" and F_DeleteFlag=0 ");
            if (!string.IsNullOrWhiteSpace(sdate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0");
            if (hjjgid != 0)
            {
                sb.Append(" and F_HJJGId=" + hjjgid);
            }
            else
            {
                sb.Append(" and isnull(F_HJJGId,'')!=''");
            }
          
            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and F_Phone like '%" + key.Trim() + "%'");
            }

            #endregion
            #region
            //modelPhoneImport.ExpandVchField1 = dr[0].ToString();//目标分类
            //modelPhoneImport.ExpandVchField2 = dr[1].ToString();//营业部
            //modelPhoneImport.F_Phone = dr[2].ToString();//号码
            //modelPhoneImport.ExpandVchField3 = dr[3].ToString();//宽带账号

            //modelPhoneImport.ExpandVchField12 = dr[4].ToString();//地址

            //modelPhoneImport.ExpandVchField4 = dr[5].ToString();//入网时间

            //modelPhoneImport.ExpandVchField5 = dr[6].ToString(); //入网渠道
            //modelPhoneImport.ExpandVchField6 = dr[7].ToString();   //营服
            //modelPhoneImport.ExpandVchField7 = dr[8].ToString(); //套餐
            //modelPhoneImport.ExpandVchField8 = dr[9].ToString();  //是否融合
            //modelPhoneImport.ExpandVchField9 = dr[10].ToString();  //状态
            #endregion
            string sql = " select  ExpandVchField1,Expandfield2,F_Phone,b.F_typeValue1,b.F_typeValue2,b.F_typeValue3,b.F_typeValue4,b.F_typeValue5,b.F_typeValue6, F_UserName,F_HJJGName,ExpandDatField1 from  T_Call_OutTaskTelNum a left join T_TypeResult b on a.F_id=b.F_phoneid  where " + sb.ToString() + " ORDER BY ExpandDatField1 desc,a.F_Id desc";

            DataTable dt = DbHelperSQL.Query(sql).Tables[0];
            #region
            //dt.Columns.Add("type1");
            //dt.Columns.Add("type2");
            //dt.Columns.Add("type3");
            //dt.Columns.Add("type4");
            //dt.Columns.Add("type5");
            //dt.Columns.Add("type6");
            //#region 判断是否已存在工单 ；再判断 如果问题里包括那六大类的问题，给分数赋值
            //foreach (DataRow item in dt.Rows)
            //{
            //    string wjid = item["F_Id"].ToString();

            //    //如果问题里包括那六大类的问题，给分数赋值
            //    //移网上网质量;移网通话质量；光网网络质量;装维服务;营业厅服务；套餐资费


            //    int F_TaskId = Convert.ToInt32(item["F_TaskId"].ToString());

            //    var model = otnBLL.GetModel(Convert.ToInt32(wjid));

            //    if (model != null)
            //    {
            //        int cusid = model.F_CusID.Value;

            //        string sql1 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '移网上网质量')   and F_SortModel = 0)";

            //        item["type1"] = DbHelperSQL.GetSingle(sql1);
            //        string sql2 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '移网通话质量')   and F_SortModel = 0)";

            //        item["type2"] = DbHelperSQL.GetSingle(sql2);

            //        string sql3 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '光网网络质量')   and F_SortModel = 0)";

            //        item["type3"] = DbHelperSQL.GetSingle(sql3);
            //        string sql4 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '装维服务')   and F_SortModel = 0)";

            //        item["type4"] = DbHelperSQL.GetSingle(sql4);

            //        string sql5 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '营业厅服务')   and F_SortModel = 0)";

            //        item["type5"] = DbHelperSQL.GetSingle(sql5);
            //        string sql6 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '套餐资费')   and F_SortModel = 0)";

            //        item["type6"] = DbHelperSQL.GetSingle(sql6);
            //    }

            //}
            //#endregion
#endregion


            NPOIHelper npoi = new NPOIHelper();
            if (npoi.ExportToExcel("我的任务结果数据", dt, col()) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }



            
        }
        private string[] col()
        {
            string[] ccc = {
                //用户分类、营业部、电话号码、【移网质量、渠道服务、光网质量、装维服务、套餐资费】（五大类所对应的分值）、分配坐席、呼叫结果、调查时间
                   "用户分类", "营业部","电话号码","移网上网质量","移网通话质量","光网网络质量"," 装维服务"," 营业厅服务","套餐资费", "分配坐席","呼叫结果","调查时间"
            };
            return ccc;
        }

        private string[] col2()
        {
            string[] ccc = {
                //用户分类、营业部、电话号码、【移网质量、渠道服务、光网质量、装维服务、套餐资费】（五大类所对应的分值）、分配坐席、呼叫结果、调查时间
                 "是否创建工单", "用户分类", "营业部","电话号码","移网上网质量","移网通话质量","光网网络质量"," 装维服务"," 营业厅服务","套餐资费", "分配坐席","呼叫结果","调查时间"
            };
            return ccc;
        }

        private string[] col3()
        {
            string[] ccc3 = {
                //用户分类、营业部、电话号码、【移网质量、渠道服务、光网质量、装维服务、套餐资费】（五大类所对应的分值）、分配坐席、呼叫结果、调查时间
                   "营业部","电话号码","分配坐席","呼叫结果","调查时间" 
            };
            return ccc3;
        }

        //获取总体任务结果
        public ActionResult GetResultList(string key, string sdate, string edate,string existworkorder, int taskid=0, int userid = 0, int hjjgid = 0, int yhfkid = 0, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();
            #region 条件查询
            sb.Append(" and F_DeleteFlag=0 ");
            if (!string.IsNullOrWhiteSpace(sdate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0");
            if (userid != 0)
            {
                sb.Append(" and F_UserId=" + userid);
            }
            if (hjjgid != 0)
            {
                sb.Append(" and F_HJJGId=" + hjjgid);
            }

            if (taskid!=0)
            {
                sb.Append(" and F_TaskId=" + taskid);
            }

            else
            {
                sb.Append(" and isnull(F_HJJGId,'')!=''");
            }
            //if (yhfkid != 0)
            //{
            //    sb.Append(" and F_YHFKId=" + yhfkid);
            //}
            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and F_Phone like '%" + key.Trim() + "%'");
            }

            if (!string.IsNullOrWhiteSpace(existworkorder))
            {
                sb.Append("  and (case  when  (select count(1) from T_Wo_WorkOrder where isnull(WjID,'')=F_id ) >0 then 1 else 0 end) ='"+existworkorder+"'");
            }

            //string sqlwhere = "";
            //if (!string.IsNullOrWhiteSpace(key))
            //{
            //    sqlwhere = " and F_TaskName like '%" + key + "%' or F_TaskRemark like '%" + key + "%' ";
            //}
            //sb.Append(" and F_TaskID in (select F_TaskID from T_Call_OutTask where F_IsStart=1 and F_DeleteFlag=0 " + sqlwhere + ") ");
            #endregion
            string tablenew = "( select a.*, (case  when  (select count(1) from T_Wo_WorkOrder where isnull(WjID,'')=a.F_id ) >0 then 1 else 0 end) existworkorder, b.F_typeValue1,b.F_typeValue2,b.F_typeValue3,b.F_typeValue4,b.F_typeValue5,b.F_typeValue6 from T_Call_OutTaskTelNum a left join T_TypeResult b on a.F_id=b.F_phoneid) as t";
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    //"T_Call_OutTaskTelNum",
                    tablenew,
                    "F_Id",
                    "*",
                    sb.ToString(),
                    "ORDER BY ExpandDatField1 desc,F_Id desc",//ExpandDatField1 调查时间倒序，id倒序
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            #region 判断是否已存在工单
            //dt.Columns.Add("type1");
            //dt.Columns.Add("type2");
            //dt.Columns.Add("type3");
            //dt.Columns.Add("type4");
            //dt.Columns.Add("type5");
            //dt.Columns.Add("type6");
            #region 判断是否已存在工单 ；再判断 如果问题里包括那六大类的问题，给分数赋值
            //foreach (DataRow item in dt.Rows)
            //{
            //    string wjid = item["F_Id"].ToString();
            //    int c = new BLL.T_Wo_WorkOrder().GetRecordCount(" isnull(WjID,'')='" + wjid + "'");
            //    if (c > 0)
            //    {
            //        item["ExpandSintField1"] = 1;
            //    }
            //    else
            //        item["ExpandSintField1"] = 0;

                //如果问题里包括那六大类的问题，给分数赋值
                //移网上网质量;移网通话质量；光网网络质量;装维服务;营业厅服务；套餐资费


                //int F_TaskId = Convert.ToInt32(item["F_TaskId"].ToString());

                //var model = otnBLL.GetModel(Convert.ToInt32(wjid));

                //if (model != null)
                //{
                //    int cusid = model.F_CusID.Value;

                //    string sql1 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '移网上网质量')   and F_SortModel = 0)";

                //    item["type1"] = DbHelperSQL.GetSingle(sql1);
                //    string sql2 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '移网通话质量')   and F_SortModel = 0)";

                //    item["type2"] = DbHelperSQL.GetSingle(sql2);

                //    string sql3 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '光网网络质量')   and F_SortModel = 0)";

                //    item["type3"] = DbHelperSQL.GetSingle(sql3);
                //    string sql4 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '装维服务')   and F_SortModel = 0)";

                //    item["type4"] = DbHelperSQL.GetSingle(sql4);

                //    string sql5 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '营业厅服务')   and F_SortModel = 0)";

                //    item["type5"] = DbHelperSQL.GetSingle(sql5);
                //    string sql6 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '套餐资费')   and F_SortModel = 0)";

                //    item["type6"] = DbHelperSQL.GetSingle(sql6);

                //}




            //}
            #endregion

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

        //导出总体任务结果
        public ActionResult ExportGetResultList(string key,string existworkorder, string sdate, string edate, int userid = 0, int taskid = 0, int hjjgid = 0, int yhfkid = 0)
        {
            StringBuilder sb = new StringBuilder();
            #region 条件查询
            sb.Append("    F_DeleteFlag=0 ");
            if (!string.IsNullOrWhiteSpace(sdate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                sb.Append(" and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0");
            if (userid != 0)
            {
                sb.Append(" and  a.F_UserId=" + userid);
            }
            if (hjjgid != 0)
            {
                sb.Append(" and F_HJJGId=" + hjjgid);
            }
            else
            {
                sb.Append(" and isnull(F_HJJGId,'')!=''");
            }

            if (taskid != 0)
            {
                sb.Append(" and F_TaskId=" + taskid);
            }
            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and F_Phone like '%" + key.Trim() + "%'");
            }

            if (!string.IsNullOrWhiteSpace(existworkorder))
            {
                sb.Append(" and (case  when  (select count(1) from T_Wo_WorkOrder where isnull(WjID,'')=a.F_id ) >0 then 1 else 0 end) ='" + existworkorder + "'");
            }

            #endregion
            // string tablenew = "( select a.*, b.F_typeValue1,b.F_typeValue2,b.F_typeValue3,b.F_typeValue4,b.F_typeValue5,b.F_typeValue6 from T_Call_OutTaskTelNum a left join T_TypeResult b on a.F_id=b.F_phoneid) as t";
            string sql = " select (case  when  (select count(1) from T_Wo_WorkOrder where isnull(WjID,'')=a.F_id ) >0 then '是' else '否' end) existworkorder,a.F_id,ExpandVchField1 ,Expandfield2,F_Phone,b.F_typeValue1,b.F_typeValue2,b.F_typeValue3,b.F_typeValue4,b.F_typeValue5,b.F_typeValue6 , F_UserName,F_HJJGName,ExpandDatField1 from  T_Call_OutTaskTelNum  a left join T_TypeResult b on a.F_id=b.F_phoneid where " + sb.ToString() + " ORDER BY ExpandDatField1 desc,a.F_Id desc";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            #region 判断是否已存在工单
            //dt.Columns.Add("type1");
            //dt.Columns.Add("type2");
            //dt.Columns.Add("type3");
            //dt.Columns.Add("type4");
            //dt.Columns.Add("type5");
            //dt.Columns.Add("type6");
            #region 判断是否已存在工单 ；再判断 如果问题里包括那六大类的问题，给分数赋值

//             dt.Columns.Add("ExpandSintField1");
//            dt.Columns["ExpandSintField1"].SetOrdinal(0);
//            foreach (DataRow item in dt.Rows)
//            {
                 
//                string wjid = item["F_Id"].ToString();
//                int c = new BLL.T_Wo_WorkOrder().GetRecordCount(" isnull(WjID,'')='" + wjid + "'");
//                if (c > 0)
//                {
//                    item["ExpandSintField1"] = "是";
//                }
//                else
//                    item["ExpandSintField1"] = "否";

//                #region
//                //如果问题里包括那六大类的问题，给分数赋值
//                //移网上网质量;移网通话质量；光网网络质量;装维服务;营业厅服务；套餐资费            

//                //if (model != null)
//                //{
//                //    int cusid = model.F_CusID.Value;

//                //    string sql1 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '移网上网质量')   and F_SortModel = 0)";

//                //    item["type1"] = DbHelperSQL.GetSingle(sql1);
//                //    string sql2 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '移网通话质量')   and F_SortModel = 0)";

//                //    item["type2"] = DbHelperSQL.GetSingle(sql2);

//                //    string sql3 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '光网网络质量')   and F_SortModel = 0)";

//                //    item["type3"] = DbHelperSQL.GetSingle(sql3);
//                //    string sql4 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '装维服务')   and F_SortModel = 0)";

//                //    item["type4"] = DbHelperSQL.GetSingle(sql4);

//                //    string sql5 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '营业厅服务')   and F_SortModel = 0)";

//                //    item["type5"] = DbHelperSQL.GetSingle(sql5);
//                //    string sql6 = " SELECT F_Answer  FROM T_Call_OutAnswers where F_TaskID = " + F_TaskId + " and F_CusID = " + cusid + "   and F_QID in (select F_QuestionId from  T_Ask_Question where  F_CategoryId in   (select F_CategoryId from  T_Ask_QuestionCategory where F_CategoryName = '套餐资费')   and F_SortModel = 0)";

//                //    item["type6"] = DbHelperSQL.GetSingle(sql6);
//#endregion

//            }

                NPOIHelper npoi = new NPOIHelper();
            dt.Columns.Remove("F_Id");
            if (npoi.ExportToExcel("任务结果数据", dt, col2()) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }


            #endregion

            #endregion

        }




        //获取任务结果详情
        public ActionResult GetTaskTelInfo(int id = 0)
        {
            //id = 40582;
            if (id <= 0)
                return Error("参数不正确");
            var model = otnBLL.GetModel(id);

            var paperid = 0;
            if (model != null)
            {
                var taskmodel = new CallPlanNewDto();
                #region 绑定任务和客户信息
                if (model.F_CusID != null)
                {
                    var cusmodel = cusBLL.GetModel(model.F_CusID.Value);
                    if (cusmodel != null)
                    {
                        taskmodel.F_CusID = model.F_CusID.Value;//客户id                
                        taskmodel.F_CityID = cusmodel.F_CityID.Value;//乡镇id                
                        taskmodel.F_CusName = cusmodel.F_CustomerName;//客户姓名                
                        taskmodel.F_Phone = cusmodel.F_Telephone;//号码                
                        taskmodel.F_Telephone = cusmodel.F_Mobile;//手机号码        
                        taskmodel.F_City = cusmodel.F_City;//乡镇   
                        taskmodel.F_Address = cusmodel.F_Address;//住址
                    }
                }
                taskmodel.F_Id = model.F_Id;//号码id
                taskmodel.F_TaskId = model.F_TaskId.Value;//任务id
                taskmodel.F_HJJGId = model.F_HJJGId != null ? model.F_HJJGId.Value : 0;//呼叫结果id

                taskmodel.F_ordernature = model.ExpandVchField1;
                taskmodel.F_broadbandaccount = model.Expandfield3;

                taskmodel.F_accesstime = model.Expandfield4;
                taskmodel.F_channel = model.ExpandVchField5;


                taskmodel.F_service = model.ExpandVchField6;
                taskmodel.F_packaget = model.ExpandVchField7;

                taskmodel.F_fusion = model.ExpandVchField8;

                taskmodel.F_status = model.ExpandVchField9;




                //if (!string.IsNullOrWhiteSpace(model.F_CusName))
                //    taskmodel.F_CusName = model.F_CusName;//客户姓名
                //if (!string.IsNullOrWhiteSpace(model.F_Phone))
                //    taskmodel.F_Phone = model.F_Phone;//号码
                //if (!string.IsNullOrWhiteSpace(model.ExpandVchField12))
                //    taskmodel.F_Address = model.ExpandVchField12;//住址
                #endregion

                var anslist = ansBLL.GetModelList(" F_TaskID=" + model.F_TaskId.Value + " and F_CusTelID=" + id + " ");
                var tmodel = otBLL.GetModel(model.F_TaskId.Value);
                var qCategorylist = qcBLL.GetModelList("");
                if (tmodel != null)
                {
                    paperid = tmodel.F_PagerID.Value;
                    #region 获取问卷试题信息以及答案
                    var pmodel = pagerInfoBLL.GetModel(paperid);
                    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_StartText = pmodel.F_StartText,
                        F_EndText = pmodel.F_EndText,
                        F_Questions = qlist.Select(q =>
                        {
                            var answers = "";
                            var qalist = anslist.Where(al => al.F_QID.Value == q.F_QuestionId).ToList<Model.T_Call_OutAnswers>();
                            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,
                                sortmodel=q.F_SortModel,
                                quesanswers = answers.Trim('|'),
                                F_CategoryName = qCategorylist.Where(m => m.F_CategoryId == q.F_CategoryId).First().F_CategoryName,
                                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,
                                    };
                                })
                            };
                        })
                    };
                    #endregion

                    
                    taskmodel.F_TaskName = tmodel.F_TaskName;//任务名称                
                    taskmodel.F_TaskRemark = tmodel.F_TaskRemark;//任务备注                
                    
                    var objy = new
                    {
                        taskModel = taskmodel,
                        paperModel = newmodel
                    };
                    return Success("获取详情成功", objy);
                }
            }
            return Error("获取详情失败");
        }
        #endregion

        #region 问卷回答
        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskid">任务ID</param>
        /// <param name="custelid">客户电话ID</param>
        /// <param name="ans">答案，数组形式["15_20_单选选项内容","17_25|36|58_复选选项内容1|选项内容2|选项内容3","30_0_问答题"]</param>
        /// <param name="hjjgid">呼叫结果</param>
        /// <param name="telphone">电话号码</param>
        /// <param name="name">姓名</param>
        /// <param name="phone">固定号码</param>
        /// <param name="countryid">乡镇id</param>
        /// <param name="address">地址</param>
        /// <returns></returns>
        public ActionResult Answers(int taskid, int custelid, string[] ans, int hjjgid,
            string name, string phone, string callid, string address,
            string fenlei, string kuandai, string dizhi, string ruwangshijian, string qudao, string yingfu, string taocan, string ronghe, string zhuangtai,
            int countryid=0)
        {//
            int cc = 0; 

            if (custelid > 0)
            {

                 

                var otnModel = otnBLL.GetModel(custelid);
                if (otnModel != null)
                {
                                     

                    otnModel.ExpandVchField1 = fenlei;//目标分类                                         

                    otnModel.Expandfield3 = kuandai;//宽带账号
                    otnModel.ExpandVchField12 = dizhi;//地址
                    otnModel.Expandfield4 = ruwangshijian;//入网时间     

                    otnModel.ExpandVchField5 = qudao; //入网渠道
                    otnModel.ExpandVchField6 = yingfu;   //营服
                    otnModel.ExpandVchField7 = taocan; //套餐
                    otnModel.ExpandVchField8 = ronghe;  //是否融合
                    otnModel.ExpandVchField9 = zhuangtai;  //状态
                    otnBLL.Update(otnModel);



                    int cusid = saveCus(otnModel.F_Phone, name, phone, countryid, address, "", ruwangshijian, kuandai, qudao, ronghe);

                    #region 保存答案
                    var ansModel = new Model.T_Call_OutAnswers();
                    string askqids = "";
                    string ansids = "";
                    if (ans != null)
                    {
                        //先删除 后添加
                        ansBLL.DeleteByTelid(custelid, taskid);

                        ansModel.F_TaskID = taskid;
                        ansModel.F_CusTelID = custelid;//F_phoneid
                        ansModel.F_CusID = cusid;
                        ansModel.F_OptBy = CurrentUser.UserData.F_UserId;
                        ansModel.F_OptByName = CurrentUser.UserData.F_UserName;
                        ansModel.F_OptOn = DateTime.Now;
                        ansModel.F_Expand1 = countryid.ToString();
                        ansModel.F_Expand3 = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        #region 循环保存
                        foreach (var item in ans)
                        {
                            if (!string.IsNullOrEmpty(item)) { 

                            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++;
                            }
                            }
                        }
                        #endregion
                    }
                    #endregion
                    #region  保存日志
                    otnModel.F_HJJGId = hjjgid;
                    var hjconfig = new BLL.T_Sys_DictionaryValue().GetModel(hjjgid);
                    if (hjconfig != null)
                        otnModel.F_HJJGName = hjconfig.F_Name;
                    //otnModel.F_YHFKId = yhfkid;
                    //var fkconfig = new BLL.T_Sys_DictionaryValue().GetModel(yhfkid);
                    //if (fkconfig != null)
                    //    otnModel.F_YHFKName = fkconfig.F_Name;
                    otnModel.ExpandVchField2 = phone;
                    otnModel.ExpandVchField3 = address;
                    var fkconfig = new BLL.T_Sys_DictionaryValue().GetModel(countryid);
                    if (fkconfig != null)
                        otnModel.ExpandVchField4 = fkconfig.F_Name;
                    otnModel.ExpandIntField1 = countryid;//乡镇
                    otnModel.ExpandDatField1 = DateTime.Now;//调查时间
                    otnModel.F_AskRes = askqids;
                    otnModel.F_AskInfo = ansids;
                    otnModel.F_CusID = cusid;
                    otnModel.F_CusName = name;
                    otnModel.CallId = callid;
                   otnBLL.Update(otnModel);
                    planrecord(otnModel);
                    #endregion
                }
            }
            if (ans != null)
            {
                //if (cc == ans.Length)
                if(cc>0)
                {
                    return Success("问卷答案提交成功！taskid=" + taskid + ",custelid=" + custelid + ",操作人：" + CurrentUser.UserData.F_UserCode, custelid);
                }
                //else
                //{
                //    ansBLL.DeleteByTelid(custelid, taskid);
                //    return Error("问卷答案提交失败！taskid=" + taskid + ",custelid=" + custelid + ",操作人：" + CurrentUser.UserData.F_UserCode);
                //}
                else
                {
                    return Error("没有问卷答案提交");
                }
            }
            else
            {
                return Error("没有问卷答案提交");
            }

        }
        #endregion


        public ActionResult AddAnswers(int phoneid,string F_typeName1,string F_typeName2, string F_typeName3, string F_typeName4, string F_typeName5, string F_typeName6,string  value1, string value2, string value3, string value4, string value5, string value6, string F_TypeName7,string value7,
            string value12,string value22,string value32,string value42,string value52,string value62)
       
        {

            Model.T_TypeResult remodel = new Model.T_TypeResult();
            remodel.F_PhoneID = phoneid;
            remodel.F_typeName1 = F_typeName1;
            remodel.F_typeName2 = F_typeName2;
            remodel.F_typeName3 = F_typeName3;
            remodel.F_typeName4 = F_typeName4;
            remodel.F_typeName5 = F_typeName5;
            remodel.F_typeName6 = F_typeName6;

            remodel.F_typeName7 = F_TypeName7;

            remodel.F_typeValue1 = value1;
            remodel.F_typeValue2 = value2;
            remodel.F_typeValue3 = value3;
            remodel.F_typeValue4 = value4;
            remodel.F_typeValue5 = value5;
            remodel.F_typeValue6 = value6;
            remodel.F_typeValue7 = value7;

            remodel.F_typeValue12 = value12;
            remodel.F_typeValue22 = value22;
            remodel.F_typeValue32 = value32;
            remodel.F_typeValue42 = value42;

            remodel.F_typeValue52 = value52;
            remodel.F_typeValue62 = value62;



            remodel.F_userId = CurrentUser.UserData.F_UserId.ToString();

            BLL.T_TypeResult bll = new BLL.T_TypeResult();
            bll.Add(remodel);
            return Success("保存成功");

        }

        #region 客户档案
        /// <summary>
        /// 保存客户档案
        /// </summary>
        /// <param name="telphone"></param>
        /// <param name="name"></param>
        /// <param name="phone"></param>
        /// <param name="countryid"></param>
        /// <param name="address"></param>
        /// <returns></returns>
        private int saveCus(string telphone, string name, string phone,int countryid, string address, string F_SaleOffice, string F_AccessTime, string F_BroadbandAccount, string F_Channel, string F_Fusion)
        {
            //F_SaleOffice,F_AccessTime,F_BroadbandAccount,F_Channele,F_Fusion

            int res = 0;
            Model.T_Cus_CustomerBase cusmodel = new Model.T_Cus_CustomerBase();
            if (!string.IsNullOrWhiteSpace(telphone))
            {
                var fkconfig = new BLL.T_Sys_DictionaryValue().GetModel(countryid);
                
                cusmodel = cusBLL.GetModelByPhone(telphone);

                if (cusmodel != null)
                {
                    cusmodel.F_Address = address;
                    if (fkconfig != null)
                        cusmodel.F_City = fkconfig.F_Name;
                    cusmodel.F_CityID = countryid;
                    cusmodel.F_CustomerName = name;
                    cusmodel.F_Telephone = phone;
                    cusmodel.F_SaleOffice = F_SaleOffice;
                    cusmodel.F_AccessTime = F_AccessTime;
                    cusmodel.F_BroadbandAccount = F_BroadbandAccount;
                    cusmodel.F_Channel = F_Channel;
                    cusmodel.F_Fusion = F_Fusion;


                    cusBLL.Update(cusmodel);
                    res = cusmodel.F_CustomerId;
                }
                else
                {
                    cusmodel = new Model.T_Cus_CustomerBase();
                    cusmodel.F_Address = address;
                    if (fkconfig != null)
                        cusmodel.F_City = fkconfig.F_Name;
                    cusmodel.F_CityID = countryid;
                    cusmodel.F_CustomerName = name;
                    cusmodel.F_Telephone = phone;
                    cusmodel.F_Mobile = telphone;
                    cusmodel.F_SaleOffice = F_SaleOffice;
                    cusmodel.F_AccessTime = F_AccessTime;
                    cusmodel.F_BroadbandAccount = F_BroadbandAccount;
                    cusmodel.F_Channel = F_Channel;
                    cusmodel.F_Fusion = F_Fusion;

                    res = cusBLL.Add(cusmodel);

                }
            }
            return res;
        }

        #endregion

        #region 获取记录
        //获取外呼通话记录
        public ActionResult GetTelList(string type, string telid, string phone, string usercode)
        {
            string sql = "";
            DataTable dt = new DataTable();
            sql += " and TaskType='1'";
            if (telid != null && telid.Trim() != "")
            {
                sql += " and CallType=1 and TaskPhoneID='" + telid.Trim() + "' ";
            }
            if (phone != null && phone.Trim() != "")
            {
                sql += " and CallNumber like'%" + phone + "%'";
            }
            if (usercode != null && usercode.Trim() != "")
            {
                sql += " and UserCode='" + usercode + "'";
            }
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;

            dt = BLL.PagerBLL.GetListPager(
               "T_Call_CallRecords",
                "CallRecordsId",
                "*",
                sql,
                "ORDER BY CallRecordsId desc",
               pagesize,
               pageindex,
               true,
               out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }
        #endregion

        #region 记录日志
        private void planrecord(Model.T_Call_OutTaskTelNum tnModel)
        {
            Model.T_Call_OutTaskRecords trModel = new Model.T_Call_OutTaskRecords();
            trModel.F_AskInfo = tnModel.F_AskInfo;
            trModel.F_AskRes = tnModel.F_AskRes;
            trModel.F_CreateTime = tnModel.F_CreateTime;
            trModel.F_CusID = tnModel.F_CusID;
            trModel.F_CusName = tnModel.F_CusName;
            trModel.F_FPState = tnModel.F_FPState;
            trModel.F_HCState = tnModel.F_HCState;
            trModel.F_HJJGId = tnModel.F_HJJGId;
            trModel.F_HJJGName = tnModel.F_HJJGName;
            trModel.F_TelID = tnModel.F_Id;
            trModel.F_OptTime = DateTime.Now;
            trModel.F_OptUserCode = CurrentUser.UserData.F_UserCode;
            trModel.F_Phone = tnModel.F_Phone;
            trModel.F_PhoneBy = tnModel.F_PhoneBy;
            trModel.F_TaskId = tnModel.F_TaskId;
            trModel.F_UserId = tnModel.F_UserId;
            trModel.F_UserName = tnModel.F_UserName;
            trModel.F_YHFKId = tnModel.F_YHFKId;
            trModel.F_YHFKName = tnModel.F_YHFKName;
            trModel.F_YJState = tnModel.F_YJState;
            trModel.ExpandIntField1 = tnModel.ExpandIntField1;
            trModel.ExpandDatField1 = tnModel.ExpandDatField1;

            new BLL.T_Call_OutTaskRecords().Add(trModel);
        }
        #endregion

        public ActionResult UdpateCallState(int phoneid)
        {
            string sql = " update T_Call_OutTaskTelNum set ExpandSintField5=1 where F_id='" + phoneid + "'";
            int i = DbHelperSQL.ExecuteSql(sql);
            if (i > 0)
            {
                return Success("更新通话状态成功");
            }
            else
            {
                return Success("更新通话状态失败");
            }

        }


        public ActionResult GetDepartList()
        {
            string sql = "    F_State=1  and F_ParentId!=0 and F_ParentName is not null  ";
            BLL.T_Sys_Department bll = new BLL.T_Sys_Department();
            List<Model.T_Sys_Department> userSeartList = bll.GetModelList(sql + " order by F_DeptId desc ");
            if (userSeartList.Count > 0)
                return Success("列表加载成功", userSeartList);
            else
                return Error("列表加载失败");
        }


        public bool IsOrNotExistWorkOrder(int phoneid)
        {
            string sql = "select count(1) from  T_Wo_WorkOrder where wjid='"+ phoneid + "'";
            object res = DbHelperSQL.GetSingle(sql);
            if (res == null ||res.ToString()=="0")
            {
                return false;
            }
            return true;




        }

    }
}