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

namespace CallCenterApi.Interface.Controllers
{
    public class LoginController : BaseController
    {
        private BLL.T_Sys_RoleFunction roleFunctionBLL = new BLL.T_Sys_RoleFunction();
        public DateTime ExpiredTime = DateTime.Now.AddDays(1);// Convert.ToDateTime(ReadFile(HttpRuntime.AppDomainAppPath + "tools\\hykj.hy"));
        [HttpPost]
        public ActionResult login(LoginModel login)
        {
            var date = DateTime.Parse(Configs.GetValue("AuthDate"));
            try
            {
                if (date < DateTime.Now)
                {
                    return Error("授权过期，请联系系统厂家。");
                }
            }
            catch (Exception ex)
            {
                var log = LogFactory.GetLogger(this.GetType().ToString());
                log.Error(Configs.GetValue("AuthDate"));
                log.Error(ex.ToString());
            }
            bool appResult = LoodLoop();
            if (appResult)
            {
                DataTable dt = new DataTable();
                try
                {
                    #region 密码解密
                    string st = DateTime.Parse(login.LoginTime).ToString("HHmmss");
                    var otherController = DependencyResolver.Current.GetService<AES256Controller>();
                    string pw = "";
                    try
                    {
                        pw = otherController.Decrypt(login.Password.Trim(), st);

                    }
                    catch (Exception e)
                    {
                        return Error("错误:" + e.Message);
                    }
                    #endregion

                    Dictionary<string, string> paras = new Dictionary<string, string>();
                    string sql = "";
                    try
                    {
                        int code = int.Parse(login.Username);
                        sql = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode and F_PassWord=@F_PassWord";
                        paras.Add("@F_UserCode", login.Username);
                        paras.Add("@F_PassWord", pw);//login.Password
                    }
                    catch
                    {
                        sql = " select * from T_Sys_UserAccount where F_UserName=@F_UserName and F_PassWord=@F_PassWord";
                        paras.Add("@F_UserName", login.Username);
                        paras.Add("@F_PassWord", pw);//login.Password
                    }

                    dt = DbHelperSQL.Query(sql, paras).Tables[0];
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            if (dt.Rows[0]["F_DeleteFlag"] != null && dt.Rows[0]["F_DeleteFlag"].ToString() == "1")
                            {
                                int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                    F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                    F_Result = "禁用账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });

                                return Error("此账号已经被禁用");
                            }
                            else if (dt.Rows[0]["F_DeleteFlag"] != null && dt.Rows[0]["F_DeleteFlag"].ToString() == "2")
                            {
                                var LoginLogs = DbHelperSQL.Query($"select top 1 *from  T_Sys_LoginLogs where F_LoginName='{dt.Rows[0]["F_UserName"].ToString()}'" +
                                    $"and F_LoginId='{Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString())}' " +
                                    $"and F_Result like '%锁定账号登录%' order by F_LoginDate desc  ").Tables[0];
                                if (LoginLogs != null )
                                {
                                    if (LoginLogs.Rows .Count >0)
                                    {
                                        if ((DateTime .Now -DateTime .Parse (LoginLogs.Rows [0]["F_LoginDate"].ToString())).TotalMinutes >30)
                                        {
                                            string sql2 = $"update T_Sys_UserAccount set F_DeleteFlag=0 where F_UserCode='{dt.Rows[0]["F_UserCode"].ToString()}'";
                                            var dt2 = DbHelperSQL.ExecuteSql(sql2);
                                        }
                                        else
                                        {
                                            int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                            {
                                                F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                                F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                                F_Result = "锁定账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                                F_LoginIP = Common.DTRequest.GetIP(),
                                                F_Hostname = Common.DTRequest.GetIP(),
                                                F_LoginDate = DateTime.Now,
                                                F_Remark = "",
                                                F_State = 0
                                            });
                                            return Error("此账号已经被锁定,请联系管理员解锁");
                                        }
                                    }
                                }
                                else
                                {
                                    int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                    {
                                        F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                        F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                        F_Result = "锁定账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                        F_LoginIP = Common.DTRequest.GetIP(),
                                        F_Hostname = Common.DTRequest.GetIP(),
                                        F_LoginDate = DateTime.Now,
                                        F_Remark = "",
                                        F_State = 0
                                    });
                                    return Error("此账号已经被锁定,请联系管理员解锁");
                                }
                               




                              
                            }
                            Dictionary<string, string> Dic = new Dictionary<string, string>();
                            Dic.Add("F_UserID", dt.Rows[0]["F_UserId"].ToString());
                            Dic.Add("F_UserCode", dt.Rows[0]["F_UserCode"].ToString());
                          
                            Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToString());
                            Dic.Add("F_SeartGroupID", dt.Rows[0]["F_SeartGroupID"].ToString());

