using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using wispro.sp.share.webViewObject;
using wispro.sp.web.Auth;
using System.Text.Json;
using wispro.sp.web.Models;
using AntDesign;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using wispro.sp.share;

namespace wispro.sp.web.Services
{
    public class AuthService : IAuthService
    {
        private readonly ILocalStorageService localStorageService;
        private readonly IHttpService httpClient;
        private readonly AuthenticationStateProvider authenticationStateProvider;
        private IUserService UserService;
        private NavigationManager NavigationManager;
        private MessageService _message;
        private IJSRuntime JSRuntime;
        public AuthService(ILocalStorageService localStorageService, IHttpService httpClient, AuthenticationStateProvider authenticationStateProvider, IUserService UserService, MessageService message, IJSRuntime _JSRuntime, NavigationManager navigation)
        {
            this.localStorageService = localStorageService;
            this.httpClient = httpClient;
            this.authenticationStateProvider = authenticationStateProvider;
            this.UserService = UserService;
            this._message = message;
            this.JSRuntime = _JSRuntime;
            this.NavigationManager = navigation;
        }

        
        public async Task<bool> LoginAsync(loginDto userInfo)
        {
            bool result = false;

            var httpResponse = await httpClient.Post<userToken>($"account/Login", userInfo);
            //Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(httpResponse));
            if (httpResponse.StatusCode != System.Net.HttpStatusCode.NotFound)
            {
                userToken userToken = httpResponse;
                await localStorageService.SetItemAsync<userToken>("authToken", userToken);

                ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserAuthentication(userToken.Token);
                
                result = true;
            }
            //System.Threading.Thread.Sleep(1000);
            return result;
        }

        public async Task<bool> ChangePassword(changePasswordDto dto)
        {
            var httpResponse = await httpClient.Post<bool>($"account/ChangePassword", dto);
            return httpResponse;
        }

        public async Task<ApiSaveResponse> ResetPassword(string account,string mail)
        {
            var httpResponse = await httpClient.Get<ApiSaveResponse>($"account/ResetPassword?accountName={account}&mail={mail}");
            return httpResponse;
        }

        public async Task LogoutAsync()
        {
            await localStorageService.RemoveItemAsync("authToken");
            ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
            //httpClient.DefaultRequestHeaders.Authorization = null;
        }

        public async Task<List<string>> GetRoles(string resourceId)
        {
            
            var httpResponse = await httpClient.Get<List<string>>($"account/GetRoles?ResourceId={resourceId}");
            return httpResponse;
            
        }

        
        
        public async Task CanVisitResource()
        {
            string strUrl = NavigationManager.Uri;
            //Console.WriteLine($"Uri:{strUrl}");
            //Console.WriteLine($"Uri:{NavigationManager.BaseUri}");
            string strResourceId = NavigationManager.Uri.Replace(NavigationManager.BaseUri, "/");
            bool canVisist = false;
            var Roles = await httpClient.Get<List<string>>($"account/GetRoles?ResourceId={strResourceId}");

            CurrentUser _user =await UserService.GetUser();

            if (Roles.Count == 0)
            {
                canVisist = true;
            }
            else
            {
                foreach (var uRole in _user.Roles)
                {
                    if (Roles.Contains(uRole))
                    {
                        canVisist = true;
                        break;
                    }
                }

                
            }

            if (!canVisist)
            {
                
                    var config = new MessageConfig()
                    {
                        Content = "您没有权限使用该功能",
                        Type = MessageType.Error
                    };

                    var ret = _message.Open(config);
                    await JSRuntime.InvokeVoidAsync("history.back");
                
            }
            

        }
    }
}
