using System;
using System.IO;
using System.Security.Cryptography;
using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ZhiZhun.AuthenticationCenter.Utility;
using ZhiZhun.AuthenticationCenter.Utility.RSA;

namespace Zhaoxi.NET6.AuthenticationCenter.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class JWTController : ControllerBase
    {
        #region MyRegion
        private ILogger<JWTController> _logger = null;
        private IJWTService _iJWTService = null;
        private readonly IConfiguration _iConfiguration;
        public JWTController(ILoggerFactory factory,
            ILogger<JWTController> logger,
            IConfiguration configuration
            , IJWTService service)
        {
            this._logger = logger;
            this._iConfiguration = configuration;
            this._iJWTService = service;
        }
        #endregion



        [Route("GetKey")]
        [HttpGet]
        public string GetKey()
        {
            string keyDir = Directory.GetCurrentDirectory();
            if (RSAHelper.TryGetKeyParameters(keyDir, false, out RSAParameters keyParams) == false)
            {
                keyParams = RSAHelper.GenerateAndSaveKey(keyDir, false);
            }

            return JsonConvert.SerializeObject(keyParams);
        }

        /// <summary>
        /// 数据库校验
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [Route("Login")]
        [HttpPost]
        public IResponseOutput Login([FromForm] string name, [FromForm] string password)
        {
            Console.WriteLine($"This is Login name={name} password={password}");
            if ("Eleven".Equals(name, StringComparison.OrdinalIgnoreCase) && "123456".Equals(password))//应该数据库
            {
                UserBasicInfo currentUser = new UserBasicInfo()
                {
                    //Id = 123,
                    //Account = "xuyang@zhaoxiEdu.Net",
                    //EMail = "57265177@qq.com",
                    //Mobile = "18664876671",
                    //Sex = 1,
                    //Age = 33,
                    //Name = "Eleven",
                    //Role = "Admin"
                };

                string token = this._iJWTService.GetToken(currentUser);
                if (!string.IsNullOrEmpty(token))
                {
                    return ResponseOutput.Ok("Token颁发成功");
                }
                else
                {
				

					return ResponseOutput.NotOk("Token获取失败");
                }
            }
            else
            {

			 return   ResponseOutput.NotOk("验证失败");
             
             
            }
        }


        /// <summary>
        /// 生成Token+RefreshToken
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [Route("LoginWithRefresh")]
        [HttpPost]
        public IResponseOutput LoginWithRefresh([FromForm] string name, [FromForm] string password)
        {
            Console.WriteLine($"This is LoginWithRefresh name={name} password={password}");

            if ("Eleven".Equals(name, StringComparison.OrdinalIgnoreCase) && "123456".Equals(password))//应该数据库
            {
                UserBasicInfo currentUser = new UserBasicInfo()
                {
                    //Id = 123,
                    //Account = "xuyang@zhaoxiEdu.Net",
                    //EMail = "57265177@qq.com",
                    //Mobile = "18664876671",
                    //Sex = 1,
                    //Age = 33,
                    //Name = "Eleven",
                    //Role = "Admin"
                };

                var tokenPair = this._iJWTService.GetTokenWithRefresh(currentUser);
                if (tokenPair != null && !string.IsNullOrEmpty(tokenPair.Item1))
                {

                    return ResponseOutput.Ok(new {
                        Token = tokenPair.Item1,
                        RefreshToken = tokenPair.Item2});
                }
                else
                {


                    return ResponseOutput.NotOk("颁发token失败");
                }
            }
            else
            {

                return ResponseOutput.NotOk("验证失败");

            }
        }





        [Route("RefreshToken")]
        [HttpPost]
        public IResponseOutput RefreshToken([FromForm] string refreshToken)
        {

            var token = this._iJWTService.GetTokenByRefresh(refreshToken);
            if (!string.IsNullOrEmpty(token))
            {

                return ResponseOutput.Ok("刷新Token成功");
            }
            else
            {

                return ResponseOutput.NotOk("刷新token失败");
            }


            #region Check refreshToken
            //string sResult = JWTTokenDeserialize.AnalysisToken(refreshToken);
            //var refreshTokenResult = await base.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
            //var expires = refreshTokenResult?.Principal?.Claims?.First(c => c.Type.Equals("expires"))?.Value ?? DateTime.Now.AddMinutes(-1).ToString();
            //if (DateTime.Parse(expires) > DateTime.Now)//有效期验证
            //{
            //    var token = this._iJWTService.GetTokenByRefresh(refreshToken);
            //    if (!string.IsNullOrEmpty(token))
            //    {
            //        return JsonConvert.SerializeObject(new AjaxResult<string>()
            //        {
            //            Result = true,
            //            Message = "刷新Token成功",
            //            TValue = token,
            //            OtherValue = refreshToken//写在OtherValue
            //        });
            //    }
            //    else
            //    {
            //        return JsonConvert.SerializeObject(new AjaxResult<string>()
            //        {
            //            Result = false,
            //            Message = "刷新token失败",
            //            TValue = ""
            //        });
            //    }
            //}
            //else
            //{
            //    return JsonConvert.SerializeObject(new AjaxResult<string>()
            //    {
            //        Result = false,
            //        Message = "RefreshToken过期了",
            //        TValue = ""
            //    });
            //}

            #endregion
        }
    }
}