using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Models.Input;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers
{
    public class IndexController : BaseController
    {
        private Bll.T_Sys_Menu menbll = new Bll.T_Sys_Menu();
        private Bll.T_Sys_Role rolebll = new Bll.T_Sys_Role();
        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();
        // GET: Index
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCurrentUser()
        {
            var Role = new Bll.T_Sys_Role().GetModel(User.F_RoleId);
            var Dept = new Bll.T_Sys_Department().GetModel(User.F_DeptId);
            if (User.F_SeatGroup != null && User.F_SeatGroup.Value > 0)
            {
                User.F_ZXZCode = new Bll.T_Sys_SeatGroup().GetModel((int)User.F_SeatGroup)?.F_ZXZCode ?? "";
            }
            else User.F_ZXZCode = "";
            return Success("成功", new { User, Role, Dept });
        }
        /// <summary>
        /// 获取当前用户菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMenu()
        {
            var dt = new DataTable();
            var Menus = CacheHelper.Get<DataTable>("RoleMenus_" + User.F_RoleId);
            if (Menus != null)
            {
                dt = Menus;
            }
            else
            {
                //if (User.F_UserCode == "8000")
                //{
                //    dt = DB.DbHelperSQL.Query("select * FROM T_Sys_Menu m with(nolock) where F_State=1 ").Tables[0];
                //}
                //else
                //{
                    dt = DB.DbHelperSQL.Query("select m.* FROM T_Sys_RoleMenu rm with(nolock) left join T_Sys_Menu m with(nolock) on rm.F_MenuId=m.F_MenuId where m.F_State=1 and rm.F_RoleId=" + User.F_RoleId + "").Tables[0];
                //}

                CacheHelper.Insert("RoleMenus_" + User.F_RoleId, dt, 10);              
              
            }
            List<Model.T_Sys_Menu> moduleInfoList = menbll.DataTableToList(dt);
            List<Model.T_Sys_Menu> newmodelList = moduleInfoList.Where(p => p.F_ParentId == 0).OrderBy(p => p.F_Sort).ToList();
            foreach (var item in newmodelList)
            {
                if (item.F_Type == 2)
                {
                    item.button = TreeRecursion(moduleInfoList, item.F_MenuId.ToString());
                }
                else if (item.F_Type == 1)
                {
                    item.children = TreeRecursion(moduleInfoList, item.F_MenuId.ToString());
                }
            }
            //moduleInfoList.Sort((x, y) => x.F_Sort ?? 0 - y.F_Sort ?? 0);
            return Success("获取符合权限的菜单", newmodelList);
        }


        private List<Model.T_Sys_Menu> TreeRecursion(List<Model.T_Sys_Menu> data, string parentId = "0")
        {
            List<Model.T_Sys_Menu> newList = new List<Model.T_Sys_Menu>();

                List<Model.T_Sys_Menu> item = data.FindAll(t => t.F_ParentId.ToString() == parentId).OrderBy(p => p.F_Sort).ToList();//data建议在调用此扩展方法前已经排序过
                if (item.Count > 0)
                {
                    foreach (Model.T_Sys_Menu entity in item)
                    {
                        if (entity.F_Type == 2)
                        {
                            entity.button = TreeRecursion(data, entity.F_MenuId.ToString());
                        }
                        else if (entity.F_Type == 1)
                        {
                            entity.children = TreeRecursion(data, entity.F_MenuId.ToString());
                        }
                        newList.Add(entity);
                    }
                }

            return newList;
        }

        /// <summary>
        /// 上传头像
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadTX()
        {
            string path = string.Empty;
            HttpPostedFileBase _upfile =   Request.Files[0];
          
            if (_upfile != null)
            {
                ImageHelper iu = new ImageHelper();
                iu.SavePath = "/Upload/ZXTX/";
                iu.PostFile = _upfile;
               
                iu.InFileName = User.F_UserCode + Path.GetExtension(_upfile.FileName);
                //  iu.InFileName = User.F_UserCode + iu.OutFileName.Split('.').GetValue(1).ToString(); 
                iu.SaveType = 1;
                iu.Upload();
                path = "/Upload/ZXTX/" + iu.OutFileName;

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

                   User.F_See = path;
                     userAccount.Update(User);

                    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);
                }

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



        /// <summary>
        /// 上传用户图片
        /// </summary>
        /// <returns></returns>
        //[Authority]
        //public ActionResult UploadTX64()
        //{
        //    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 = User.F_UserCode + ".jpg";
        //        iu.SaveType = 1;
        //        iu.Upload64();

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

        //            User.F_See = path;
        //            new BLL.T_Sys_UserAccount().Update(User);

        //            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>
        public ActionResult GetTelRecordsTotal()
        {
            if (User != null)
            {

                var date = DateTime.Now;
                string strDate = date.ToString("yyyy-MM-dd");
                string strMonth = date.ToString("yyyy-MM");
                string where = " 1=1 ";
                if (User.F_RoleCode != "GLY")
                {
                    where = " UserCode='" + User.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 + "' ");
                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 = 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);
            }
            else return Error("无操作权限！");
        }

        //话务量总体统计
        public ActionResult GetTelCount()
        {
            //话务量
            DataTable dt = DbHelperSQL.Query(" select count(1) con from T_Call_CallRecords where datediff(day, BeginTime, getdate()) = 0 ").Tables[0];

            var hwcon = dt.Rows[0]["con"].ToString();//话务量
            string where = " 1=1 ";
            if (User.F_RoleCode != "GLY")
            {
                where = " UserCode='" + User.F_UserCode + "' ";
            }
            Bll.T_Call_CallRecords bll = new Bll.T_Call_CallRecords();
            var dayinlist = bll.GetModelList(where + " and CallType='0' and datediff(day, BeginTime, getdate()) = 0 "); //来话量
            var dayoutlist = bll.GetModelList(where + " and CallType='1' and datediff(day, BeginTime, getdate()) = 0 ");  //去电量
                                                                                                                          ////来话量
                                                                                                                          //DataTable dt1 = DbHelperSQL.Query(" select count(1) con from T_Call_CallRecords where CallType=0 and datediff(day, BeginTime, getdate()) = 0 ").Tables[0];
                                                                                                                          //var lhcon = dt1.Rows[0]["con"].ToString();//呼入话务量
                                                                                                                          ////去电量
                                                                                                                          //DataTable dt3 = DbHelperSQL.Query(" select count(1) con from T_Call_CallRecords where CallType=1 and datediff(day, BeginTime, getdate()) = 0 ").Tables[0];
                                                                                                                          //var outcon = dt3.Rows[0]["con"].ToString();//呼出话务量

            //接通量,通话时长
            //DataTable dt2 = DbHelperSQL.Query(" select count(1) con,sum(TalkLongTime) tltimes from T_Call_CallRecords where CallState=1 and datediff(day, BeginTime, getdate()) = 0 ").Tables[0];
            var thlist = bll.GetModelList( where + " and CallState=1 and datediff(day, BeginTime, getdate()) = 0 ");
            var jtconin = thlist.Where(p=>p.CallType =='0').Count().ToString();//接通量 来电
            var thsin = thlist.Where(p => p.CallType == '0').Sum(t=>t.TalkLongTime);//通话时长 来电

            var jtconout = thlist.Where(p => p.CallType == '1').Count().ToString();//接通量 去电
            var thsout = thlist.Where(p => p.CallType == '1').Sum(t => t.TalkLongTime);//通话时长 去电

            var thtimesin = "0";
            var thtimesout = "0";
            if (thsin != null && thsin.ToString() != "")
            {
                thtimesin = DateTimeConvert.parseTimeSeconds(int.Parse(thsin.ToString()),0);
            }
            if (thsout != null && thsout.ToString() != "")
            {
                thtimesout = DateTimeConvert.parseTimeSeconds(int.Parse(thsout.ToString()), 0);
            }
            string jtlin = "-";//接通率 --来电
            string jtlout = "-";//接通率 --去电
            if (hwcon != "0")
            {
                jtlin = (double.Parse(jtconin) / double.Parse(hwcon)).ToString("0.00%");
                jtlout = (double.Parse(jtconout) / double.Parse(hwcon)).ToString("0.00%");

            }

            double pjthtimesin = 0.00;//平均通话时长  --来电
            double pjthtimesout = 0.00;//平均通话时长  --去电
            if (jtconin != "0")
            {
                pjthtimesin = Math.Round(double.Parse(thtimesin) / double.Parse(jtconin));
            }
            if (jtconout != "0")
            {
                pjthtimesout = Math.Round(double.Parse(thtimesout) / double.Parse(jtconout));
            }

            var obj = new
            {
                hwcon = hwcon,
                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) },
                jtconin = jtconin,
                jtconout = jtconout,
                thtimesin = thtimesin,
                thtimesout= thtimesout,
                pjthtimesin = pjthtimesin,
                pjthtimesout = pjthtimesout,
                jtlin = jtlin,
                jtlout= jtlout
            };
            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>
        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>
        public ActionResult GetUserListByRoleId(int roleid, string keyword)
        {
            DataTable dt = new DataTable();
            //取得前天日期
            DateTime start = DateTime.Parse(DateTime.Now.AddDays(-2).ToShortDateString() + " 00:00:00");

            string sql1 = "SELECT FromUserId,COUNT(1)AS counts FROM T_Msg_Chat_Map WHERE ToUserId = " + User.F_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_Sex,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 = " + User.F_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);
        }

        public DataTable GetFileData(string ids, string prefix)
        {
            DataTable dt = DbHelperSQL.Query("select * from T_Sys_Accessories WITH(NOLOCK) where F_FileId in (" + ids + ")").Tables[0];
            


            foreach (DataRow dr in dt.Rows)
            {
                if (FileHelper.Exists(FileHelper.GetPath() + dr["F_FileUrl"].ToString()))
                {
                    dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
                }
                else
                {
                    string url = HomeController.Upload(dr["F_FileUrl"].ToString(), dr["F_FileName"].ToString(), "/" + dr["F_FileUrl"].ToString().Replace(dr["F_FileName"].ToString(), ""));
                    if (url == "1")
                        dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
                    else
                        dr["F_FileUrl"] = url;
                }
                
            }

            return dt;
        }
        private string fileurlpath = ConfigHelper.GetValue("fileurlpath");
        /// <summary>
        /// 即时聊天 - 获取最新通讯(获取双方记录【聊天】)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetChatList(int fromuserId)
        {
            DataTable dt = null;
            int recordCount = 0;
            //取得前天日期
            DateTime start = DateTime.Parse(DateTime.Now.AddDays(-2).ToShortDateString() + " 00:00:00");
            //接收坐席Id

            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 (User.F_UserId > 0)
                {
                    sql += " and (b.ToUserId = " + User.F_UserId + " or b.FromUserId = " + User.F_UserId + ") ";
                }
                if (start != null)
                {
                    sql += " and b.CreateDate > '" + start + "' ";
                }
                //查询（聊天记录）
                string sql1 = "SELECT a.Id,a.FromUserId,a.Content,a.Files,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;


                dt.Columns.Add("FileUrl", typeof(object));
            
             //  var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

                foreach (DataRow dr in dt.Rows)
                {
                  
                    if (!string .IsNullOrEmpty (fileurlpath) && !string.IsNullOrEmpty(dr["Files"].ToString()))
                    {
                        dr["FileUrl"] = GetFileData(dr["Files"].ToString(), fileurlpath);
                    }
                }





                    //修改（设置已读）
               string sqlwhere = " ISNULL(IsRead,0) = 0 ";
                if (fromuserId > 0)
                {
                    sqlwhere += " and FromUserId = " + fromuserId + " ";
                }
                if (User.F_UserId > 0)
                {
                    sqlwhere += " and ToUserId = " + User.F_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>
        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

            string sql = " and ISNULL(a.IsDelete,0) = 0 AND ISNULL(c.F_DeleteFlag,0) = 0 ";



            #region 权限设置
            //管理员，坐席班长
            if (User.F_RoleCode == "GLY" || User.F_RoleCode == "DDZG" || User.F_RoleCode == "ZXBZ")
            {
                //
            }
            else
            {
                sql += " and (b.ToUserId = " + User.F_UserId + " OR b.FromUserId = " + User.F_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 desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

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

        /// <summary>
        /// 即时聊天 - 保存最新通讯
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveChatInfo(ChatInput input)
        {
            //发送坐席Id

            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 = User.F_UserId;
            model.ToUserId = input.ToUserId;
            model.ToRoleId = input.ToRoleId;
            model.CreateDate = DateTime.Now;
            model.Files = input.Files;
           
            //如果用户和角色都为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.IsRead = 0;
                modelmap.FromUserId = User.F_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 = " + User.F_UserId + " ";
                DbHelperSQL.ExecuteSql(sqlwhere1);
                //后添加新的信息
                bllmap.Add(modelmap);
                return Success("发送成功");
            }
            return Error("发送失败");
        }

        /// <summary>
        /// 即时通讯 - 获取最新通讯（单方查看）
        /// </summary>
        /// <param name="isread">0未读1已读2全部</param>
        /// <returns></returns>
        public ActionResult GetChatLists(int top, int fromid, int isread = 0)
        {
            DataTable dt = null;
            int recordCount = 0;
            //接收坐席Id

            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 = " + User.F_UserId + " or b.FromUserId = " + User.F_UserId + ") ";
            //}
            //else
            //{
                sql += " and b.ToUserId = " + User.F_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.Files,a.IsToAll,a.CreateDate,b.IsRead,c.F_UserName,c.F_RoleId,c.F_Sex,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;
            dt.Columns.Add("FileUrl", typeof(object));

            //var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

            foreach (DataRow dr in dt.Rows)
            {

                if (!string .IsNullOrEmpty (fileurlpath ) && !string.IsNullOrEmpty(dr["Files"].ToString()))
                {
                    dr["FileUrl"] = GetFileData(dr["Files"].ToString(), fileurlpath);
                }
            }

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

        /// <summary>
        /// 即时通讯 - 获取最新通讯数量（单方查看）
        /// </summary>
        /// <param name="isread">0未读1已读2全部</param>
        /// <returns></returns>
        public ActionResult GetChatCount(int top)
        {
            DataTable dt = null;
            int recordCount = 0;
            //接收坐席Id

            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 = " + User.F_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="User.F_UserId"></param>
        /// <returns></returns>
        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

            string sql = " ISNULL(a.IsDelete,0) = 0 AND ISNULL(c.F_DeleteFlag,0) = 0 "; // AND ISNULL(b.IsRead,0) = 0
            if (User.F_UserId > 0)
            {
                sql += " and b.ToUserId = " + User.F_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 (User.F_UserId > 0)
            {
                sqlwhere += " and ToUserId = " + User.F_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="User.F_UserId"></param>
        /// <returns></returns>
        public ActionResult CloseChat(int id)
        {
            //接收坐席Id

            int recordCount = 0;
            //修改（设置已读）
            string sqlwhere = " ISNULL(IsRead,0) = 0 ";
            if (User.F_UserId > 0)
            {
                sqlwhere += " and ToUserId = " + User.F_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
        /// <summary>
        /// 获取24小时话务受理量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetHWCount24ByNow(string datetime)
        {
            var date = DateTime.Now;
            if (!string .IsNullOrEmpty (datetime))
            {
                date = DateTime.Parse(datetime);
            }
            var hr =24;
            int[] hours = Enumerable.Range(0, hr).ToArray<int>();
            var obj = new
            {
                hours,
                hwcount = new List<int[]>(),
                jtcount = new List<int[]>()
            };

            if (RedisHelper.StringGet("GetHWCount24ByNow" + date.ToString("yyyy-MM-dd")) != null)
            {
                return Content(RedisHelper.StringGet("GetHWCount24ByNow" + date.ToString("yyyy-MM-dd")).ToString());
            }
            else
            {
                string                                                                                                       sql = $"   and datediff(day, BeginTime, '{date.ToString("yyyy-MM-dd")}') = 0  ";
                string sqlhw = " select datepart(hh, BeginTime ) hour,SUM(case CallState when 1 then 1 else 0 end ) jietong ,count(1) count from T_Call_CallRecords where  1=1" + sql + " group by datepart(hh, BeginTime) order by datepart(hh, BeginTime)";
                DataTable dthw = DbHelperSQL.Query(sqlhw).Tables[0];

                int[] hwc = new int[hours.Length]; int[] jcc = new int[hours.Length];
                for (int i = 0; i < hours.Length; i++)
                {
                    var drs = dthw.Select("hour='" + hours[i] + "'");
                    int hw = 0; int jt = 0;
                    if (drs.Length > 0)
                    {
                        hw = (from DataRow dr in drs select dr.Field<int>("count")).FirstOrDefault();
                        jt = (from DataRow dr in drs select dr.Field<int>("jietong")).FirstOrDefault();
                    }
                    jcc[i] = jt;
                    hwc[i] = hw;
                }
                obj.jtcount.Add(jcc);
                obj.hwcount.Add(hwc);
                RedisHelper.StringSet("GetHWCount24ByNow" + date.ToString("yyyy-MM-dd"), obj.ToJson(), new TimeSpan(0, 10, 0));
                return Content(obj .ToJson ());
            }

           

          
        }
    }
}