using System.Threading.Tasks;
using System.Transactions;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using YGNT.QuestionLibrary.Core.Tasks;
using YGNT.QuestionLibrary.Core.Tasks.Enum;

namespace YGNT.Exam.Messages.Event
{
    /// <summary>
    /// 解析任务完成处理
    /// </summary>
    public class TaskHandler : ITransientDependency,
        IAsyncEventHandler<EntityUpdatedEventData<QuestionResolveTask>>,
        IAsyncEventHandler<EntityUpdatedEventData<PaperProduceTask>>
    {
        private readonly IRepository<UserMessage, long> _userMessageRepository;

        public TaskHandler(IRepository<UserMessage, long> userMessageRepository)
        {
            _userMessageRepository = userMessageRepository;
        }

        /// <summary>
        /// 发送试题解析任务信息
        /// </summary>
        /// <param name="eventData">Event data</param>
        [UnitOfWork(TransactionScopeOption.Suppress)]
        public async Task HandleEventAsync(EntityUpdatedEventData<QuestionResolveTask> eventData)
        {
            var taskState = eventData.Entity.State;
            if (taskState == TaskState.成功 || taskState == TaskState.失败)
            {
                string msg = $"你的试题解析任务:{eventData.Entity.Name}执行{taskState}.";
                await _userMessageRepository.InsertAndGetIdAsync(new UserMessage()
                {
                    UserId = eventData.Entity.UserId,
                    Message = msg,
                    MessageType = MessageType.解析
                });
            }
        }

        /// <summary>
        /// 发送试卷生成任务信息
        /// </summary>
        /// <param name="eventData">Event data</param>
        [UnitOfWork(TransactionScopeOption.Suppress)]
        public async Task HandleEventAsync(EntityUpdatedEventData<PaperProduceTask> eventData)
        {
            var taskState = eventData.Entity.TaskState;
            if (taskState == TaskState.成功 || taskState == TaskState.失败)
            {
                string msg = $"你的试卷生成任务:{eventData.Entity.Name}执行{taskState}.";
                await _userMessageRepository.InsertAndGetIdAsync(new UserMessage()
                {
                    UserId = eventData.Entity.UserId,
                    Message = msg,
                    MessageType = MessageType.生成
                });
            }
        }
    }
}