using EntityFrameworkCore.Triggered;
using IRaCIS.Core.Domain.Share;

namespace IRaCIS.Core.Application.Triggers
{

    //访视 质疑状态  触发修改
    public class ChallengeStateTrigger : IAfterSaveTrigger<QCChallenge>
    {
        private readonly IRepository _repository;

        public ChallengeStateTrigger(IRepository repository)
        {
            _repository = repository;
        }

        public async Task AfterSave(ITriggerContext<QCChallenge> context, CancellationToken cancellationToken)
        {
            var subjectVisitId = context.Entity.SubjectVisitId;

            ChallengeStateEnum subjectVisitChallengeState = default;


            var closedStateList = await _repository.Where<QCChallenge>(t => t.SubjectVisitId == subjectVisitId).Select(t => t.IsClosed).ToListAsync();

            if (closedStateList.Count == 0)
            {
                subjectVisitChallengeState = ChallengeStateEnum.No;
            }
            else if (closedStateList.All(t => t is true))
            {
                subjectVisitChallengeState = ChallengeStateEnum.HaveAndAllClosed;
            }
            else
            {
                subjectVisitChallengeState = ChallengeStateEnum.HaveAndHaveNotClosed;
            }


            await _repository.BatchUpdateAsync<SubjectVisit>(t => t.Id == subjectVisitId,
                u => new SubjectVisit() { ChallengeState = subjectVisitChallengeState });
        }
    }



    
}