using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Localization;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.UI;
using YGNT.Exam.Authorization.Roles;

namespace YGNT.Exam.Authorization.Users
{
    public class UserManager : AbpUserManager<Role, User>
    {
        private readonly UserStore _store;

        public UserManager(
            RoleManager roleManager,
            UserStore store,
            IOptions<IdentityOptions> optionsAccessor,
            IPasswordHasher<User> passwordHasher,
            IEnumerable<IUserValidator<User>> userValidators,
            IEnumerable<IPasswordValidator<User>> passwordValidators,
            ILookupNormalizer keyNormalizer,
            IdentityErrorDescriber errors,
            IServiceProvider services,
            ILogger<UserManager<User>> logger,
            IPermissionManager permissionManager,
            IUnitOfWorkManager unitOfWorkManager,
            ICacheManager cacheManager,
            IRepository<OrganizationUnit, long> organizationUnitRepository,
            IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
            IOrganizationUnitSettings organizationUnitSettings,
            ISettingManager settingManager)
            : base(
                roleManager,
                store,
                optionsAccessor,
                passwordHasher,
                userValidators,
                passwordValidators,
                keyNormalizer,
                errors,
                services,
                logger,
                permissionManager,
                unitOfWorkManager,
                cacheManager,
                organizationUnitRepository,
                userOrganizationUnitRepository,
                organizationUnitSettings,
                settingManager)
        {
            _store = store;
        }



        /// <summary>
        /// 将邮箱替换为手机(不再检查邮箱)
        /// </summary>
        /// <param name="expectedUserId"></param>
        /// <param name="userName"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        public override async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string email)
        {
            var user = (await FindByNameAsync(userName));
            if (user != null && user.Id != expectedUserId)
            {
                throw new UserFriendlyException($"用户名'{userName}' 已被占用.");
            }

            return IdentityResult.Success;
        }

        public override async Task<IdentityResult> CreateAsync(User user)
        {
            await CheckPhoneUsed(user);
            return await base.CreateAsync(user);
        }


        public override async Task<IdentityResult> CreateAsync(User user, string password)
        {
            await CheckPhoneUsed(user);
            return await base.CreateAsync(user, password);
        }


        public override async Task<IdentityResult> UpdateAsync(User user)
        {
            await CheckPhoneUsed(user);
            return await base.UpdateAsync(user);
        }


        /// <summary>
        /// 检查手机号是否已使用
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task CheckPhoneUsed(User user)
        {

            var byPhoneUser = (await _store.FindByPhoneNumberAsync(user.PhoneNumber));
            if (byPhoneUser != null && byPhoneUser.Id != user.Id)
            {
                throw new UserFriendlyException($"手机号码 '{user.PhoneNumber}' 已被占用.");
            }
        }
    }
}
