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

namespace CallCenterApi.Interface.Controllers
{
    public class IndexController : BaseController
    {
        private BLL.T_Sys_ModuleInfo moduleInfoBLL = new BLL.T_Sys_ModuleInfo();
        private BLL.T_Sys_RoleFunction roleFunctionBLL = new BLL.T_Sys_RoleFunction();

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMenu()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                var roleId = CurrentUser.UserData.F_RoleId;
                var functionIdList = roleFunctionBLL.DataTableToList(roleFunctionBLL.GetList(" F_RoleId=" + roleId).Tables[0]).Select(x => x.F_FunctionId);
                var moduleInfoList = moduleInfoBLL.DataTableToList(moduleInfoBLL.GetList(" F_StateFlag=1 ").Tables[0]);
                moduleInfoList.Sort((x, y) => x.F_Sort - y.F_Sort);
                var authModuleFunctionList = moduleInfoList.Where(x => functionIdList.Contains(x.F_ModuleId)).ToList();
                res = Success("获取符合权限的菜单", TreeRecursion(authModuleFunctionList));
            }
            return res;
        }

        private List<Model.T_Sys_ModuleInfo> TreeRecursion(List<Model.T_Sys_ModuleInfo> data, string parentId = "0")
        {
            List<Model.T_Sys_ModuleInfo> newList = new List<Model.T_Sys_ModuleInfo>();
            List<Model.T_Sys_ModuleInfo> item = data.FindAll(t => t.F_ParentID.ToString() == parentId);//data建议在调用此扩展方法前已经排序过
            if (item.Count > 0)
            {
                foreach (Model.T_Sys_ModuleInfo entity in item)
                {
                    entity.ChildNodes = TreeRecursion(data, entity.F_ModuleId.ToString());
                    newList.Add(entity);
                }
            }

            return newList;
        }

        /// <summary>
        /// 上传用户图片
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadTX()
        {
            ActionResult res = NoToken("未知错误，请重新登录");

            if (Request.IsAuthenticated)
            {
                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (userModel != null)
                    {
                        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.Upload();
                            path = "/Upload/ZXTX/" + iu.OutFileName;

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

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

            }
            return res;
        }

        /// <summary>
        /// 上传用户图片
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadTX64()
        {
            ActionResult res = NoToken("未知错误，请重新登录");

            if (Request.IsAuthenticated)
            {

                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (userModel != null)
                    {
                        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.Upload64();

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

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

                                res = 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;
                                }
                                res = Error(msg);
                            }
                        }
                        else
                        {
                            res = Error("请选择要上传的文件");
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 通话记录数量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTelRecordsTotal()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                int userId = CurrentUser.UserData.F_UserId;
                string usercode = CurrentUser.UserData.F_UserCode;
                int roleid = CurrentUser.UserData.F_RoleId;
                if (userId != 0)
                {
                    var date = DateTime.Now;
                    string strDate = date.ToString("yyyy-MM-dd");
                    string strMonth = date.ToString("yyyy-MM");

                    string uwhere = " 1=1 ";
                    if (roleid != 17)
                    {
                        uwhere += " and UserCode='" + usercode + "' ";
                    }

                    BLL.T_Call_CallRecords bll = new BLL.T_Call_CallRecords();
                    //var dayinlist = bll.GetModelList(uwhere + " and CallType='0' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' and CallState='1' ");
                    //var dayoutlist = bll.GetModelList(uwhere + " and CallType='1' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' and CallState='1' ");
                    //var moninlist = bll.GetModelList(uwhere + " and CallType='0' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' and CallState='1' ");
                    //var monoutlist = bll.GetModelList(uwhere + " and CallType='1' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' and CallState='1' ");
                    //int daynocon = bll.GetList("CallType='0' and CONVERT(varchar(100),BeginTime, 23)='" + strDate + "' and CallState='0' ").Tables[0].Rows.Count;

                    //2018-05-03 lihai 首页统计问题
                    var dayinlist = bll.GetModelList(uwhere + " and CallType='0' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' ");
                    var dayoutlist = bll.GetModelList(uwhere + " and CallType='1' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' ");
                    var moninlist = bll.GetModelList(uwhere + " and CallType='0' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' ");
                    var monoutlist = bll.GetModelList(uwhere + " and CallType='1' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' ");

                    int daynocon = bll.GetList("CallType='0' and CallState='0' and datediff(day,BeginTime, '" + strDate + "')=0 ").Tables[0].Rows.Count;
                    //int daynocon = bll.GetList("CallType='0' and CONVERT(varchar(100),BeginTime, 23)='" + strDate + "' ").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
                    };
                    res = Success("成功", obj);
                }
            }
            return res;
        }

        /// <summary>
        /// 获取当月/当天的工单量(已完成，未完成)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkTotal()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                int userId = CurrentUser.UserData.F_UserId;
                int deptid = CurrentUser.UserData.F_DeptId;         //部门id
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (ua != null)
                    {
                        var date = DateTime.Now;//DateTime.Parse("2015-04-14"); //
                        string strDate = date.ToString("yyyy-MM-dd");
                        string strMonth = date.ToString("yyyy-MM");

                        //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];
                        //部门信息
                        var modelDep = new BLL.T_Sys_Department().GetModel(deptid);
                        int depType = 0;
                        if (modelDep != null)
                            depType = modelDep.F_Type ?? 0;  //部门操作权限：1接待部，2办理人员，3区域客服，4监管

                        string uwhere = " 1=1 ";
                        if (ua.F_RoleId != 17 && depType != 1 && depType != 3)
                        {
                            uwhere += " and F_CreateBy='" + ua.F_UserCode + "' ";
                        }

                        BLL.T_Wo_WorkOrder bll = new BLL.T_Wo_WorkOrder();
                        var list1 = bll.GetList(uwhere + " and CONVERT(varchar(10),F_CreateOn, 23)='" + strDate + "' and F_State in(" + (int)EnumWorkOrderState.finish +","+(int)EnumWorkOrderState.evaluate + ") and F_IsDelete=0 ").Tables[0];
                        var list2 = bll.GetList(uwhere + " and CONVERT(varchar(10),F_CreateOn, 23)='" + strDate + "' and F_State in (0,1,2,3,4,5,6,7,12,14,16) and F_IsDelete=0 ").Tables[0];
                        var list3 = bll.GetList(uwhere + " and CONVERT(char(7),F_CreateOn,20)='" + strMonth + "' and F_State in(" + (int)EnumWorkOrderState.finish + "," + (int)EnumWorkOrderState.evaluate+ ") and F_IsDelete=0 ").Tables[0];
                        var list4 = bll.GetList(uwhere + " and CONVERT(char(7),F_CreateOn,20)='" + strMonth + "' and F_State in (0,1,2,3,4,5,6,7,12,14,16) and F_IsDelete=0 ").Tables[0];
                        #region
                        //var list1 = bll.GetList(uwhere + " and CONVERT(varchar(10),CreateTime, 23)='" + strDate + "' and State =2 and IsDel=0 ").Tables[0];
                        //var list2 = bll.GetList(uwhere + " and CONVERT(varchar(10),CreateTime, 23)='" + strDate + "' and State in (0,1) and IsDel=0 ").Tables[0];
                        //var list3 = bll.GetList(uwhere + " and CONVERT(char(7),CreateTime,20)='" + strMonth + "' and State =2 and IsDel=0 ").Tables[0];
                        //var list4 = bll.GetList(uwhere + " and CONVERT(char(7),CreateTime,20)='" + strMonth + "' and State in (0,1) and IsDel=0 ").Tables[0];

                        ////日已完成
                        //var list1 = bll.GetList(uwhere + " and CONVERT(varchar(10),CreateTime, 23)='" + strDate + "' and State =1 and IsDel=0 ").Tables[0];
                        ////日未完成
                        //var list2 = bll.GetList(uwhere + " and CONVERT(varchar(10),CreateTime, 23)='" + strDate + "' and State=0 and IsDel=0 ").Tables[0];
                        ////月已完成
                        //var list3 = bll.GetList(uwhere + " and CONVERT(char(7),CreateTime,20)='" + strMonth + "' and State =1 and IsDel=0 ").Tables[0];
                        ////月未完成
                        //var list4 = bll.GetList(uwhere + " and CONVERT(char(7),CreateTime,20)='" + strMonth + "' and State=0 and IsDel=0 ").Tables[0];
                        #endregion
                        var obj = new
                        {
                            daywc = list1.Rows.Count,
                            daywwc = list2.Rows.Count,
                            monwc = list3.Rows.Count,
                            monwwc = list4.Rows.Count
                        };
                        res = Success("成功", obj);
                     //   res = Success("成功");
                    }
                }
            }
            return res;
        }

        /// <summary>
        /// 当天每小时的总通话量和接通量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTelRecordsByHour()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                int userId = CurrentUser.UserData.F_UserId;
                string usercode = CurrentUser.UserData.F_UserCode;
                int roleid = CurrentUser.UserData.F_RoleId;
                if (userId != 0)
                {
                    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" };

                    string uwhere = " 1=1 ";
                    if (roleid != 17)
                    {
                        uwhere += " and UserCode='" + usercode + "' ";
                    }

                    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(uwhere + " 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
                    };
                    res = Success("成功", obj);
                }

            }
            return res;
        }

        /// <summary>
        /// 获取当月每天的工单量和话务量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkTelByDay()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                int userId = CurrentUser.UserData.F_UserId;
                int deptid = CurrentUser.UserData.F_DeptId;         //部门id
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (ua != 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_Wo_WorkOrderBase workbll = new BLL.T_Wo_WorkOrderBase();
                        //    BLL.T_Wo_WorkOrder workbll = new BLL.T_Wo_WorkOrder();
                        //    int[] teltotal = new int[days];
                        //    int[] worktotal = new int[days];
                        //    //部门信息
                        //    var modelDep = new BLL.T_Sys_Department().GetModel(deptid);
                        //    int depType = 0;
                        //    if (modelDep != null)
                        //        depType = modelDep.F_Type ?? 0;  //部门操作权限：1接待部，2办理人员，3区域客服，4监管

                        //    string uwhere = " 1=1 ";
                        //    string u1where = " 1=1 ";
                        //    if (ua.F_RoleId != 17 && depType != 1 && depType != 3)
                        //    {
                        //        uwhere += " and CreateUser='" + ua.F_UserCode + "' ";
                        //        u1where += " and UserCode='" + ua.F_UserCode + "' ";
                        //    }

                        //    for (int i = 0; i < cols.Count; i++)
                        //    {
                        //        //var tellist = telbll.GetModelList(" UserId='" + userId + "' and CONVERT(varchar(10),BeginTime, 23)='" + (strDate + "-" + cols[i]) + "' ");
                        //        var tellist = telbll.GetModelList(u1where + " and CONVERT(varchar(10),BeginTime, 23)='" + (strDate + "-" + cols[i]) + "' ");
                        //        teltotal[i] = tellist.Count;
                        //        newcount = newcount + tellist.Count;
                        //        //var worklist = workbll.GetList(" F_USERID='" + userId + "' and CONVERT(varchar(10),F_CREATEDATE, 23)='" + (strDate + "-" + cols[i]) + "' ").Tables[0];
                        //        var worklist = workbll.GetList(uwhere + " and CONVERT(varchar(10),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;
                        //    var oldcount = telbll.GetModelList(u1where + " 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
                        //    };

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

                }

            }
            return res;
        }

        /// <summary>
        /// 获取当前用户待派单、待接单、待处理工单数量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkOrderCount()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                int userId = CurrentUser.UserData.F_UserId;
                int deptid = CurrentUser.UserData.F_DeptId;         //部门id
                string deptCode = CurrentUser.UserData.F_DeptCode;  //部门code
                int userRegionId = CurrentUser.UserData.RegionId;  //项目id
                if (userId != 0)
                {
                    var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='TimeLimitDays' ").FirstOrDefault();
                    int days = config != null ? Convert.ToInt32(config.F_ParamValue) : 60;  //默认60天

                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (ua != null)
                    {
                        #region 权限限制    
                        string sql = " and IsDel=0 ";
                        ////部门信息
                        //var modelDep = new BLL.T_Sys_Department().GetModel(deptid);
                        //int depType = 0, depRegion = 0;
                        //if (modelDep != null)
                        //{
                        //    depType = modelDep.F_Type ?? 0;  //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                        //    depRegion = modelDep.F_Header ?? 0; //部门权限范围：9全部，1区域，2项目，3期
                        //}
                        //if (ua.F_RoleId != 17)
                        //{
                        //    if (depType == 2)
                        //    {
                        //        if (depRegion == 1)
                        //        {
                        //            // 查看该区域工单
                        //            //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
                        //            sql += $" and IsUserSend = {userRegionId} ";
                        //        }
                        //        else if (depRegion == 2)
                        //        {
                        //            // 查看该项目工单
                        //            sql += $" and IsAdminSend = {userRegionId} ";
                        //        }
                        //    }
                        //    else if (depType == 3)
                        //    {
                        //        if (depRegion == 1)
                        //        {
                        //            // 查看该区域工单
                        //            //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
                        //            sql += $" and IsUserSend = {userRegionId} ";
                        //        }
                        //    }
                        //    else if (depType == 4)
                        //    {
                        //        if (depRegion == 2)
                        //        {
                        //            // 查看该项目工单
                        //            sql += $" and IsAdminSend = {userRegionId} ";
                        //        }
                        //        else if (depRegion == 9)
                        //        {
                        //            // 查看该部门工单（包括一级，二级）
                        //            string deptCodeNew = String.Empty;
                        //            int deptCodeIndex = 0;                                  //变量声明
                        //            string deptCodeN = deptCode.TrimEnd('|');      //去掉最后一个|
                        //            deptCodeIndex = deptCodeN.LastIndexOf("|");             //获得|的索引
                        //            deptCodeNew = deptCodeN.Substring(0, deptCodeIndex + 1);    //获得目标字符串（//去掉最后一个|后面的字符串）
                        //            //============== 部门权限条件 - 部门 ================
                        //            string arrUser = " select F_UserCode from T_Sys_UserAccount where F_DeptCode LIKE '" + deptCodeNew + "%' ";
                        //            sql += $" and WorkOrderID in (SELECT DISTINCT WorkOrderID FROM dbo.T_Wo_WorkOrderItem WHERE ToUser IN ({arrUser})) ";
                        //        }
                        //    }
                        //}
                        #endregion

                        //BLL.T_Wo_WorkOrder bll = new BLL.T_Wo_WorkOrder();
                        //WorkOrderController woController = new WorkOrderController();
                        //string uwhere = " 1=1  ";
                        ////1、待指派的
                        //if (ua.F_RoleId != 17)
                        //{
                        //    uwhere += " and CreateUser='" + ua.F_UserCode + "' ";
                        //    uwhere += " and State =" + (int)EnumWorkOrderState.neworder + " ";
                        //    //uwhere += " and State =0 ";
                        //}
                        ////2、待接单的
                        //string djdwhere = $" 1=1 and State =" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.ID in ( " + woController.GetDJDWorkOrderID(ua.F_UserCode) + ") ";//" 1=1 and State =1 and WorkOrderID in ( " + woController.GetDJDWorkOrderID(ua.F_UserCode) + ") ";
                        ////3、待完成（处理）的
                        //string dclwhere = $" 1=1 and State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + ") and T_Wo_WorkOrder.ID in ( " + woController.GetDWCWorkOrderID(ua.F_UserCode) + ") ";//" 1=1 and State =1 and WorkOrderID in ( " + woController.GetDWCWorkOrderID(ua.F_UserCode) + ") ";
                        ////4、已处理的
                        //string yclwhere = $" 1=1 and State =" + (int)EnumWorkOrderState.finish + " and LastDealUser = '" + ua.F_UserCode + "' ";//" 1=1 and State =2 and LastDealUser = '" + ua.F_UserCode + "' ";
                        ////5、我参与的
                        //string wcywhere = $" 1=1 and (CreateUser= '" + ua.F_UserCode + "' or T_Wo_WorkOrder.ID in ( " + woController.GetCYWorkOrderID(ua.F_UserCode) + ")) ";//" 1=1 and  (CreateUser= '" + ua.F_UserCode + "' or WorkOrderID in ( " + woController.GetCYWorkOrderID(ua.F_UserCode) + ")) ";
                        ////5、
                        ///工单
                        //string cqwhere = $" 1=1 and DATEADD(DAY,{days},CreateTime) < GETDATE() AND State < " + (int)EnumWorkOrderState.finish + " ";//$" 1=1 and DATEADD(DAY,{days},CreateTime) < GETDATE() AND State < 2  ";
                        ////5、未审核微信工单
                        //string wxwhere = $" 1=1 ";  // ANd Type = (SELECT F_DictionaryValueId FROM dbo.T_Sys_DictionaryValue (NOLOCK) WHERE F_DictionaryFlag = 'GDLY' AND F_Name = '微信')
                        //var obj = new
                        //{
                        //    dpd = bll.GetList(uwhere + sql + " and State=" + (int)EnumWorkOrderState.neworder + " and IsAudit = 1 ").Tables[0].Rows.Count,                    //待指派的统计
                        //    djd = bll.GetList(djdwhere + sql + " and State =" + (int)EnumWorkOrderState.assign + " and IsAudit = 1 ").Tables[0].Rows.Count,    //待接单的统计
                        //    dcl = bll.GetList(dclwhere + sql + " and State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + ") and IsAudit = 1 ").Tables[0].Rows.Count,    //待处理的统计
                        //    ycl = bll.GetList(yclwhere + sql + " and State =" + (int)EnumWorkOrderState.finish + " and IsAudit = 1 ").Tables[0].Rows.Count,    //已处理的统计
                        //    wyc = bll.GetList(wcywhere + sql + " and IsAudit = 1 ").Tables[0].Rows.Count,    //我参与的的统计
                        //    cq = bll.GetList(cqwhere + sql + " AND State < " + (int)EnumWorkOrderState.finish + " and IsAudit = 1 ").Tables[0].Rows.Count,    //超期工单的统计
                        //    wx = bll.GetList(wxwhere + sql + " and IsAudit = 0 ").Tables[0].Rows.Count,    //微信工单的统计
                        //    //dpd = bll.GetList(uwhere + sql+ " and State=0 and IsAudit = 1 ").Tables[0].Rows.Count,                    //待指派的统计
                        //    //djd = bll.GetList(djdwhere + sql + " and State =1 and IsAudit = 1 ").Tables[0].Rows.Count,    //待接单的统计
                        //    //dcl = bll.GetList(dclwhere + sql + " and State =1 and IsAudit = 1 ").Tables[0].Rows.Count,    //待处理的统计
                        //    //ycl = bll.GetList(yclwhere + sql + " and State =2 and IsAudit = 1 ").Tables[0].Rows.Count,    //已处理的统计
                        //    //wyc = bll.GetList(wcywhere + sql + " and IsAudit = 1 ").Tables[0].Rows.Count,    //我参与的的统计
                        //    //cq = bll.GetList(cqwhere + sql + " AND State < 2 and IsAudit = 1 ").Tables[0].Rows.Count,    //超期工单的统计
                        //    //wx = bll.GetList(wxwhere + sql + " and IsAudit = 0 ").Tables[0].Rows.Count,    //微信工单的统计
                        //    //djd = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and Type=1 and (state='0' and ','+ToUser+',' like '%," + ua.F_UserCode + ",%')  ").Select(p => p.WorkOrderID).Distinct().Count(),
                        //    //dcl = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and Type=1 and (state='1' and SureUser='" + ua.F_UserCode + "')  ").Select(p => p.WorkOrderID).Distinct().Count()
                        //};
                        //res = Success("成功", obj);
                        res = Success("");
                    }
                }
            }
            return res;
        }

        /// <summary>
        /// 最近通话记录
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLastCallList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                DataTable dt = new DataTable();
                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (userModel != null)
                    {
                        string strnum = HttpUtility.UrlDecode(RequestString.GetQueryString("num"));

                        int n = 0;
                        if (strnum.Trim() != "")
                        {
                            n = Convert.ToInt32(strnum);
                        }

                        dt = new BLL.T_Call_CallRecords().GetList(n, " UserCode='" + userModel.F_UserCode + "' ", "CallRecordsId desc").Tables[0];
                        var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
                        foreach (DataRow dr in dt.Rows)
                        {
                            string path = dr["FilePath"] != null ? dr["FilePath"].ToString() : "";
                            if (path != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                            {
                                var ym = config.F_ParamValue;
                                if (ym.Substring(ym.Length - 1) == "/")
                                {
                                    ym = ym.Substring(0, ym.Length - 1);
                                }
                                dr["FilePath"] = ym + path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                            }
                        }
                        res = Success("成功", dt);
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 最近消息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLastMsgList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                DataTable dt = new DataTable();
                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (userModel != null)
                    {
                        string strnum = HttpUtility.UrlDecode(RequestString.GetQueryString("num"));

                        int n = 0;
                        if (strnum.Trim() != "")
                        {
                            n = Convert.ToInt32(strnum);
                        }

                        dt = new BLL.T_Msg_List().GetList(n, " ToUser='" + userModel.F_UserCode + "' and IsDel=0 ", "ID desc").Tables[0];

                        res = Success("成功", dt);
                    }
                }

            }
            return res;
        }
    }
}