using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using wispro.sp.share.webViewObject;
using wispro.sp.web.Services;

namespace wispro.sp.web.Pages
{
    public partial class ChangePassword
    {
        private changePasswordDto dto = new changePasswordDto();
        private Models.CurrentUser user;
        private string ChecknewPassword;

        [Parameter]
        public bool FirstLogin { get; set; }

        [Inject]
        protected IUserService userService { get; set; }

        [Inject] public NavigationManager navigation { get; set; }
        [Inject] public IJSRuntime JSRuntime { get; set; }

        [Inject] public IAuthService authService { get; set; }

        protected async override Task OnInitializedAsync()
        {
            user =await userService.GetUser();
            dto = new changePasswordDto();
            dto.UserId = user.Userid.Value;

            //Console.WriteLine($"OnInitializedAsync:{System.Text.Json.JsonSerializer.Serialize(user)}");
            await base.OnInitializedAsync();
        }

        private string ErrorMsg;
        public async  void OnSubmit()
        {
            //Console.WriteLine($"OnSubmit:{System.Text.Json.JsonSerializer.Serialize(user)}");
            //Console.WriteLine($"用户ID：{dto.UserId}");
            //Console.WriteLine($"用户名：{user.Name}-{user.Userid}");
            //Console.WriteLine($"旧密码：{dto.oldPassword}");
            //Console.WriteLine($"新密码：{dto.newPassword}");
            //Console.WriteLine($"Check新密码：{ChecknewPassword}");
            
            ErrorMsg = "";

            if(dto.newPassword  == ChecknewPassword)
            {
                if (string.IsNullOrEmpty(dto.newPassword))
                {
                    ErrorMsg = "密码不能为空！";
                    return;
                }
                
                var result = await authService.ChangePassword(dto);

                if (result)
                {
                    OnCancel();
                }
                else
                {
                    ErrorMsg = "修改发生了一些错误，请重试！";
                }
            }
            else
            {
                ErrorMsg = "新密码两次输入不一致！";
            }

            StateHasChanged();
        }

        public async void OnCancel()
        {
            if (FirstLogin)
            {
                navigation.NavigateTo("/Home");
            }
            else
            {
                await JSRuntime.InvokeVoidAsync("history.back");
            }
        }
    }
}
