using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using Long.Common.Enums;
using Long.DAO.Basedata;
using Long.Utils.Encryptor;
using System.Security.Claims;

namespace Auth
{
    public class DefaultResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly ISystemUserDatabase _systemUserDatabase = new SystemUserDatabase();
        private readonly IUserDatabase _userDatabase = new UserDatabase();
        private string _encryptionKey;

        public DefaultResourceOwnerPasswordValidator(IConfiguration configuration)
        {
            this._encryptionKey = configuration["EncryptorKey"] ?? "";
        }

        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            // 是否登录
            var isLogin = false;

            // 内码
            string id = string.Empty;

            if (context.Request.ClientId == UserTypeEnum.Admin.ToString().ToLower())
            {
                // 系统用户登录
                var systemUser = await _systemUserDatabase.GetByUserNameAsync(context.UserName);
                if (systemUser != null && DESEncryptor.Encrypt(context.Password, _encryptionKey) == systemUser.Password)
                {
                    isLogin = true;
                    id = systemUser.Id.ToString();
                }
            }
            else if (context.Request.ClientId == UserTypeEnum.User.ToString().ToLower())
            {
                // 普通用户登录
                var user = await _userDatabase.GetByUserNameAsync(context.UserName);
                if (user != null && DESEncryptor.Encrypt(context.Password, _encryptionKey) == user.Password)
                {
                    isLogin = true;
                    id = user.Id.ToString();
                }
            }

            if (isLogin)
            {
                var claims = new List<Claim>()
                {
                    new Claim(JwtClaimTypes.Id, id),
                    new Claim(JwtClaimTypes.PreferredUserName, context.UserName)
                };
                context.Result = new GrantValidationResult(id, OidcConstants.AuthenticationMethods.Password, claims);
                return;
            }


            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
        }
    }
}
