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

namespace IRaCIS.Core.Application.Auth
{

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


    public class TokenService : ITokenService
    {
        private readonly JwtSetting _jwtSetting;

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

        public string GetToken(IRaCISClaims user)
        {
            //创建用户身份标识,可按需要添加更多信息
            var claims = new Claim[]
            {
                new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtIRaCISClaimType.Id, user.Id.ToString()),
                new Claim(JwtIRaCISClaimType.Name, user.FullName),
                new Claim(JwtIRaCISClaimType.RealName, user.RealName),
                new Claim(JwtIRaCISClaimType.Code,user.Code),
                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)
            };

            ////创建令牌
            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;

        }
    }

   
}