using CrazyStudio.Core.Common.CryptHelper;
using CrazyStudio.Core.Common.Eitities;
using CrazyStudio.Core.Common.Eitities.Page;
using CrazyStudio.Core.Common.JWT;
using CrazyStudio.Core.Common.Tools;
using Duende.IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using XPrintServer.Business.Dto;
using XPrintServer.Business.Services;
using XPrintServer.DataModel.Models;

namespace XPrintServer.Admin.Api.Controllers
{

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BackstageUserController : ControllerBase
    {

        private readonly IHttpContextAccessor _httpContextAccessor;
        //获取JwtSettings对象信息
        private readonly JwtConfigures _jwtConfigures;
        private readonly BackstatgeUserService _backstatgeUserService;
        private readonly ActionLogService _actionLogService;
        private readonly SM2Infos _sm2Infos;
        public BackstageUserController(IHttpContextAccessor httpContextAccessor, JwtConfigures jwtConfigures, BackstatgeUserService backstatgeUserService, ActionLogService actionLogService, SM2Infos sm2Infos)
        {
            _httpContextAccessor = httpContextAccessor;
            _jwtConfigures = jwtConfigures;
            _backstatgeUserService = backstatgeUserService;
            _actionLogService = actionLogService;
            _sm2Infos = sm2Infos;
        }

        /// <summary>
        /// 后台用户登录接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<dynamic?> RegisterAdminAndRefreshToken([FromBody] BackstatgeUserInfo user)
        {
            try
            {
                var dbUser = await _backstatgeUserService.AddOrGetBackstageUserID(new BackstageUser
                {
                    Password = SM2Tool.Encrypt("qwe123", _sm2Infos.PublicKey),//MD5Crypt.GetMD5("qwe123"),//默认注册密码
                    IsActive = true,
                    UserName = user.UserName,
                    RoleId = Guid.CreateVersion7()//Debug
                });

                var result = new
                {
                    errMsg = "",
                    resCode = 200
                };

                return result;
            }
            catch (Exception ex)
            {
                await _actionLogService.AddActionLog(new ActionLog
                {
                    Title = "后台管理用户注册异常",
                    Content = $"{ex.Message} {ex.StackTrace}"
                });
                return new
                {
                    errMsg = $"{ex.Message} {ex.StackTrace}",
                    resCode = 500
                };
            }
        }

        /// <summary>
        /// 后台用户登录接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<dynamic?> LoginAdminAndRefreshToken([FromBody] BackstatgeUserInfo user)
        {
            try
            {
                var dbUser = await _backstatgeUserService.GetBackstageUserID(user.UserName);
                if (dbUser == null)
                {
                    return new
                    {
                        access_token = "",
                        token_type = "",
                        profile = new
                        {
                            name = user.UserName
                        },
                        rescode = 1
                    };
                }

                if (dbUser.Password == null || user.Password == null || SM2Tool.Decrypt(dbUser.Password, _sm2Infos.PrivateKey) != user.Password)
                {
                    return new
                    {
                        access_token = "",
                        token_type = "",
                        profile = new
                        {
                            name = user.UserName
                        },
                        rescode = 2
                    };
                }

                var tokenHandler = new JwtSecurityTokenHandler();

                var key = Encoding.UTF8.GetBytes(_jwtConfigures.SecretKey);
                var authTime = DateTime.Now;//授权时间
                var expiresAt = authTime.AddDays(7);//过期时间//Test 7 Days
                var tokenDescripor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity([
                        new Claim(JwtClaimTypes.Audience,_jwtConfigures.Audience),
                        new Claim(JwtClaimTypes.Issuer,_jwtConfigures.Issuer),
                        new Claim(JwtClaimTypes.Name, dbUser.UserName),
                        new Claim(JwtClaimTypes.NickName, dbUser.NickName == null?"":dbUser.NickName!),
                        new Claim(JwtClaimTypes.Id, dbUser.Id.ToString()),
                        new Claim(JwtClaimTypes.Picture, dbUser.AvatarUrl== null?"":dbUser.AvatarUrl!)
                    ]),


                    IssuedAt = authTime,
                    Expires = expiresAt,
                    //对称秘钥SymmetricSecurityKey
                    //签名证书(秘钥，加密算法)SecurityAlgorithms
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescripor);
                var tokenString = tokenHandler.WriteToken(token);
                var result = new
                {
                    access_token = tokenString,
                    token_type = "Bearer",
                    profile = new
                    {
                        name = user.UserName,
                        //phone = user.phone,
                        auth_time = authTime,
                        expires_at = expiresAt
                    },
                    errMsg = "",
                    resCode = 200
                };

                return result;
            }
            catch (Exception ex)
            {
                await _actionLogService.AddActionLog(new ActionLog
                {
                    Title = "后台管理用户登录,获取 BackgroundUser Token 异常",
                    Content = $"{ex.Message} {ex.StackTrace}"
                });
                return new
                {
                    access_token = "",
                    token_type = "Bearer",
                    profile = new
                    {
                        name = user.UserName,
                        //phone = user.phone,
                        auth_time = DateTime.Now,
                        expires_at = DateTime.Now
                    },
                    errMsg = $"{ex.Message} {ex.StackTrace}",
                    resCode = 500
                };
            }
        }

        /// <summary>
        /// 确定登录信息接口，由于有 Authorize 属性做判断，直接返回 true 即可
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public bool CheckAuth()
        {
            return true;
        }



        [HttpPost]
        public async Task<ActionResult<PageResult<BackstageUser>>> GetBackstageUserList([FromBody] PageData pageData)
        {
            try
            {
                var userList = await _backstatgeUserService.GetBackstageUserList(pageData);
                return Ok(userList);
            }
            catch (Exception ex)
            {
                await _actionLogService.AddActionLog(new ActionLog { Title = "GetBackstageUserList Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                return StatusCode(500, ex.Message);
            }
        }

    }
}
