using CallCenter.Utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ZXDT.CallCenter.Model;
using ZXDT.CallCenter.MVCWeb.Commons;
using ZXDT.CallCenter.MVCWeb.Models;
using ZXDT.Common;
using ZXDT.DBUtility;

namespace ZXDT.CallCenter.MVCWeb.Controllers
{
    public class CallRecordController : BaseController
    {



        //工单信息
        BLL.T_Wo_WorkOrderBase orderBLL = new BLL.T_Wo_WorkOrderBase();
        //客户信息
        BLL.T_Cus_CustomerBase cusBLL = new BLL.T_Cus_CustomerBase();
        //部门表
        BLL.T_Sys_Department deptBll = new BLL.T_Sys_Department();

        //用户表
        BLL.T_Sys_UserAccount userBll = new BLL.T_Sys_UserAccount();
        //通话记录
        BLL.T_Call_CallRecords recordBLL = new BLL.T_Call_CallRecords();

        #region 来电弹屏信息
        /// <summary>
        /// 来电弹屏页面
        /// </summary>
        /// <param name="workOrderNum">工单编号</param>
        /// <returns></returns>
        public ActionResult CallScreen(string workOrderNum)
        {

            //workOrderNum = "12";
            //实例化基础信息表
            CallScreenModel callScreenModel = new CallScreenModel();

            //获取业务工单信息
            if (!string.IsNullOrEmpty(workOrderNum))
            {
                callScreenModel.WorkOrderBaseModel = orderBLL.GetModel(int.Parse(workOrderNum.ToString()));
                if (callScreenModel.WorkOrderBaseModel==null)
                {
                    callScreenModel.WorkOrderBaseModel = new Model.T_Wo_WorkOrderBase()
                    {
                        CustomerBaseModel = new T_Cus_CustomerBase { F_CustomerId = 0 },
                        F_WORKORDERID = 0
                    };
                }
                //如果电话号码不为空
                if (callScreenModel.WorkOrderBaseModel != null && !string.IsNullOrEmpty(callScreenModel.WorkOrderBaseModel.F_CUSTOMERTELEPHONE))
                {
                    //获取客户基本信息
                    callScreenModel.WorkOrderBaseModel.CustomerBaseModel = cusBLL.GetCusInfoModel(callScreenModel.WorkOrderBaseModel.F_CUSTOMERTELEPHONE);
                }

                if (callScreenModel.WorkOrderBaseModel != null && !string.IsNullOrEmpty(callScreenModel.WorkOrderBaseModel.F_KSHADDRESSCODE))
                {
                    Model.T_Call_CallRecords callRecordModel = recordBLL.GetModelByCallId(callScreenModel.WorkOrderBaseModel.F_KSHADDRESSCODE);

                    if (callRecordModel != null)
                    {
                        if (callRecordModel.BusinessType != null)
                        {
                            //业务选择按键
                            callScreenModel.SelectBussType = int.Parse(callRecordModel.BusinessType.ToString());
                        }
                        else
                        {
                            callScreenModel.SelectBussType =1;
                        }

                    }
                }

            }
            callScreenModel.WorkOrderTypeModelList = GetWorkTypeModelList();//业务类型字典表
            //获取处理年龄段字典表                                                             
            callScreenModel.AgeModelList = GetCodeType("NLD");


            return View(callScreenModel);
        }
        /// <summary>
        /// 业务工单录入页面
        /// </summary>
        /// <param name="workOrderNum">工单编号</param>
        /// <param name="flowid">业务类型</param>
        /// <returns></returns>
        public ActionResult CallWorkFolw(string workOrderNum, int? flowid)
        {

            //实例化基础信息表
            CallScreenModel callScreenModel = new CallScreenModel();
            //选择的业务类型
            if (flowid != null && flowid > 0)
            {
                callScreenModel.Flowid = flowid;
            }
            else
            {
                callScreenModel.Flowid = 0;
            }
            //获取业务工单信息
            if (!string.IsNullOrEmpty(workOrderNum))
            {
                callScreenModel.WorkOrderBaseModel = orderBLL.GetModel(int.Parse(workOrderNum.ToString()));
                if (callScreenModel.WorkOrderBaseModel == null)
                {
                    callScreenModel.WorkOrderBaseModel = new Model.T_Wo_WorkOrderBase()
                    {
                        CustomerBaseModel = new T_Cus_CustomerBase { F_CustomerId = 0 },
                        F_WORKORDERID = 0
                    };
                }
               
                //如果电话号码不为空
                if (callScreenModel.WorkOrderBaseModel != null && !string.IsNullOrEmpty(callScreenModel.WorkOrderBaseModel.F_CUSTOMERTELEPHONE))
                {
                    T_Cus_CustomerBase baseCusModel = cusBLL.GetCusInfoModel(callScreenModel.WorkOrderBaseModel.F_CUSTOMERTELEPHONE);


                    if (baseCusModel != null && baseCusModel.F_CustomerId > 0)
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = baseCusModel;
                    }
                    else
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = new T_Cus_CustomerBase();
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel.F_CustomerName = callScreenModel.WorkOrderBaseModel.F_CUSTOMERNAME;
                    }

                    //选择的业务类型
                    if (flowid != null && flowid > 0)
                    {

                        callScreenModel.BussnessContnet = GetTypeContenet(int.Parse(flowid.ToString()), callScreenModel.WorkOrderBaseModel.F_CREATEDATE.ToString());
                    }
                }
                else
                {
                    callScreenModel.WorkOrderBaseModel.CustomerBaseModel = new T_Cus_CustomerBase();
                    callScreenModel.WorkOrderBaseModel.CustomerBaseModel.F_CustomerName = callScreenModel.WorkOrderBaseModel.F_CUSTOMERNAME;
                }
                //获取客户基本信息

            }
            //业务类型字典表
            callScreenModel.WorkOrderTypeModelList = GetWorkTypeModelList();
            //获取处理方式字典表
            callScreenModel.GoTypeModelList = GetCodeType("CLFS");
            //获取处理年龄段字典表
            callScreenModel.AgeModelList = GetCodeType("NLD");
            //获取部门列表
            callScreenModel.DepartmentList = deptBll.GetModelList("F_ParentId=0");
            callScreenModel.HistoryOrderList = historyBll.GetModelList("F_INSTANCEID=" + workOrderNum.ToInt32());

