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;
using CallCenterApi.Common;

namespace CallCenterApi.Interface.Controllers.callout
{
    [Authority]
    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();

        #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 with(nolock)",
                    "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("请填写名称" + ",操作人：" + User.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 = User.F_UserCode;
                model.F_DeleteFlag = 0;
                if (otBLL.Add(model) > 0)
                    return Success("添加成功" + ",操作人：" + User.F_UserCode);
                return Error("添加失败" + ",操作人：" + User.F_UserCode);
            }
            model = otBLL.GetModel(id);
            model.F_TaskName = name;
            model.F_TaskRemark = remark;
            model.F_PagerID = pagerid;
            if (otBLL.Update(model))
                return Success("修改成功" + ",操作人：" + User.F_UserCode);
            return Error("修改失败" + ",操作人：" + User.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("删除成功" + ",操作人：" + User.F_UserCode);
                }
                else
                {
                    return Error("删除失败!" + ",操作人：" + User.F_UserCode);
                }
            }
            return Error("参数传入失败");
        }
        //清理号码
        public ActionResult DeletesTaskTel(int id = 0)
        {
            if (otnBLL.DeleteByTask(id))
            {
                return Success("清理任务下号码成功" + ",操作人：" + User.F_UserCode);
            }
            else
            {
                return Error("清理任务下号码失败!" + ",操作人：" + User.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 + ",操作人：" + User.F_UserCode);
                    }
                    else
                    {
                        //otnBLL.DeleteByTask(taskid);
                        return Error("计划启动失败！taskid=" + taskid + ",操作人：" + User.F_UserCode);
                    }
                    // }
                }
            }
            else
            {
                var taskmodel = otBLL.GetModel(taskid);
                if (taskmodel.F_IsStart == state)
                {
                    return Error("计划未启动，无法停止！taskid=" + taskid + ",操作人：" + User.F_UserCode);
                }
                else
                {
                    if (otBLL.UpdateStart(taskid, 0, taskmodel.F_StartTime.Value, DateTime.Now))
                    {
                        //otnBLL.DeleteByTask(taskid);
                        return Success("计划已停止！taskid=" + taskid + ",操作人：" + User.F_UserCode);
                    }
                }
            }
            return Error("计划操作失败！taskid=" + taskid + ",操作人：" + User.F_UserCode);
        }
        #endregion
        #region 号码导入
        int vfileid = 0;
        // 导入号码读取填入数据库
        public ActionResult TelInput(int taskid)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                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 ds = ReadEcxel(Excelsource, 0);

                    HttpPostedFile _upfile = RequestString.GetFile("upFile");
                    DataTable dt = new NPOIHelper().ExcelToTable(_upfile,0);
                    try
                    {
                        //var dt = ds.Tables[0];
                        if (dt != null && dt.Rows.Count != 0)
                        {
                            rcount = dt.Rows.Count;
                            ccount = dt.Columns.Count;
                            strBuilder = new System.Text.StringBuilder();//用于如果导入失败，删除已经导入过的

                            DataTable dtInputData = dt;//要导入的电话号码
                            List<string> sqlList = new List<string>();
                            List<string> lstsql = new List<string>();
                            int ilns = dt.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;//行数

                                    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 = User.F_UserId.ToString();//导入坐席ID
                                    modelPhoneImport.ExpandVchField13 = User.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.F_CusName = dr[0].ToString();//客户名称
                                                modelPhoneImport.F_Phone = dr[1].ToString();//号码
                                                modelPhoneImport.ExpandVchField12 = dr[2].ToString();//地址
                                                #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 != "")
                {
                    res = Error("导入失败！错误信息：" + errres);
                }
                else
                {
                    string info = "本文件有" + rcount.ToString() + "行" + ccount.ToString() + "列数据";
                    res = Success("导入成功！" + info, vfileid);
                }
            }

            return res;
        }
        #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 = User.F_UserCode;
                    filesmodel.F_InputUserID = User.F_UserId;

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

        //导入后获取
        public ActionResult GetList(int? fileid, int? taskid)
        {
            ActionResult res = Error("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string sql = " and F_DeleteFlag=0 ";
                DataTable dt = new DataTable();
                string userid = User.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
                };

                res = Content(obj.ToJson());
            }
            return res;
        }

        //删除号码
        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("请选择要删除的记录");
            }
        }

        #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.User.XSSFWorkbook(fs);
        //        else if (filePath.IndexOf(".xls") > 0) // 2003版本
        //            book = new NPOI.HSSF.User.HSSFWorkbook(fs);
        //        //NPOI.HSSF.User.HSSFWorkbook book = new NPOI.HSSF.User.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 < 5; 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 < 5; 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)
        {
            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 + "%'";
            }
            sb.Append(" and F_Taskid in (select F_TaskID from T_Call_OutTask with(nolock) 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 = User.F_UserId;
            string username = User.F_UserName;
            #region 按数量平均分配
            DataTable dt = DbHelperSQL.Query("select *,NEWID() from T_Call_OutTaskTelNum with(nolock) 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 User = userlist.Where(u => u.F_UserCode == arruser[n].ToString()).FirstOrDefault();
                                bool b = otnBLL.UpdateFP(dt.Rows[i]["F_Id"].ToString(), 1, User.F_UserId.ToString(), User.F_UserName);
                                if (b)
                                {
                                    successcount++;
                                }
                            }
                            m++;
                        }
                        else
                        {
                            n++;
                            m = 0;
                            i--;
                        }
                        #endregion
                    }
                }
                return Success("成功分配外呼计划任务" + successcount.ToString() + "条数据" + ",操作人：" + User.F_UserCode);
            }
            #endregion
            return Error("分配外呼计划任务失败" + ",操作人：" + User.F_UserCode);
        }
        //未分配列表 
        public ActionResult GetTaskWPF(string key, 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='" + key + "' or  F_TaskName like '%" + key + "%' or F_TaskRemark like '%" + key + "%'";
            }
            sb.Append(" and F_Taskid in (select F_TaskID from T_Call_OutTask with(nolock) where  F_IsStart=1 and F_DeleteFlag=0 " + sql+" ) ");

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Call_OutTaskTelNum with(nolock)",
                    "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 =User.F_RoleId;
            int deptid = User.F_DeptId;
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                                    "T_Sys_UserAccount with(nolock)",
                                    "F_UserId",
                                    "*",
                                    sql,
                                    "ORDER BY F_UserId desc",
                                    pagesize,
                                    pageindex,
                                    true,
                                    out recordCount);
            #region 条件调整
            string sqlc = " select F_UserId,COUNT(1) Count from T_Call_OutTaskTelNum with(nolock) where F_DeleteFlag=0 and isnull(F_HJJGName,'') not in ('正常接通','停机','空号','正常接通-不满意','不在本地居住') and F_TaskID in (select F_TaskID from T_Call_OutTask with(nolock) where F_IsStart=1 and F_DeleteFlag=0) group by F_UserId";
            DataTable dtCount = DbHelperSQL.Query(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,
                    WWCCount = dtCount.Select(" F_UserId=" + x.F_UserId).FirstOrDefault()?.ItemArray[1].ToString() ?? "0"
                }),
                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_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

                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 GetMyTaskList(string key, string sdate, string edate, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();
            int userid = User.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 ('正常接通','停机','空号','正常接通-不满意','不在本地居住')");
            #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 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 = User.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;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Call_OutTaskTelNum",
                    "F_Id",
                    "*",
                    sb.ToString(),
                    "ORDER BY ExpandDatField1 desc,F_Id desc",//ExpandDatField1 调查时间倒序，id倒序
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            #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;
            //}
            #endregion
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        //获取总体任务结果
        public ActionResult GetResultList(string key, string sdate, string edate, 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);
            }
            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;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Call_OutTaskTelNum",
                    "F_Id",
                    "*",
                    sb.ToString(),
                    "ORDER BY ExpandDatField1 desc,F_Id desc",//ExpandDatField1 调查时间倒序，id倒序
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            #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;
            //}
            #endregion
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        //获取任务结果详情
        public ActionResult GetTaskTelInfo(int id = 0)
        {
            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

                //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);
                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,
                                quesanswers = answers.Trim('|'),
                                quesitems = qilist.Where(qq => qq.F_QuestionId == q.F_QuestionId).Select(qi =>
                                {
                                    return new
                                    {
                                        itemid = qi.F_ItemId,
                                        itemname = qi.F_ItemName,
                                        itemremark = qi.F_Remark,
                                    };
                                })
                            };
                        })
                    };
                    #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, int countryid, string address)
        {
            int cc = 0; 
            if (custelid > 0)
            {
                var otnModel = otnBLL.GetModel(custelid);
                if (otnModel != null)
                {
                    int cusid = saveCus(otnModel.F_Phone, name, phone, countryid, address);

                    #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;
                        ansModel.F_CusID = cusid;
                        ansModel.F_OptBy = User.F_UserId;
                        ansModel.F_OptByName = User.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)
                        {
                            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_Value;
                    //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_Area().GetModel(countryid);
                    if (fkconfig != null)
                        otnModel.ExpandVchField4 = fkconfig.F_AreaName ;
                    otnModel.ExpandIntField1 = countryid;//乡镇
                    otnModel.ExpandDatField1 = DateTime.Now;//调查时间
                    otnModel.F_AskRes = askqids;
                    otnModel.F_AskInfo = ansids;
                    otnModel.F_CusID = cusid;
                    otnModel.F_CusName = name;
                    otnBLL.Update(otnModel);
                    planrecord(otnModel);
                    #endregion
                }
            }
            if (ans != null)
            {
                if (cc == ans.Length)
                {
                    return Success("问卷答案提交成功！taskid=" + taskid + ",custelid=" + custelid + ",操作人：" + User.F_UserCode);
                }
                else
                {
                    ansBLL.DeleteByTelid(custelid, taskid);
                    return Error("问卷答案提交失败！taskid=" + taskid + ",custelid=" + custelid + ",操作人：" + User.F_UserCode);
                }
            }
            else
            {
                return Error("没有问卷答案提交");
            }

        }
        #endregion

        #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)
        {
            int res = 0;
            Model.T_Cus_CustomerBase cusmodel = new Model.T_Cus_CustomerBase();
            if (!string.IsNullOrWhiteSpace(telphone))
            {
                var fkconfig = new BLL.T_Sys_Area().GetModel(countryid);
                
                cusmodel = cusBLL.GetModelByPhone(telphone);

                if (cusmodel != null)
                {
                    cusmodel.F_Address = address;
                    if (fkconfig != null)
                        cusmodel.F_City = fkconfig.F_AreaName;
                    cusmodel.F_CityID = countryid;
                    cusmodel.F_CustomerName = name;
                    cusmodel.F_Telephone = phone;
                    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_AreaName;
                    cusmodel.F_CityID = countryid;
                    cusmodel.F_CustomerName = name;
                    cusmodel.F_Telephone = phone;
                    cusmodel.F_Mobile = telphone;
                    res = cusBLL.Add(cusmodel);
                }
            }
            return res;
        }
        
        #endregion

        #region 获取记录
        //获取外呼通话记录
        public ActionResult GetTelList(string type, string telid, string phone, string usercode)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                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 with(nolock)",
                    "CallRecordsId",
                    "*",
                    sql,
                    "ORDER BY CallRecordsId desc",
                   pagesize,
                   pageindex,
                   true,
                   out recordCount);

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

                res = Content(obj.ToJson());
            }
            return res;
        }
        #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 = User.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
    }
}