using System.Linq;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using YGNT.QuestionLibrary.Core.Questions.Cache;

namespace YGNT.QuestionLibrary.Core.Papers.Domain
{
    public class PaperSettingManager : IPaperSettingManager
    {
        private readonly IRepository<PaperQuestionTypeScoringSetting> _paperQuestionTypeScoringSettingRepository;
        private readonly IQuestionTypeCache _questionTypeCache;

        public PaperSettingManager(IRepository<PaperQuestionTypeScoringSetting> paperQuestionTypeScoringSettingRepository, IQuestionTypeCache questionTypeCache)
        {
            _paperQuestionTypeScoringSettingRepository = paperQuestionTypeScoringSettingRepository;
            _questionTypeCache = questionTypeCache;
        }

        /// <summary>
        /// 获取试卷试题类型评分标准
        /// </summary>
        /// <param name="paperId"></param>
        /// <param name="questionTypeId"></param>
        /// <returns></returns>
        public async Task<Scoring> GetPaperQuestionScoringAsync(int paperId, int questionTypeId)
        {
            var scoringSetting = await _paperQuestionTypeScoringSettingRepository.GetAll()
                .Include(x => x.Scoring)
                .Where(x => paperId == x.PaperId)
                .Where(x => x.QuestionTypeId == questionTypeId)
                .FirstOrDefaultAsync();
            if (scoringSetting == null)
            {
                var questionType = await _questionTypeCache.GetAsync(questionTypeId);
                throw new UserFriendlyException($"试题类型{questionType.Name}尚未设置评分标准");
            }
            return scoringSetting.Scoring;
        }
    }
}