using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Controllers.workorder;
using CallCenterApi.Interface.Models.Enum;
using CallCenterAPI.WechatSDK;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.tel
{
    public class CallInScreenController : BaseController
    {
        private BLL.T_Sys_UserAccount sysUserAccountBll = new BLL.T_Sys_UserAccount();
        private BLL.T_Sys_Department sysDeptBll = new BLL.T_Sys_Department();
        private BLL.T_Sys_DictionaryValue dicvalueBll = new BLL.T_Sys_DictionaryValue();
        /// <summary>
        /// 添加黑名单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddBlack()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (ua != null)
                    {
                        string tel = HttpUtility.UrlDecode(RequestString.GetFormString("tel"));
                        string callid = HttpUtility.UrlDecode(RequestString.GetFormString("callid"));
                        int n = RequestString.GetInt("num", 0);
                        int type = RequestString.GetInt("type", 0);
                        Model.T_Call_Blacklist dModel = new BLL.T_Call_Blacklist().GetModelList(" F_TelPhone='" + tel + "' ").FirstOrDefault();

                        var date = DateTime.Now;
                        var enddate = date;
                        switch (type)
                        {
                            case 1: enddate = enddate.AddDays(n); break;
                            case 2: enddate = enddate.AddHours(n); break;
                            case 3: enddate = enddate.AddMinutes(n); break;
                            case 4: enddate = DateTime.MaxValue; break;
                        }
                        if (dModel == null)
                        {
                            dModel = new Model.T_Call_Blacklist();
                            dModel.F_CallId = callid;
                            dModel.F_TelPhone = tel.Trim();
                            dModel.F_SetTime = date;
                            dModel.F_RemoveTime = enddate;
                            dModel.F_InterceptNum = 1;
                            dModel.F_UserId = ua.F_UserId;
                            int b = new BLL.T_Call_Blacklist().Add(dModel);
                            if (b > 0)
                            {
                                res = Success("添加成功", enddate.ToString("yyyy-MM-dd HH:mm:ss"));
                            }
                            else
                            {
                                res = Error("添加失败");
                            }
                        }
                        else
                        {

                            dModel.F_RemoveTime = enddate;
                            if (new BLL.T_Call_Blacklist().Update(dModel))
                            {
                                res = Success("修改成功", enddate.ToString("yyyy-MM-dd HH:mm:ss"));
                            }
                            else
                            {
                                res = Error("修改失败");
                            }
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 取消黑名单
        /// </summary>
        /// <returns></returns>
        public ActionResult DelBlack()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
                Model.T_Call_Blacklist dModel = new BLL.T_Call_Blacklist().GetModelList(" F_TelPhone='" + tel + "' ").FirstOrDefault();

                if (dModel != null)
                {
                    bool bl = new BLL.T_Call_Blacklist().Delete(dModel.F_BlackId);
                    if (bl)
                    {
                        res = Success("取消成功");
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 根据来电号码获取客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCustomerByTel()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
                //var sql = $" and (F_LegalTel like '%" + tel.Trim() + "%') or  F_CustomerId in (select F_CustomerId from T_Cus_ContactPersonNew where F_Telephone like '%" + tel.Trim() + "%')";
                var sql = $" ( F_CompanyName like '%" + tel.Trim() + "%' or F_CustomerCode like '%" + tel.Trim() + "%' ) ";

                var userModel = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_DeleteFlag = 0 " + sql);
                if (userModel.Count() > 0)
                {
                    var model = userModel.Last();
                    int cusid = model.F_CustomerId;
                    //var conlist = new BLL.T_Cus_ContactPersonNew().GetModelList(" F_DeleteFlag=0 and  F_CustomerId=" + cusid);
                    #region 绑定部门
                    //var deptname = "";
                    //var deptmodel = new BLL.T_Sys_Department().GetModel(model.F_BeDept.Value);
                    //if (deptmodel != null)
                    //    deptname = deptmodel.F_DeptName;
                    #endregion
                    var obj = new
                    {
                        CustomerBase = model,
                        //BeDeptName = deptname,
                        //ContactList = conlist,
                    };
                    return Success("获取成功", obj);
                }
            }
            return res;
        }

        /// <summary>
        /// 根据来电号码获取最近的callid
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCallIdByPhone()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                DataTable dt = new DataTable();

                string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
                Model.T_Call_CallRecords model = new BLL.T_Call_CallRecords().GetModelByTelphone(tel);

                res = Success("加载成功", model);

            }
            return res;
        }

        /// <summary>
        /// 根据callid获取最近的通话记录
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTelRecordByCallid()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                DataTable dt = new DataTable();

                string callid = HttpUtility.UrlDecode(RequestString.GetQueryString("callid"));
                Model.T_Call_CallRecords model = new BLL.T_Call_CallRecords().GetModelByCallId(callid);

                res = Success("通话记录加载成功", model);

            }
            return res;
        }

        /// <summary>
        /// 来电归属地查询
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPhoneLocation()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string location = "未知";

                string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
                if (tel.Trim().Length == 11 && tel.Substring(0, 1) != "0")
                {
                    BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                    Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModelList(" F_MobileNum='" + tel.Substring(0, 7) + "' ").FirstOrDefault();

                    if (mobileModel != null)
                    {
                        location = mobileModel.F_CityDes + mobileModel.F_CardDes;
                    }
                }
                else
                {
                    BLL.T_Sys_TelTitleData numbBll = new BLL.T_Sys_TelTitleData();
                    List<Model.T_Sys_TelTitleData> mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + tel.Substring(0, 4) + "'");
                    if (mobileModel == null || mobileModel.Count <= 0)
                    {
                        mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + tel.Substring(0, 3) + "'");
                    }
                    if (mobileModel.Count > 0)
                    {
                        location = mobileModel[0].F_TitleName;
                    }
                }

                res = Success("归属地加载成功", location);

            }
            return res;
        }

        /// <summary>
        /// 历史记录列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOldList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (ua != null)
                    {
                        string sql = "";
                        string sqlcount = "";
                        DataTable dt = new DataTable();
                        //来电号码
                        string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
                        string strcalltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
                        string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
                        string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

                        string strpageindex = RequestString.GetQueryString("pageindex");
                        int pageindex = 1;
                        string strpagesize = RequestString.GetQueryString("pagesize");
                        int pagesize = 10;
                        //除管理员外，各坐席只能看到自己的
                        //20180507 每个人都能看到该来电的所有历史记录 machenyang
                        //if (ua.F_RoleId != 17)
                        //    sql += " and UserId = '" + userId + "'";
                        ////20180514 坐席能看到同组的 
                        //var usergroup = ua.F_SeartGroup;
                        //var usercodes = new BLL.T_Sys_UserAccount().GetModelList("F_SeartGroup='" + usergroup + "'") == null ? null : new BLL.T_Sys_UserAccount().GetModelList("F_SeartGroup='" + usergroup + "'").Select(p => p.F_UserCode);
                        //var str = "";
                        //if (usercodes != null)
                        //{
                        //    foreach (var item in usercodes)
                        //    {
                        //        str += item.ToString() + ',';
                        //    }
                        //    str = str.TrimEnd(',');
                        //    sql += " and UserCode in ("+str+") ";
                        //}
                        //else
                        //    sql += " and UserCode='"+ua.F_UserCode+"' ";

                        if (strcalltype.Trim() != "" && strcalltype != "undefined")
                        {
                            sql += " and CallType=" + strcalltype + " ";
                        }
                        if (strtel.Trim() != "" && strtel != "undefined")
                        {
                            sql += " and CallNumber= '" + strtel.Trim() + "' ";
                            sqlcount += " and CallNumber= '" + strtel.Trim() + "' ";
                        }
                        //else
                        //{
                        //    sql += " and 1=0 ";
                        //}
                        if (strstarttime.Trim() != "" && strstarttime != "undefined")
                        {
                            sql += " and datediff(day,BeginTime,'" + strstarttime + "')<=0 ";
                            sqlcount += " and datediff(day,BeginTime,'" + strstarttime + "')<=0 ";
                        }
                        if (strendtime.Trim() != "" && strendtime != "undefined")
                        {
                            sql += " and datediff(day,BeginTime,'" + strendtime + "')>=0   ";
                            sqlcount += " and datediff(day,BeginTime,'" + strendtime + "')>=0   ";
                        }

                        if (strpageindex.Trim() != "")
                        {
                            pageindex = Convert.ToInt32(strpageindex);
                        }

                        if (strpagesize.Trim() != "")
                        {
                            pagesize = Convert.ToInt32(strpagesize);
                        }
                        int recordCount = 0;
                        dt = BLL.PagerBLL.GetListPager(
                            "T_Call_CallRecords",
                            "CallRecordsId",
                            "*",
                            sql,
                            "ORDER BY CallRecordsId desc",
                            pagesize,
                            pageindex,
                            true,
                            out recordCount);
                        dt.Columns.Add("CusName");
                        var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
                        foreach (DataRow dr in dt.Rows)
                        {
                            string path = dr["FilePath"] != null ? dr["FilePath"].ToString() : "";
                            if (path != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                            {
                                var ym = config.F_ParamValue;
                                if (ym.Substring(ym.Length - 1) == "/")
                                {
                                    ym = ym.Substring(0, ym.Length - 1);
                                }
                                dr["FilePath"] = ym + path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                            }
                            string tephone = dr["CallNumber"] != null ? dr["CallNumber"].ToString() : "";
                            if (!string.IsNullOrEmpty(tephone))
                            {
                                Model.T_Cus_CustomerBaseNew cus = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_LegalPhone ='" + tephone + "'  ")
                     .FirstOrDefault();
                                if (cus != null)
                                {
                                    dr["CusName"] = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_LegalPhone ='" + tephone + "'  ")
                           .FirstOrDefault().F_Legal;
                                }
                            }
                        }

                        int hrcount = new BLL.T_Call_CallRecords().GetRecordCount(" calltype=0 " + sqlcount);
                        int hccount = new BLL.T_Call_CallRecords().GetRecordCount(" calltype=1 " + sqlcount);
                        
                        var obj = new
                        {
                            state = "success",
                            message = "成功",
                            rows = dt,
                            total = recordCount,
                            hrcount = hrcount,
                            hccount = hccount,
                        };
                        res = Content(obj.ToJson());
                    }
                }
            }
            return res;
        }
        public DataTable GetFileData(string ids, string prefix)
        {
            DataTable dt = new DataTable();
            if (!string.IsNullOrEmpty(ids))
            {
                dt = DbHelperSQL.Query("select * from T_Sys_Accessories where F_FileId in (" + ids + ")").Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
                }
            }
            return dt;
        }
        /// <summary>
        /// 获取最新知识库
        /// </summary>
        /// <returns></returns>
        public ActionResult GetZSKList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                DataTable dt = new DataTable();
                string pid = HttpUtility.UrlDecode(RequestString.GetQueryString("pid"));
                string keywords = HttpUtility.UrlDecode(RequestString.GetQueryString("keywords"));
                var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                DataTable FileUrl = new DataTable();

                int topNum = 8;
                string sql = " F_DeleteFlag=0";
                if (pid.Trim() != "")
                {
                    sql += " and F_CategoryId=" + pid.Trim();
                }
                if (keywords.Trim() != "")
                {
                    sql += " and (F_Content like '%" + keywords.Trim() + "%' or F_Title like '%"
                        + keywords.Trim() + "%' or F_KeyWords like '%" + keywords.Trim() + "%')";
                    topNum = 0; //为零时不限制条数

                }

                dt = new BLL.T_RepositoryInformation().GetList(topNum, sql, " F_RepositoryId desc").Tables[0];
               List <Model.T_RepositoryInformation> modellist= new BLL.T_RepositoryInformation().DataTableToList(dt);
               
             
                var obj=new 
                {
                    rows = modellist.Select(x => new
                    {
                        F_RepositoryId = x.F_RepositoryId,
                        F_CategoryId = x.F_CategoryId,
                        F_CustomerId = x.F_CustomerId,
                        F_CustomerName = x.F_CustomerName,
                        F_ManId = x.F_ManId,
                        F_ManName = x.F_ManName,
                        F_Title = x.F_Title,
                        F_Content = x.F_Content,
                        F_Description = x.F_Description,
                        F_Comments = x.F_Comments,
                        F_Url = x.F_Url,
                        F_KeyWords = x.F_KeyWords,
                        F_Expand1 = x.F_Expand1,
                        F_Expand2 = x.F_Expand2,
                        F_IntExpand1 = x.F_IntExpand1,
                        F_CreateOn = x.F_CreateOn,
                        F_CreateBy = x.F_CreateBy,
                        F_CreateName = x.F_CreateName,
                        F_ModifyOn = x.F_ModifyOn,
                        F_ModifyBy = x.F_ModifyBy,
                        F_ModifyName = x.F_ModifyName,
                        F_DeleteFlag = x.F_DeleteFlag,
                        FileUrl = GetFileData(x.F_Expand2, configfj.F_ParamValue)
                    }),

                };
                res = Success("加载成功", obj);

            }
            return res;
        }

        /// <summary>
        /// 振铃事件
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateZL()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (ua != null)
                    {
                        Model.T_Call_CallRecords model = new Model.T_Call_CallRecords();
                        model.CallId = RequestString.GetFormString("callid");
                        //model.UserId = ua.F_UserId;
                        //model.UserCode = ua.F_UserCode;
                        //model.UserName = ua.F_UserName;
                        ////model.ExtNumber = ua.F_WorkNumber;
                        //model.ExtNumber = CurrentUser.UserData.F_ExtensionNumber;

                        model.DealType = 5;
                        bool bl = new BLL.T_Call_CallRecords().UpdateCallInRingTelRecord(model);
                        if (bl)
                        {
                            res = Success("更新振铃状态成功");
                        }
                        else
                        {
                            // res = Error("更新振铃状态失败");
                            res = Success("更新振铃状态失败");
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 摘机事件
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateZJ()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                Model.T_Call_CallRecords model = new Model.T_Call_CallRecords();
                model.CallId = RequestString.GetFormString("callid");
                model.CallState = 1;
                model.DealType = 6;
                bool bl = new BLL.T_Call_CallRecords().UpdateCallInAnswerTelRecord(model);
                if (bl)
                {
                    Model.T_Call_CallRecords vmodel = new BLL.T_Call_CallRecords().GetModelByCallId(model.CallId);
                    string type = vmodel.OperateType.ToString();
                    if (type == "7")
                    {
                        new BLL.T_Call_TaskTelNum().UpdateYJ(Convert.ToInt32(vmodel.OperateObject.ToString()), 1);
                    }

                    res = Success("更新摘机状态成功");
                }
                else
                {
                    //res = Error("更新摘机状态失败");
                    res = Success("更新摘机状态失败");
                }

            }
            return res;
        }

        /// <summary>
        /// 挂机事件
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateGJ()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                string strid = RequestString.GetFormString("callid");
                bool bl = new BLL.T_Call_CallRecords().UpdateCallInHookTelRecord(strid);
                if (bl)
                {
                    res = Success("更新挂机状态成功");
                }
                else
                {
                    res = Success("更新挂机状态失败");
                }

            }
            return res;
        }

        /// <summary>
        /// 录音事件
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateLY()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                Model.T_Call_CallRecords model = new Model.T_Call_CallRecords();
                model.CallId = RequestString.GetFormString("callid");
                model.CallState = 1;
                model.DealType = 6;
                //model.FilePath = RequestString.GetFormString("path");
                bool bl = new BLL.T_Call_CallRecords().UpdateCallInPathTelRecord(model);
                if (bl)
                {
                    Model.T_Call_CallRecords vmodel = new BLL.T_Call_CallRecords().GetModelByCallId(model.CallId);
                    string type = vmodel.OperateType.ToString();
                    if (type == "7")
                    {
                        new BLL.T_Call_TaskTelNum().UpdateYJ(Convert.ToInt32(vmodel.OperateObject.ToString()), 1);
                    }

                    res = Success("更新挂机状态成功");
                }
                else
                {
                    res = Success("更新挂机状态失败");
                }

            }
            return res;
        }

        /// <summary>
        /// 创建工单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrder()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                if (ua != null)
                {

                    //工单来源
                    string source = RequestString.GetFormString("source");
                    //工单类型
                    int gdlx = RequestString.GetFormInt("gdlx", 0);
                    //业务类型
                    int ywlx = RequestString.GetFormInt("ywlx", 0);
                    //客户id
                    int customerid = RequestString.GetFormInt("customerid", 0);
                    //客户姓名
                    string callCustomer = RequestString.GetFormString("callCustomer");
                    //公司名称
                    string company = RequestString.GetFormString("company");
                    //联系电话
                    string tel = RequestString.GetFormString("tel");
                    //受理人 - 审核人工号
                    string auditusercode = RequestString.GetFormString("auditusercode");
                    //接待描述 - 反馈内容
                    string fkcont = RequestString.GetFormString("fkcont");
                    string callid = HttpUtility.UrlDecode(RequestString.GetFormString("callid"));
                    //是否有效工单项(0有效，1无效)
                    int iseffective = RequestString.GetFormInt("iseffective", 0);
                    //咨询类工单指派部门
                    int clbm = RequestString.GetFormInt("clbm", 0);
                    //咨询类工单指派接收人
                    int clid = RequestString.GetFormInt("clid", 0);
                    //备注
                    string note = RequestString.GetFormString("note");
                    //是否结束
                    int isover = RequestString.GetFormInt("isover", 0);

                    #region 添加验证判断
                    if (string.IsNullOrEmpty(callCustomer))
                        return Error("姓名不能为空！");
                    if (string.IsNullOrEmpty(tel))
                        return Error("电话不能为空！");
                    if (clbm != 0 && clid == 0)
                        return Error("请选择接收人");
                    #endregion
                    #region
                    //Model.T_Wo_WorkOrder model = new Model.T_Wo_WorkOrder();
                    //model.WorkOrderID = DateTime.Now.ToString("yyyyMMddHHmmssfff");  //工单编号                        
                    //model.Type = gdlx;              //工单类型                    
                    //model.TypeClass = ywlx;         //业务办理-数据字典读取
                    //model.Customer = callCustomer;  //客户姓名
                    //model.CustomerTel = tel;        //联系电话  
                    //model.CustomerID = customerid;  //用户档案Id
                    //model.County = company;//公司名称
                    //model.IsAudit = 1;     //是否需要审核（0未审核，1已审核）pc端默认审核，微信端默认为审核
                    //model.IsEffective = iseffective;
                    //if (iseffective == 1)
                    //    model.Province = System.Web.HttpUtility.UrlDecode(note, System.Text.Encoding.UTF8); //备注
                    //model.Source = source;  //工单来源
                    //model.AuditUser = auditusercode;  //受理人 - 审核人工号
                    //model.State = (int)EnumWorkOrderState.neworder;//0;    //工单状态
                    //model.ResponDept = clbm;//指派部门
                    //#region 获取接收人
                    //string touser = ""; string tousername = "";
                    //if (clid != 0)
                    //{
                    //    Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModel(clid);
                    //    if (clus != null)
                    //    {
                    //        touser = clus.F_UserCode;
                    //        tousername = clus.F_UserName + "(" + touser + ")";
                    //    }
                    //}
                    //else
                    //{
                    //    string users = string.Empty;
                    //    var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
                    //    foreach (var l in list)
                    //    {
                    //        if (string.IsNullOrEmpty(users))
                    //        {
                    //            users = l.F_UserCode;
                    //            tousername = l.F_UserName + "(" + l.F_UserCode + ")";
                    //        }
                    //        else
                    //        {
                    //            users = users + "," + l.F_UserCode;
                    //            tousername = tousername + "," + l.F_UserName + "(" + l.F_UserCode + ")";
                    //        }
                    //    }
                    //    touser = users;
                    //}
                    //#endregion
                    //model.F_IsOver = isover;
                    //if (isover == 1)
                    //{
                    //    model.LastDealUser = usercode;
                    //    model.LastDealTime = DateTime.Now;
                    //    model.State = (int)EnumWorkOrderState.finish;//2;
                    //}
                    //else
                    //{
                    //    //无接收人时，状态修改成 0待指派
                    //    if (clid == 0)
                    //    {
                    //        model.State = (int)EnumWorkOrderState.neworder;    //工单状态 待指派
                    //    }
                    //    else
                    //    {
                    //        model.AuditUser = touser;
                    //        model.State = (int)EnumWorkOrderState.assign;    //待处理
                    //    }
                    //}
                    ////接待描述 - 反馈内容
                    //var detailutf8 = System.Web.HttpUtility.UrlDecode(fkcont, System.Text.Encoding.UTF8);
                    //model.Detail = detailutf8;
                    //model.CallID = callid;      //存入callid             
                    //model.CreateTime = DateTime.Now;
                    //model.IsDel = 0;
                    //model.IsReturn = 0;
                    //model.IsReturnBak = 0;
                    //model.Answer = "";
                    //model.CreateUser = usercode;
                    //long orderid = new BLL.T_Wo_WorkOrder().Add(model);
                    //if (orderid > 0)
                    //{
                    //    #region 创建工单 处理记录
                    //    var opt = "创建工单"; int optbut = (int)EnumItemOpt.create;
                    //    string deptname = "";
                    //    if (!string.IsNullOrWhiteSpace(touser))
                    //    {
                    //        #region 读取当前登录人部门
                    //        var deptmodel = sysDeptBll.GetModel(ua.F_DeptId);
                    //        if (deptmodel != null)
                    //        {
                    //            deptname = deptmodel.F_DeptName + "-";
                    //        }
                    //        #endregion
                    //        opt = "创建并指派工单给" + tousername;
                    //        optbut = (int)EnumItemOpt.assign;
                    //    }
                    //    if (isover == 1)
                    //        opt = "创建并处理完结工单"; optbut = (int)EnumItemOpt.end;
                    //    var content = deptname + ua.F_UserName + "(" + ua.F_UserCode + ")" + opt;
                    //    var itemid = new WorkOrderController().AddLog((int)orderid, model.State.Value, content, (int)EnumItemType.deal, optbut, touser, clbm, "", 0, "", "", ua);
                    //    if (itemid > 0)
                    //    {
                    //        if (!string.IsNullOrWhiteSpace(touser))
                    //        {
                    //            model.ID = orderid;
                    //            new WorkOrderController().sendsysmsg(model, ua, touser, (int)orderid, opt);//推送系统消息
                    //            var modelUser2 = sysUserAccountBll.GetModel(touser);  //被指派人
                    //            if (modelUser2 != null)
                    //            {
                    //                if (!string.IsNullOrEmpty(modelUser2.F_WxOpenId))
                    //                {
                    //                    new WorkOrderController().sendwxmsg(model, modelUser2.F_WxOpenId, ua, "指派");
                    //                }
                    //            }
                    //        }
                    //    }
                    //    #endregion
                    //    #region 通话记录绑定工单
                    //    if (!string.IsNullOrEmpty(callid))
                    //    {
                    //        var rec = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
                    //        if (rec != null)
                    //        {
                    //            rec.IsExitWorkOrder = true;
                    //            new BLL.T_Call_CallRecords().Update(rec);
                    //        }
                    //    }
                    //    #endregion
                    //    return Success("新增成功！");
                    //}
                    //else
                    //{
                    //    return Error("新增失败！");
                    //}
                    #endregion
                }
            }
            return Error("未知错误，请重新登录");
        }

        /// <summary>
        /// 获取受理人下拉 by 部门，区域，项目、期，案场经理
        /// </summary>
        /// <param name="depid">部门id</param>
        /// <param name="arearid">区域id</param>
        /// <param name="proid">项目id</param>
        /// <returns></returns>
        public ActionResult GetUserListByBuildingidDrop(int depid = 0, int arearid = 0, int proid = 0)
        {
            //查询条件是根据：受理人（销售类直接根据项目名称、房间号关联下拉点选各案场经理；物业类直接根据项目名称、房间号关联下拉框点选各物业负责人；客服类直接根据项目名称、房间号关联下拉框点选各区域客服）
            string sql = " F_DeleteFlag = 0 ";
            bool isExists = false;
            //SELECT TOP 1 F_DeptId FROM dbo.T_Sys_Department  这个地方排序有要求，部门排序要求

            int depRegion = 0;
            if (depid == 0)
                return Error("请选择接收部门");
            if (depid > 0)
            {
                ////部门信息
                //var modelDep = new BLL.T_Sys_Department().GetModel(depid);
                //if (modelDep != null)
                //{
                //    depType = modelDep.F_Type ?? 0;  //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                //    depRegion = modelDep.F_Header ?? 0; //部门权限范围：9全部，1区域，2项目，3期
                //}
                //通过一级栏目查到一级栏目中的第一条部门信息
                var list = new BLL.T_Sys_Department().DataTableToList(new BLL.T_Sys_Department().GetList($" F_ParentId = {depid} ").Tables[0]);
                var modelDep = list.FirstOrDefault();
                //部门信息
                //modelDep = new BLL.T_Sys_Department().GetModel(deptid);
                if (modelDep != null)
                {
                    depRegion = modelDep.F_Header ?? 0;  //部门权限范围：9全部，1区域，2项目，3期  
                    //deptids = modelDep.F_DeptId;
                }
                sql += $" and F_DeptId = (SELECT TOP 1 F_DeptId FROM dbo.T_Sys_Department WHERE F_ParentId = {depid} ORDER BY F_Sort ASC) ";
                //sql += $" and (F_DeptId = (SELECT TOP 1 F_DeptId FROM dbo.T_Sys_Department WHERE F_ParentId = {depid} ORDER BY F_Sort ASC) or F_DeptId = {depid}) ";
            }

            if (depRegion == 1)
            {
                //if (arearid == 0)
                //    return Error("请选择区域下拉");
                if (arearid > 0)
                {
                    isExists = true;
                    sql += $" AND RegionId = {arearid} ";
                }
            }
            else
            {
                //if (proid == 0)
                //    return Error("请选择项目下拉");
                if (proid > 0)
                {
                    isExists = true;
                    sql += $" AND RegionId = {proid} ";
                }
            }
            if (isExists)
            {
                var listUser = sysUserAccountBll.GetModelList(sql + " order by f_userid desc ");
                var rows = listUser.Select(x => new
                {
                    F_UserId = x.F_UserId,
                    F_UserCode = x.F_UserCode,
                    F_ExtensionNumber = x.F_ExtensionNumber,
                    F_UserName = x.F_UserName,
                    F_DeptId = x.F_DeptId,
                    F_RoleId = x.F_RoleId,
                    F_SeatFlag = x.F_SeatFlag
                });
                return Success("列表加载成功", listUser);
            }
            else
            {
                return Success("列表加载成功", null);
            }
        }

        /// <summary>
        /// 获取当前坐席所在部门及坐席组
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCurrUserDep()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                int? groid =int .Parse ( CurrentUser.UserData.F_SeartGroupID);
                //string groname = CurrentUser.UserData.F_SeartGroup;
                string groname = "", grocode = "";
                string depname = "";
                int depid = CurrentUser.UserData.F_DeptId;
                if (depid != 0)
                {
                    Model.T_Sys_Department depModel = new BLL.T_Sys_Department().GetModel(depid);
                    if (depModel != null)
                    {
                        depname = depModel.F_DeptName;
                        Model.T_Sys_SeatGroup groModel = new BLL.T_Sys_SeatGroup().GetModel(groid == null ? 0 : int.Parse(groid.ToString()));
                        if (groModel != null)
                        {
                            groname = groModel.F_ZXZName;
                            grocode = groModel.F_ZXZCode;
                        }

                    }
                }
                var obj = new
                {
                    depid = depid,
                    depname = depname,
                    groid = groid,
                    groname = groname,
                    grocode = grocode
                };
                res = Success("获取坐席部门成功！", obj);
            }
            return res;
        }

        /// <summary>
        /// 获取所有坐席
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUsers()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                List<Model.T_Sys_UserAccount> userModel = new BLL.T_Sys_UserAccount().GetModelList("F_DeleteFlag=0");
                var list = userModel.Select(p => new { p.F_UserId, p.F_UserCode, p.F_UserName });
                var obj = new
                {
                    user = list
                };
                res = Success("获取坐席成功！", obj);
            }
            return res;
        }
    }
}