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.Threading.Tasks;
using wispro.sp.entity;
using wispro.sp.share;
using wispro.sp.web.Auth;
using static System.Net.WebRequestMethods;

namespace wispro.sp.web.Services
{
    public class StaffGradeService
    {
        private readonly HttpClient _httpClient;
        private readonly JwtAuthenticationStateProvider _jwt;

        public StaffGradeService(HttpClient httpClient, AuthenticationStateProvider jwt)
        {
            _httpClient = httpClient;
            _jwt = (JwtAuthenticationStateProvider)jwt;
        }
        
        public async Task<List<StaffGrade>> GetAll()
        {
            try
            {
                var _StaffGrade = await _httpClient.GetFromJsonAsync<List<StaffGrade>>($"http://localhost:39476/api/StaffGrade/GetAll");
                return _StaffGrade;
            }
            catch(Exception ex)
            {
                if (ex.Message.Contains("Unauthorized"))
                {
                    _jwt.NotifyUserLogOut();
                }
                
                return null;
                
            }
        }

        public async Task<ApiSaveResponse> Save(StaffGrade staffGrade)
        {
            var data = await _httpClient.PostAsJsonAsync<StaffGrade>($"http://localhost:39476/api/StaffGrade/Save", staffGrade);

            if (data.IsSuccessStatusCode)
            {
                ApiSaveResponse result = await data.Content.ReadFromJsonAsync<ApiSaveResponse>();
                //await Task.Delay(1000);
                return result;
            }
            else
            {
                if(data.StatusCode ==  System.Net.HttpStatusCode.Unauthorized)
                {
                    _jwt.NotifyUserLogOut();
                }

                return new ApiSaveResponse() { Success = false , ErrorMessage = $"请求发生错误 {data.StatusCode}" };
            }
        }
    }
}
