using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Common;
using CallCenterApi.Interface.Models.Input;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    public class IndexController : BaseController
    {
        private BLL.T_Sys_UserAccount userBLL = new BLL.T_Sys_UserAccount();
        private BLL.T_Sys_Function moduleFunctionBLL = new BLL.T_Sys_Function();
        private BLL.T_Sys_RoleFunction roleFunctionBLL = new BLL.T_Sys_RoleFunction();
        private BLL.T_Sys_RoleInfo rolebll = new BLL.T_Sys_RoleInfo();
        private BLL.T_Msg_Chat bllchat = new BLL.T_Msg_Chat();
        private BLL.T_Msg_Chat_Map bllmap = new BLL.T_Msg_Chat_Map();
        private readonly BLL.T_Sys_UserAccount userAccount = new BLL.T_Sys_UserAccount();
        private BLL.T_Sys_SystemConfig configBll = new BLL.T_Sys_SystemConfig();

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetMenu()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            var fids = new BLL.T_Sys_RoleFunction().GetModelList(" F_RoleId='" + userModel.F_RoleId + "'").Select(p => p.F_FunctionId).ToList();
            if (fids.Count > 0)
            {
                var ids = string.Join(",", fids);
                var dt = new BLL.T_Sys_Function().GetList(0, " F_FunctionId in (" + ids + ") and F_State=1 and F_ParentId=-1 ", " F_Sort asc").Tables[0];
                dt.Columns.Add("item", typeof(object));
                foreach (DataRow dr in dt.Rows)
                {
                    dr["item"] = new BLL.T_Sys_Function().GetList(0, " F_FunctionId in (" + ids + ") and F_State=1 and F_ParentId=" + dr["F_FunctionId"].ToString(), " F_Sort asc").Tables[0];
                }

                return Success("成功", dt);
            }
            else
            {
                return Error("失败");
            }
        }

        /// <summary>
        /// 上传用户图片
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UploadTX()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            string path = string.Empty;
            HttpPostedFile _upfile = RequestString.GetFile("upFile");
            if (_upfile != null)
            {
                //byte[] buffer = new Byte[(int)_upfile.InputStream.Length]; //声明文件长度的二进制类型
                //_upfile.InputStream.Read(buffer, 0, buffer.Length); //将文件转成二进制

                ImageUpload iu = new ImageUpload();
                iu.SavePath = "/Upload/ZXTX/";
                iu.PostFile = _upfile;
                iu.InFileName = userModel.F_UserCode + ".jpg";
                iu.SaveType = 1;
                iu.Upload();
                path = "/Upload/ZXTX/" + iu.OutFileName;

                userModel.F_See = path;
                new BLL.T_Sys_UserAccount().Update(userModel);

                return Success("成功", path);
            }
            else
            {
                return Error("请选择要上传的文件");
            }
        }

        /// <summary>
        /// 上传用户图片
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UploadTX64()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            string path = string.Empty;

            string dataurl = HttpUtility.UrlDecode(RequestString.GetFormString("dataurl"));
            if (!string.IsNullOrEmpty(dataurl))
            {
                ImageUpload iu = new ImageUpload();
                iu.SavePath = "/Upload/ZXTX/";
                iu.DataUrl = dataurl;
                iu.InFileName = userModel.F_UserCode +".jpg";
                iu.SaveType = 1;
                iu.Upload64();

                int n = iu.Error;
                if (n == 0)
                {
                    path = "/Upload/ZXTX/" + iu.OutFileName;

                    userModel.F_See = path;
                    new BLL.T_Sys_UserAccount().Update(userModel);

                    return Success("成功", path);
                }
                else
                {
                    string msg = string.Empty;
                    switch (n)
                    {
                        case 1: msg = "请选择要上传的文件"; break;
                        case 2: msg = "上传的文件类型不支持"; break;
                        case 3: msg = "上传的文件过大"; break;
                        case 4: msg = "未知错误"; break;
                    }
                    return Error(msg);
                }
            }
            else
            {
                return Error("请选择要上传的文件");
            }
        }

        /// <summary>
        /// 通话记录数量
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetTelRecordsTotal()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);

            var date = DateTime.Now;
            string strDate = date.ToString("yyyy-MM-dd");
            string strMonth = date.ToString("yyyy-MM");

            string where = " 1=1 ";
            if (ua.F_RoleCode == "ZXHWY" || ua.F_RoleCode == "ZXBZ")
            {
                where = " UserCode='" + ua.F_UserCode + "' ";
            }

            BLL.T_Call_CallRecords bll = new BLL.T_Call_CallRecords();
            //var dayinlist = bll.GetModelList(where + " and CallType='0' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' and CallState='1' ");
            //var dayoutlist = bll.GetModelList(where + " and CallType='1' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' and CallState='1' ");
            //var moninlist = bll.GetModelList(where + " and CallType='0' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' and CallState='1' ");
            //var monoutlist = bll.GetModelList(where + " and CallType='1' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' and CallState='1' ");
            var dayinlist = bll.GetModelList(where + " and CallType='0' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' ");
            var dayoutlist = bll.GetModelList(where + " and CallType='1' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' ");
            var moninlist = bll.GetModelList(where + " and CallType='0' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' ");
            var monoutlist = bll.GetModelList(where + " and CallType='1' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' ");

            int daynocon = bll.GetList("CallType='0' and CONVERT(varchar(100),BeginTime, 23)='" + strDate + "' and CallState='0' ").Tables[0].Rows.Count;

            var obj = new
            {
                //dayin = new { count = dayinlist.Count, totaltime = dayinlist.Select(p => p.TalkLongTime).Sum() },
                //dayout = new { count = dayoutlist.Count, totaltime = dayoutlist.Select(p => p.TalkLongTime).Sum() },
                //monin = new { count = moninlist.Count, totaltime = moninlist.Select(p => p.TalkLongTime).Sum() },
                //monout = new { count = monoutlist.Count, totaltime = monoutlist.Select(p => p.TalkLongTime).Sum() },
                dayin = new { count = dayinlist.Count, totaltime = DateTimeConvert.parseTimeSeconds(int.Parse(dayinlist.Select(p => p.TalkLongTime).Sum().ToString()), 0) },
                dayout = new { count = dayoutlist.Count, totaltime = DateTimeConvert.parseTimeSeconds(int.Parse(dayoutlist.Select(p => p.TalkLongTime).Sum().ToString()), 0) },
                monin = new { count = moninlist.Count, totaltime = DateTimeConvert.parseTimeSeconds(int.Parse(moninlist.Select(p => p.TalkLongTime).Sum().ToString()), 0) },
                monout = new { count = monoutlist.Count, totaltime = DateTimeConvert.parseTimeSeconds(int.Parse(monoutlist.Select(p => p.TalkLongTime).Sum().ToString()), 0) },
                daynocon = daynocon
            };
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取当月/当天的工单量(已完成，未完成)
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetWorkTotal()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);

            var date = DateTime.Now;//DateTime.Parse("2015-04-14"); //
            string strDate = date.ToString("yyyy-MM-dd");
            string strMonth = date.ToString("yyyy-MM");

            string where = " F_IsDelete=0 ";
            if (ua.F_RoleCode == "ZXHWY")
            {
                where += " and F_CreateUser='" + ua.F_UserCode + "' ";
            }

            //BLL.T_Wo_WorkOrderBase bll = new BLL.T_Wo_WorkOrderBase();
            //var list1 = bll.GetList(" F_USERID='" + userId + "' and CONVERT(varchar(10),F_CREATEDATE, 23)='" + strDate + "' and F_WORKORDERSTATEID in (0,8) ").Tables[0];
            //var list2 = bll.GetList(" F_USERID='" + userId + "' and CONVERT(varchar(10),F_CREATEDATE, 23)='" + strDate + "' and F_WORKORDERSTATEID in (4,5,6,7,9,12,13) ").Tables[0];
            //var list3 = bll.GetList(" F_USERID='" + userId + "' and CONVERT(char(7),F_CREATEDATE,20)='" + strMonth + "' and F_WORKORDERSTATEID in (0,8) ").Tables[0];
            //var list4 = bll.GetList(" F_USERID='" + userId + "' and CONVERT(char(7),F_CREATEDATE,20)='" + strMonth + "' and F_WORKORDERSTATEID in (4,5,6,7,9,12,13) ").Tables[0];

            BLL.T_Bus_WorkOrder bll = new BLL.T_Bus_WorkOrder();
            var list1 = bll.GetList(where + " and CONVERT(varchar(10),F_CreateTime, 23)='" + strDate + "' and F_WorkState =9 and F_IsDelete=0 ").Tables[0];
            var list2 = bll.GetList(where + " and CONVERT(varchar(10),F_CreateTime, 23)='" + strDate + "' and F_WorkState !=9 and F_IsDelete=0 ").Tables[0];
            var list3 = bll.GetList(where + " and CONVERT(char(7),F_CreateTime,20)='" + strMonth + "' and F_WorkState =9 and F_IsDelete=0 ").Tables[0];
            var list4 = bll.GetList(where + " and CONVERT(char(7),F_CreateTime,20)='" + strMonth + "' and F_WorkState !=9 and F_IsDelete=0 ").Tables[0];

            var obj = new
            {
                daywc = list1.Rows.Count,
                daywwc = list2.Rows.Count,
                monwc = list3.Rows.Count,
                monwwc = list4.Rows.Count
            };
            return Success("成功", obj);
        }

        /// <summary>
        /// 当天每小时的总通话量和接通量
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetTelRecordsByHour()
        {

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);

            string where = " CallType=0 ";
            if (ua.F_RoleCode == "ZXHWY")
            {
                where += " and UserCode='" + ua.F_UserCode + "' ";
            }
            else
            {
                where += " and UserCode is not null ";
            }

            var date = DateTime.Now;//DateTime.Parse("2014-05-05"); //
            string strDate = date.ToString("yyyy-MM-dd");
            where += " and datediff(day,BeginTime,'" + strDate + "')=0";
            //string[] cols = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" };
            string[] cols = Enumerable.Range(0, 24).ToList<int>().ConvertAll<string>(x => x < 10 ? "0" + x.ToString() : x.ToString()).ToArray<string>();
            DataTable dtTel = DbHelperSQL.Query("select datepart(hour,BeginTime) hourtime,count(1) telcount from T_Call_CallRecords WITH(NOLOCK) where " + where + " group by datepart(hour,BeginTime) order by datepart(hour,BeginTime)").Tables[0];
            DataTable dtTelJT = DbHelperSQL.Query("select datepart(hour,BeginTime) hourtime,count(1) telcount from T_Call_CallRecords WITH(NOLOCK) where " + where + " and CallState=1 group by datepart(hour,BeginTime) order by datepart(hour,BeginTime)").Tables[0];
            //BLL.T_Call_CallRecords bll = new BLL.T_Call_CallRecords();
            int[] total = new int[24];
            int[] count = new int[24];
            for (int i = 0; i < cols.Length; i++)
            {
                var drTel = dtTel.Select("hourtime='" + (i+1) + "'");
                if (drTel.Length > 0)
                {
                    int drTelCount = (from DataRow dr in drTel select dr.Field<int>("telcount")).FirstOrDefault();
                    total[i] = drTelCount;
                }
                else
                    total[i] = 0;
                var drTelJT = dtTelJT.Select("hourtime='" + (i + 1) + "'");
                if (drTelJT.Length > 0)
                {
                    int drTelCount = (from DataRow dr in drTelJT select dr.Field<int>("telcount")).FirstOrDefault();
                    count[i] = drTelCount;
                }
                else
                    count[i] = 0;
                #region 优化前
                //var list = bll.GetModelList(where + " and CONVERT(varchar(13),BeginTime, 120)='" + (strDate + " " + cols[i]) + "' ");
                //var conlist = list.Where(p => p.CallState == 1);
                //total[i] = list.Count;
                //count[i] = conlist.Count();
                #endregion
            }

            var obj = new
            {
                col = cols,
                total = total,
                count = count
            };
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取当月每天的工单量和话务量
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetWorkTelByDay()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);

            string telwhere = " 1=1 ";
            string workwhere = " F_IsDelete=0 ";
            if (ua.F_RoleCode == "ZXHWY" || ua.F_RoleCode == "ZXBZ")
            {
                telwhere += " and UserCode='" + ua.F_UserCode + "' ";
                workwhere += " and F_CreateUser='" + ua.F_UserCode + "' ";
            }
            else
            {
                telwhere += " and UserCode is not null ";
            }
            

            var date = DateTime.Now;//DateTime.Parse("2015-04-05"); //
            telwhere += " and datediff(month,BeginTime,'"+ date + "')=0";
            workwhere += " and datediff(month,F_CreateTime,'" + date + "')=0";
            string strDate = date.ToString("yyyy-MM");

            int days = DateTime.DaysInMonth(date.Year, date.Month);

            //string[] strcols = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
            //                      "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
            //                      "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" };
            string[] strcols = Enumerable.Range(1, 31).ToList<int>().ConvertAll<string>(x => x < 10 ? "0" + x.ToString() : x.ToString()).ToArray<string>();
            int newcount = 0;
            List<string> cols = strcols.Take(days).ToList();
            //BLL.T_Call_CallRecords telbll = new BLL.T_Call_CallRecords();
            //BLL.T_Bus_WorkOrder workbll = new BLL.T_Bus_WorkOrder();
            int[] teltotal = new int[days];
            int[] worktotal = new int[days];
            DataTable dtTel = DbHelperSQL.Query("select DAY(BeginTime) daytime,count(1) telcount from T_Call_CallRecords WITH(NOLOCK) where " + telwhere + " group by DAY(BeginTime) order by DAY(BeginTime)").Tables[0];
            DataTable dtOrder = DbHelperSQL.Query("select DAY(F_CreateTime) daytime,count(1) ordercount from T_Bus_WorkOrder WITH(NOLOCK) where " + workwhere+ " group by DAY(F_CreateTime) order by DAY(F_CreateTime)").Tables[0];
            for (int i = 0; i < cols.Count; i++)
            {
                var drTel = dtTel.Select("daytime='" + (i + 1) + "'");
                if (drTel.Length > 0)
                {
                    int drTelCount = (from DataRow dr in drTel select dr.Field<int>("telcount")).FirstOrDefault();
                    teltotal[i] = drTelCount;
                    newcount = newcount + drTelCount;
                }
                else
                    teltotal[i] = 0;

                var drOrder = dtOrder.Select("daytime='" + (i + 1) + "'");
                if (drOrder.Length > 0)
                {
                    int drOrderCount = (from DataRow dr in drOrder select dr.Field<int>("ordercount")).FirstOrDefault();
                    worktotal[i] = drOrderCount;
                }
                else
                    worktotal[i] = 0;
                #region 优化前
                //var tellist = telbll.GetModelList(telwhere + " and CONVERT(varchar(10),BeginTime, 23)='" + (strDate + "-" + cols[i]) + "' ");
                //teltotal[i] = tellist.Count;
                //newcount = newcount + tellist.Count;
                //var worklist = workbll.GetList(workwhere + " and CONVERT(varchar(10),F_CreateTime, 23)='" + (strDate + "-" + cols[i]) + "' ").Tables[0];
                //worktotal[i] = worklist.Rows.Count;
                #endregion
            }

            var olddate = date.AddYears(-1);
            string strold1 = olddate.ToString("yyyy-MM") + "-1";
            string strold2 = olddate.ToString("yyyy-MM-dd");

            string bl = string.Empty;
            string oldwhere = " 1=1 ";
            if (ua.F_RoleCode == "ZXHWY" || ua.F_RoleCode == "ZXBZ")
            {
                oldwhere += " and UserCode='" + ua.F_UserCode + "'";
            }
            else
            {
                oldwhere += " and UserCode is not null ";
            }

            DataTable dtOldTel = DbHelperSQL.Query("select count(1) telcount from T_Call_CallRecords WITH(NOLOCK) where " + oldwhere + " and CONVERT(varchar(10),BeginTime, 23)>='" + strold1 + "' and CONVERT(varchar(10),BeginTime, 23)<='" + strold2 + "' ").Tables[0];
            //var oldcount = telbll.GetModelList(oldwhere + " and CONVERT(varchar(10),BeginTime, 23)>='" + strold1 + "' and CONVERT(varchar(10),BeginTime, 23)<='" + strold2 + "' ").Count;
            int oldcount = 0;
            var drOldTel = dtOldTel.Select();
            if (drOldTel.Length > 0)
            {
                oldcount = (from DataRow dr in drOldTel select dr.Field<int>("telcount")).FirstOrDefault();
            }

            if (oldcount == newcount)
            {
                bl = " 持平";
            }
            else
            {
                if (newcount != 0)
                {
                    if (oldcount > newcount)
                    {
                        bl = " ↓ " + (Convert.ToDouble(oldcount - newcount) / Convert.ToDouble(newcount)).ToString("0.0%");
                    }
                    else if (oldcount < newcount)
                    {
                        bl = " ↑ " + (Convert.ToDouble(newcount - oldcount) / Convert.ToDouble(newcount)).ToString("0.0%");
                    }
                }
                else
                {
                    bl = " --";
                }
            }

            var obj = new
            {
                bl = bl,
                col = cols.Select(p => p + "日"),
                worktotal = worktotal,
                teltotal = teltotal
            };

            return Success("成功", obj);
        }
        /// <summary>
        /// 获取工单数量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkOrderCount()
        {

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            string where = " F_IsDelete=0";
            string dh = "select count(1) from T_Bus_WorkOrder where" + where + " and F_InfoConBigType=0";
            string djb = "select count(1) from T_Bus_WorkOrder where" + where + "  and F_WorkState in (" + (int)EnumWorkState.submit + "," + (int)EnumWorkState.resubmit + ")";
            string dyssh = "select count(1) from T_Bus_WorkOrder where" + where + "and F_WorkState = '" + (int)EnumWorkState.auditdelay + "' and F_WorkOrderID in(select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 )";
            string dshth = "select count(1) from T_Bus_WorkOrder where" + where + " and F_WorkState = '3'";
            string dja = "select count(1) from T_Bus_WorkOrder where" + where + " and F_WorkState = '7'";
            string dhc = "select count(1) from T_Bus_WorkOrder where" + where + "and (IsExport != '" + 1 + "'or IsExport is null) and F_WorkState = '9' ";
            var obj = new
            {
                djb = DbHelperSQL.GetSingle(djb).ToString(),//待交办
                dyssh = DbHelperSQL.GetSingle(dyssh).ToString(),//待延时审核
                dshth = DbHelperSQL.GetSingle(dshth).ToString(),//退回审核中
                dja = DbHelperSQL.GetSingle(dja).ToString(),//待结案
                dhc = DbHelperSQL.GetSingle(dhc).ToString(),//待回传
                dh = DbHelperSQL.GetSingle(dh).ToString()//电话工单
            };

            return Success("成功", obj);
        }

        /// <summary>
        /// 获取工单数量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkOrderCountNew()
        {

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            string where = " F_IsDelete=0";
            string dh = "select count(1) from T_Bus_WorkOrder where" + where + " ";
            string djb = "select count(1) from T_Bus_WorkOrder where" + where + "  and F_WorkState in " +
                "(4,8)";
            string dyssh = "select count(1) from T_Bus_WorkOrder where  " + where + " and " +
                "F_WorkOrderID in (select F_WorkOrderID from T_Bus_DelayTime WITH(NOLOCK) where F_State= 1 and F_IsDelete = 0  " +
                "  and F_IsAudit='0'  ";
            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "ZXLD" && userModel.F_RoleCode != "DDZG")
            {
                dyssh += " and F_CreateUser='" + userModel.F_UserCode + "')";
            }
            else
            {
                dyssh += ")";
            }
            string dja = "select count(1) from T_Bus_WorkOrder where" + where + " and F_WorkState = '7'";
            string dhc = "select count(1) from T_Bus_WorkOrder where" + where + "and (IsExport != '" + 1 + 
                "'or IsExport is null) and F_WorkState = '9' ";
            var obj = new
            {
                交单量 = DbHelperSQL.GetSingle(dh).ToString(),//交单量
                办理中 = DbHelperSQL.GetSingle(djb).ToString(),//办理中
                延时数量 = DbHelperSQL.GetSingle(dyssh).ToString(),//延时数量
                未结案 = DbHelperSQL.GetSingle(dja).ToString(),//待结案
                已结案 = DbHelperSQL.GetSingle(dhc).ToString(),//待回传
            };

            return Success("成功", obj);
        }
        /// <summary>
        /// 获取未处理的工单数
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetNoDealWorkTotal()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
            #region 与前端对应状态
            //0-待处理-话务员、班长 ：0
            //1-待交办-调度专员：1
            //2-待查收-二级单位：2
            //3-退回审核中-调度专员：3
            //4-办理中（主办）-二级单位：2，4，8
            //5-延时审核中-调度专员：5
            //6-待回访-质检专员：6
            //7-已回访-质检专员：7
            //8-重办中-二级单位：8
            //9-已结案-所有：9
            //10-办理中（协办）-协办单位：2，4，8
            //11-待处理-三级网络单位：4，5 **办理中和延时审核的指派给三级单位的工单
            //12-待审核-话务班长：12
            //13-待督办-督办专员：提交督办的所有工单
            //15-超期工单-
            //16-重办驳回-质检专员：13
            #endregion
            #region 中心话务员(ZXHWY)
            if (userModel.F_RoleCode == "ZXHWY")
            {//中心话务员(ZXHWY)
                int[] sts = { 0 };

                string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (0) "
                    + "and F_CreateUser='" + userModel.F_UserCode + "' group by F_WorkState order by F_WorkState";

                var dt = DbHelperSQL.Query(sql).Tables[0];
                var obj = sts.Select(p =>
                {
                    var list = dt.Select(" state=" + p);
                    return new
                    {
                        state = p,
                        con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                    };
                });

                return Success("成功", obj);
            }
            #endregion
            #region 坐席班长/话务组长(ZXBZ)
            if (userModel.F_RoleCode == "ZXBZ")
            {//坐席班长/话务组长(ZXBZ)
                int[] sts = { 0, 12 };

                string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (0,10) "
                    + "and F_CreateUser='" + userModel.F_UserCode + "' group by F_WorkState order by F_WorkState";

                var dt = DbHelperSQL.Query(sql).Tables[0];
                var obj = sts.Select(p =>
                {
                    var list = dt.Select(" state=" + p);
                    if (p == 12)
                        list = dt.Select(" state=10 ");
                    return new
                    {
                        state = p,
                        con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                    };
                });

                return Success("成功", obj);
            }
            #endregion
            #region
            //20190315需求变动，待回访改为待审核 中心话务员只有待处理 话务组长有待处理和待审核  20190328 zhengbingbing
            //if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ")
            //{//中心话务员(ZXHWY) 坐席班长/话务组长(ZXBZ)
            //    int[] sts = { 0, 6 };

            //    string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (0,6) "
            //        + "and F_CreateUser='" + userModel.F_UserCode + "' group by F_WorkState order by F_WorkState";

            //    var dt = DbHelperSQL.Query(sql).Tables[0];
            //    var obj = sts.Select(p => {
            //        var list = dt.Select(" state=" + p);
            //        return new
            //        {
            //            state = p,
            //            con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
            //        };
            //    });

            //    return Success("成功", obj);
            //}
            #endregion
            #region 调度专员(ZXLD) 中心领导(ZXLDGLY) 中心领导管理员(ZXLDGLYGLY) 调度主管(DDZG)
            if ( userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "ZXLDGLYGLY" )
            {//调度专员(ZXLD) 中心领导(ZXLDGLY) 中心领导管理员(ZXLDGLYGLY)
                int[] sts = { 1, 3, 5 };

                string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (3,5) and "
                    + "F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo where F_State=1 and F_IsDelete=0 and F_CreateUser='"
                    + userModel.F_UserCode + "')  group by F_WorkState order by F_WorkState";

                var dt = DbHelperSQL.Query(sql).Tables[0];
                DataRow dr = dt.NewRow();
                dr["state"] = 1;
                string sqlcon = "select count(1) from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState=1 and (F_WorkOrderId in "
                    + "(select F_WorkOrderId from T_Bus_AssignedInfo where F_State=1 and F_IsDelete=0 and F_CreateUser='"
                    + userModel.F_UserCode + "') or (select top 1 F_WorkOrderId from T_Bus_AssignedInfo where F_State=1 and F_IsDelete=0 "
                    + "and T_Bus_AssignedInfo.F_WorkOrderId = T_Bus_WorkOrder.F_WorkOrderId ) is null)";
                dr["con"] = DbHelperSQL.GetSingle(sqlcon).ToString();

                dt.Rows.InsertAt(dr, 0);
                var obj = sts.Select(p =>
                {
                    var list = dt.Select(" state=" + p);
                    return new
                    {
                        state = p,
                        con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                    };
                });

                return Success("成功", obj);
            }
            #endregion
            #region 二级网络单位(WLDW)
            if (userModel.F_RoleCode == "WLDW")
            {//二级网络单位(WLDW)
                int[] sts = { 2, 4, 10, 8 };
                var sql = " where F_IsDelete=0 and F_WorkState in (2,4,8) and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo "
                    + " where F_State=1 and F_IsDelete=0 and F_IsSure in (0,1) and ISNULL(F_FeedbackTime, '')='' "
                    //+ " and (F_MainDeptId = " + userModel.F_DeptId + " or ','+F_OtherDeptIds+',' like '," + userModel.F_DeptId + ",'))";
                    + " and F_MainDeptId = " + userModel.F_DeptId + " )";

                string sql1 = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder " + sql + " group by F_WorkState order by F_WorkState";

                var dt = DbHelperSQL.Query(sql1).Tables[0];
                var obj = sts.Select(p =>
                {
                    if (p != 10)
                    {
                        var list = dt.Select(" state=" + p);
                        return new
                        {
                            state = p,
                            con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                        };
                    }
                    else
                    {
                        string sqlxb = " select count(1) from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (2,4,8) and F_WorkOrderId in "
                        + "(select F_WorkOrderId from T_Bus_AssignedItemInfo where F_State=1 and F_IsDelete=0 and "
                        + " ISNULL(F_FeedbackTime, '')='' and F_DeptId =" + userModel.F_DeptId + ")";
                        return new
                        {
                            state = p,
                            con = DbHelperSQL.GetSingle(sqlxb).ToString()
                        };
                    }
                });

                return Success("成功", obj);
            }
            #endregion
            #region 三级网络单位(EJWLDW)
            if (userModel.F_RoleCode == "EJWLDW")
            {//三级网络单位
                var sql = " where F_IsDelete=0 and F_WorkState in (4,5) and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo_Next where F_State=1 "
                    + "and F_IsDelete=0 and ISNULL(F_FeedbackTime, '')='' and F_MainDeptId =" + userModel.F_DeptId + " and F_IsSure in (0,1))";

                string sql1 = "select count(1) con from T_Bus_WorkOrder " + sql;

                var con = DbHelperSQL.GetSingle(sql1).ToString();
                var obj = new
                {
                    state = 11,
                    con = con
                };

                return Success("成功", obj);
            }
            #endregion
            #region 管理员(GLY)
            if (userModel.F_RoleCode == "GLY" ||userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "DDZG")
            {//管理员
                int[] sts = { 0, 12, 1, 2, 3, 4, 10, 5, 7, 8,16 };
                string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState !=9 "
                    + " group by F_WorkState order by F_WorkState";

                string sqlbh = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (13) "
                    + " and F_WorkOrderID in (select F_WorkOrderId from T_Bus_Operation where F_Id in (select max(F_Id) from T_Bus_Operation where F_State = 11 and F_WorkOrderId in (select F_WorkOrderId from T_Bus_Operation where F_State=13) group by F_WorkOrderId) )" + " group by F_WorkState order by F_WorkState";

                var dt = DbHelperSQL.Query(sql).Tables[0];
                var dtbh = DbHelperSQL.Query(sqlbh).Tables[0];//重办驳回
                var obj = sts.Select(p =>
                {
                    if (p != 10)
                    {
                        var list = dt.Select(" state=" + p);
                        if (p == 12)
                            list = dt.Select(" state=10 ");
                        return new
                        {
                            state = p,
                            con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                        };
                    }
                    else if (p == 16)
                    {
                        var list = dtbh.Select();
                        return new
                        {
                            state = p,
                            con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                        };
                    }
                    else
                    {
                        string sqlxb = " select count(1) from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (2,4,8) and F_WorkOrderId in "
                        + "(select F_WorkOrderId from T_Bus_AssignedItemInfo where F_State=1 and F_IsDelete=0 and ISNULL(F_FeedbackTime, '')='' )";
                        return new
                        {
                            state = p,
                            con = DbHelperSQL.GetSingle(sqlxb).ToString()
                        };
                    }
                });

                return Success("成功", obj);
            }
            #endregion
            #region 质检专员(ZJZY)
            if (userModel.F_RoleCode == "ZJZY")
            {//质检专员
                int[] sts = { 6,7, 16 };

                string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (6,7) "//+ "and F_CreateUser='" + userModel.F_UserCode 
                    + " group by F_WorkState order by F_WorkState";

                string sqlbh = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (13) "
                    + " and F_WorkOrderID in (select F_WorkOrderId from T_Bus_Operation where F_Id in (select max(F_Id) from T_Bus_Operation where F_State = 11 and F_WorkOrderId in (select F_WorkOrderId from T_Bus_Operation where F_State=13) group by F_WorkOrderId) and F_CreateUser='" + userModel.F_UserCode + "')"+ " group by F_WorkState order by F_WorkState";

                var dt = DbHelperSQL.Query(sql).Tables[0];//已办理
                var dtbh = DbHelperSQL.Query(sqlbh).Tables[0];//重办驳回
                var obj = sts.Select(p =>
                {
                    var list = dt.Select(" state=" + p);
                    if (p == 16)
                        list = dtbh.Select();
                    return new
                    {
                        state = p,
                        con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                    };
                });

                return Success("成功", obj);
            }
            #endregion
            #region 督办专员(DBZY)
            if (userModel.F_RoleCode == "DBZY")
            {
                string sql = "select count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkOrderID in(select F_WorkOrderID from T_Bus_RemindRecord where F_State=0 and F_IsDelete=0 and F_Type =1 ) "
                    + "and F_CreateUser='" + userModel.F_UserCode + "'";// + " group by F_WorkState order by F_WorkState";

                var con = DbHelperSQL.GetSingle(sql).ToString();
                int[] sts = { 13 };
                var obj = sts.Select(p =>
                {
                    return new
                    {
                        state = p,
                        con = con
                    };
                });

                return Success("成功", obj);
            }
            #endregion
            return Success("成功");
        }
        #region 20191129 zhengbingbing 新增接口
        [Authority]
        public ActionResult GetNoDealOrderCounts()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (userId > 0)
            {
                Model.T_Sys_UserAccount userModel = userAccount.GetModel(userId);
                if (userModel != null)
                {
                    var IsEject = 0;//是否弹窗
                    var roleModel = rolebll.GetModel(userModel.F_RoleId);
                    if (roleModel != null)
                        IsEject = roleModel.F_IsEject;
                    object obj = new object();
                    if(IsEject==1)
                    {
                        #region 中心话务员(ZXHWY)
                        if (userModel.F_RoleCode == "ZXHWY")
                        {//中心话务员(ZXHWY)
                            int[] sts = { 0 };

                            string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState in (0) "
                                + "and F_CreateUser='" + userModel.F_UserCode + "' group by F_WorkState order by F_WorkState";

                            var dt = DbHelperSQL.Query(sql).Tables[0];
                            obj = sts.Select(p =>
                            {
                                var list = dt.Select(" state=" + p);
                                return new
                                {
                                    state = p,
                                    con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                                };
                            });
                        }
                        #endregion
                        #region 坐席班长/话务组长(ZXBZ)
                        if (userModel.F_RoleCode == "ZXBZ")
                        {//坐席班长/话务组长(ZXBZ)
                            int[] sts = { 0, 12 };

                            string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState in (0,10) "
                                + "and F_CreateUser='" + userModel.F_UserCode + "' group by F_WorkState order by F_WorkState";

                            var dt = DbHelperSQL.Query(sql).Tables[0];
                            obj = sts.Select(p =>
                            {
                                var list = dt.Select(" state=" + p);
                                if (p == 12)
                                    list = dt.Select(" state=10 ");
                                return new
                                {
                                    state = p,
                                    con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                                };
                            });
                        }
                        #endregion
                        #region 调度专员(ZXLD) 中心领导(ZXLDGLY) 中心领导管理员(ZXLDGLYGLY)
                        if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "ZXLDGLYGLY")
                        {//调度专员(ZXLD) 中心领导(ZXLDGLY) 中心领导管理员(ZXLDGLYGLY)
                            int[] sts = { 1, 3, 5 };

                            string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState in (3,5) and "
                                + "F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_CreateUser='"
                                + userModel.F_UserCode + "')  group by F_WorkState order by F_WorkState";

                            var dt = DbHelperSQL.Query(sql).Tables[0];
                            DataRow dr = dt.NewRow();
                            dr["state"] = 1;
                            string sqlcon = "select count(1) from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState=1 and (F_WorkOrderId in "
                                + "(select F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_CreateUser='"
                                + userModel.F_UserCode + "') or (select top 1 F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 "
                                + "and T_Bus_AssignedInfo.F_WorkOrderId = T_Bus_WorkOrder.F_WorkOrderId ) is null)";
                            dr["con"] = DbHelperSQL.GetSingle(sqlcon).ToString();

                            dt.Rows.InsertAt(dr, 0);
                            obj = sts.Select(p =>
                            {
                                var list = dt.Select(" state=" + p);
                                return new
                                {
                                    state = p,
                                    con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                                };
                            });
                        }
                        #endregion
                        #region 二级网络单位(WLDW)
                        if (userModel.F_RoleCode == "WLDW")
                        {//二级网络单位(WLDW)
                            int[] sts = { 2, 4, 10, 8 };
                            var sql = " where F_IsDelete=0 and F_WorkState in (2,4,8) and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo "
                                + " where F_State=1 and F_IsDelete=0 and F_IsSure in (0,1) and ISNULL(F_FeedbackTime, '')='' "
                                //+ " and (F_MainDeptId = " + userModel.F_DeptId + " or ','+F_OtherDeptIds+',' like '," + userModel.F_DeptId + ",'))";
                                + " and F_MainDeptId = " + userModel.F_DeptId + " )";

                            string sql1 = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder WITH(NOLOCK) " + sql + " group by F_WorkState order by F_WorkState";

                            var dt = DbHelperSQL.Query(sql1).Tables[0];
                            obj = sts.Select(p =>
                            {
                                if (p != 10)
                                {
                                    var list = dt.Select(" state=" + p);
                                    return new
                                    {
                                        state = p,
                                        con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                                    };
                                }
                                else
                                {
                                    string sqlxb = " select count(1) from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState in (2,4,8) and F_WorkOrderId in "
                                    + "(select F_WorkOrderId from T_Bus_AssignedItemInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and "
                                    + " ISNULL(F_FeedbackTime, '')='' and F_DeptId =" + userModel.F_DeptId + ")";
                                    return new
                                    {
                                        state = p,
                                        con = DbHelperSQL.GetSingle(sqlxb).ToString()
                                    };
                                }
                            });
                        }
                        #endregion
                        #region 三级网络单位(EJWLDW)
                        if (userModel.F_RoleCode == "EJWLDW")
                        {//三级网络单位
                            var sql = " where F_IsDelete=0 and F_WorkState in (4,5) and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo_Next where F_State=1 "
                                + "and F_IsDelete=0 and ISNULL(F_FeedbackTime, '')='' and F_MainDeptId =" + userModel.F_DeptId + " and F_IsSure in (0,1))";

                            string sql1 = "select count(1) con from T_Bus_WorkOrder WITH(NOLOCK) " + sql;

                            var con = DbHelperSQL.GetSingle(sql1).ToString();
                            obj = new
                            {
                                state = 11,
                                con = con
                            };
                        }
                        #endregion
                        #region 管理员(GLY)
                        if (userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
                        {//管理员
                            int[] sts = { 0, 12, 1, 2, 3, 4, 10, 5, 6, 7, 8 };
                            string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState !=9 "
                                + " group by F_WorkState order by F_WorkState";

                            string sqlbh = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState in (13) "
                    + " and F_WorkOrderID in (select F_WorkOrderId from T_Bus_Operation WITH(NOLOCK) where F_Id in (select max(F_Id) from T_Bus_Operation where F_State = 11 and F_WorkOrderId in (select F_WorkOrderId from T_Bus_Operation WITH(NOLOCK) where F_State=13) group by F_WorkOrderId) )" + " group by F_WorkState order by F_WorkState";

                            var dt = DbHelperSQL.Query(sql).Tables[0];
                            var dtbh = DbHelperSQL.Query(sqlbh).Tables[0];//重办驳回
                            obj = sts.Select(p =>
                            {
                                if (p != 10)
                                {
                                    var list = dt.Select(" state=" + p);
                                    if (p == 12)
                                        list = dt.Select(" state=10 ");
                                    return new
                                    {
                                        state = p,
                                        con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                                    };
                                }
                                else if (p == 16)
                                {
                                    var list = dtbh.Select();
                                    return new
                                    {
                                        state = p,
                                        con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                                    };
                                }
                                else
                                {
                                    string sqlxb = " select count(1) from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState in (2,4,8) and F_WorkOrderId in "
                                    + "(select F_WorkOrderId from T_Bus_AssignedItemInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and ISNULL(F_FeedbackTime, '')='' )";
                                    return new
                                    {
                                        state = p,
                                        con = DbHelperSQL.GetSingle(sqlxb).ToString()
                                    };
                                }
                            });
                        }
                        #endregion
                        #region 质检专员(ZJZY)
                        if (userModel.F_RoleCode == "ZJZY")
                        {//质检专员
                            int[] sts = { 6 };

                            string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState in (6) "
                                + " group by F_WorkState order by F_WorkState";

                            string sqlbh = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkState in (13)  and F_WorkOrderID in (select F_WorkOrderId from T_Bus_Operation WITH(NOLOCK) where F_Id in (select max(F_Id) from T_Bus_Operation where F_State = 11 and F_WorkOrderId in (select F_WorkOrderId from T_Bus_Operation WITH(NOLOCK) where F_State=13) group by F_WorkOrderId) and F_CreateUser='" + userModel.F_UserCode + "')" + " group by F_WorkState order by F_WorkState";

                            var dt = DbHelperSQL.Query(sql).Tables[0];//已办理
                            var dtbh = DbHelperSQL.Query(sqlbh).Tables[0];//重办驳回
                            obj = sts.Select(p =>
                            {
                                var list = dt.Select(" state=" + p);
                                if (p == 16)
                                    list = dtbh.Select();
                                return new
                                {
                                    state = p,
                                    con = list.Count() > 0 ? list[0]["con"].ToString() : "0"
                                };
                            });
                        }
                        #endregion
                        #region 督办专员(DBZY)
                        if (userModel.F_RoleCode == "DBZY")
                        {
                            string sql = "select count(1) con from T_Bus_WorkOrder WITH(NOLOCK) where F_IsDelete=0 and F_WorkOrderID in(select F_WorkOrderID from T_Bus_RemindRecord WITH(NOLOCK) where F_State=0 and F_IsDelete=0 and F_Type =1 ) "
                                + "and F_CreateUser='" + userModel.F_UserCode + "'";// + " group by F_WorkState order by F_WorkState";

                            var con = DbHelperSQL.GetSingle(sql).ToString();
                            int[] sts = { 13 };
                            obj = sts.Select(p =>
                            {
                                return new
                                {
                                    state = p,
                                    con = con
                                };
                            });
                        }
                        #endregion
                    }
                    var newobj = new
                    {
                        IsEject,
                        lists = obj
                    };
                    return Success("成功", newobj);
                }
            }
            return Error("权限不足");
        }
        #endregion

        /// <summary>
        /// 及时提醒工单（获取最新工单数和内容）
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetPromptOrder(string mid)
        {
            int recordCount = 0, fid = 0;
            DataTable dt = null;
            BLL.T_Bus_WorkOrder bll = new BLL.T_Bus_WorkOrder();
            int.TryParse(mid, out fid);

            //获取最大id
            int maxid = bll.GetMaxId() - 1;
            if (fid > 0)
            {
                dt = bll.GetList(" F_IsDelete=0 and F_Id > " + fid + " ").Tables[0];
                recordCount = dt.Rows.Count;
            }
            var obj = new
            {
                rows = dt,
                total = recordCount,
                maxid = maxid
            };
            return Content(obj.ToJson());
        }

        ///// <summary>
        ///// 及时提醒工单（获取最新工单数和内容） => 获取未处理的工单数
        ///// workorder\WorkOrderController.cs 接口：GetDWDealList
        ///// </summary>
        ///// <returns></returns>
        //[Authority]
        //public ActionResult GetNoDealOrder(string top)
        //{
        //    DataTable dt = null;
        //    int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
        //    string strpageindex = RequestString.GetQueryString("page");
        //    int pageindex = 1;
        //    string strpagesize = RequestString.GetQueryString("top");
        //    int pagesize = 10;
        //    if (strpageindex.Trim() != "")
        //    {
        //        pageindex = Convert.ToInt32(strpageindex);
        //    }
        //    if (strpagesize.Trim() != "")
        //    {
        //        pagesize = Convert.ToInt32(strpagesize);
        //    }
        //    Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
        //    string sql = " and F_IsDelete=0 and F_WorkState in (2,4,8)";
        //    //管理员GLY
        //    //if (userModel.F_RoleCode != "GLY")
        //    //{
        //    //    sql += " and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo where F_State=1 and F_IsDelete=0 and "
        //    //    + " ISNULL(F_FeedbackTime, '')='' and F_MainDeptId =" + userModel.F_DeptId + " and F_IsSure in (0,1)";
        //    //    sql += ")";
        //    //}
        //    sql += " and ( F_WorkOrderId in (select F_WorkOrderId  from T_Bus_AssignedInfo where F_State=1 and F_IsDelete=0 and F_LimitTime<getdate() and isnull(F_FeedbackTime,'')='' and F_IsSure in (0,1) ";

        //    if (userModel.F_RoleCode != "GLY")
        //    {
        //        sql += " and  F_MainDeptId = '" + userModel.F_DeptId + "' ";
        //    }

        //    sql += ") or F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedItemInfo where F_State=1 and F_IsDelete=0 and F_LimitTime<getdate() and ISNULL(F_FeedbackTime, '')='' ";

        //    if (userModel.F_RoleCode != "GLY")
        //    {
        //        sql += " and  F_DeptId = '" + userModel.F_DeptId + "' ";
        //    }
        //    sql += "))";

        //    string cols = "F_Id,F_WorkOrderId,F_CusName,F_CusPhone,F_ComTitle,F_ComContent,F_SourceAddress,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName ";
        //    int recordCount = 0;
        //    dt = BLL.PagerBLL.GetListPager(
        //        "T_Bus_WorkOrder",
        //        "F_WorkOrderId",
        //        cols,
        //        sql,
        //        "ORDER BY F_CreateTime DESC",
        //        pagesize,
        //        pageindex,
        //        true,
        //        out recordCount);


        //    var obj = new
        //    {
        //        rows = dt,
        //        total = recordCount,
        //        timeoutcount = DbHelperSQL.GetSingle(" select count(1) as con from T_Bus_WorkOrder where 1=1 " + sql)
        //    };


        //    return Content(obj.ToJson());
        //}

        /// <summary>
        /// 及时提醒工单（获取最新工单数和内容） => 获取未处理的工单数
        /// workorder\WorkOrderController.cs 接口：GetDWDealList
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetNoDealOrder(int top)
        {
            DataTable dt = null;
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            string sql = " and F_IsDelete=0 and F_WorkState in (2,4,8)";

            if (userModel.F_RoleCode == "ZXHWY")
            {
                sql += " and F_CreateUser = '" + userModel.F_UserCode + "' ";
            }


            sql += " and ( F_WorkOrderId in (select F_WorkOrderId  from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and isnull(F_FeedbackTime,'')='' and F_IsSure in (0,1) ";

            if (userModel.F_RoleCode == "WLDW")
            {
                sql += " and  F_MainDeptId = '" + userModel.F_DeptId + "') or F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedItemInfo"
                    + " where F_State=1 and F_IsDelete=0 and ISNULL(F_FeedbackTime, '')='' and  F_DeptId = '" + userModel.F_DeptId + "' ";
            }

            if (userModel.F_RoleCode == "ZXLD")
            {
                sql += " and  F_CreateUser = '" + userModel.F_UserCode + "' ";
            }

            sql += "))";

            string sqltimeout = " and F_IsDelete=0 and F_WorkState in (2,4,8)";

            if (userModel.F_RoleCode == "ZXHWY")
            {
                sqltimeout += " and F_CreateUser = '" + userModel.F_UserCode + "' ";
            }

            sqltimeout += " and ( F_WorkOrderId in (select F_WorkOrderId  from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_LimitTime<getdate() and isnull(F_FeedbackTime,'')='' and F_IsSure in (0,1) ";

            if (userModel.F_RoleCode == "WLDW")
            {
                sqltimeout += " and  F_MainDeptId = '" + userModel.F_DeptId + "') or F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedItemInfo  WITH(NOLOCK) "
                    + " where F_State=1 and F_IsDelete=0 and F_LimitTime<getdate() and ISNULL(F_FeedbackTime, '')='' and  F_DeptId = '" + userModel.F_DeptId + "' ";
            }

            if (userModel.F_RoleCode == "ZXLD")
            {
                sqltimeout += " and  F_CreateUser = '" + userModel.F_UserCode + "' ";
            }

            sqltimeout += "))";

            string cols = "F_Id,F_WorkOrderId,F_CusName,F_CusPhone,F_ComTitle,F_ComContent,F_SourceAddress,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName ";

            dt = DbHelperSQL.Query("select top "+ top+ " "+ cols + " from T_Bus_WorkOrder with (nolock) where 1=1 " + sql+ " ORDER BY F_CreateTime DESC ").Tables[0];

            var obj = new
            {
                rows = dt,
                total = DbHelperSQL.GetSingle(" select count(1) as con from T_Bus_WorkOrder with (nolock) where 1=1 " + sql),
                timeoutcount = DbHelperSQL.GetSingle(" select count(1) as con from T_Bus_WorkOrder with (nolock) where 1=1 " + sqltimeout)
            };


            return Content(obj.ToJson());
        }

        #region 及时通讯

        #region 模仿微信聊天（暂时不用）
        /// <summary>
        /// 即时聊天 - 角色信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetRoleList()
        {
            //var dtCache = CacheHelper.Get<DataTable>($"RoleList");
            var dtCache = RedisHelper.StringGet("RoleList");
            if (dtCache != null)
            {
                return Success("获取成功", dtCache.ToString().ToObject<DataTable>());
            }
            DataTable dt = new DataTable();
            dt = rolebll.GetAllList().Tables[0];
            //CacheHelper.Insert($"RoleList", dt, 10);
            RedisHelper.StringSet("RoleList", dt.ToJson(), new TimeSpan(0, 10, 0));
            return Success("获取成功", dt);
        }

        /// <summary>
        /// 即时聊天 - 坐席人员
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetUserListByRoleId(int roleid, string keyword)
        {
            DataTable dt = new DataTable();
            //取得前天日期
            DateTime start = DateTime.Parse(DateTime.Now.AddDays(-2).ToShortDateString() + " 00:00:00");
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            string sql1 = "SELECT FromUserId,COUNT(1)AS counts FROM T_Msg_Chat_Map WHERE ToUserId = " + userId + " AND ISNULL(IsRead,0) = 0 AND CreateDate > '" + start + "' group by FromUserId order by FromUserId";
            var dt1 = DbHelperSQL.Query(sql1).Tables[0];
            //缓存
            //var dtCache = CacheHelper.Get<DataTable>($"UserList{roleid}");
            var objCache = RedisHelper.StringGet($"UserList{roleid}");
            if (objCache != null)
            {
                var dtCache = objCache.ToString().ToObject<DataTable>();
                #region 提示统计
                if (!string.IsNullOrEmpty(keyword))
                {
                    dtCache = ToDataTable1(dtCache.Select("F_UserName LIKE '%" + keyword + "%' OR F_UserCode LIKE '%" + keyword + "%'"));
                }
                foreach (DataRow dr in dtCache.Rows)
                {
                    var list = dt1.Select(" FromUserId=" + dr["F_UserId"]);
                    dr["counts"] = list.Count() > 0 ? list[0]["counts"].ToString() : "0";
                }
                #endregion                
                return Success("获取成功", dtCache);
            }
            //实时查询
            var sql = " F_DeleteFlag=0 ";
            if (roleid != 0)
            {
                sql += " and F_RoleId = " + roleid + "";
            }
            string sqldt = "SELECT F_UserId,F_UserCode,F_UserName,F_RoleId,F_SexFlag,F_See FROM T_Sys_UserAccount WHERE " + sql + " ";
            dt = DbHelperSQL.Query(sqldt).Tables[0];

            #region 提示统计
            dt.Columns.Add("counts", typeof(string)); //统计
            //string sql1 = "SELECT FromUserId,COUNT(1)AS counts FROM T_Msg_Chat_Map WHERE ToUserId = " + userId + " AND ISNULL(IsRead,0) = 0 AND CreateDate > '" + start + "' group by FromUserId order by FromUserId";
            //var dt1 = DbHelperSQL.Query(sql1).Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                var list = dt1.Select(" FromUserId=" + dr["F_UserId"]);
                dr["counts"] = list.Count() > 0 ? list[0]["counts"].ToString() : "0";
            }
            //缓存保存
            //CacheHelper.Insert($"UserList{roleid}", dt, 10);
            RedisHelper.StringSet($"UserList{roleid}",dt.ToJson(), new TimeSpan(0, 10, 0));
            if (!string.IsNullOrEmpty(keyword))
            {
                dt = ToDataTable1(dt.Select("F_UserName LIKE '%" + keyword + "%' OR F_UserCode LIKE '%" + keyword + "%'"));
            }
            #endregion
            return Success("获取成功", dt);
        }

        /// <summary>
        /// 即时聊天 - 获取最新通讯(获取双方记录【聊天】)
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetChatList(int fromuserId)
        {
            DataTable dt = null;
            int recordCount = 0;
            //取得前天日期
            DateTime start = DateTime.Parse(DateTime.Now.AddDays(-2).ToShortDateString() + " 00:00:00");
            //接收坐席Id
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (fromuserId > 0)
            {
                //条件（最近3天的记录）
                string sql = " ISNULL(a.IsDelete,0) = 0 AND ISNULL(c.F_DeleteFlag,0) = 0 "; // AND ISNULL(b.IsRead,0) = 0
                if (fromuserId > 0)
                {
                    sql += " and (b.FromUserId = " + fromuserId + " or b.ToUserId = " + fromuserId + ") ";
                }
                if (userId > 0)
                {
                    sql += " and (b.ToUserId = " + userId + " or b.FromUserId = " + userId + ") ";
                }
                if (start != null)
                {
                    sql += " and b.CreateDate > '" + start + "' ";
                }
                //查询（聊天记录）
                string sql1 = "SELECT a.Id,a.FromUserId,a.Content,a.IsToAll,a.CreateDate,c.F_UserName FROM dbo.T_Msg_Chat a RIGHT JOIN dbo.T_Msg_Chat_Map b ON b.ChatId = a.Id LEFT JOIN dbo.T_Sys_UserAccount c ON c.F_UserId = a.FromUserId WHERE " + sql + " ORDER BY a.CreateDate ASC";
                dt = DbHelperSQL.Query(sql1).Tables[0];
                recordCount = dt.Rows.Count;

                //修改（设置已读）
                string sqlwhere = " ISNULL(IsRead,0) = 0 ";
                if (fromuserId > 0)
                {
                    sqlwhere += " and FromUserId = " + fromuserId + " ";
                }
                if (userId > 0)
                {
                    sqlwhere += " and ToUserId = " + userId + " ";
                }
                string sqlwhere1 = "UPDATE dbo.T_Msg_Chat_Map SET IsRead = 1 WHERE " + sqlwhere + " ";
                DbHelperSQL.ExecuteSql(sqlwhere1);

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

        #region 及时通讯 - 通讯列表
        /// <summary>
        /// 即时通讯 - 获取通讯列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetChatListSearch()
        {
            DataTable dt = new DataTable();
            int fromid = RequestString.GetInt("fromid", 0);
            int isread = RequestString.GetInt("isread", -1);
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("strstarttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("strendtime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            //接收坐席Id
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            string sql = " and ISNULL(a.IsDelete,0) = 0 AND ISNULL(c.F_DeleteFlag,0) = 0 ";
                        
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            #region 权限设置
            //管理员，坐席班长
            if (userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG" || userModel.F_RoleCode == "ZXBZ")
            {
                //
            }
            else {
                sql += " and (b.ToUserId = " + userId + " OR b.FromUserId = " + userId + ") ";
            }
            #endregion

            if (fromid > 0)
            {
                sql += " and (b.FromUserId = " + fromid + " or b.ToUserId = " + fromid + ") ";
            }
            if (isread != -1)
            {
                sql += " and ISNULL(b.IsRead,0) = " + isread + " ";
            }
            if (!string.IsNullOrEmpty(strstarttime))
            {
                sql += " and datediff(day,b.CreateDate,'" + strstarttime + "')<=0 ";
            }
            if (!string.IsNullOrEmpty(strendtime))
            {
                sql += " and datediff(day,b.CreateDate,'" + strendtime + "')>=0 ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            var col = "a.Id,b.FromUserId,b.ToUserId,a.Content,a.IsToAll,a.CreateDate,b.IsRead,c.F_UserName,c.F_UserCode,c.F_RoleId,d.F_UserName AS ToUserName,d.F_UserCode AS ToUserCode,d.F_RoleId AS ToRoleId";
            dt = BLL.PagerBLL.GetListPager(
                    " dbo.T_Msg_Chat a RIGHT JOIN dbo.T_Msg_Chat_Map b ON b.ChatId = a.Id LEFT JOIN dbo.T_Sys_UserAccount c ON c.F_UserId = b.FromUserId LEFT JOIN dbo.T_Sys_UserAccount d ON d.F_UserId = b.ToUserId ",
                    "b.Id",
                    col,
                    sql,
                    " ORDER BY a.CreateDate ASC",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

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

        /// <summary>
        /// 即时聊天 - 保存最新通讯
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult SaveChatInfo(ChatInput input)
        {
            //发送坐席Id
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            var model = new Model.T_Msg_Chat();
            var modelmap = new Model.T_Msg_Chat_Map();
            model.Content = input.Content;          //必填
            model.VoiceUrl = input.VoiceUrl;
            model.FromUserId = userId;
            model.ToUserId = input.ToUserId;
            model.ToRoleId = input.ToRoleId;
            //如果用户和角色都为0，则发送所有人
            if (input.ToUserId == 0 && input.ToRoleId == 0) {
                input.IsToAll = 1;
            }
            model.IsToAll = input.IsToAll;
            int chatId = bllchat.Add(model);
            if (chatId > 0)
            {
                modelmap.ChatId = chatId;
                modelmap.FromUserId = userId;   
                //群发聊天          
                if (input.IsToAll > 0)
                {
                    var userList = userAccount.DataTableToList(userAccount.GetList(" F_DeleteFlag=0 ").Tables[0]);
                    foreach (var u in userList)
                    {
                        modelmap.ToUserId = u.F_UserId;
                        bllmap.Add(modelmap);
                    }
                    return Success("发送成功");
                }
                //角色聊天
                if (input.ToRoleId > 0 && input.ToUserId == 0) {
                    var userList = userAccount.DataTableToList(userAccount.GetList(" F_DeleteFlag=0 AND F_RoleId=" + input.ToRoleId + " ").Tables[0]);
                    foreach (var u in userList)
                    {
                        modelmap.ToUserId = u.F_UserId;
                        bllmap.Add(modelmap);
                    }
                    return Success("发送成功");
                }
                //私人聊天
                modelmap.ToUserId = input.ToUserId;
                //关闭之前所有的信息
                string sqlwhere1 = "UPDATE dbo.T_Msg_Chat_Map SET IsRead = 1 WHERE FromUserId = " + input.ToUserId + " or ToUserId = " + userId + " ";
                DbHelperSQL.ExecuteSql(sqlwhere1);
                //后添加新的信息
                bllmap.Add(modelmap);
                return Success("发送成功");
            }
            return Error("发送失败");
        }

        /// <summary>
        /// 即时通讯 - 获取最新通讯（单方查看）
        /// </summary>
        /// <param name="isread">0未读1已读2全部</param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetChatLists(int top,int fromid, int isread = 0)
        {
            DataTable dt = null;
            int recordCount = 0;
            //接收坐席Id
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            string sql = " ISNULL(a.IsDelete,0) = 0 AND ISNULL(c.F_DeleteFlag,0) = 0 "; // AND ISNULL(b.IsRead,0) = 0
            if (top <= 0)
            {
                top = 50;
            }
            if (fromid > 0)
            {
                //sql += " and ISNULL(b.FromUserId,0) = " + fromid + " ";
                sql += " and (b.FromUserId = " + fromid + " or b.ToUserId = " + fromid + ") ";
                sql += " and (b.ToUserId = " + userId + " or b.FromUserId = " + userId + ") ";
            }
            else
            {
                sql += " and b.ToUserId = " + userId + " ";
            }
            if (isread != 2)
            {
                sql += " and ISNULL(b.IsRead,0) = " + isread + " ";
            }
            //查询（聊天记录）
            string sql1 = "SELECT TOP " + top + " a.Id,b.FromUserId,b.ToUserId,a.Content,a.IsToAll,a.CreateDate,b.IsRead,c.F_UserName,c.F_RoleId,c.F_SexFlag,c.F_See FROM dbo.T_Msg_Chat a RIGHT JOIN dbo.T_Msg_Chat_Map b ON b.ChatId = a.Id LEFT JOIN dbo.T_Sys_UserAccount c ON c.F_UserId = a.FromUserId WHERE " + sql + " ORDER BY a.CreateDate ASC";
            dt = DbHelperSQL.Query(sql1).Tables[0];
            recordCount = dt.Rows.Count;

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

        /// <summary>
        /// 即时通讯 - 获取最新通讯数量（单方查看）
        /// </summary>
        /// <param name="isread">0未读1已读2全部</param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetChatCount(int top)
        {
            DataTable dt = null;
            int recordCount = 0;
            //接收坐席Id
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (top <= 0)
            {
                top = 50;
            }
            string sql = " ISNULL(a.IsDelete,0) = 0 AND ISNULL(c.F_DeleteFlag,0) = 0 "; // AND ISNULL(b.IsRead,0) = 0
            sql += " and b.ToUserId = " + userId + " and ISNULL(b.IsRead,0) = 0 ";
            //查询（聊天记录）
            string sql1 = "SELECT TOP " + top + " a.Id FROM dbo.T_Msg_Chat a WITH (NOLOCK) RIGHT JOIN dbo.T_Msg_Chat_Map b WITH (NOLOCK) ON b.ChatId = a.Id LEFT JOIN dbo.T_Sys_UserAccount c WITH (NOLOCK) ON c.F_UserId = a.FromUserId WHERE " + sql + " ORDER BY a.CreateDate ASC";
            dt = DbHelperSQL.Query(sql1).Tables[0];
            recordCount = dt.Rows.Count;

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

        /// <summary>
        /// 即时通讯 - 获取最新通讯信息（单方查看）
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetChatInfoById(int id)
        {
            if (id <= 0)
            {
                return Error("参数出错");
            }
            DataTable dt = null;
            string cid = string.Empty, content = string.Empty, createDate = string.Empty, userName = string.Empty, isread = string.Empty, roleId=string.Empty;
            //接收坐席Id
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            string sql = " ISNULL(a.IsDelete,0) = 0 AND ISNULL(c.F_DeleteFlag,0) = 0 "; // AND ISNULL(b.IsRead,0) = 0
            if (userId > 0)
            {
                sql += " and b.ToUserId = " + userId + " ";
            }
            if (id > 0)
            {
                sql += " and a.Id = " + id + " ";
            }
            //查询（聊天记录）
            string sql1 = "SELECT a.Id,a.FromUserId,a.Content,a.IsToAll,a.CreateDate,b.IsRead,c.F_UserName,c.F_RoleId FROM dbo.T_Msg_Chat a RIGHT JOIN dbo.T_Msg_Chat_Map b ON b.ChatId = a.Id LEFT JOIN dbo.T_Sys_UserAccount c ON c.F_UserId = a.FromUserId WHERE " + sql + " ORDER BY a.CreateDate ASC";
            dt = DbHelperSQL.Query(sql1).Tables[0];
            if (dt.Rows.Count > 0)
            {
                cid = dt.Rows[0]["Id"].ToString();
                content = dt.Rows[0]["Content"].ToString();
                createDate = dt.Rows[0]["CreateDate"].ToString();
                userName = dt.Rows[0]["F_UserName"].ToString();
                roleId = dt.Rows[0]["F_RoleId"].ToString();
                isread = dt.Rows[0]["IsRead"].ToString();
            }

            //修改（设置已读）
            string sqlwhere = " ISNULL(IsRead,0) = 0 ";
            if (userId > 0)
            {
                sqlwhere += " and ToUserId = " + userId + " ";
            }
            if (id > 0)
            {
                sqlwhere += " and ChatId = " + id + " ";
            }
            string sqlwhere1 = "UPDATE dbo.T_Msg_Chat_Map SET IsRead = 1 WHERE " + sqlwhere + " ";
            DbHelperSQL.ExecuteSql(sqlwhere1);

            var obj = new
            {
                id = cid,
                username = userName,
                content = content,
                createdate = createDate,
                roleId = roleId,
                isread = isread
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 即时通讯 - 关闭通讯信息（单方查看）
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult CloseChat(int id)
        {
            //接收坐席Id
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            int recordCount = 0;
            //修改（设置已读）
            string sqlwhere = " ISNULL(IsRead,0) = 0 ";
            if (userId > 0)
            {
                sqlwhere += " and ToUserId = " + userId + " ";
            }
            if (id > 0)
            {
                sqlwhere += " and ChatId = " + id + " ";
            }
            string sqlwhere1 = "UPDATE dbo.T_Msg_Chat_Map SET IsRead = 1 WHERE " + sqlwhere + " ";
            int n = DbHelperSQL.ExecuteSql(sqlwhere1);
            if (n > 0)
            {
                recordCount = n;
            }

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

        /// <summary>
        /// DataRow转成DataTable
        /// </summary>
        /// <param name="rows"></param>
        /// <returns></returns>
        public DataTable ToDataTable1(DataRow[] rows)
        {
            if (rows == null || rows.Length == 0) return null;
            DataTable tmp = rows[0].Table.Clone(); // 复制DataRow的表结构
            foreach (DataRow row in rows)
            {
                tmp.ImportRow(row); // 将DataRow添加到DataTable中
            }
            return tmp;
        }

        #endregion
    }
}