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;
using Newtonsoft.Json.Linq;

namespace CallCenterApi.Interface.Controllers
{
    public class LoginController : BaseController
    {
        private BLL.T_Sys_RoleFunction roleFunctionBLL = new BLL.T_Sys_RoleFunction();
       private string appId = Configs.GetValue("appId");
        private string appSecret = Configs.GetValue("appSecret");
        private string channel = Configs.GetValue("channel");
        private string clientUserName = Configs.GetValue("clientUserName");

        public ActionResult auth(string value)
        {
            DbHelperSQL.ExecuteSql(" update T_Sys_Work set work='" + value + "'");
            return Success("成功");
        }

        public ActionResult getAuthTime()
        {

            string ww = DbHelperSQL.GetSingle("select top 1 work from T_Sys_Work").ToString();
            var tp3 = EncryptHelper.DecryptAES(ww);

            DateTime time = DateTimeConvert.FromTimetag(long.Parse(tp3));
            return Success("成功", time);
        }
        //appId=[zmds12345szrxzx]
        //appSecret=[63846190e8f346cd8e5a75e4ecc0bae4]
        //systemId=[zmds12345szrxzx] channel=[4413]


        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"));
            //var days = int.Parse(Configs.GetValue("AuthDateDays"));
            //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());
           // }
            if (string.IsNullOrEmpty(login.Code))
                return Error("请输入验证码");
            if (string.IsNullOrEmpty(login.Username))
                return Error("账号不能为空！");
            if (string.IsNullOrEmpty(login.Password))
                return Error("密码不能为空！");

            int exi = Convert.ToInt32(DbHelperSQL.GetSingle("  select  count(1) from  syscolumns  where  id=object_id('t_sys_work')   "));
            if (exi == 0)
            {
                DbHelperSQL.ExecuteSql(" create table T_Sys_Work ( Id INT PRIMARY KEY identity(1,1),Work Nvarchar(200) )");               


                long tp = DateTimeConvert.ToTimetag(DateTime.Now.AddDays(11));

                string work = EncryptHelper.EncryptAES(tp.ToString());

                DbHelperSQL.ExecuteSql(" insert into T_Sys_Work(work) values('" + work + "')");


                string ww = DbHelperSQL.GetSingle("select top 1 work from T_Sys_Work").ToString();
                var tp3 = EncryptHelper.DecryptAES(ww);

                DateTime time = DateTimeConvert.FromTimetag(long.Parse(tp3));
                if (DateTime.Now > time)
                {
                    return Error("授权时间已过期");
                }


            }
            else
            {
                string ww = DbHelperSQL.GetSingle("select top 1 work from T_Sys_Work").ToString();
                var tp = EncryptHelper.DecryptAES(ww);

                DateTime time = DateTimeConvert.FromTimetag(long.Parse(tp));
                if (DateTime.Now > time)
                {
                    return Error("授权时间已过期");
                }

            }



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

                    dt = DbHelperSQL.Query(sql, paras).Tables[0];
                 if (dt != null && dt.Rows.Count>0)
                      
                        {

                        var code = new BLL.T_Sys_VerificationCode().GetModelList("F_Timestamp='" + login.Timestamp + "' " +
                            "and F_Code='" + login.Code + "'order by F_CreateTime desc");
                        if (code != null && code.Count > 0)
                        {
                            var modelSms = code.First();
                            if ((DateTime.Now - modelSms.F_CreateTime.Value).Minutes > 10)
                            {
                                return Error("验证码已失效");
                            }
                        }
                        else
                        {
                            return Error("验证码错误");
                        }



                        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_DeptId", dt.Rows[0]["F_DeptId"].ToString());
                            Dic.Add("F_UserName", dt.Rows[0]["F_UserName"].ToString());
                            //Dic.Add("F_Telephone", dt.Rows[0]["F_Telephone"].ToString());
                            Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToString());
                            Dic.Add("F_SeatFlag", dt.Rows[0]["F_SeatFlag"].ToString());

                            if (dt.Rows[0]["F_GroupId"].ToString() != null)
                            {
                                Dic.Add("F_GroupId", dt.Rows[0]["F_GroupId"].ToString());
                            }
                            if (dt.Rows[0]["F_SeatRight"].ToString() != null)
                            {
                                Dic.Add("F_SeatRight", dt.Rows[0]["F_SeatRight"].ToString());
                            }
                            if (!string.IsNullOrEmpty(login.ExtensionPhone))
                            {
                                Dic.Add("F_ExtensionNumber", login.ExtensionPhone);
                            }
                            else
                            {
                                Dic.Add("F_ExtensionNumber", "");
                            }
                            Dic.Add("F_WorkNumber", dt.Rows[0]["F_WorkNumber"].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 = "登录成功",
                                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);

