using IRaCIS.Core.Domain.Share;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace IRaCIS.Core.Application.Auth
{

    public interface ITokenService
    {
        string GetToken(UserTokenInfo user);
    }


    public class TokenService : ITokenService
    {
        private readonly JwtSetting _jwtSetting;

        public TokenService(IOptions<JwtSetting> option)
        {
            _jwtSetting = option.Value;
        }

        public string GetToken(UserTokenInfo user)
        {
            //创建用户身份标识,可按需要添加更多信息
            var claims = new Claim[]
            {
                new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                 new Claim(JwtIRaCISClaimType.IdentityUserId, user.IdentityUserId.ToString()),
                new Claim(JwtIRaCISClaimType.UserRoleId, user.UserRoleId.ToString()),
                new Claim(JwtIRaCISClaimType.UserName, user.UserName),
                new Claim(JwtIRaCISClaimType.FullName, user.FullName),
                new Claim(JwtIRaCISClaimType.UserTypeId,user.UserTypeId.ToString()),
                new Claim(JwtIRaCISClaimType.UserTypeEnum,user.UserTypeEnum.ToString()),
                new Claim(JwtIRaCISClaimType.UserTypeEnumInt,((int)user.UserTypeEnum).ToString()),
                new Claim(JwtIRaCISClaimType.UserTypeShortName,user.UserTypeShortName),
                new Claim(JwtIRaCISClaimType.PermissionStr,user.PermissionStr),
                new Claim(JwtIRaCISClaimType.IsZhiZhun,user.IsZhiZhun.ToString()),
                new Claim(JwtIRaCISClaimType.IsTestUser,user.IsTestUser.ToString())
            };

            ////创建令牌
            var token = new JwtSecurityToken(
                    issuer: _jwtSetting.Issuer,
                    audience: _jwtSetting.Audience,
                    signingCredentials: _jwtSetting.Credentials,
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddDays(_jwtSetting.TokenExpireDays)
                );

            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return jwtToken;

        }
    }


}