using Alipay.EasySDK.Kernel;

using CloudGaming.Code.Account.Contract;
using CloudGaming.Code.AppExtend;
using CloudGaming.DtoModel.Account;

using HuanMeng.DotNetCore.JwtInfrastructure;
using HuanMeng.DotNetCore.JwtInfrastructure.Interface;

using Microsoft.IdentityModel.Tokens;

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace CloudGaming.Code.Account.Login
{
    /// <summary>
    /// 自动登录,只能登录，不能注册
    /// </summary>
    public class AuthorizationUserLogin(string token, CloudGamingBase cloudGamingBase) : IUserAccount
    {
        /// <summary>
        /// 
        /// </summary>
        public int LastLoginType { get; set; } = 0;

        /// <summary>
        /// 
        /// </summary>
        public string DeviceNumber { get; set; }

        public async Task<int> LoginAsync()
        {
            if (string.IsNullOrEmpty(token))
            {
                throw MessageBox.Show(ResponseCode.ParamError, "登录失败");
            }
            var (principal, jwtToken) = cloudGamingBase.JwtAuthManager.DecodeJwtToken(token);
            if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256Signature))
            {
                throw MessageBox.Show(ResponseCode.ParamError, "无效的token");
                //throw new SecurityTokenException("无效的token");
            }
            var exp = principal.FindFirst("exp")?.Value;
            if (string.IsNullOrEmpty(exp))
            {
                throw MessageBox.Show(ResponseCode.JwtError, "无效的token");
            }
            var exptime = long.Parse(exp);

            long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            if (exptime < timestamp)
            {
                throw MessageBox.Show(ResponseCode.JwtError, "token已经过期");
            }
            var _userId = principal.FindFirst("userId")?.Value;
            var tokenMd5 = MD5Encryption.ComputeMD5Hash(token);
            int userId = 0;
            if (_userId == null || !int.TryParse(_userId, out userId))
            {
                throw MessageBox.Show(ResponseCode.JwtError, "token错误");
            }
            var tokenUser = await cloudGamingBase.Dao.DaoUser.Context.T_User_Token.Where(it => it.UserId == userId && it.TokenMd5 == tokenMd5).FirstOrDefaultAsync();
            if (tokenUser == null)
            {
                throw MessageBox.Show(ResponseCode.UserNotLogin, "token登录失败");
            }
            return tokenUser?.UserId ?? 0;
        }

        public Task CreateLoginAsync(T_User user)
        {
            return Task.CompletedTask;
        }

        public string GetUserDataProperty(UserDataPropertyEnum userDataPropertyEnum)
        {

            return "";
        }
    }
}