                            ////放入缓存
                            //CacheHelper.Insert(token, Dic, 1440, System.Web.Caching.CacheItemPriority.NotRemovable, onRemove);
                            //放入redis缓存
                            RedisHelper.StringSet(token,Dic.ToJson(),new TimeSpan(24,0,0));

                            //var datetime = date - DateTime.Now;
                            //string message = "";
                            //if (datetime.TotalDays< days)
                            //{
                            //    message = datetime.TotalDays.ToString ();
                                
                            //}

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

                        }
                        else
                        {
                            //写入登录日志
                            DataTable dt1 = new CallCenterApi.BLL.T_Sys_UserAccount().GetList("F_UserCode='" + login.Username + "'").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 = "登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });
                                if (dt.Rows[0]["F_DeleteFlag"] != null && dt.Rows[0]["F_DeleteFlag"].ToString() == "1")
                                {
                                    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=1 " +
                                            $"where F_UserCode='{dt1.Rows[0]["F_UserCode"].ToString()}'";
                                        var dt2 = DbHelperSQL.ExecuteSql(sql2);
                                        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);
                                    }
                                }
                                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);
                                }
                            }
                            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"));
            var days = int.Parse(Configs.GetValue("AuthDateDays"));
            var datetime = date - DateTime.Now;
            string message = "";

            try
            {

                if (date < DateTime.Now)
                {
                    return Error("授权过期，请联系系统厂家。");
                }
                else
                {
                    if (datetime.TotalDays < days)
                    {
                        return Success("系统将在" + datetime.TotalDays + "天后到期停止使用，请及时联系管理员");
                    }
                }
            }
            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
                {
                    Dictionary<string, string> paras = new Dictionary<string, string>();
                    string sql = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode and F_PassWord=@F_PassWord and F_DeleteFlag=0";
                    paras.Add("@F_UserCode", 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 == "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_DeptId", dt.Rows[0]["F_DeptId"].ToString());
                            Dic.Add("F_UserName", dt.Rows[0]["F_UserName"].ToString());
                            Dic.Add("F_Telephone", dt.Rows[0]["F_Telephone"].ToString());
                            Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToString());
                            Dic.Add("F_SeatFlag", dt.Rows[0]["F_SeatFlag"].ToString());

                            if (dt.Rows[0]["F_GroupId"].ToString() != null)
                            {
                                Dic.Add("F_GroupId", dt.Rows[0]["F_GroupId"].ToString());
                            }
                            if (dt.Rows[0]["F_SeatRight"].ToString() != null)
                            {
                                Dic.Add("F_SeatRight", dt.Rows[0]["F_SeatRight"].ToString());
                            }
                            if (!string.IsNullOrEmpty(login.ExtensionPhone))
                            {
                                Dic.Add("F_ExtensionNumber", login.ExtensionPhone);
                            }
                            else
                            {
                                Dic.Add("F_ExtensionNumber", "");
                            }
                            Dic.Add("F_WorkNumber", dt.Rows[0]["F_WorkNumber"].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);

                            ////放入缓存
                            //CacheHelper.Insert(token, Dic, 1440, System.Web.Caching.CacheItemPriority.NotRemovable);
                            //放入redis缓存
                            RedisHelper.StringSet(token, Dic.ToJson(), new TimeSpan(24, 0, 0));
                            return Success("登录成功", new
                            {
                                token = token
                            });
                            
                        }
                        else
                        {
                            return Error("权限不足");
                        }
                    }
                    else
                    {
                        //写入登录日志
                        DataTable dt1 = new CallCenterApi.BLL.T_Sys_UserAccount().GetList("F_UserCode='" + login.Username + "'").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("授权过期，请联系系统厂家。");
            }
        }

        public ActionResult Logout(string token = "")
        {
            if (Request.IsAuthenticated)
            {
                //CacheHelper.Remove(token);
                RedisHelper.KeyDelete(token);
            }
            return Success("退出成功");
        }

        [Authority]
        public ActionResult Authority(string token = "", string url = "")
        {
            var roleId = Utils.StrToInt(User.UserData["F_RoleID"], 0);
            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);
        }

       
        public ActionResult AutoLogin(string usercode)
        {
            //只有一个账户免鉴权自动登录，别的账户跳转到舆情登录页面

            if (usercode!= clientUserName)
            {
                string url = "http://hnlt.yqt365.com";
                return Success("成功", url);
            }

            //1  .获取授权码
            string authorizeCode = CallBack();
            if (string.IsNullOrEmpty(authorizeCode))
            {
                return Error("自动登录失败");
            }
            //2 .获取access_token
            string accesstoken=CallBackAccessToken(authorizeCode);
            if (string.IsNullOrEmpty(accesstoken))
            {
                return Error("自动登录失败");
            }
            //3;
            try
            {
                DateTime stime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970,1,1,0,0,0,0));
                long times = (long)(DateTime.Now - stime).TotalMilliseconds;
                string timeStamp = times.ToString();
                 
             
                //获取授权过的Access Token    通过Authorization Code 
                string token_url = "https://api-open.yqt365.com/api/login/v1/ssoLogin?responseType=code&"
                + "systemId=" + appId + "&timeStamp=" + timeStamp + "&clientUserName=" + clientUserName + "&channel=" + channel + "&accessToken=" + accesstoken;

                return Success("成功", token_url);

            


            }
            catch (Exception ex)
            {
                FileLog.Error("获取舆情登录authorizeCode失败:" + ex.Message + "");
                return Error("跳转登录失败") ;
            }




           
          
        }
        //获取授权码
        public string CallBack()
        {
            string returnauthorizeCode = "";
            if (RedisHelper.StringGet("authorizeCode") != null)
            {
                returnauthorizeCode = RedisHelper.StringGet("authorizeCode").ToString();
                return returnauthorizeCode;
            };
        
            Random random = new Random();
            int randomNumber = random.Next(1000, 9999); // 生成1到100的随机整数
            string state = "state" + randomNumber.ToString();
            try
            {
                //获取授权过的Access Token    通过Authorization Code 
                string token_url = "https://api-open-wx-www.yqt365.com/dataapp/api/oauth2/authorize?responseType=code&"
                + "appId=" + appId + "&state=" + state;
                string response = HttpMethods.HttpPost(token_url);
                //获取用户信息    使用Access Token来获取用户的OpenID
                JObject result = JObject.Parse(response);
                FileLog.Info("获取authorizeCode result的值是" + result);
                if (result["code"].ToString() == "0000" && result["authorizeCode"]["state"].ToString()==state)
                {
                    returnauthorizeCode = result["authorizeCode"]["authorizeCode"].ToString();
                    RedisHelper.StringSet("authorizeCode", returnauthorizeCode, new TimeSpan(0, 8, 0));

                    return returnauthorizeCode;
                }
                else
                {
                    return "";
                }


            }
            catch (Exception ex)
            {
                FileLog.Error("获取舆情登录authorizeCode失败:" + ex.Message + "");
                return "";
            }
        }

        public string CallBackAccessToken(string authorizeCode)
        {
            string returnaccesstoken = "";
            if (RedisHelper.StringGet("accessToken") != null)
            {
                returnaccesstoken = RedisHelper.StringGet("accessToken").ToString();
                return returnaccesstoken;
            };
 
 
            try
            {
                //获取 通过Authorization Code 
                string token_url = "https://api-open-wx-www.yqt365.com/dataapp/api/oauth2/token?grantType=authorization_code&"
                + "appId=" + appId + "&appSecret=" + appSecret+ "&authorizeCode="+ authorizeCode;
                string response = HttpMethods.HttpPost(token_url);
                //   获取 accessToken
                JObject result = JObject.Parse(response);
                FileLog.Info(" 获取accessToken result的值是" + result);
                if (result["code"].ToString() == "0000"  )
                {
                    returnaccesstoken = result["accessToken"]["accessToken"].ToString();
                    RedisHelper.StringSet("accessToken", returnaccesstoken, new TimeSpan(22, 30, 0));

                    return returnaccesstoken;
                }
                else
                {
                    return "";
                }


            }
            catch (Exception ex)
            {
                FileLog.Error("获取舆情登录accesstoken失败:" + ex.Message + "");
                return "";
            }
        }
        /// <summary>
        /// Log4net 日志
        /// </summary>

    }
}