                            new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                F_Result = "登录成功",
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                            var token = FormsPrincipal<Dictionary<string, string>>.GetCookieValue(Dic["F_UserCode"], Dic);
                            var user = new BLL.T_Sys_UserAccount().GetModel(dt.Rows[0]["F_UserCode"].ToString());
                            if (user != null)
                            {
                                user.F_LastActiveTime = DateTime.Now;
                                new BLL.T_Sys_UserAccount().Update(user);
                            }

                            if (dt.Rows[0]["F_TmId"] != null && dt.Rows[0]["F_TmId"].ToString() != "")
                            {
                                if (int.Parse(dt.Rows[0]["F_TmId"].ToString()) >0)
                                {
                                    string sql2 = $"update T_Sys_UserAccount set F_TmId=0 where F_UserCode='{dt.Rows[0]["F_UserCode"].ToString()}'";
                                    var dt2 = DbHelperSQL.ExecuteSql(sql2);
                                }
                               
                            }
                            return Success("登录成功", new
                            {
                                token = token
                            });

                        }
                        else
                        {
                            //写入登录日志
                            //DataTable dt1 = new CallCenterApi.BLL.T_Sys_UserAccount().GetList("F_UserCode='" + login.Username + "'").Tables[0];

                            Dictionary<string, string> paras1 = new Dictionary<string, string>();

                            string sql1 = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode or F_UserName=@F_UserName ";
                            paras1.Add("@F_UserCode", login.Username);
                            paras1.Add("@F_UserName", login.Username);

                            var dt1 = DbHelperSQL.Query(sql1, paras1).Tables[0];
                            if (dt1.Rows.Count > 0)
                            {

                                if (dt1.Rows[0]["F_DeleteFlag"] != null && dt1.Rows[0]["F_DeleteFlag"].ToString() == "2")
                                {
                                    var LoginLogs = DbHelperSQL.Query($"select top 1 * from  T_Sys_LoginLogs where F_LoginName='{dt1.Rows[0]["F_UserName"].ToString()}'" +
                                        $"and F_LoginId='{Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString())}' " +
                                        $"and F_Result like '%锁定账号登录%' order by F_LoginDate desc  ").Tables[0];
                                    if (LoginLogs != null)
                                    {
                                        if (LoginLogs.Rows.Count > 0)
                                        {
                                            if ((DateTime.Now - DateTime.Parse(LoginLogs.Rows[0]["F_LoginDate"].ToString())).TotalMinutes > 30)
                                            {
                                                string sql2 = $"update T_Sys_UserAccount set F_DeleteFlag=0 where F_UserCode='{dt1.Rows[0]["F_UserCode"].ToString()}'";
                                                var dt2 = DbHelperSQL.ExecuteSql(sql2);
                                                dt1.Rows[0]["F_TmId"] = "0";
                                            }
                                            else
                                            {
                                                int rt = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                                {
                                                    F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                                    F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                                    F_Result = "锁定账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                                    F_LoginIP = Common.DTRequest.GetIP(),
                                                    F_Hostname = Common.DTRequest.GetIP(),
                                                    F_LoginDate = DateTime.Now,
                                                    F_Remark = "",
                                                    F_State = 0
                                                });
                                                return Error("此账号已经被锁定,请联系管理员解锁");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        int rt = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                        {
                                            F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                            F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                            F_Result = "锁定账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                            F_LoginIP = Common.DTRequest.GetIP(),
                                            F_Hostname = Common.DTRequest.GetIP(),
                                            F_LoginDate = DateTime.Now,
                                            F_Remark = "",
                                            F_State = 0
                                        });
                                        return Error("此账号已经被锁定,请联系管理员解锁");
                                    }
                                }

                              
                                if (dt1.Rows[0]["F_TmId"]!=null && dt1.Rows[0]["F_TmId"].ToString ()!="")
                                {
                                    if (int .Parse (dt1.Rows[0]["F_TmId"].ToString()) >=4)
                                    {
                                        string sql2 = $"update T_Sys_UserAccount set F_TmId=0,F_DeleteFlag=2 where F_UserCode='{dt1.Rows[0]["F_UserCode"].ToString()}'";
                                        var dt2 = DbHelperSQL.ExecuteSql(sql2);
                                        int rt = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                        {
                                            F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                            F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                            F_Result = "锁定账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                            F_LoginIP = Common.DTRequest.GetIP(),
                                            F_Hostname = Common.DTRequest.GetIP(),
                                            F_LoginDate = DateTime.Now,
                                            F_Remark = "",
                                            F_State = 0
                                        });

                                        return Error("此账号已经被锁定,请联系管理员解锁");
                                    }
                                    else 
                                    {
                                        int n = int.Parse(dt1.Rows[0]["F_TmId"].ToString()) + 1;
                                        string sql2 = $"update T_Sys_UserAccount set F_TmId={n} where F_UserCode='{dt1.Rows[0]["F_UserCode"].ToString()}'";
                                        var dt2 = DbHelperSQL.ExecuteSql(sql2);
                                        int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                        {
                                            F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                            F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                            F_Result = "登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                            F_LoginIP = Common.DTRequest.GetIP(),
                                            F_Hostname = Common.DTRequest.GetIP(),
                                            F_LoginDate = DateTime.Now,
                                            F_Remark = "",
                                            F_State = 0
                                        });
                                        // RedisHelper2.KeyDelete("T_Sys_UserAccount");
                                    }
                                }
                                else
                                {
                                    string sql2 = $"update T_Sys_UserAccount set F_TmId=1 where F_UserCode='{dt1.Rows[0]["F_UserCode"].ToString()}'";
                                    var dt2 = DbHelperSQL.ExecuteSql(sql2);
                                    int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                    {
                                        F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                        F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                        F_Result = "登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                        F_LoginIP = Common.DTRequest.GetIP(),
                                        F_Hostname = Common.DTRequest.GetIP(),
                                        F_LoginDate = DateTime.Now,
                                        F_Remark = "",
                                        F_State = 0
                                    });
                                    // RedisHelper2.KeyDelete("T_Sys_UserAccount");
                                }


                            }
                            else
                            {
                                int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = login.Username,
                                    F_LoginId = -1,
                                    F_Result = "登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });
                            }
                            return Error("账号或密码错误，请重新登录");
                        }
                    }
                    else
                    {
                        return Error("账号或密码错误，请重新登录");
                    }
                }
                catch (Exception ex)
                {
                    return Error("错误:" +ex .Message );
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }
            }
            else
            {
                return Error("授权过期，请联系系统厂家。");
            }
        }
        public ActionResult GetAuAuthDate()
        {
            var date = DateTime.Parse(Configs.GetValue("AuthDate"));
            try
            {
               
                if (date < DateTime.Now)
                {
                    return Error("授权过期，请联系系统厂家。");
                }
            }
            catch (Exception ex)
            {
                var log = LogFactory.GetLogger(this.GetType().ToString());
               log.Error(Configs.GetValue("AuthDate"));
                log.Error(ex.ToString());
            }
            return Success("成功", date);
       }



        [HttpPost]
        public ActionResult applogin(LoginModel login)
        {
            bool appResult = LoodLoop();
            if (appResult)
            {
                DataTable dt = new DataTable();
                try
                {
                    #region 密码解密
                    string st = DateTime.Parse(login.LoginTime).ToString("HHmmss");
                    var otherController = DependencyResolver.Current.GetService<AES256Controller>();
                    string pw = "";
                    try
                    {
                        pw = otherController.Decrypt(login.Password.Trim(), st);

                    }
                    catch (Exception e)
                    {
                        return Error("错误:" + e.Message);
                    }
                    #endregion

                    Dictionary<string, string> paras = new Dictionary<string, string>();
                    string sql = "";
                    try
                    {
                        int code = int.Parse(login.Username);
                        sql = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode and F_PassWord=@F_PassWord";
                        paras.Add("@F_UserCode", login.Username);
                        paras.Add("@F_PassWord", pw);//login.Password
                    }
                    catch
                    {
                        sql = " select * from T_Sys_UserAccount where F_UserName=@F_UserName and F_PassWord=@F_PassWord";
                        paras.Add("@F_UserName", login.Username);
                        paras.Add("@F_PassWord", pw);//login.Password
                    }

                    dt = DbHelperSQL.Query(sql, paras).Tables[0];
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            if (dt.Rows[0]["F_DeleteFlag"] != null && dt.Rows[0]["F_DeleteFlag"].ToString() == "1")
                            {
                                int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                    F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                    F_Result = "禁用账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });

                                return Error("此账号已经被禁用");
                            }
                            Dictionary<string, string> Dic = new Dictionary<string, string>();
                            Dic.Add("F_UserID", dt.Rows[0]["F_UserId"].ToString());
                            Dic.Add("F_UserCode", dt.Rows[0]["F_UserCode"].ToString());

                            Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToString());


                            new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                F_Result = "登录成功",
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                            var token = FormsPrincipal<Dictionary<string, string>>.GetCookieValue(Dic["F_UserCode"], Dic);
                            var user = new BLL.T_Sys_UserAccount().GetModel(dt.Rows[0]["F_UserCode"].ToString());
                            if (user != null)
                            {
                                user.F_LastActiveTime = DateTime.Now;
                                new BLL.T_Sys_UserAccount().Update(user);
                            }


                            return Success("APP登录成功", new
                            {
                                token = token
                            });

                        }
                        else
                        {
                         

                            Dictionary<string, string> paras1 = new Dictionary<string, string>();

                            string sql1 = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode or F_UserName=@F_UserName ";
                            paras1.Add("@F_UserCode", login.Username);
                            paras1.Add("@F_UserName", login.Username);

                            var dt1 = DbHelperSQL.Query(sql1, paras1).Tables[0];
                            if (dt1.Rows.Count > 0)
                            {
                                int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                    F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                    F_Result = "APP登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });
                            }
                            else
                            {
                                int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = login.Username,
                                    F_LoginId = -1,
                                    F_Result = "APP登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });
                            }
                            return Error("账号或密码错误，请重新登录");
                        }
                    }
                    else
                    {
                        return Error("账号或密码错误，请重新登录");
                    }
                }
                catch (Exception ex)
                {
                    return Error("错误:" + ex.Message);
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }
            }
            else
            {
                return Error("授权过期，请联系系统厂家。");
            }
        }
        //[HttpPost]
        //public ActionResult applogin(LoginModel login)
        //{
        //    bool appResult = LoodLoop();
        //    if (appResult)
        //    {
        //        DataTable dt = new DataTable();
        //        try
        //        {
        //            Dictionary<string, string> paras = new Dictionary<string, string>();
        //            string sql = " select * from T_Sys_UserAccount where (F_UserCode=@F_UserCode or F_UserName=@F_UserName) and F_PassWord=@F_PassWord and F_DeleteFlag=0";
        //            paras.Add("@F_UserCode", login.Username);
        //            paras.Add("@F_UserName", login.Username);
        //            paras.Add("@F_PassWord", login.Password);

        //            dt = DbHelperSQL.Query(sql, paras).Tables[0];

        //            if (dt.Rows.Count > 0)
        //            {
        //                if (dt.Rows[0]["F_DeleteFlag"] != null && dt.Rows[0]["F_DeleteFlag"].ToString() == "1")
        //                {
        //                    int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
        //                    {
        //                        F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
        //                        F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
        //                        F_Result = "禁用账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
        //                        F_LoginIP = Common.DTRequest.GetIP(),
        //                        F_Hostname = Common.DTRequest.GetIP(),
        //                        F_LoginDate = DateTime.Now,
        //                        F_Remark = "",
        //                        F_State = 0
        //                    });

        //                    return Error("此账号已经被禁用");
        //                }

        //                string rid = dt.Rows[0]["F_RoleID"].ToString();
        //                var role = new BLL.T_Sys_RoleInfo().GetModel(Int32.Parse(rid));
        //                if (role.F_RoleCode == "EJWLDW" || role.F_RoleCode == "WLDW" || role.F_RoleCode=="DBZY"
        //                    || role.F_RoleCode == "ZXLD"|| role .F_RoleCode == "MTDD" || role.F_RoleCode == "ZXLDGLY" || role.F_RoleCode == "GLY" || role.F_RoleCode== "DDZG" || role.F_RoleCode == "DFZF")
        //                {
        //                    Dictionary<string, string> Dic = new Dictionary<string, string>();
        //                    Dic.Add("F_UserID", dt.Rows[0]["F_UserId"].ToString());
        //                    Dic.Add("F_UserCode", dt.Rows[0]["F_UserCode"].ToString());

        //                    Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToString());

        //                    //CookieUtil.SetCookie("BaseCallCenter_T_User", Dic);
        //                    //写入登录日志
        //                    new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
        //                    {
        //                        F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
        //                        F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
        //                        F_Result = "APP登录成功",
        //                        F_LoginIP = Common.DTRequest.GetIP(),
        //                        F_Hostname = Common.DTRequest.GetIP(),
        //                        F_LoginDate = DateTime.Now,
        //                        F_Remark = "",
        //                        F_State = 0
        //                    });

        //                    var token = FormsPrincipal<Dictionary<string, string>>.GetCookieValue(Dic["F_UserCode"], Dic);


        //                    return Success("登录成功", new
        //                    {
        //                        token = token
        //                    });

        //                }
        //                else
        //                {
        //                    return Error("权限不足");
        //                }
        //            }
        //            else
        //            {
        //                //写入登录日志
        //                //DataTable dt1 = new CallCenterApi.BLL.T_Sys_UserAccount().GetList("F_UserCode='" + login.Username + "'").Tables[0];
        //                Dictionary<string, string> paras1 = new Dictionary<string, string>();

        //                string sql1 = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode or F_UserName=@F_UserName ";
        //                paras1.Add("@F_UserCode", login.Username);
        //                paras1.Add("@F_UserName", login.Username);
        //                var dt1 = DbHelperSQL.Query(sql1, paras1).Tables[0];
        //                if (dt1.Rows.Count > 0)
        //                {
        //                    int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
        //                    {
        //                        F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
        //                        F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
        //                        F_Result = "APP登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
        //                        F_LoginIP = Common.DTRequest.GetIP(),
        //                        F_Hostname = Common.DTRequest.GetIP(),
        //                        F_LoginDate = DateTime.Now,
        //                        F_Remark = "",
        //                        F_State = 0
        //                    });
        //                }
        //                else
        //                {
        //                    int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
        //                    {
        //                        F_LoginName = login.Username,
        //                        F_LoginId = -1,
        //                        F_Result = "APP登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
        //                        F_LoginIP = Common.DTRequest.GetIP(),
        //                        F_Hostname = Common.DTRequest.GetIP(),
        //                        F_LoginDate = DateTime.Now,
        //                        F_Remark = "",
        //                        F_State = 0
        //                    });
        //                }
        //                return Error("账号或密码错误，请重新登录");
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            return Error("错误:" + ex.Message);
        //        }
        //        finally
        //        {
        //            dt.Clear();
        //            dt.Dispose();
        //        }
        //    }
        //    else
        //    {
        //        return Error("授权过期，请联系系统厂家。");
        //    }
        //}
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public ActionResult Logout(string token = "")
        {
            if (Request.IsAuthenticated)
            {
                //CacheHelper.Remove(token);
                //RedisHelper.KeyDelete(CommonHelper.MD5(token));
            }
            return Success("退出成功");
        }

        [Authority]
        public ActionResult Authority(string token = "", string url = "")
        {
            var roleId = User.F_RoleId;
            var role = new BLL.T_Sys_RoleInfo().GetModel(roleId);
            if (role != null)
            {
                //var roleFunctionList = roleFunctionBLL.DataTableToList(roleFunctionBLL.GetList(" F_RoleId=" + role.F_RoleId).Tables[0]);
                //var moduleFunction = new BLL.T_Sys_Function().GetModel(url);
                //if (moduleFunction != null)
                //{
                //    var single = roleFunctionList.SingleOrDefault(x => x.F_FunctionId == moduleFunction.F_FunctionId);
                //    if (single != null)
                //    {
                //        return Success("", moduleFunction.F_OptUrl);
                //    }
                //}
                return Success("成功");
            }
            return UnAuthorized("未授权");

        }

        /// <summary>
        /// 移除缓存后调用
        /// </summary>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <param name="reason"></param>
        public void onRemove(string key, object val, CacheItemRemovedReason reason)
        {
            var obj = new
            {
                key = key,
                val = val,
                reason = reason
            };
            Warn(obj.ToJson());
        }

        /// <summary>
        /// 验证授权
        /// </summary>
        /// <returns></returns>
        private bool LoodLoop()
        {
            bool result = CheckValid();
            //return true;
            if (result)
                return true;
            else
                return false;
        }
        private bool CheckValid()
        {
            return DateTime.Now < ExpiredTime;
        }
        private static string ReadFile(string filepath)
        {
            string str = System.IO.File.ReadAllText(filepath, Encoding.UTF8);
            return DESEncrypt.Decrypt(str);
        }
    }
}