using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Threading.Tasks;
using wispro.sp.share.webViewObject;
using wispro.sp.web.Utils;

namespace wispro.sp.web
{
    //AuthProvider.cs
    public class AuthProvider : AuthenticationStateProvider
    {
        private readonly HttpClient HttpClient;
        private readonly ILocalStorageService localStorageService;
        public string UserName { get; set; }

        public AuthProvider(ILocalStorageService localStorageService, HttpClient httpClient)
        {
            this.localStorageService = localStorageService;
            HttpClient = httpClient;
        }

        public async override Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            //var token = await localStorageService.GetItemAsync<string>("authToken");
            //var userName = await localStorageService.GetItemAsync<string>("authUserName");

            userToken result = new userToken();

            //if (string.IsNullOrEmpty(token))
            //{
            //    //这里获得用户登录状态
            result = await HttpClient.GetFromJsonAsync<userToken>($"http://localhost:39476/api/account/GetUser");
            //}
            //else
            //{
            //    result.Name = userName;
            //    result.Token = token;
            //}


            if (result?.Name == null)
            {
                MarkUserAsLoggedOut();
                return new AuthenticationState(new ClaimsPrincipal());
            }
            else
            {
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Name, result.Name));
                var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "apiauth"));
                return new AuthenticationState(authenticatedUser);
            }
        }

        /// <summary>
        /// 标记授权
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        public async void MarkUserAsAuthenticated(userToken userDto)
        {
            HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", userDto.Token);
            UserName = userDto.Name;

            var claims = JwtParser.ParseClaimsFromJwt(userDto.Token);
            //JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            //JwtSecurityToken token = jwtSecurityTokenHandler.ReadJwtToken(userDto.Token);

            var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "apiauth"));
            var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
            NotifyAuthenticationStateChanged(authState);

            ////可以将Token存储在本地存储中，实现页面刷新无需登录
            await localStorageService.SetItemAsync<string>("authToken", userDto.Token);
            await localStorageService.SetItemAsync<string>("authUserName", userDto.Name);
        }

        /// <summary>
        /// 标记注销
        /// </summary>
        public async void MarkUserAsLoggedOut()
        {
            await localStorageService.RemoveItemAsync("authToken");
            await localStorageService.RemoveItemAsync("authUserName");
            HttpClient.DefaultRequestHeaders.Authorization = null;
            UserName = null;

            var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity());
            var authState = Task.FromResult(new AuthenticationState(anonymousUser));
            NotifyAuthenticationStateChanged(authState);
        }
    }
}