            return View(callScreenModel);
        }

        //历史工单表
        BLL.T_Wo_WorkOrderHistory historyBll = new BLL.T_Wo_WorkOrderHistory();

        /// <summary>
        /// 业务工单录入页面
        /// </summary>
        /// <param name="workOrderNum">工单编号</param>
        /// <param name="flowid">业务类型</param>
        /// <returns></returns>
        public ActionResult EditCallWorkFolw(string workOrderNum)
        {

            //实例化基础信息表
            CallScreenModel callScreenModel = new CallScreenModel();

            //获取业务工单信息
            if (!string.IsNullOrEmpty(workOrderNum))
            {
                callScreenModel.WorkOrderBaseModel = orderBLL.GetModel(int.Parse(workOrderNum.ToString()));
                //如果电话号码不为空
                if (callScreenModel.WorkOrderBaseModel != null && !string.IsNullOrEmpty(callScreenModel.WorkOrderBaseModel.F_CUSTOMERTELEPHONE))
                {
                    T_Cus_CustomerBase baseCusModel = cusBLL.GetCusInfoModel(callScreenModel.WorkOrderBaseModel.F_CUSTOMERTELEPHONE);


                    if (baseCusModel != null && baseCusModel.F_CustomerId > 0)
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = baseCusModel;
                    }
                    else
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = new T_Cus_CustomerBase();
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel.F_CustomerName = callScreenModel.WorkOrderBaseModel.F_CUSTOMERNAME;
                      
                    }

                }
                else
                { 
                    callScreenModel.WorkOrderBaseModel.CustomerBaseModel = new T_Cus_CustomerBase();
                    callScreenModel.WorkOrderBaseModel.CustomerBaseModel.F_CustomerName = callScreenModel.WorkOrderBaseModel.F_CUSTOMERNAME;
                }
                //获取客户基本信息
                if (!string.IsNullOrEmpty( callScreenModel.WorkOrderBaseModel.F_EMPCODE))
                {
                    T_Cus_CustomerBase baseCusModel = cusBLL.GetCusInfoModel(1,callScreenModel.WorkOrderBaseModel.F_EMPCODE);


                    if (baseCusModel != null && baseCusModel.F_CustomerId > 0)
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = baseCusModel;
                    }
                    else
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = new T_Cus_CustomerBase();
                    }
                } 
            }
            //业务类型字典表
            callScreenModel.WorkOrderTypeModelList = GetWorkTypeModelList();
            //获取处理方式字典表
            callScreenModel.GoTypeModelList = GetCodeType("CLFS");
            //回访满意度
            callScreenModel.MYdModelList = GetCodeType("khyjfl");
            //获取处理年龄段字典表
            callScreenModel.AgeModelList = GetCodeType("NLD");
            //获取部门列表
            callScreenModel.DepartmentList = deptBll.GetModelList("F_ParentId=0");


            return View(callScreenModel);
        }


        /// <summary>
        /// 编辑历史工单
        /// </summary>
        /// <param name="workOrderBaseModel"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public bool workOrderEditData(T_Wo_WorkOrderBase workOrderBaseModel)
        {
            //工单来源
            //workOrderBaseModel.F_REPAIRMANID = 1;
            //workOrderBaseModel.F_WORKORDERFROM = "语音";
            string F_UserCode = "";
            if (Request.Cookies["BaseCallCenter_T_User"] != null)
            {
                F_UserCode = Request.Cookies["BaseCallCenter_T_User"]["F_UserCode"];
            }
            string bu = "";
            if (workOrderBaseModel.CustomerBaseModel != null)
                {

           string linkman=  DbHelperSQL.GetSingle("select F_LINKMAN from T_Wo_WorkOrderBase where F_WORKORDERID='"+
               workOrderBaseModel.F_WORKORDERID + "'").ToString();
                if (linkman.Equals(F_UserCode))
                {
                    //最近联络方式
                    if (workOrderBaseModel.F_REPAIRMANID.ToString() == "4")
                    {
                        workOrderBaseModel.CustomerBaseModel.F_Kind = "3";
                        workOrderBaseModel.F_CUSTOMERTELEPHONE = workOrderBaseModel.CustomerBaseModel.F_Mobile;
                    }
                    else
                    {
                        workOrderBaseModel.CustomerBaseModel.F_Kind = workOrderBaseModel.F_REPAIRMANID.ToString();
                    }
                    workOrderBaseModel.CustomerBaseModel.F_CustomerNature = workOrderBaseModel.F_WORKORDERFROM;
                    //业务类型
                    workOrderBaseModel.CustomerBaseModel.F_IndustryId = workOrderBaseModel.F_REPAIRLEVEL;
                    workOrderBaseModel.CustomerBaseModel.F_Url = workOrderBaseModel.F_ADSLACCOUNT;
                    //修改客户基础信息

                    bu += "F_Kind old is:" + workOrderBaseModel.F_REPAIRMANID.ToString() + " F_Kind new is:" + workOrderBaseModel.CustomerBaseModel.F_Kind;
                    bu += "F_CustomerNature old is:" + workOrderBaseModel.F_WORKORDERFROM + " F_CustomerNature new is:" + workOrderBaseModel.CustomerBaseModel.F_CustomerNature;
                    bu += "F_IndustryId old is:" + workOrderBaseModel.F_REPAIRLEVEL + " F_IndustryId new is:" + workOrderBaseModel.CustomerBaseModel.F_IndustryId;
                    bu += "F_Url old is:" + workOrderBaseModel.F_ADSLACCOUNT + " F_Url new is:" + workOrderBaseModel.CustomerBaseModel.F_Url;

                    int cusid = cusBLL.EditCusInfoModel(workOrderBaseModel.CustomerBaseModel);
                    if (cusid > 0)
                    {
                        workOrderBaseModel.F_CUSTOMERID = cusid;
                    }
                }

             var res=   DbHelperSQL.Query("select top 1 *  from T_Wo_WorkOrderBase where F_WORKORDERID='" +
              workOrderBaseModel.F_WORKORDERID + "'").Tables[0];

         
                for (int i = 0; i < res.Rows.Count; i++)
                {
                    bu += "F_CUSTOMERTELEPHONE old is:" + res.Rows[i]["F_CUSTOMERTELEPHONE"] + " CustomerBaseModel new is:" + workOrderBaseModel.F_CUSTOMERTELEPHONE ;
      
                    bu += "F_CUSTOMERID old is:" + res.Rows[i]["F_CUSTOMERID"] + " F_CUSTOMERID new is:" + workOrderBaseModel.F_CUSTOMERID;
                }

                AddLog("T_Cus_CustomerBase", "T_Cus_CustomerBase", "记录工单操作记录", bu, "操作记录");
              

                return orderBLL.UpdateHistoryWorkOrderInfoModel(workOrderBaseModel);
            }
            else
            {
                return false;
            }

        
        }

        /// <summary>
        /// 编辑工单列表 的撤回按钮 ；撤回历史工单
        /// </summary>
        /// <param name="workOrderBaseModel"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public bool ResetWorkOrder(int workOrderId, string reason)
        {
            string F_UserCode = "";
            if (Request.Cookies["BaseCallCenter_T_User"] != null)
            {
                F_UserCode = Request.Cookies["BaseCallCenter_T_User"]["F_UserCode"];
            }
            BLL.T_Wo_WorkOrderHistory his = new BLL.T_Wo_WorkOrderHistory();
            int n = his.GetRecordCount("F_StateName = '已处理' AND  F_INSTANCEID = '" + workOrderId + "'");
            if (n > 0)
            {
                return false;
            }
            string linkman = DbHelperSQL.GetSingle("select F_LINKMAN from T_Wo_WorkOrderBase where F_WORKORDERID='" +
                   workOrderId + "'").ToString();
            if (linkman.Equals(F_UserCode))
            {
                bool result = false; ;
                string bycode = F_UserCode;
                string byname = F_UserName;
                int bmid = F_DeptId;
                string bmmc = "";
                if (F_UserID > 0)
                {
                    ZXDT.CallCenter.BLL.T_Sys_Department depBll = new BLL.T_Sys_Department();
                    List<Model.T_Sys_Department> list = new List<T_Sys_Department>();
                    list = depBll.GetModelList("F_DeptId=" + bmid);
                    if (list.Count > 0)
                    {
                        bmmc = list[0].F_DeptName.ToString();
                        result = orderBLL.ResetWorkOrder(workOrderId, F_UserID, F_UserName, F_DeptId, bmmc, reason);
                    }
                }
                return result;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 获取业务术语模板信息
        /// </summary>
        /// <param name="bussnessType">业务类型</param>
        /// <returns></returns>
        public string GetTypeContenet(int bussnessType, string creatDateTime)
        {
            try
            {
                //模板内容
                string bussContent = "";
                if (bussnessType > 0)
                {
                    if (bussnessType > 0)
                    {
                        BLL.T_Wo_WorkOrderType bll = new BLL.T_Wo_WorkOrderType();
                        Model.T_Wo_WorkOrderType orderTypeModel = new T_Wo_WorkOrderType();

                        orderTypeModel = bll.GetModel(bussnessType);
                        if (orderTypeModel != null && !string.IsNullOrEmpty(orderTypeModel.F_Remark))
                        {
                            bussContent += string.Format(orderTypeModel.F_Remark, DateTime.Parse(creatDateTime).ToString("f") + "分");
                        }
                    }
                }
                return bussContent;
            }
            catch (Exception ex)
            {

            }
            return null;

        }


        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="workOrderBaseModel"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public bool SaveCunInfo(T_Cus_CustomerBase CustomerBaseModel)
        {

            #region 来电弹屏选投诉工单时，走这个接口保存客户信息；已存在的客户不保存
            ZXDT.CallCenter.Model.T_Cus_CustomerBase model = cusBLL.GetCusInfoModel(CustomerBaseModel.F_Telephone);
            if (model != null)
            {
                return true;
            }
            #endregion



            //客户属性

            if (string.IsNullOrEmpty(CustomerBaseModel.F_Kind))
            {
                CustomerBaseModel.F_Kind = "1";
            }
            if (string.IsNullOrEmpty(CustomerBaseModel.F_CustomerNature))
            {
                CustomerBaseModel.F_CustomerNature = "语音";
            }
            if (CustomerBaseModel.F_CustomerId > 0)
            {
                AddAction("t_cus_customerbase", CustomerBaseModel.F_CustomerId.ToMyString(), "更新客户信息", CustomerBaseModel.F_CustomerName.ToMyString());
                AddAction("t_cus_customerbase", CustomerBaseModel.F_CustomerId.ToMyString(), "更新客户信息", "数据：" + JsonConvert.SerializeObject(CustomerBaseModel), "关键信息");
            }
            else
            {
                ZXDT.CallCenter.Model.T_Cus_CustomerBase modelcus= cusBLL.GetCusInfoModel(CustomerBaseModel.F_Telephone);
                if ( modelcus.F_CustomerId>0)
                {

                }
                AddAction("t_cus_customerbase", CustomerBaseModel.F_Telephone, "添加客户信息", CustomerBaseModel.F_CustomerName.ToMyString());
                AddAction("t_cus_customerbase", CustomerBaseModel.F_Telephone, "添加客户信息","数据："+JsonConvert.SerializeObject(CustomerBaseModel), "关键信息");
            }
            if (CustomerBaseModel.F_CustomerId > 0)
            { }
            else
            {
                CustomerBaseModel.F_CreateBy = F_UserID;
            }

            return cusBLL.UpdateCusInfoModel(CustomerBaseModel);
        }
        


        /// <summary>
        /// 获取员工信息
        /// </summary>
        /// <param name="deptId">部门id</param>
        /// <returns></returns>
        public string GetDeptUsers(string deptId)
        {

            try
            {
                return JsonConvert.SerializeObject(userBll.GetModelList("F_DeptId=" + deptId));
            }
            catch (Exception ex)
            {

            }
            return null;

        }


        #endregion
        #region 微博工单
        /// <summary>
        /// 微信微博工单录入页面
        /// </summary>
        /// <param name="workOrderNum">工单编号</param>
        /// <param name="flowid">业务类型</param>
        /// <returns></returns>
        public ActionResult WBWorkFlow(string workOrderNum, int? flowid)
        {
            workOrderNum = "0"; flowid = 0;
             //实例化基础信息表
             CallScreenModel callScreenModel = new CallScreenModel();
            //选择的业务类型
            if (flowid != null && flowid > 0)
            {
                callScreenModel.Flowid = flowid;
            }
            else
            {
                callScreenModel.Flowid = 0;
            } 
            //业务类型字典表
            callScreenModel.WorkOrderTypeModelList = GetWorkTypeModelList();
            //获取处理方式字典表
            callScreenModel.GoTypeModelList = GetCodeType("CLFS");
            //获取处理年龄段字典表
            callScreenModel.AgeModelList = GetCodeType("NLD");
            //获取部门列表
            callScreenModel.DepartmentList = deptBll.GetModelList("F_ParentId=0");
            
            return View(callScreenModel);
        }

        /// <summary>
        /// 微信编辑
        /// </summary>
        /// <param name="webChartNum">微信号</param>
        /// <param name="recordId">历史记录号</param>
        /// <param name="recordId">工单id</param>
        /// <returns></returns>
        public ActionResult WXWorkFlowEdit(int workOrderNum)
        {
          
        
            //实例化基础信息表
            CallScreenModel callScreenModel = new CallScreenModel();

            if ( workOrderNum > 0)
            {
                callScreenModel.WorkOrderBaseModel = orderBLL.GetModel(workOrderNum);
                //获取业务工单信息
                if (!string.IsNullOrEmpty(callScreenModel.WorkOrderBaseModel.F_EMPCODE))
                {
                    T_Cus_CustomerBase baseCusModel = cusBLL.GetCusInfoModel(1, callScreenModel.WorkOrderBaseModel.F_EMPCODE);

                    if (baseCusModel != null && baseCusModel.F_CustomerId > 0)
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = baseCusModel;
                    }
                    else
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = new T_Cus_CustomerBase();
                    }

                }
                else
                {
                    callScreenModel.WorkOrderBaseModel.CustomerBaseModel = new T_Cus_CustomerBase();
                }
                //业务类型字典表
                callScreenModel.WorkOrderTypeModelList = GetWorkTypeModelList();
                //获取处理方式字典表
                callScreenModel.GoTypeModelList = GetCodeType("CLFS");
                //获取处理年龄段字典表
                callScreenModel.AgeModelList = GetCodeType("NLD");
                //获取部门列表
                callScreenModel.DepartmentList = deptBll.GetModelList("F_ParentId=0");

                callScreenModel.HistoryOrderList = historyBll.GetModelList("F_INSTANCEID=" + int.Parse(workOrderNum.ToString()));
                return View(callScreenModel);

            }

          
            return View();
        }
        /// <summary>
        /// 微博编辑
        /// </summary>
        /// <param name="webChartNum">微信号</param>
        /// <param name="recordId">历史记录号</param>
        /// <param name="recordId">工单id</param>
        /// <returns></returns>
        public ActionResult WBWorkFlowEdit(int workOrderNum)
        {
            //实例化基础信息表
            CallScreenModel callScreenModel = new CallScreenModel();

            if (workOrderNum > 0)
            {
                callScreenModel.WorkOrderBaseModel = orderBLL.GetModel(workOrderNum);
                //获取业务工单信息
                if (!string.IsNullOrEmpty(callScreenModel.WorkOrderBaseModel.F_EMPCODE))
                {//1微信，2微博
                    T_Cus_CustomerBase baseCusModel = cusBLL.GetCusInfoModel(1, callScreenModel.WorkOrderBaseModel.F_EMPCODE);

                    if (baseCusModel != null && baseCusModel.F_CustomerId > 0)
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = baseCusModel;
                    }
                    else
                    {
                        callScreenModel.WorkOrderBaseModel.CustomerBaseModel = new T_Cus_CustomerBase();
                    }

                }
                else
                {
                    callScreenModel.WorkOrderBaseModel.CustomerBaseModel = new T_Cus_CustomerBase();
                }
                //业务类型字典表
                callScreenModel.WorkOrderTypeModelList = GetWorkTypeModelList();
                //获取处理方式字典表
                callScreenModel.GoTypeModelList = GetCodeType("CLFS");
                //获取处理年龄段字典表
                callScreenModel.AgeModelList = GetCodeType("NLD");
                //获取部门列表
                callScreenModel.DepartmentList = deptBll.GetModelList("F_ParentId=0");

                callScreenModel.HistoryOrderList = historyBll.GetModelList("F_INSTANCEID=" + int.Parse(workOrderNum.ToString()));
                return View(callScreenModel);

            }


            return View();
        }

        #endregion



        /// <summary>
        /// 补录工单处理信息
        /// </summary>
        /// <param name="workOrderBaseModel"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public bool workOrderAddData(T_Wo_WorkOrderBase workOrderBaseModel)
        {
            if (workOrderBaseModel.F_REPAIRMANID == 4)
            {
                workOrderBaseModel.F_WORKORDERFROM = "语音工单";
                string wbh = workOrderBaseModel.CustomerBaseModel.F_CustomerEName.ToMyString().Trim();
                if (!string.IsNullOrEmpty(wbh))
                {
                    workOrderBaseModel.F_EMPCODE = wbh;
                    workOrderBaseModel.CustomerBaseModel.F_PostCode = wbh;
                }
                ////客户等级
                workOrderBaseModel.CustomerBaseModel.F_Kind = "3";
                workOrderBaseModel.CustomerBaseModel.F_ScaleResume = "1";
                workOrderBaseModel.CustomerBaseModel.F_CustomerClass = "一般客户";
            }
            else if (workOrderBaseModel.F_REPAIRMANID == 3)
            {
                workOrderBaseModel.F_WORKORDERFROM = "微信工单";
                string wbh = workOrderBaseModel.CustomerBaseModel.F_CustomerEName.ToMyString().Trim();
                if (!string.IsNullOrEmpty(wbh))
                {
                    workOrderBaseModel.F_EMPCODE = wbh;
                    workOrderBaseModel.CustomerBaseModel.F_PostCode = wbh;
                }
                ////客户等级
                workOrderBaseModel.CustomerBaseModel.F_Kind = "2";
                workOrderBaseModel.CustomerBaseModel.F_ScaleResume = "1";
                workOrderBaseModel.CustomerBaseModel.F_CustomerClass = "一般客户";
            }

            workOrderBaseModel.F_USERID = F_UserID;//id
            workOrderBaseModel.F_LINKMAN = F_UserCode;//工号
            workOrderBaseModel.F_REPAIRMANNAME = F_UserName;//姓名
            workOrderBaseModel.F_LINKMANTELEPHONE = workOrderBaseModel.CustomerBaseModel.F_Mobile;
            workOrderBaseModel.F_USERNAME = F_UserName;
            workOrderBaseModel.F_DEPTID = F_DeptId;

            T_Sys_Department deptmodel = deptBll.GetModel(F_DeptId);
            if (deptmodel != null)
            {
                workOrderBaseModel.F_DEPTCODE = deptmodel.F_DeptName;
            }
            AddAction("T_Wo_WorkOrderBase", workOrderBaseModel.F_WORKORDERID.ToMyString(), "录入工单", "数据："+JsonConvert.SerializeObject(workOrderBaseModel), "关键信息");

            if (workOrderBaseModel.F_CONTENT == null)
            {
                workOrderBaseModel.F_CONTENT = "-";
            }
            if (workOrderBaseModel.F_RETURNVISITCONTENT == null)
            {
                workOrderBaseModel.F_RETURNVISITCONTENT = "-";
            }
            if (workOrderBaseModel.CustomerBaseModel != null)
            {
                //最近联络方式
                if (workOrderBaseModel.F_REPAIRMANID != 4&& workOrderBaseModel.F_REPAIRMANID != 3)
                {
                    workOrderBaseModel.CustomerBaseModel.F_Kind = workOrderBaseModel.F_REPAIRMANID.ToString();
                }
                workOrderBaseModel.CustomerBaseModel.F_CustomerNature = workOrderBaseModel.F_WORKORDERFROM;
                //业务类型
                workOrderBaseModel.CustomerBaseModel.F_IndustryId = workOrderBaseModel.F_REPAIRLEVEL;
                workOrderBaseModel.CustomerBaseModel.F_Url = workOrderBaseModel.F_ADSLACCOUNT;

                //修改客户基础信息
                int cusid = cusBLL.EditCusInfoModel(workOrderBaseModel.CustomerBaseModel);
                if (cusid > 1)
                {  
                    workOrderBaseModel.F_CUSTOMERID = cusid;
                }
            }

            if (workOrderBaseModel.F_WORKORDERSTATEID > 0)
            {
                if (workOrderBaseModel.F_HOUSING == "表扬")
                {
                    workOrderBaseModel.F_WORKORDERTYPEID = 1;
                }

                workOrderBaseModel.F_CODE= orderBLL.GetOrderNumber(workOrderBaseModel.F_REPAIRLEVEL.ToInt32());
                if (workOrderBaseModel.F_HOUSING == "表扬" || workOrderBaseModel.F_HOUSING == "咨询" || workOrderBaseModel.F_HOUSING == "挂失")
                {
                    //workOrderBaseModel.F_WORKORDERTYPEID = 3;
                    if (workOrderBaseModel.F_WORKORDERTYPEID == 1)
                    { 
                    if (workOrderBaseModel.HistoryOrderList != null && workOrderBaseModel.HistoryOrderList.Count > 0)
                    {
                        Dictionary<int, string> dict = new Dictionary<int, string>() { };

                        for (int i = workOrderBaseModel.HistoryOrderList.Count - 1; i >= 0; i--)
                        {
                            T_Wo_WorkOrderHistory modelhis = workOrderBaseModel.HistoryOrderList[i];

                            Model.T_Sys_Department model = new BLL.T_Sys_Department().GetModel(string.Format("F_DeptId=(select top 1 F_DeptId from T_Sys_UserAccount where F_UserId={0})", modelhis.F_OPTUSERID));
                            if (model != null && model.F_DeptId > 0)
                            {
                                if (dict.ContainsKey(model.F_DeptId))
                                {
                                    workOrderBaseModel.HistoryOrderList.Remove(workOrderBaseModel.HistoryOrderList[i]);
                                    continue;
                                }
                                modelhis.F_OPTBTNID = model.F_DeptId;
                                modelhis.F_NEXTOWNERARRID = model.F_DeptName;
                                dict.Add(model.F_DeptId, "1");
                            }
                        }
                    }
                    }

                }
                if (workOrderBaseModel.F_WORKORDERTYPEID == 3)
                {

                    #region 如果是客服处理 回访相关的字段给赋值为空

                    workOrderBaseModel.F_RETURNVISITFLAG = 0;
                    workOrderBaseModel.F_RETURNVISITTIME = null;
                    workOrderBaseModel.F_REQUESTSERVICETIME = null;
                    #endregion


                    Model.T_Wo_WorkOrderHistory historyModel = new Model.T_Wo_WorkOrderHistory();

                    historyModel.F_INSTANCEID =  0;//  workOrderBaseModel.F_WORKORDERID;客服处理的工单按说不应该创建T_Wo_WorkOrderHistory，不知道为什么他要创建这个。所以给关联工单id的字段改成了0
                    historyModel.F_OPTDATE = DateTime.Now;
                    historyModel.ReplayTime = DateTime.Now;

                    if (workOrderBaseModel.F_WORKORDERSTATEID >0)
                        historyModel.F_WORKORDERSTATEID = (int)workOrderBaseModel.F_WORKORDERSTATEID;

                    else
                        historyModel.F_WORKORDERSTATEID = 1;
                    historyModel.F_StateName = "已处理";
                    historyModel.NeedReplayTime = workOrderBaseModel.F_REQUESTSERVICETIME;
                    historyModel.F_OPTUSERID = F_UserID;
                    historyModel.F_OPTBTNID = F_DeptId;
                    historyModel.F_UserName = F_UserName;
                    historyModel.F_REMARK = workOrderBaseModel.F_RETURNVISITCONTENT;
                    Model.T_Sys_Department model = new BLL.T_Sys_Department().GetModel(string.Format("F_DeptId=(select top 1 F_DeptId from T_Sys_UserAccount where F_UserId={0})", F_UserID));
                    if (model != null && model.F_DeptId > 0)
                    {
                        
                        historyModel.F_NEXTOWNERARRID = model.F_DeptName;
                    }
                    else
                    {
                        historyModel.F_NEXTOWNERARRID = "全媒体客服";
                    }
                    workOrderBaseModel.HistoryOrderList = new List<T_Wo_WorkOrderHistory>();
                    workOrderBaseModel.HistoryOrderList.Add(historyModel);
                }
                else
                {
                    if (workOrderBaseModel.HistoryOrderList != null && workOrderBaseModel.HistoryOrderList.Count > 0)
                    {
                        Dictionary<int, string> dict = new Dictionary<int, string>() { };
                        
                        for (int i= workOrderBaseModel.HistoryOrderList.Count-1; i>=0;i--)
                        {
                            T_Wo_WorkOrderHistory modelhis = workOrderBaseModel.HistoryOrderList[i];
                            if (dict.ContainsKey(modelhis.F_OPTUSERID.ToInt32()))
                            {
                                workOrderBaseModel.HistoryOrderList.Remove(workOrderBaseModel.HistoryOrderList[i]);
                                continue;
                            }
                            new BLL.T_Com_Class().UpdateRate(F_UserCode, modelhis.F_OPTUSERID.ToInt32());
                            Model.T_Sys_Department model=  new BLL.T_Sys_Department().GetModel(string.Format("F_DeptId=(select top 1 F_DeptId from T_Sys_UserAccount where F_UserId={0})", modelhis.F_OPTUSERID));
                            if (model != null && model.F_DeptId > 0)
                            {
                                modelhis.F_OPTBTNID = model.F_DeptId;
                                modelhis.F_NEXTOWNERARRID = model.F_DeptName; 
                            }
                            dict.Add(modelhis.F_OPTUSERID.ToInt32(), "1");
                        }
                    }
                }
                if (workOrderBaseModel.F_WORKORDERTYPEID == 1)
                {
                    AddAction("t_wo_workorderbase", workOrderBaseModel.F_WORKORDERID.ToMyString(), "转单处理工单", workOrderBaseModel.F_CODE);
                }
                else
                {
                    workOrderBaseModel.F_REMAINDERTIME = DateTime.Now;
                    AddAction("t_wo_workorderbase", workOrderBaseModel.F_WORKORDERID.ToMyString(), "即时处理工单", workOrderBaseModel.F_CODE);
                }
            }
            else
            { workOrderBaseModel.F_CODE = ""; }

            try
            {
                if (string.IsNullOrEmpty(workOrderBaseModel.F_CUSTOMERNAME))
                {

                    if (!string.IsNullOrEmpty(workOrderBaseModel.F_CUSTOMERTELEPHONE))
                    {
                        T_Cus_CustomerBase baseCusModel = cusBLL.GetCusInfoModel(workOrderBaseModel.F_CUSTOMERTELEPHONE);


                        if (baseCusModel != null && baseCusModel.F_CustomerId > 0)
                        {
                            workOrderBaseModel.F_CUSTOMERNAME = baseCusModel.F_CustomerName;
                        }
                    }
                }
            }
            catch
            {

               
            }
           
            if (workOrderBaseModel.F_WORKORDERID == 0&& (workOrderBaseModel.F_REPAIRMANID == 4|| workOrderBaseModel.F_REPAIRMANID==3))
            {
                //model.F_SERVICEWAY  记录id
                workOrderBaseModel.F_CREATEDATE = DateTime.Now;
                workOrderBaseModel.F_HASTENCOUNTS = 0;
                int workid = orderBLL.AddWbgd(workOrderBaseModel);
                if (workid == 0)
                {
                    return false;
                }
                else if(workOrderBaseModel.F_REPAIRMANID == 3)
                {
                    try
                    {
                        StringBuilder returnStr = new StringBuilder();
                        string wxAddUrl = string.Format("http://rexian.zzmetro.com/api/customer/close/{0}/{1}", workOrderBaseModel.F_SERVICEWAY, workid);
                        HttpHelper.HttpGet(wxAddUrl);
                    }
                    catch (Exception ex)
                    {

                    }
                }
                workOrderBaseModel.F_WORKORDERID = workid;
            }
            return orderBLL.UpdateWorkOrderInfoModel(workOrderBaseModel);
        }


        /// <summary>
        /// 来电弹屏处理工单   新增工单
        /// </summary>
        /// <param name="workOrderBaseModel"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public bool workOrderAddDatanew(T_Wo_WorkOrderBase workOrderBaseModel)
        {
            bool bl = false;
            try
            {
                //工单来源
                workOrderBaseModel.F_REPAIRMANID = 4;
                workOrderBaseModel.F_WORKORDERFROM = "语音工单";
                string wbh = workOrderBaseModel.CustomerBaseModel.F_CustomerEName.Trim();
                if (!string.IsNullOrEmpty(wbh))
                {
                    workOrderBaseModel.F_EMPCODE = wbh;
                    workOrderBaseModel.CustomerBaseModel.F_PostCode = wbh;
                }

                //当前用户信息
                workOrderBaseModel.F_USERID = F_UserID;//id
                workOrderBaseModel.F_LINKMAN = F_UserCode;//工号
                workOrderBaseModel.F_REPAIRMANNAME = F_UserName;//姓名
                workOrderBaseModel.F_LINKMANTELEPHONE = workOrderBaseModel.CustomerBaseModel.F_Mobile;
                if (F_UserID > 0)
                {
                    T_Sys_UserAccount usermodel = new T_Sys_UserAccount();
                    usermodel = userBll.GetModel(F_UserID);
                    workOrderBaseModel.F_REPAIRMANNAME = usermodel.F_UserName;//姓名
                }
                if (workOrderBaseModel.CustomerBaseModel != null)
                {
                    //最近联络方式
                    if (workOrderBaseModel.F_REPAIRMANID.ToString() == "4")
                    { workOrderBaseModel.CustomerBaseModel.F_Kind = "3"; }
                    else
                    {
                        workOrderBaseModel.CustomerBaseModel.F_Kind = workOrderBaseModel.F_REPAIRMANID.ToString();
                    }
                    workOrderBaseModel.CustomerBaseModel.F_CustomerNature = workOrderBaseModel.F_WORKORDERFROM;
                    //业务类型
                    workOrderBaseModel.CustomerBaseModel.F_IndustryId = workOrderBaseModel.F_REPAIRLEVEL;
                    workOrderBaseModel.CustomerBaseModel.F_Url = workOrderBaseModel.F_ADSLACCOUNT;
                    workOrderBaseModel.CustomerBaseModel.F_CustomerId = Convert.ToInt32(workOrderBaseModel.F_CUSTOMERID);
                    ////客户等级
                    workOrderBaseModel.CustomerBaseModel.F_ScaleResume = "1";
                    workOrderBaseModel.CustomerBaseModel.F_CustomerClass = "一般客户";
                    //保存工单基础信息

                    //修改客户基础信息
                    int cusid = cusBLL.EditCusInfoModel(workOrderBaseModel.CustomerBaseModel);
                    if (cusid > 0)
                    {
                        workOrderBaseModel.F_CUSTOMERID = cusid;
                    }

                }
                if (workOrderBaseModel.F_WORKORDERID == 0)
                {
                    workOrderBaseModel.F_CREATEDATE = DateTime.Now;
                    workOrderBaseModel.F_HASTENCOUNTS = 0;
                    bl = orderBLL.AddWbgd(workOrderBaseModel)>0;
                }
                else
                {
                    try
                    {
                        ZXDT.CallCenter.Model.T_Wo_WorkOrderBase m = new ZXDT.CallCenter.BLL.T_Wo_WorkOrderBase().GetModel(workOrderBaseModel.F_WORKORDERID);
                        workOrderBaseModel.F_LINKMANTELEPHONE = m.F_LINKMANTELEPHONE;
                        workOrderBaseModel.F_CUSTOMERTELEPHONE = m.F_CUSTOMERTELEPHONE;
                        workOrderBaseModel.F_NUMBER = m.F_CODE;
                    }
                    catch
                    { }
                    if (workOrderBaseModel.F_SERVICETYPE == "待处理")
                    {
                        workOrderBaseModel.F_WORKORDERNAME = "手工工单";
                        return orderBLL.UpdateWorkOrderInfoModel(workOrderBaseModel);
                    }
                    else
                    {
                        workOrderBaseModel.F_WORKORDERNAME = "手工工单";
                        return orderBLL.UpdateWorkOrderInfoModel(workOrderBaseModel);
                    }

                }



            }
            catch (Exception ex) { }
            return bl;
        }



        /// <summary>
        /// 初始化列表
        /// </summary>
        /// <returns></returns>
        public ActionResult CallRecordList()
        {
            WorkOrderMyModel model = new WorkOrderMyModel();
            return View(model);

        }

        /// <summary>
        /// 听取录音
        /// </summary>
        /// <returns></returns>
        public ActionResult VoicePlay(string type, string callid)
        {
            Models.VoicePlayModel model = new VoicePlayModel();
            model.playpath = type;
            AddAction("VoicePlay", callid, "听录音", string.Format("听了callid={0}的录音", callid), "敏感信息");
            if (!string.IsNullOrEmpty(callid))
            {
                if (callid.Contains("http://"))
                {
                   
                    model.downpath = callid;
                }
                else
                {
                    BLL.rec_file_info busFile = new BLL.rec_file_info();
                    if (type == "0")
                    {
                        //录音
                         Model.rec_file_info modelfile=   busFile.GetModel(callid);
                        if (modelfile != null)
                        {
                            if (modelfile.FileName.Length > 10)
                            {
                                model.downpath = string.Format("{0}/oldyuyin/{1}", "http://10.200.46.21:8020", modelfile.FileName);
                            }
                        }

                    }
                    else if (type == "1")
                    {
                        //留言
                        model.downpath = string.Format("{0}/oldliuyan/{1}", "http://10.200.46.21:8020", callid);// GetSysconfig("newPlayPath")

                    }
                } }
            return View(model);
        }


        public ActionResult VoicePlay1(string type, string callid)
        {
            VoicePlayModel voicePlayModel = new VoicePlayModel();
            voicePlayModel.playpath = "";
            voicePlayModel.downpath = "";
            try
            {
                voicePlayModel.playpath = this.GetSrc(type, callid);
                voicePlayModel.downpath = !(type == "0") ? voicePlayModel.playpath.Replace("playvoicemail", "downvoicemail") : voicePlayModel.playpath.Replace("playbyappid", "downbyappid");
                if (!string.IsNullOrEmpty(voicePlayModel.playpath))
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    string str = HttpHelper.HttpPost(voicePlayModel.playpath, (object)null);
                    voicePlayModel.playpath = str;
                }
            }
            catch
            {
            }
            AddAction("VoicePlay1", callid, "听录音", string.Format("听了callid={0}的录音", callid), "敏感信息");
            return (ActionResult)this.View((object)voicePlayModel);
        }



        public string GetSrc(string type, string callid)
        {
            string s = "";
            BLL.T_Sys_SystemConfig bll_T_Sys_SystemConfig = new BLL.T_Sys_SystemConfig();
            try
            {
                string valueByParamCode = bll_T_Sys_SystemConfig.GetParamValueByParamCode(!(type == "0") ? "PlayLeaveVoice" : "PlayPath");
                string str = callid;
                s = str.IndexOf(":") >= 0 ? str.Replace("D:", valueByParamCode) : valueByParamCode + str;
                s = HttpUtility.HtmlEncode(s);
            }
            catch
            {
            }
            return s;
        }



        //public string GetSrc(string type, string callid)
        //{
        //    string res = "";
        //    try
        //    {
        //        string para = "PlayPath";
        //        if (type == "0")
        //        {
        //            para = "PlayPath";
        //        }
        //        else
        //        {
        //            para = "PlayLeaveVoice";
        //        }
        //        BLL.T_Sys_SystemConfig bll_T_Sys_SystemConfig = new BLL.T_Sys_SystemConfig();
        //        string CTIserverIP = bll_T_Sys_SystemConfig.GetParamValueByParamCode(para);//CTIIP

        //        string path = callid;
        //        if (path.IndexOf(":") < 0)
        //        {
        //            res = CTIserverIP + path;
        //        }
        //        else
        //        {
        //            res = path.Replace("D:", CTIserverIP);
        //        }
        //        res = HttpUtility.HtmlEncode(res);
        //    }
        //    catch
        //    {
        //    }
        //    return res;
        //}


        /// <summary>
        /// 留言管理
        /// </summary>
        /// <returns></returns>
        public ActionResult CallLeaveList()
        {
            string userid = "0";
            ZXDT.CallCenter.Model.T_Sys_UserAccount p_LoginUser = new ZXDT.CallCenter.Model.T_Sys_UserAccount();
            try
            {
                if (Request.Cookies["BaseCallCenter_T_User"] != null)
                {
                    userid = Request.Cookies["BaseCallCenter_T_User"]["F_UserId"];
                }
                int u = Convert.ToInt32(userid);
            }
            catch
            { }
            if (userid != "0")
            {
                p_LoginUser = new BLL.T_Sys_UserAccount().GetModel(Convert.ToInt32(userid));
                if (p_LoginUser != null)
                {
                    if (Request.Cookies["BaseCallCenter_T_User"] != null)
                    {
                        p_LoginUser.F_ExtensionNumber = Request.Cookies["BaseCallCenter_T_User"]["F_ExtensionNumber"];
                    }
                }
            }
            else
            {
                Response.Redirect("/Default/Login");
            }
            return View(p_LoginUser);
        }

        /// <summary>
        /// 坐席监控
        /// </summary>
        /// <returns></returns>
        public ActionResult SeatMonitoringList()
        {
            return View();
        }


        /// <summary>
        /// 获取通话记录
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页数据量</param>
        /// <param name="sqlWhere">查询条件</param>
        /// <returns></returns>
        [ActionName("CallRecordData")]
        [HttpGet]
        public string CallRecordData(DateTime? NowDateTime, int page, int limit, string callnumber, string usercode, string callType, 
            string callStatus, string dateParty,
            int F_WORKORDERTYPEID=0,string F_CONTENT="", string F_HOUSING="", string callid="0",string sort="",int ringtimes=0)
        {
            AddAction("T_Call_CallRecords", callid.ToMyString(), "获取通话记录列表", string.Format("获取{0}通话记录列表", dateParty), "敏感信息");
            //数据结果集
            ResponseData dataModel = new ResponseData();

            string sql = "";
            if (callid!="0"&&!string.IsNullOrEmpty(callid))
            {
                sql += string.Format(" and callid='{0}'", callid);
            }
            if (ringtimes > 0)
            {
                sql += string.Format(" and RingLongTime>{0}", ringtimes);
            }
            if (!string.IsNullOrEmpty(dateParty))
            {
                string startDate = dateParty.Substring(0, 10);
                string endDate = dateParty.Substring(12);
                sql += " and BeginTime>= '" + startDate + " 00:00:00" + "'";
                sql += " and BeginTime<= '" + endDate + " 23:59:59" + "'";

            }
            else
            {
                sql += " and BeginTime>= '" + DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00" + "'";
                sql += " and BeginTime<= '" + DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59" + "'";
            }
            if (!string.IsNullOrEmpty(callnumber))
            {
                sql += " and CallNumber like '%" + callnumber.Trim() + "%'";
            }
            if (!string.IsNullOrEmpty(usercode))
            {
                sql += " and UserCode like '%" + usercode.Trim() + "%'";
            }
            //呼叫类型,0呼入1呼出
            if (!string.IsNullOrEmpty(callType))
            {
                sql += " and CallType =" + callType;
            }
            //呼叫状态,0:未接通电话1已接通电话
            if (!string.IsNullOrEmpty(callStatus))
            {
                sql += " and CallState =" + callStatus;
            }

            //工单类型 F_HOUSING select F_WORKORDERTYPEID,F_CONTENT,F_HOUSING from  T_Wo_WorkOrderBase where 1=1  and  F_CONTENT like '%'++'%'

            

            //工单类型
            if (!string.IsNullOrEmpty(F_HOUSING))
            {
                //sql += string.Format("  AND  F_WorkOrderTypeId IS NOT null and T2.F_HOUSING='{0}'", F_HOUSING);
                string F_HOUSINGint = "0";
                switch (F_HOUSING)
                {
                    case "咨询":
                        F_HOUSINGint = "1";
                        break;
                    case "投诉":
                        F_HOUSINGint = "2";
                        break;
                    case "建议":
                        F_HOUSINGint = "3";
                        break;
                    case "表扬":
                        F_HOUSINGint = "4";
                        break;
                    case "挂失":
                        F_HOUSINGint = "5";
                        break;
                }
                sql += string.Format("AND F_ServiceType={0} ", F_HOUSINGint);
            }


            //呼叫状态,0:未接通电话1已接通电话
            if (!string.IsNullOrEmpty(callStatus))
            {
                sql += " and CallState =" + callStatus;
            }

            DataTable dt = new DataTable(); 
            int recordCount = 0;
            //BLL.T_Call_CallRecords busCall_CallRecords = new BLL.T_Call_CallRecords();
            //busCall_CallRecords.GetListByPage();
            Model.PageData<Model.T_Call_CallRecords_All> pageModel = new Model.PageData<Model.T_Call_CallRecords_All>();
//            dt = BLL.PagerBLL.GetTableList(
//                " (T_Call_CallRecords T1 LEFT JOIN T_Wo_WorkOrderBase T2 ON T1.CallId=T2.F_KSHADDRESSCODE ) ",
//                "CallRecordsId",
//                "T1.*,F_WORKORDERID,F_HOUSING,CONVERT(varchar,BeginTime, 120 ) as BeginTimeNew,CONVERT(varchar,TalkStartTime, 120 ) as TalkStartTimeNew,CONVERT(varchar,TalkEndTime, 120 ) as TalkEndTimeNew"
//                + @",(select top 1 F_ScaleResume from T_Cus_CustomerBase n where
//CallNumber=F_Telephone) as F_ScaleResume,
//replace(replace(FilePath,'\','/'),'" + GetSysconfig("newFilePath") + "','" + GetSysconfig("newPlayPath") + "')" +
//@" as fileurl,case
// when  BusinessType=1 then '咨询'
// when  BusinessType=2 then '建议'
// when  BusinessType=3 then '表扬'
// when  BusinessType=4 then '挂失'
// when  BusinessType=9 then '投诉'

// when  T1.F_ServiceType=1 then '咨询'
// when  T1.F_ServiceType = 2 then '投诉'
// when  T1.F_ServiceType = 3 then '建议'
// when  T1.F_ServiceType = 4 then '表扬'
// when  T1.F_ServiceType = 5 then '挂失'
// else '' end as
//BType, case when (isnull(BusinessType,0)>0 or isnull(T1.F_ServiceType,0)>0) then '人工服务' else '' end  as ywtype  ", 
//                sql,
//                // "ORDER BY LongTime,CallRecordsId desc",
//                string.IsNullOrEmpty(sort) ? " BeginTime desc":  sort + " desc"
//                ,
               
//                limit,
//                page,
//                out recordCount);



            dt = BLL.PagerBLL.GetListPager(
    " T_Call_CallRecords ",
    "CallRecordsId",
    "*," +
    "(select top 1 F_WORKORDERID from T_Wo_WorkOrderBase where F_KSHADDRESSCODE=CallId) as F_WORKORDERID," +
    "CONVERT(varchar,BeginTime, 120 ) as BeginTimeNew,CONVERT(varchar,TalkStartTime, 120 ) as TalkStartTimeNew,CONVERT(varchar,TalkEndTime, 120 ) as TalkEndTimeNew"
    + @",(select top 1 F_ScaleResume from T_Cus_CustomerBase n where
CallNumber=F_Telephone) as F_ScaleResume,
replace(replace(FilePath,'\','/'),'" + GetSysconfig("newFilePath") + "','" + GetSysconfig("newPlayPath") + "')" +
@" as fileurl,case
 when  BusinessType=1 then '咨询'
 when  BusinessType=2 then '建议'
 when  BusinessType=3 then '表扬'
 when  BusinessType=4 then '挂失'
 when  BusinessType=9 then '投诉'

 when  F_ServiceType=1 then '咨询'
 when  F_ServiceType = 2 then '投诉'
 when  F_ServiceType = 3 then '建议'
 when  F_ServiceType = 4 then '表扬'
 when  F_ServiceType = 5 then '挂失'
 else '' end as
 BType, case when (isnull(BusinessType,0)>0 or isnull(F_ServiceType,0)>0) then '人工服务' else '' end  as ywtype  ",
    sql,
    // "ORDER BY LongTime,CallRecordsId desc",
    string.IsNullOrEmpty(sort) ? "ORDER BY BeginTime desc" : "ORDER BY "+ sort + " desc"
    ,
    limit,
    page,
    true,
    out recordCount);


            dataModel.code = 0;
            dataModel.count = recordCount;
            dataModel.data = dt;
            string json = JsonConvert.SerializeObject(dataModel);
            return json;
        }

        /// <summary>
        /// 获取留言记录
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页数据量</param>
        /// <param name="sqlWhere">查询条件</param>
        /// <returns></returns>
        [ActionName("LeaveRecordData")]
        [HttpGet]
        public string LeaveRecordData(DateTime? NowDateTime, int page, int limit, string callnumber, string leavedate, string status)
        {
            AddAction("T_Call_LeaveRecord", status, "获取通话记录列表", string.Format("获取{0}留言记录列表", leavedate), "敏感信息");
            //数据结果集
            ResponseData dataModel = new ResponseData();

            string sql = "";
            if (!string.IsNullOrEmpty(callnumber))
            {
                sql += " and F_Phone like '%" + callnumber.Trim() + "%'";
            }
            //if (!string.IsNullOrEmpty(leavedate))
            //{
            //    sql += " and datediff(day,'" + leavedate + "',F_LeaveTime)=0 ";
            //}

            string startDate = "";
            string endDate = "";
            if (!string.IsNullOrEmpty(leavedate))
            {
                 startDate = leavedate.Substring(0, 10);
                 endDate = leavedate.Substring(12);
                sql += " and F_LeaveTime>= '" + startDate + " 00:00:00" + "'";
                sql += " and F_LeaveTime<= '" + endDate + " 23:59:59" + "'";

            }
            else {
                startDate = DateTime.Now.AddYears(-1).ToString("yyyy-MM-dd"); 
                endDate =  DateTime.Now.ToString("yyyy-MM-dd"); 
                sql += " and F_LeaveTime>= '" + startDate + " 00:00:00" + "'";
                sql += " and F_LeaveTime<= '" + endDate + " 23:59:59" + "'";
            }

            if (!string.IsNullOrEmpty(status))
            {
                sql += " and F_Status=" + status + " ";
            } 

            DataTable dt = new DataTable();
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                  "T_Call_LeaveRecord",
                  "F_Id",
                 "*,CONVERT(varchar,F_LeaveTime, 120 ) as F_LeaveTimeNew,CONVERT(varchar,F_DealTime, 120 ) as F_DealTimeNew"
                + ",(select top 1 F_ScaleResume from T_Cus_CustomerBase n where F_Phone=F_Telephone) as F_ScaleResume ," +
                @"replace(replace(F_RecFileUrl, '\','/'),'" + GetSysconfig("newFilePath") + "','" + GetSysconfig("newPlayPath") + "') as TheLuyin",                
                 sql,
                 "ORDER BY F_Id desc", 
                limit,
                page,
                true,
                out recordCount);


            dataModel.code = 0;
            dataModel.count = recordCount;
            dataModel.data = dt;
            if (dt != null && recordCount > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["F_RecFileUrl"].ToMyString().Contains(GetSysconfig("newFilePath").Substring(0,2)))
                    {
                        if (!System.IO.File.Exists(dr["F_RecFileUrl"].ToMyString()))
                        {
                            dr["TheLuyin"] = "";
                        }
                    }
                }
            }
            string json = JsonConvert.SerializeObject(dataModel);
            return json;
        }

        /// <summary>
        /// 留言创建工单处理
        /// </summary>
        /// <param name="LeaveOptAjax"></param>
        /// <returns></returns>
        [ActionName("LeaveOptAjax")]
        [HttpGet]
        public string LeaveOptAjax(string optaction, string timeno, string callid, string userid, string usercode, string username, string extnumber, string callernum, string leaveid)
        {
            //&timeno=" + timeno+"&callid=" + callID + "&userid=" + userid + "&usercode=" + usercode 
            //+ "&username=" + username + "&extnumber" + extnumber + "&callernum=" + callerNum
            string res = "error";
            try
            {
                switch (optaction)
                {
                    case "leaveAddOrderEvent":
                        //振铃事件
                        res = leaveAddOrderEvent(callid, userid, usercode, username, extnumber, callernum, leaveid);
                        break;
                }
            }
            catch
            { }
            return res;
        }

        #region 来电归属地查询
        public string GetPhoneLocation(string phoneNumber, bool isPhone)
        {
            string location = "未知";
            try
            {
                //如果是手机号码
                if (isPhone)
                {
                    BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                    Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModel(phoneNumber.Substring(0, 7));
                    return mobileModel != null ? (mobileModel.F_CityDes + mobileModel.F_CardDes) : location;
                }
                else//如果是电话号码 
                {
                    BLL.T_Sys_TelTitleData numbBll = new BLL.T_Sys_TelTitleData();
                    List<Model.T_Sys_TelTitleData> mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + phoneNumber.Substring(0, 4) + "'");
                    if (mobileModel == null || mobileModel.Count <= 0)
                        mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + phoneNumber.Substring(0, 3) + "'");
                    return mobileModel.Count > 0 ? mobileModel[0].F_TitleName : location;
                }
            }
            catch (System.Exception ex)
            {
                return location;
            }


        }
        #endregion

        #region 自动添加工单

        public bool SubmitOSubmit(string phone, string recordid, string callid, string locationaddress, string userid, string username, string usercode, out int workorderid)
        {
            bool bl = false;
            workorderid = 0;
            try
            {
                Model.T_Wo_WorkOrderBase model = new Model.T_Wo_WorkOrderBase();

                #region 工单信息

                //model.F_WORKORDERTYPEID = Convert.ToInt32(typeid);//类型ID
                model.F_WORKORDERSTATEID = 0;//状态ID
                model.F_REPAIRREQUEST = "未处理";
                model.F_CODE = "";//工单编号
                model.F_WORKORDERNAME = "";//工单名称
                model.F_NUMBER = model.F_CODE;
                //model.F_CUSTOMERNAME = txtCustomerName.Text.Trim();//客户姓名
                model.F_CUSTOMERTELEPHONE = phone.Trim();//客户电话
                model.F_USERID = Convert.ToInt32(userid);//坐席id
                model.F_LINKMAN = usercode.Trim();//坐席工号
                model.F_REPAIRMANNAME = username.Trim();//坐席名称
                model.F_LINKMANTELEPHONE = phone.Trim();//联系人电话
                //model.F_ADSLACCOUNT = hfCallId.Value.Trim();
                model.F_BANDWIDTH = "";
                model.F_STANDARDADDRESS = locationaddress.Trim();
                //model.F_INSTALLADDRESS = F_INSTALLADDRESS;
                model.F_KSHADDRESSCODE = callid;
                model.F_RANGEID = Convert.ToInt32(recordid);
                model.F_PROVINCE = "";
                model.F_CITY = "";
                model.F_AREA = "";
                model.F_ROAD = "";
                model.F_HOUSING = "";
                model.F_REPAIRMANID = 2;
                model.F_WORKORDERFROM = "留言工单";
                //model.F_WORKORDERLEVELID = F_WORKORDERLEVELID;
                model.F_FILEFLAG = 0;
                model.F_CREATEBY = Convert.ToInt32(userid.Trim());
                model.F_CREATEDATE = DateTime.Now;
                model.F_RETURNVISITFLAG = 0;
                model.F_RETURNVISITSTATE = 0;
                model.F_RETURNVISITRESULT = 0;
                model.F_RETURNVISITCONTENT = "";
                model.F_DELETEFLAG = 0;
                model.F_ALLUSETIMES = 0;
                model.F_STARTTIME = DateTime.Now;
                model.F_OVERTIMES = 0;
                model.F_FORMID = 0;
                model.F_HASTENCOUNTS = 0;
                model.F_RANGEX = 0;
                model.F_RANGEY = 0;
                model.F_REPAIRCLOSEMANID = 0;
                model.F_REPAIRCLOSEMANNAME = "";
                model.F_REPAIRCLOSEREASONS = "";
                model.F_REPAIRCLOSEREPTID = 0;
                model.F_REPAIRCLOSEREPT = "";

                #endregion

                int resorderbase = new BLL.T_Wo_WorkOrderBase().Add(model);//添加基本信息  
                workorderid = resorderbase;
                if (resorderbase > 0)
                {
                    bl = true;
                }
                else
                {
                    bl = false;
                }

            }
            catch (Exception ex)
            {
            }
            return bl;
        }

        #endregion

        #region 处理留言创建工单事件

        public string leaveAddOrderEvent(string callid, string userid, string usercode, string username, string extnumber, string callernum, string leaveid)
        {
            string res = "error";
            try
            {
                AddAction("leaveAddOrderEvent", callid, "创建留言工单", string.Format("{0}创建callid={1}留言工单{2}", username, callid, leaveid), "关键信息");

                Model.T_Call_CallRecords vmodel = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
                if (vmodel != null)
                {
                    string phone = callernum;
                    #region 来电归属地查询
                    string location = "";
                    //来电归属地查询
                    if (phone.Trim().Length == 11 && phone.Substring(0, 1) != "0")
                    {
                        location = GetPhoneLocation(phone, true);
                    }
                    else
                    {
                        location = GetPhoneLocation(phone, false);
                    }

                    #endregion
                    #region 创建工单
                    int workorderid = 0;
                    bool wobl = SubmitOSubmit(phone, vmodel.CallRecordsId.ToString(), callid, location, userid, username, usercode, out workorderid);
                    if (wobl)
                    {
                        //处理留言
                        #region 处理留言
                        Model.T_Call_LeaveRecord leavemodel = new BLL.T_Call_LeaveRecord().GetModel(Convert.ToInt32(leaveid));
                        if (leavemodel != null)
                        {
                            //leavemodel.F_CallAppId = workorderid.ToString();
                            //leavemodel.F_Status = 1;
                            //leavemodel.F_UserId = Convert.ToInt32(userid);
                            //leavemodel.F_UserName = username;
                            //leavemodel.F_UserCode = usercode;
                            //leavemodel.F_DealTime = DateTime.Now;
                            //leavemodel.F_DealContent = "留言创建工单";
                            //new BLL.T_Call_LeaveRecord().Update(leavemodel);

                            string strSql = @"
update T_Call_LeaveRecord set
F_CallAppId = " + workorderid.ToString() + @",F_Status = 1,
F_UserId = " + Convert.ToInt32(userid) + @",F_UserName = '" + username + @"',F_UserCode = '" + usercode + @"',F_DealTime = '" + DateTime.Now + @"',
F_DealContent = '留言创建工单' where F_Id = " + leavemodel.F_Id;
                            int rows = DbHelperSQL.ExecuteSql(strSql);

                        }
                        #endregion
                        try
                        {
                            Model.T_Call_WorkOrder modelorder = new Model.T_Call_WorkOrder();
                            modelorder.CallId = callid;
                            modelorder.F_WORKORDERID = workorderid;
                            modelorder.F_WORKORDERSTATEID = 0;
                            new BLL.T_Call_WorkOrder().Add(modelorder);
                        }
                        catch { }
                        res = workorderid.ToString();
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                //res = ex.ToString();
            }
            return res;
        }

        #endregion

        /// <summary>
        /// 获取坐席监控坐席列表
        /// </summary>
        /// <returns></returns>
        [ActionName("getseatnewlist")]
        [HttpGet]
        public string getseatnewlist()
        {
            string strHtml = "";
            string strList = "";

            DataTable dt = new DataTable();
            try
            {
                AddAction("T_Sys_UserAccount", "0", "获取坐席监控列表", "", "关键信息");

                BLL.T_Sys_UserAccount bll = new BLL.T_Sys_UserAccount();
                dt = bll.GetList(" f_seatflag=1 order by f_userid desc ").Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        strList += dt.Rows[i]["F_WorkNumber"] + ",";// "-" + dt.Rows[i]["ExtensionCode"] + ",";
                        strHtml += "<div id=\"div_" + dt.Rows[i]["F_WorkNumber"] + "\"  style='float: left; width: 120px; height: 120px; text-align: center; padding: 8px;cursor:pointer'>";
                        strHtml += "<div style='height: 90px; border: 1px solid #CCCCCC; padding: 3px; text-align: center;cursor:pointer'";
                        strHtml += "onmouseover=\"this.style.border='1px solid #3A8BDC'\" onmouseout=\"this.style.border='1px solid #CCCCCC'\">";
                        strHtml += "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\" height=\"100%\" style=\"text-align: center;cursor:pointer\" ";
                        strHtml += "  onclick=\"GetOneState('" + dt.Rows[i]["F_WorkNumber"] + "','"+ dt.Rows[i]["ExtensionCode"] + "','" + dt.Rows[i]["F_UserName"] + "')\">";
                        strHtml += " <tr><td><input type=\"text\" id=\"" + dt.Rows[i]["F_WorkNumber"] + "\" style=\"display: none\" /><input type=\"text\" id=\"txtSeatState_" + dt.Rows[i]["F_WorkNumber"] + "\" value=\"0\" style=\"display: none\" />";
                        strHtml += "   <span id=\"span_" + dt.Rows[i]["F_WorkNumber"] + "\" style=\"color: #000000;\">";
                        strHtml += dt.Rows[i]["F_WorkNumber"] + "(" + dt.Rows[i]["F_UserName"] + ")</span>";
                        strHtml += "</td></tr> <tr> <td><img id=\"img_" + dt.Rows[i]["F_WorkNumber"] + "\" src=\"/Content/images/seatimgs/weiqianru.jpg\" />";
                        strHtml += "</td></tr><tr><td><span id=\"span_state_" + dt.Rows[i]["F_WorkNumber"] + "\" style=\"color: #cccccc;\">未签入</span>";
                        strHtml += " </td></tr></table></div></div>";
                    }

                }
                strList += "!@#";
                strList = strList.Replace(",!@#", "").Replace("!@#", "");
            }
            catch
            {
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
            }
            return strList + "~" + strHtml;
        }





        //外呼判断本地外地以及加前缀返回
        [ActionName("GetCallOutprefix")]
        [HttpGet]
        public string  GetCallOutprefix(string phone)      {

            AddAction("T_Sys_UserAccount", phone, "外呼获取外呼前缀", phone);

            string phone1 = RequestString.ToDBC(RequestString.RemoveNotNumber(StringHelper.NoHTML(phone)));
                string tophone = phone1;
                string zipcode = ""; string bfix = ""; string wfix = ""; string fix = "";
            // string userseatgroupid = CurrentUser.UserData.F_SeartGroupID.ToString();
            //if (userseatgroupid != "" && userseatgroupid != "0")
            //{

            //Model.T_Sys_SeatGroup smodel = new BLL.T_Sys_SeatGroup().GetModel(int.Parse(userseatgroupid));
            //if (smodel != null)
            //{
            zipcode = "0371";
            bfix ="9";
            wfix = "90";
            //}
            //}
            int zip = GetZipCodeByPhone(phone1, zipcode);
            #region 
            if (zip == 0)
            {//没有号码归属地

            }
            else if (zip == 1)
            {//手机本地号码
                fix = bfix;
            }
            else if (zip == 2)
            {//手机外地号码
                fix = wfix;
            }
            else
            {
                //tophone = phone1.TrimStart('0');
                //if (zip == 3)
                //{//本地固话去0加9 比如：988888517，937188888517
                //    fix = bfix;
                //}
                //else if (zip == 4)
                //{//外地固话前加9 比如：9037188888517
                //    fix = wfix;
                //}

                //固话前加9不管是本地还是外地
                fix = bfix;
            }

            #endregion
            var obj = new
                {
                    phone = fix + tophone,
                    fix = fix
                };

                return fix;
               // return Success("外呼号码加前缀" + phone, obj);
          
        }


        /// <summary>
        /// 根据号码和区号判断号码是否为归属地号码
        /// 返回0为分机号或特殊号码
        /// 返回1为手机本地号码
        /// 返回2为手机外地号码
        /// 返回3为固定电话本地号码
        /// 返回4为固定电话外地号码
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="zipcode"></param>
        /// <returns></returns>
        [NonAction]
        public int GetZipCodeByPhone(string phone, string zipcode)
        {
            int n = 0;
            if (phone.Trim().Length >= 7)
            {
                //7位及7位以上是固定电话或手机
                //判断是否手机
                if (phone.Trim().Length == 11 && phone[0] == '1')
                {//号码为11位，首位是1，为手机号
                    BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                    Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModelList("F_MobileNum='" + phone.Substring(0, 7) + "'").FirstOrDefault();
                    if (mobileModel != null)
                    {
                        if (mobileModel.F_ZipCode.Equals(zipcode))
                        {
                            return 1;
                        }
                        else
                        {
                            return 2;
                        }
                    }
                }
                else
                {
                    //if (phone.Trim().Length == 11)
                    //{//号码为11位
                    //    //截取前三位区号判断是否本地
                    //    bool resbd3 = phone.Substring(0, 3).Equals(zipcode);
                    //    //截取前四位区号判断是否本地
                    //    bool resbd4 = phone.Substring(0, 4).Equals(zipcode);
                    //    if (resbd3 || resbd4)
                    //    {
                    //        return 3;
                    //    }
                    //    else
                    //    {
                    //        return 4;
                    //    }
                    //}
                    //else if (phone.Trim().Length < 11)
                    //{//号码小于11位，为本地
                    //    return 3;
                    //}
                    //else if (phone.Trim().Length > 11 && phone.Substring(0, 4).Equals(zipcode))
                    //{//号码大于11位，截取前四位区号判断是否本地
                    //    return 3;
                    //}
                    //else
                    //{
                    //    return 4;
                    //}
                    return 3;
                }
            }

            else
            {
                return 3;
            }

            return n;
        }

        /// <summary>
        /// 获取来电业务类型  
        /// </summary>
        /// <param name="CallId">通话记录Callid </param>
        /// <returns></returns>
        [ActionName("GetCallType")]
        [HttpGet]
        public string GetCallType(string CallId)
        {

            //数据结果集
            ResponseData dataModel = new ResponseData();
            //来电业务类型
            string sql = " select  F_ServiceType  from  T_Call_CallRecords where CallId='" + CallId + "'   order by BeginTime desc ";
            //排队数量
           // string sql2 = " select  COUNT(CallId) as  CallId from  T_Call_CallRecords where F_linenum=1  ";

            DataTable dt = new DataTable();
            DataSet ds = DbHelperSQL.Query(sql);
            dt = ds.Tables[0];
            //来电业务类型
            dataModel.code = Convert.ToInt32(dt.Rows[0]["F_ServiceType"].ToString() == "" ? "0" : dt.Rows[0]["F_ServiceType"].ToString());

            //DataTable dt2 = new DataTable();
            //DataSet ds2 = DbHelperSQL.Query(sql2);
            //dt2 = ds2.Tables[0];
            ////排队数量
            //dataModel.msg = dt2.Rows[0]["CallId"].ToString() == "" ? "0" : dt2.Rows[0]["CallId"].ToString();

            // dataModel.count = recordCount;
            // dataModel.data = dt;
            string json = JsonConvert.SerializeObject(dataModel);
            return json;
        }

        /// <summary>
        /// 获取排队数量
        /// </summary>
        /// <param name="CallId">通话记录Callid </param>
        /// <returns></returns>
        [ActionName("GetCallLineNum")]
        [HttpGet]
        public string GetCallLineNum()
        {

            //数据结果集
            ResponseData dataModel = new ResponseData();
             //排队数量
            string sql2 = " select  COUNT(CallId) as  CallId from  T_Call_CallRecords where F_linenum=1  and isnull(TalkStartTime,0)=0 ";
            DataTable dt2 = new DataTable();
            DataSet ds2 = DbHelperSQL.Query(sql2);
            dt2 = ds2.Tables[0];
            //排队数量
            dataModel.code = Convert.ToInt32(dt2.Rows[0]["CallId"].ToString() == "" ? "0" : dt2.Rows[0]["CallId"].ToString());

            // dataModel.count = recordCount;
            // dataModel.data = dt;
            string json = JsonConvert.SerializeObject(dataModel);
            // return json;
            return dataModel.code.ToString();
        }

    }
}
