using AutoTurnOver.Models;
using AutoTurnOver.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace AutoTurnOver.Common
{
    public class AutoUtility
    {
        /// <summary>
        /// 获取当前登陆用户
        /// </summary>
        /// <returns></returns>
        public static UserData GetUser()
        {
            var token = MyHttpContext.Current.Request.Headers["Authorization"];
            if (string.IsNullOrWhiteSpace(token))
            {
                token = MyHttpContext.Current.Request.Query["token"].FirstOrDefault();
            }
            var tokenDecode = WebUtility.UrlDecode(token);
            var dd = new JwtSecurityToken(tokenDecode.Replace("Bearer ", ""));
            var userId = dd.Claims.FirstOrDefault(m => m.Type == "UserId").Value;
            var exp = dd.Claims.FirstOrDefault(m => m.Type == "exp").Value;

            var userInfo = RedisHelper.Get<tokenUser>("sso-aims-authorization-user-info-" + userId + "-" + exp, () => { return null; }).result;
            return new UserData
            {
                UserName = userInfo.Account,
                UserAccount = userInfo.Account,
                DepartmentName = "",//saasUser.Department==null?"":saasUser.Department.Name
                tree_menu_list = userInfo.tree_menu_list()
            };

            //var userInfo = MyHttpContext.Current.Session.GetString("UserInfo");
            //var saasUser = userInfo.ToObj<SaasUserInfo>();
            //return new UserData
            //{
            //    UserName = saasUser.Account,
            //    UserAccount = saasUser.Account,
            //    DepartmentName = "",//saasUser.Department==null?"":saasUser.Department.Name
            //    tree_menu_list = saasUser.tree_menu_list()
            //};

        }

        /// <summary>
        /// 获取注销路径
        /// </summary>
        /// <returns></returns>
        public static string LoginOutUrl()
        {
            return ConfigurationManager.AppSettings["WebHost_LoginOut"].ToString();
        }
    }
}
