using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using YGNT.QuestionLibrary.Core.Papers.Cache;

namespace YGNT.QuestionLibrary.Core.Papers.Event
{
    /// <summary>
    /// 计算试卷总分
    /// </summary>
    public class PaperScoreCalculate : ITransientDependency,
        IAsyncEventHandler<EntityCreatingEventData<PaperQuestion>>,
        IAsyncEventHandler<EntityDeletingEventData<PaperQuestion>>
    {
        private readonly IRepository<Paper> _paperRepository;
        private readonly IScoringCache _scoringCache;

        public PaperScoreCalculate(IRepository<Paper> paperRepository, IScoringCache scoringCache)
        {
            _paperRepository = paperRepository;
            _scoringCache = scoringCache;
        }

        /// <summary>
        /// 添加新试题时
        /// </summary>
        /// <param name="eventData"></param>
        /// <returns></returns>
        public async Task HandleEventAsync(EntityCreatingEventData<PaperQuestion> eventData)
        {
            var paperQuestion = eventData.Entity;
            if (paperQuestion.Paper == null)
                paperQuestion.Paper = await _paperRepository.GetAsync(paperQuestion.PaperId);
            var score = paperQuestion.SingleScore;
            if (paperQuestion.ScoringId.HasValue)
            {
                var scoringCacheItem = await _scoringCache.GetAsync(paperQuestion.ScoringId ?? default);
                score += scoringCacheItem.Score;
            }
            paperQuestion.Paper.TotalScore = score ?? default;
        }

        /// <summary>
        /// 删除试题时
        /// </summary>
        /// <param name="eventData"></param>
        /// <returns></returns>
        public async Task HandleEventAsync(EntityDeletingEventData<PaperQuestion> eventData)
        {
            var paperQuestion = eventData.Entity;
            if (paperQuestion.Paper == null)
                paperQuestion.Paper = await _paperRepository.GetAsync(paperQuestion.PaperId);
            var score = paperQuestion.SingleScore;
            if (paperQuestion.ScoringId.HasValue)
            {
                var scoringCacheItem = await _scoringCache.GetAsync(paperQuestion.ScoringId ?? default);
                score += scoringCacheItem.Score;
            }
            paperQuestion.Paper.TotalScore -= score ?? default;
        }

    }
}