using AutoMapper;
using EasyCaching.Core;
using EntityFrameworkCore.Triggered;
using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using System.Linq.Expressions;

namespace IRaCIS.Core.Application.Triggers
{

    public class VisitTaskIAfterSignTrigger : IAfterSaveTrigger<VisitTask>,IBeforeSaveTrigger<VisitTask>
    {

        private readonly IRepository<VisitTask> _visitTaskRepository;

        private readonly IRepository<Subject> _subjectRepository;
        private readonly IUserInfo _userInfo;
        private readonly IEmailSendService _emailSendService;

        

        public VisitTaskIAfterSignTrigger(IRepository<VisitTask> visitTaskRepository, IRepository<Subject> subjectRepository, IUserInfo userInfo, IEmailSendService emailSendService)
        {
            _visitTaskRepository = visitTaskRepository;
            _subjectRepository = subjectRepository;
            _userInfo = userInfo;

            _emailSendService = emailSendService;
        }


        public async Task AfterSave(ITriggerContext<VisitTask> context, CancellationToken cancellationToken)
        {
            var visitTask = context.Entity;

           
            if (visitTask.SignTime != null && visitTask.ReadingTaskState == ReadingTaskState.HaveSigned )
            {
                //任务阅片完成 自动释放
                await _visitTaskRepository.BatchUpdateNoTrackingAsync(t => t.SubjectId == visitTask.SubjectId && t.TrialReadingCriterionId==visitTask.TrialReadingCriterionId , t=>new VisitTask() { SubjectCriterionClaimUserId=null});
            }


        }

        public async Task BeforeSave(ITriggerContext<VisitTask> context, CancellationToken cancellationToken)
        {
            var visitTask = context.Entity;

            if (context.ChangeType == ChangeType.Modified && visitTask.ReadingTaskState==ReadingTaskState.HaveSigned && visitTask.ReadingTaskState != context.UnmodifiedEntity.ReadingTaskState    &&        _userInfo.UserTypeEnumInt == (int)UserTypeEnum.PI)
            {
                visitTask.PIAuditState = PIAuditState.PIAgree;
            }

            if (context.ChangeType == ChangeType.Modified && visitTask.PIAuditState!=context.UnmodifiedEntity.PIAuditState  && visitTask.PIAuditState==PIAuditState.PIAgree)
            {
                await _emailSendService.SendPIAuditResultAsync(visitTask.Id);
            }
        }
    }
}