using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
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();

        /// <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");

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

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

            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"); //
            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" };
            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];
            for (int i = 0; i < cols.Count; i++)
            {
                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;
            }

            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 ";
            }
            var oldcount = telbll.GetModelList(oldwhere + " and CONVERT(varchar(10),BeginTime, 23)>='" + strold1 + "' and CONVERT(varchar(10),BeginTime, 23)<='" + strold2 + "' ").Count;

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

            if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "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);
            }
            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLY")
            {
                int[] sts = { 1, 3, 5, 7 };

                string sql = "select F_WorkState as state,count(1) con from T_Bus_WorkOrder where F_IsDelete=0 and F_WorkState in (1,3,5,7) "
                    + " 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);
            }
            if (userModel.F_RoleCode == "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);
            }
            if (userModel.F_RoleCode == "GLY")
            {
                int[] sts = { 0, 1, 2, 3, 4, 10, 5, 6, 7, 8 };
                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";

                var dt = DbHelperSQL.Query(sql).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, '')='' )";
                        return new
                        {
                            state = p,
                            con = DbHelperSQL.GetSingle(sqlxb).ToString()
                        };
                    }
                });

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

        /// <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 += ")";
            }
            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
            };
            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()
        {
            DataTable dt = new DataTable();
            dt = rolebll.GetAllList().Tables[0];
            var dtCache = CacheHelper.Get<DataTable>($"RoleList");
            if (dtCache != null)
            {
                return Success("获取成功", dtCache);
            }
            CacheHelper.Insert($"RoleList", dt, 10);
            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}");
            if (dtCache != null)
            {
                #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);
            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

        /// <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="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
    }
}