using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Runtime.Session;
using Mapster;
using Microsoft.EntityFrameworkCore;
using YGNT.Exam.Authorization.Users;
using YGNT.Exam.Users.Dto.UserDiscipline;
using YGNT.QuestionLibrary.Core.Disciplines;
using YGNT.QuestionLibrary.Core.Tasks;

namespace YGNT.Exam.Users
{
    public class UserManagerAppService : IUserManagerAppService
    {
        private readonly IRepository<UserDiscipline, long> _userDisciplineRepository;
        private readonly IRepository<QuestionResolveTask, long> _questionResolveTaskRepository;
        private readonly IRepository<User, long> _userRepository;
        public IAbpSession AbpSession { get; set; }

        public UserManagerAppService(IRepository<UserDiscipline, long> userDisciplineRepository, IRepository<User, long> userRepository, IRepository<QuestionResolveTask, long> questionResolveTaskRepository)
        {
            _userDisciplineRepository = userDisciplineRepository;
            _userRepository = userRepository;
            _questionResolveTaskRepository = questionResolveTaskRepository;
            AbpSession = NullAbpSession.Instance;
        }

        /// <summary>
        /// 获取用户所属学科
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<UserDisciplineDto>> GetUserDisciplineAsync([Required] long userId)
        {
            return await _userDisciplineRepository.GetAll()
                .Where(x => x.UserId == userId)
                .Select(x => x.Adapt(new UserDisciplineDto()
                {
                    Discipline = x.Discipline.Name,
                    EducationCategoryId = x.Discipline.GradeId,
                    EducationCategory = x.Discipline.Grade.Name
                })).ToListAsync();
        }

        /// <summary>
        /// 分配用户所属学科
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="update"></param>
        /// <returns></returns>
        public async Task UpdateUserDisciplineAsync([Required] long userId, UpdateUserDisciplineDto update)
        {
            await _userDisciplineRepository.DeleteAsync(x => x.UserId == userId);
            foreach (var disciplineId in update.DisciplineList)
            {
                await _userDisciplineRepository.InsertAsync(new UserDiscipline()
                {
                    DisciplineId = disciplineId,
                    UserId = userId
                });
            }
        }
    }
}